Moved all bindings to the "bindings" sub-directory

Renamed the CSFML directory to c
Renamed the DSFML directory to d
--> bindings must now be updated to match the new organization!

git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/branches/sfml2@1630 4e206d99-4929-0410-ac5d-dfc041789085
This commit is contained in:
LaurentGom 2010-11-09 17:13:17 +00:00
parent 0cc5563cac
commit 0e2297af28
417 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,36 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.audio.all;
public import
dsfml.audio.listener,
dsfml.audio.music,
dsfml.audio.sound,
dsfml.audio.soundbuffer,
dsfml.audio.soundbufferrecorder,
dsfml.audio.soundrecorder,
dsfml.audio.soundstream;

View file

@ -0,0 +1,185 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.audio.listener;
import dsfml.system.common;
import dsfml.system.vector;
/**
* Listener is a global interface for defining the audio
* listener properties ; the audio listener is the point in
* the scene from where all the sounds are heard.
*
* See_Also:
* SFML Tutorial for sound spatialization example.
*/
class Listener
{
/**
* Change the global volume of all the sounds.
* The default volume is 100
*
* Params:
* volume = New global volume, in the range [0, 100]
*/
static void setGlobalVolume(float volume)
in
{
assert (volume >= 0.f && volume <= 100.f);
}
body
{
sfListener_SetGlobalVolume(volume);
}
/**
* Get the current value of the global volume of all the sounds
*
* Returns:
* Current global volume, in the range [0, 100]
*/
static float getGlobalVolume()
{
return sfListener_GetGlobalVolume();
}
/**
* Change the position of the listener.
* The default position is (0, 0, 0)
*
* Params:
* posX = X position of the listener in the world
* posY = Y position of the listener in the world
* posZ = Z position of the listener in the world
*/
static void setPosition(float posX, float posY, float posZ)
{
sfListener_SetPosition(posX, posY, posZ);
}
/**
* Change the position of the listener.
* The default position is (0, 0, 0)
*
* Params:
* position = new position
*/
static void setPosition(Vector3f position)
{
sfListener_SetPosition(position.x, position.y, position.z);
}
/**
* Get the current position of the listener
*
* Returns:
* Current position
*/
static Vector3f getPosition()
{
Vector3f ret;
sfListener_GetPosition(&ret.x, &ret.y, &ret.z);
return ret;
}
/**
* Change the orientation of the listener
* The default direction is (0, 0, -1)
*
* Params:
* directionX = X component of the listener's direction
* directionY = Y component of the listener's direction
* directionZ = Z component of the listener's direction
*/
static void setDirection(float directionX, float directionY, float directionZ)
{
sfListener_SetDirection(directionX, directionY, directionZ);
}
/**
* Change the orientation of the listener
* The default direction is (0, 0, -1)
*
* Params:
* direction = Position of the point the listener must look at
*/
static void setDirection(Vector3f position)
{
sfListener_SetDirection(position.x, position.y, position.z);
}
/**
* Get the current orientation of the listener
*
* Returns:
* Position of the point the listener is looking at
*/
static Vector3f getDirection()
{
Vector3f ret;
sfListener_GetDirection(&ret.x, &ret.y, &ret.z);
return ret;
}
private:
// External ====================================================================
extern (C)
{
typedef void function(float) pf_sfListener_SetGlobalVolume;
typedef float function() pf_sfListener_GetGlobalVolume;
typedef void function(float, float, float) pf_sfListener_SetPosition;
typedef void function(float*, float*, float*) pf_sfListener_GetPosition;
typedef void function(float, float, float) pf_sfListener_SetDirection;
typedef void function(float*, float*, float*) pf_sfListener_GetDirection;
static pf_sfListener_SetGlobalVolume sfListener_SetGlobalVolume;
static pf_sfListener_GetGlobalVolume sfListener_GetGlobalVolume;
static pf_sfListener_SetPosition sfListener_SetPosition;
static pf_sfListener_GetPosition sfListener_GetPosition;
static pf_sfListener_SetDirection sfListener_SetDirection;
static pf_sfListener_GetDirection sfListener_GetDirection;
}
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-audio-d");
else
DllLoader dll = DllLoader.load("csfml-audio");
sfListener_SetGlobalVolume = cast(pf_sfListener_SetGlobalVolume)dll.getSymbol("sfListener_SetGlobalVolume");
sfListener_GetGlobalVolume = cast(pf_sfListener_GetGlobalVolume)dll.getSymbol("sfListener_GetGlobalVolume");
sfListener_SetPosition = cast(pf_sfListener_SetPosition)dll.getSymbol("sfListener_SetPosition");
sfListener_GetPosition = cast(pf_sfListener_GetPosition)dll.getSymbol("sfListener_GetPosition");
sfListener_SetDirection = cast(pf_sfListener_SetDirection)dll.getSymbol("sfListener_SetDirection");
sfListener_GetDirection = cast(pf_sfListener_GetDirection)dll.getSymbol("sfListener_GetDirection");
}
}

View file

@ -0,0 +1,188 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.audio.music;
import dsfml.audio.soundsource;
import dsfml.system.common;
import dsfml.system.exception;
import dsfml.system.stringutil;
import dsfml.system.vector;
/**
* Music defines a big sound played using streaming,
* so usually what we call a music :)
*/
class Music : SoundSource!("sfMusic")
{
/**
* Open a music file (doesn't play it -- call Play for that)
*
* Params:
* filename = Path of the file to open
*
*/
this(string filename)
{
if (filename is null || filename.length == 0)
throw new LoadingException("LoadingException : Filename is invalid.");
m_ptr = sfMusic_CreateFromFile(toStringz(filename)); // TODO: this is a hack, should properly call the super constructor
}
/**
* Open a music file from memory (doesn't play it -- call Play() for that)
*
* Params:
* data = file data in memory
*
*/
this(byte[] data)
{
if (data is null || data.length == 0)
throw new Exception("LoadingException : Memory stream is invalid.");
m_ptr = sfMusic_CreateFromMemory(data.ptr, data.length); // TODO: ditto
}
/**
* Start playing the audio stream
*/
void play()
{
sfMusic_Play(m_ptr);
}
/**
* Stop playing the audio stream
*/
void stop()
{
sfMusic_Stop(m_ptr);
}
/**
* Pause the audio stream
*/
void pause()
{
sfMusic_Pause(m_ptr);
}
/**
* Return the number of channels (1 = mono, 2 = stereo)
*
* Returns:
* Number of channels
*/
uint getChannelsCount()
{
return sfMusic_GetChannelsCount(m_ptr);
}
/**
* Get the stream sample rate
*
* Returns:
* Stream frequency (number of samples per second)
*/
uint getSampleRate()
{
return sfMusic_GetSampleRate(m_ptr);
}
/**
* Get the music duration
*
* Returns:
* Music duration, in seconds
*/
float getDuration()
{
return sfMusic_GetDuration(m_ptr);
}
/**
* Tell whether or not the music is looping
*
* Returns:
* True if the music is looping, false otherwise
*/
bool getLoop()
{
return cast(bool)sfMusic_GetLoop(m_ptr);
}
/**
* Set the music loop state.
* This parameter is disabled by default
*
* Params:
* loop = True to play in loop, false to play once
*/
void setLoop(bool loop)
{
sfMusic_SetLoop(m_ptr, loop);
}
}
private:
extern(C)
{
SFMLClass function(cchar*) sfMusic_CreateFromFile;
SFMLClass function(byte*, size_t) sfMusic_CreateFromMemory;
void function(SFMLClass, int) sfMusic_SetLoop;
bool function(SFMLClass) sfMusic_GetLoop;
float function(SFMLClass) sfMusic_GetDuration;
void function(SFMLClass) sfMusic_Play;
void function(SFMLClass) sfMusic_Pause;
void function(SFMLClass) sfMusic_Stop;
uint function(SFMLClass) sfMusic_GetChannelsCount;
uint function(SFMLClass) sfMusic_GetSampleRate;
}
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-audio-d");
else
DllLoader dll = DllLoader.load("csfml-audio");
mixin(loadFromSharedLib("sfMusic_CreateFromFile"));
mixin(loadFromSharedLib("sfMusic_CreateFromMemory"));
mixin(loadFromSharedLib("sfMusic_SetLoop"));
mixin(loadFromSharedLib("sfMusic_GetLoop"));
mixin(loadFromSharedLib("sfMusic_GetDuration"));
mixin(loadFromSharedLib("sfMusic_Play"));
mixin(loadFromSharedLib("sfMusic_Pause"));
mixin(loadFromSharedLib("sfMusic_Stop"));
mixin(loadFromSharedLib("sfMusic_GetChannelsCount"));
mixin(loadFromSharedLib("sfMusic_GetSampleRate"));
}

View file

@ -0,0 +1,224 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.audio.sound;
import dsfml.audio.soundbuffer;
import dsfml.audio.soundsource;
import dsfml.system.common;
import dsfml.system.exception;
import dsfml.system.vector;
/**
* Sound defines the properties of the sound such as position,
* volume, pitch, etc.
*/
class Sound : SoundSource!("sfSound")
{
/**
* Default constructor
*/
this()
{
super();
}
/**
* Construct the sound from its parameters
*
* Params:
* soundbuffer = Sound buffer to play
* loop = Loop flag (false by default)
* pitch = Value of the pitch (1 by default)
* volume = Volume (100 by default)
* x = X position (0 by default)
* y = Y position (0 by default)
* z = Z position (0 by default)
*
* Throws:
* NullParameterException if buffer is null
*/
this(SoundBuffer soundbuffer, bool loop = false, float pitch = 1.f, float volume = 100.f, float x = 0.f, float y = 0.f, float z = 0.f)
{
if (soundbuffer is null)
throw new NullParameterException("NullParameterException : SoundBuffer is null.");
super();
buffer = soundbuffer;
loop = loop;
pitch = pitch;
volume = volume;
setPosition(x, y, z);
}
/**
* Play the sound
*/
void play()
{
sfSound_Play(m_ptr);
}
/**
* Pause the sound
*/
void pause()
{
sfSound_Pause(m_ptr);
}
/**
* Stop the sound
*/
void stop()
{
sfSound_Stop(m_ptr);
}
@property
{
/**
* Set the source buffer
*
* Params:
* buffer = New sound buffer to bind to the sound
*/
void buffer(SoundBuffer buffer)
{
if (buffer is null)
throw new NullParameterException("NullParameterException : SoundBuffer is null.");
m_buffer = buffer;
sfSound_SetBuffer(m_ptr, buffer.nativePointer);
}
/**
* Set the sound loop state.
* This parameter is disabled by default
*
* Params:
* loop = True to play in loop, false to play once
*/
void loop(bool loop)
{
sfSound_SetLoop(m_ptr, loop);
}
/**
* Set the current playing offset of a sound
*
* Params:
* offset = new playing position, expressed in seconds
*/
void playingOffset(float offset)
{
sfSound_SetPlayingOffset(m_ptr, offset);
}
/**
* Get the source buffer
*
* Returns:
* Sound buffer bound to the sound (can be NULL)
*/
SoundBuffer buffer()
{
return m_buffer;
}
/**
* Tell whether or not the sound is looping
*
* Returns:
* True if the sound is looping, false otherwise
*/
bool loop()
{
return cast(bool)(sfSound_GetLoop(m_ptr));
}
/**
* Get the current playing position of the sound
*
* Returns:
* Current playing position, expressed in seconds
*/
float playingOffset()
{
return sfSound_GetPlayingOffset(m_ptr);
}
}
private:
SoundBuffer m_buffer;
// External ====================================================================
extern (C)
{
typedef void function(SFMLClass) pf_sfSound_Play;
typedef void function(SFMLClass) pf_sfSound_Pause;
typedef void function(SFMLClass) pf_sfSound_Stop;
typedef void function(SFMLClass, SFMLClass) pf_sfSound_SetBuffer;
typedef SFMLClass function(SFMLClass) pf_sfSound_GetBuffer;
typedef void function(SFMLClass, int) pf_sfSound_SetLoop;
typedef int function(SFMLClass) pf_sfSound_GetLoop;
typedef float function(SFMLClass) pf_sfSound_GetPlayingOffset;
typedef void function(SFMLClass, float) pf_sfSound_SetPlayingOffset;
static pf_sfSound_Play sfSound_Play;
static pf_sfSound_Pause sfSound_Pause;
static pf_sfSound_Stop sfSound_Stop;
static pf_sfSound_SetBuffer sfSound_SetBuffer;
static pf_sfSound_GetBuffer sfSound_GetBuffer;
static pf_sfSound_SetLoop sfSound_SetLoop;
static pf_sfSound_GetLoop sfSound_GetLoop;
static pf_sfSound_GetPlayingOffset sfSound_GetPlayingOffset;
static pf_sfSound_SetPlayingOffset sfSound_SetPlayingOffset;
}
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-audio-d");
else
DllLoader dll = DllLoader.load("csfml-audio");
sfSound_Play = cast(pf_sfSound_Play)dll.getSymbol("sfSound_Play");
sfSound_Pause = cast(pf_sfSound_Pause)dll.getSymbol("sfSound_Pause");
sfSound_Stop = cast(pf_sfSound_Stop)dll.getSymbol("sfSound_Stop");
sfSound_SetBuffer = cast(pf_sfSound_SetBuffer)dll.getSymbol("sfSound_SetBuffer");
sfSound_GetBuffer = cast(pf_sfSound_GetBuffer)dll.getSymbol("sfSound_GetBuffer");
sfSound_SetLoop = cast(pf_sfSound_SetLoop)dll.getSymbol("sfSound_SetLoop");
sfSound_GetLoop = cast(pf_sfSound_GetLoop)dll.getSymbol("sfSound_GetLoop");
sfSound_GetPlayingOffset = cast(pf_sfSound_GetPlayingOffset)dll.getSymbol("sfSound_GetPlayingOffset");
sfSound_SetPlayingOffset = cast(pf_sfSound_SetPlayingOffset)dll.getSymbol("sfSound_SetPlayingOffset");
}
}

View file

@ -0,0 +1,205 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.audio.soundbuffer;
import dsfml.system.common;
import dsfml.system.exception;
import dsfml.system.stringutil;
/**
* SoundBuffer is the low-level for loading and manipulating
* sound buffers
*/
class SoundBuffer : DSFMLObject
{
/**
* Load the sound buffer from a file
*
* Params:
* filename = Path of the sound file to load
*
* Throws:
* LoadingException on failure
*/
this(string filename)
{
if (filename is null || filename.length == 0)
throw new LoadingException("LoadingException : Filename is invalid.");
super(sfSoundBuffer_CreateFromFile(toStringz(filename)));
}
/**
* Load the sound buffer from a file in memory
*
* Params:
* data = Array of file data in memory
*
* Throws:
* LoadingException on failure
*/
this(byte[] data)
{
if (data is null || data.length == 0)
throw new Exception("LoadingException : Memory stream is invalid.");
super(sfSoundBuffer_CreateFromMemory(data.ptr, data.length));
}
/**
* Load the sound buffer from an array of samples - assumed format for
* samples is 16 bits signed integer
*
* Params:
* samples = Array of samples in memory
* channelsCount = Number of channels (1 = mono, 2 = stereo, ...)
* sampleRate = Frequency (number of samples to play per second)
*
* Throws:
* LoadingException on failure
*/
this(const(short)[] samples, uint channelsCount, uint sampleRate)
{
if (samples is null || samples.length == 0)
throw new Exception("LoadingException : Samples array is invalid.");
super(sfSoundBuffer_CreateFromSamples(samples.ptr, samples.length, channelsCount, sampleRate));
}
override void dispose()
{
sfSoundBuffer_Destroy(m_ptr);
}
/**
* Save the sound buffer to a file
*
* Params:
* filename = Path of the sound file to write
*
* Returns:
* True if saving has been successful
*/
bool saveToFile(string filename)
{
if (filename !is null && filename.length > 0 )
{
return cast(bool)sfSoundBuffer_SaveToFile(m_ptr, toStringz(filename));
}
return false;
}
@property
{
/**
* Return the sound samples
*
* Returns:
* Array of sound samples, in 16 bits signed integer format
*/
short[] samples()
{
short* temp = null;
temp = sfSoundBuffer_GetSamples(m_ptr);
return temp is null ? null : temp[0..samplesCount()];
}
/**
* Return the samples count
*
* Returns:
* Number of samples
*/
size_t samplesCount()
{
return sfSoundBuffer_GetSamplesCount(m_ptr);
}
/**
* Get the sample rate
*
* Returns:
* Sound frequency (number of samples per second)
*/
uint sampleRate()
{
return sfSoundBuffer_GetSampleRate(m_ptr);
}
/**
* Return the number of channels (1 = mono, 2 = stereo, ...)
*
* Returns:
* Number of channels
*/
uint channelsCount()
{
return sfSoundBuffer_GetChannelsCount(m_ptr);
}
/**
* Get the sound duration
*
* Returns:
* Sound duration, in seconds
*/
float duration()
{
return sfSoundBuffer_GetDuration(m_ptr);
}
}
package:
this(SFMLClass ptr)
{
super(ptr, true);
}
private:
static extern(C)
{
SFMLClass function(cchar*) sfSoundBuffer_CreateFromFile;
SFMLClass function(const(byte)*, size_t) sfSoundBuffer_CreateFromMemory;
SFMLClass function(const(short)*, size_t, uint, uint) sfSoundBuffer_CreateFromSamples;
void function(SFMLClass) sfSoundBuffer_Destroy;
int function(SFMLClass, cchar*) sfSoundBuffer_SaveToFile;
short* function(SFMLClass) sfSoundBuffer_GetSamples;
size_t function(SFMLClass) sfSoundBuffer_GetSamplesCount;
uint function(SFMLClass) sfSoundBuffer_GetSampleRate;
uint function(SFMLClass) sfSoundBuffer_GetChannelsCount;
float function(SFMLClass) sfSoundBuffer_GetDuration;
}
mixin(loadFromSharedLib2("csfml-audio", "sfSoundBuffer",
"CreateFromFile", "CreateFromMemory", "CreateFromSamples", "Destroy", "SaveToFile", "GetSamples", "GetSamplesCount",
"GetSampleRate", "GetChannelsCount", "GetDuration"));
}

View file

@ -0,0 +1,109 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.audio.soundbufferrecorder;
import dsfml.system.common;
import dsfml.audio.soundbuffer;
import dsfml.audio.soundrecorder;
/**
* Specialized sfSoundRecorder which saves the captured
* audio data into a sound buffer
*/
class SoundBufferRecorder : SoundRecorder
{
/**
* Constructor
*/
this()
{
super(sfSoundBufferRecorder_Create());
}
override void dispose()
{
sfSoundBufferRecorder_Destroy(m_ptr);
}
/**
* Get the sound buffer containing the captured audio data
*
* Returns:
* SoundBuffer containing the captured audio data
*
*/
SoundBuffer getBuffer()
{
return new SoundBuffer(sfSoundBufferRecorder_GetBuffer(m_ptr));
}
protected:
override bool onStart()
{
return true;
}
override bool onProcessSamples(short[] s)
{
return true;
}
override void onStop()
{
}
private:
// External ====================================================================
extern (C)
{
typedef SFMLClass function() pf_sfSoundBufferRecorder_Create;
typedef void function(SFMLClass) pf_sfSoundBufferRecorder_Destroy;
typedef SFMLClass function(SFMLClass) pf_sfSoundBufferRecorder_GetBuffer;
static pf_sfSoundBufferRecorder_Create sfSoundBufferRecorder_Create;
static pf_sfSoundBufferRecorder_Destroy sfSoundBufferRecorder_Destroy;
static pf_sfSoundBufferRecorder_GetBuffer sfSoundBufferRecorder_GetBuffer;
}
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-audio-d");
else
DllLoader dll = DllLoader.load("csfml-audio");
sfSoundBufferRecorder_Create = cast(pf_sfSoundBufferRecorder_Create)dll.getSymbol("sfSoundBufferRecorder_Create");
sfSoundBufferRecorder_Destroy = cast(pf_sfSoundBufferRecorder_Destroy)dll.getSymbol("sfSoundBufferRecorder_Destroy");
sfSoundBufferRecorder_GetBuffer = cast(pf_sfSoundBufferRecorder_GetBuffer)dll.getSymbol("sfSoundBufferRecorder_GetBuffer");
}
}

View file

@ -0,0 +1,316 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.audio.soundrecorder;
import dsfml.audio.soundbuffer;
import dsfml.system.alloc;
import dsfml.system.common;
import dsfml.system.linkedlist;
import dsfml.system.lock;
import core.thread;
import core.sync.mutex;
/**
* SoundRecorder is an interface for capturing sound data.
*
* $(B onProcessSamples and onStop will be called by a different thread, take care of synchronization issues.)
*
* Examples:
* -------
* class MySoundRecorder : SoundRecorder
* {
* this()
* {
*
* }
*
* protected bool onStart()
* {
* return true;
* }
*
* protected void onStop()
* {
*
* }
*
* protected bool onProcessSamples(out short[])
* {
* // Process data here
*
* return true; //return true to continue capture, else return false
* }
* }
* -------
*/
abstract class SoundRecorder : DSFMLObject
{
override void dispose()
{
if (m_flag)
stop();
m_instances.remove(m_id);
sfSoundRecorder_Destroy(m_ptr);
}
/**
* Start the capture.
*
* Only one capture can happen at the same time
*
* Params:
* sampleRate : Sound frequency (the more samples, the higher the quality)
* (44100 by default = CD quality)
*/
void start(uint sampleRate = 44100)
{
sfSoundRecorder_Start(m_ptr, sampleRate);
m_t = new Thread(&threadPoll);
m_t.start();
}
/**
* Stop the capture
*/
void stop()
{
sfSoundRecorder_Stop(m_ptr);
m_flag = false;
m_t.join();
m_t = null;
}
/**
* Get the sample rate
*
* Returns:
* Frequency, in samples per second
*/
uint getSampleRate()
{
return sfSoundRecorder_GetSampleRate(m_ptr);
}
/**
* Tell if the system supports sound capture.
* If not, this class won't be usable
*
* Returns:
* True if audio capture is supported
*
*/
static bool isAvailable()
{
return cast(bool) sfSoundRecorder_IsAvailable();
}
protected:
/**
* Protected constructor
*/
this()
{
m_id = ++seed;
m_instances[m_id] = this;
super(sfSoundRecorder_Create(&internalOnStart, &internalCallback, &internalOnStop, &m_id));
init(true);
}
this(SFMLClass ptr)
{
super(ptr);
init(false);
}
/**
* Start recording audio data
*
* Returns:
* False to abort recording audio data, true to start
*/
abstract bool onStart();
/**
* Stop recording audio data
*/
abstract void onStop();
/**
* callback function
*
* Parameters:
* samples = Array of samples
*
* Returns:
* true to continue recording, false to stop.
*/
abstract bool onProcessSamples(short[] samples);
bool m_disposed;
private:
/*
* an init function to initialize id of the object.
*/
void init(bool flag)
{
if (flag)
{
m_list = new LinkedList!(Samples)();
m_flag = true;
m_continue = true;
m_mutex = new Mutex();
}
}
void* m_userData;
int m_id;
static int seed = 0;
static SoundRecorder[int] m_instances;
/*
* Extern C callback function
*
* This function must be static for C interop. To retrieve the current
* instance, we retrieve id of the sender in the user data, and search associated instance
* in the associative array.
*
* We don't call delegate or derived class on that thread because GC is not aware of this thread
* instead we enqueue data informations in a queue and poll this queue with a managed thread.
*/
extern(C) static int internalCallback(short* s, size_t size, void* user)
{
int id;
// retrieve instance
if ((id = *cast(int*)(user)) in m_instances)
{
SoundRecorder temp = m_instances[id];
scope Lock l = new Lock(temp.m_mutex);
if (temp.m_continue)
// this new is allowed because Samples is an custom alloc class.
temp.m_list.enqueue(new Samples(s, size));
return temp.m_continue;
}
return false;
}
extern(C) static int internalOnStart(void* user)
{
int id;
bool ret = false;
if ((id = *cast(int*)(user)) in m_instances)
{
SoundRecorder temp = m_instances[id];
ret = temp.onStart();
}
return ret;
}
extern(C) static void internalOnStop(void* user)
{
// Nothing to do
}
/*
* Managed thread loop
*/
void threadPoll()
{
while (m_flag)
{
Thread.sleep(50_000_0); // 50ms
// if samples are available
if (!m_list.empty)
{
// Lock ressources
scope Lock l = new Lock(m_mutex);
Samples s = m_list.dequeue;
m_continue = this.onProcessSamples(s.data[0..s.length].dup);
delete s;
if (!m_continue)
{
// delete all samples left
foreach(Samples dummy; m_list)
delete dummy;
break;
}
}
}
onStop();
}
Mutex m_mutex;
bool m_flag;
bool m_continue = true;
LinkedList!(Samples) m_list;
Thread m_t;
// External ====================================================================
static extern (C)
{
SFMLClass function(int function(void*), int function(const(short)*, size_t, void*), void function(void*), void*) sfSoundRecorder_Create;
void function(SFMLClass) sfSoundRecorder_Destroy;
void function(SFMLClass, uint SampleRate) sfSoundRecorder_Start;
void function(SFMLClass) sfSoundRecorder_Stop;
uint function(SFMLClass) sfSoundRecorder_GetSampleRate;
int function() sfSoundRecorder_IsAvailable;
}
mixin(loadFromSharedLib2("csfml-audio", "sfSoundRecorder", "Create", "Destroy", "Start",
"Stop", "GetSampleRate", "IsAvailable"));
}
// Use explicit alloc to allow instaciation by C thread
private class Samples
{
mixin Alloc;
this(short* data, size_t length)
{
this.data = data;
this.length = length;
}
public short* data;
public size_t length;
}

View file

@ -0,0 +1,311 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.audio.soundsource;
import dsfml.system.vector;
import dsfml.system.common;
/// the sound's current status
enum SoundStatus
{
Stopped, /// Sound is not playing
Paused, /// Sound is paused
Playing /// Sound is playing
}
/// base class
package class SoundSource(alias derivedClassName) : DSFMLObject
{
protected:
/**
* Default constructor
*
* This constructor is meant ot be called by derived classes only.
*
*/
this()
{
super(sfSoundSource_Create());
}
this(SFMLClass ptr)
{
super(ptr);
}
override void dispose()
{
sfSoundSource_Destroy(m_ptr);
}
public:
/**
* 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).
*
* Params:
* 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
*/
void setPosition(float x, float y, float z)
{
sfSoundSource_SetPosition(m_ptr, x, y, z);
}
@property
{
/**
* Get the current status of the sound (stopped, paused, playing)
*
* Returns:
* current status of the sound
*/
SoundStatus status()
{
return sfSoundSource_GetStatus(m_ptr);
}
/**
* 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.
*
* Params:
* pitch = New pitch to apply to the sound
*/
void pitch(float pitch)
{
sfSoundSource_SetPitch(m_ptr, pitch);
}
/**
* Get the pitch of the sound
*
* Returns:
* pitch of the sound
*/
float pitch()
{
return sfSoundSource_GetPitch(m_ptr);
}
/**
* 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.
*
* Params:
* volume = volume of the sound
*/
void volume(float volume)
in
{
assert(volume >= 0 && volume <= 100);
}
body
{
sfSoundSource_SetVolume(m_ptr, volume);
}
/**
* Get the volume of the sound
*
* Returns:
* Volume of the sound, in the range [0, 100]
*/
float volume()
{
return sfSoundSource_GetVolume(m_ptr);
}
/**
* 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).
*
* Params:
* position = Position of the sound in the scene
*/
void position(Vector3f position)
{
sfSoundSource_SetPosition(m_ptr, position.x, position.y, position.z);
}
/**
* Get the 3D position of the sound in the audio scene
*
* Returns:
* Position of the sound
*/
Vector3f position()
{
Vector3f ret;
sfSoundSource_GetPosition(m_ptr, &ret.x, &ret.y, &ret.z);
return ret;
}
/**
* 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 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).
*
* Params:
* relative = True to set the position relative, false to set it absolute
*/
void relativeToListener(bool relative)
{
sfSoundSource_SetRelativeToListener(m_ptr, relative);
}
/**
* 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
*/
bool relativeToListener()
{
return sfSoundSource_IsRelativeToListener(m_ptr);
}
/**
* 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.
*
* Params:
* distance = New minimum distance of the sound
*
* \see GetMinDistance, SetAttenuation
*
*/
void minDistance(float distance)
{
sfSoundSource_SetMinDistance(m_ptr, distance);
}
/**
* Get the minimum distance of the sound
*
* Returns:
* Minimum distance of the sound
*
* \see SetMinDistance, GetAttenuation
*
*/
float minDistance()
{
return sfSoundSource_GetMinDistance(m_ptr);
}
/**
* 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.
*
* Params:
* attenuation = New attenuation factor of the sound
*
* \see GetAttenuation, SetMinDistance
*
*/
void attenuation(float attenuation)
{
sfSoundSource_SetAttenuation(m_ptr, attenuation);
}
/**
* Get the attenuation factor of the sound
*
* Returns:
* Attenuation factor of the sound
*
* \see SetAttenuation, GetMinDistance
*
*/
float attenuation()
{
return sfSoundSource_GetAttenuation(m_ptr);
}
} // of @property
private:
static extern(C)
{
SFMLClass function() sfSoundSource_Create;
void function(SFMLClass) sfSoundSource_Destroy;
SoundStatus function(SFMLClass) sfSoundSource_GetStatus;
void function(SFMLClass, float) sfSoundSource_SetPitch;
void function(SFMLClass, float) sfSoundSource_SetVolume;
void function(SFMLClass, float, float, float) sfSoundSource_SetPosition;
float function(SFMLClass) sfSoundSource_GetPitch;
float function(SFMLClass) sfSoundSource_GetVolume;
void function(SFMLClass, float*, float*, float*) sfSoundSource_GetPosition;
float function(SFMLClass) sfSoundSource_GetMinDistance;
float function(SFMLClass) sfSoundSource_GetAttenuation;
void function(SFMLClass, float) sfSoundSource_SetMinDistance;
void function(SFMLClass, float) sfSoundSource_SetAttenuation;
void function(SFMLClass, bool) sfSoundSource_SetRelativeToListener;
bool function(SFMLClass) sfSoundSource_IsRelativeToListener;
}
mixin(loadDerivedFromSharedLib("csfml-audio", "sfSoundSource", derivedClassName,
"Create", "Destroy", "GetStatus", "GetPitch", "SetPitch", "GetVolume", "SetVolume", "GetPosition", "SetPosition",
"GetMinDistance", "SetMinDistance", "GetAttenuation", "SetAttenuation", "SetRelativeToListener", "IsRelativeToListener"));
}

View file

@ -0,0 +1,384 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.audio.soundstream;
import dsfml.system.alloc;
import dsfml.system.common;
import dsfml.system.vector;
import dsfml.system.linkedlist;
import dsfml.system.lock;
import core.thread;
import core.sync.mutex;
import dsfml.audio.sound;
import dsfml.audio.soundsource;
/**
* SoundStream is a streamed sound, ie samples are acquired
* while the sound is playing. Use it for big sounds that would
* require hundreds of MB in memory, or for streaming sound from the network.
*
* SoundStream is a base class and cannot be instanciated directly.
*
* $(B onGetData override will be called by a different thread, take care of synchronization issues.) onStart is called by the thread which called .play().
*
* ------------------------
* class MySoundStream : SoundStream
* {
* this()
* {
* super(2, 44100); // you need to initialize the base class before any operation.
* }
* protected bool onGetData(out short[] data)
* {
* //You need to fill data array with some samples
*
* return true; //or false if you want to stop playback
* }
*
* protected bool onStart()
* {
* return true;
* }
* }
* ------------------------
*/
abstract class SoundStream : SoundSource!("sfSoundStream")
{
override void dispose()
{
stop();
sfSoundStream_Destroy(m_ptr);
s_instances.remove(m_id);
}
/**
* Start playing the stream
*/
void play()
{
m_flag = true;
sfSoundStream_Play(m_ptr);
if (status != SoundStatus.Paused)
{
m_t = new Thread(&threadPoll);
m_t.start();
}
}
/**
* Pause the stream
*/
void pause()
{
sfSoundStream_Pause(m_ptr);
}
/**
* Stop the stream
*/
void stop()
{
m_flag = false;
sfSoundStream_Stop(m_ptr);
m_t.join();
if (m_dummy !is null)
delete m_dummy;
}
@property
{
/**
* Get number of channels of the stream
*
* Returns:
* number of channels
*/
uint channelsCount()
{
return m_channelsCount;
}
/**
* Get the sample rate of the stream
*
* Returns:
* sample rate
*/
uint sampleRate()
{
return m_sampleRate;
}
/**
* Get the current playing offset of the stream
*
* Returns:
* current playing offset, in seconds.
*/
float playingOffset()
{
return sfSoundStream_GetPlayingOffset(m_ptr);
}
/**
* Set the current playing position of a music
*
* Params:
* timeOffset = New playing position, expressed in seconds
*/
void playingOffset(float timeOffset)
{
sfSoundStream_SetPlayingOffset(m_ptr, timeOffset);
}
/**
* Tell whether or not the stream is looping
*
* Returns:
* True if the music is looping, false otherwise
*/
bool loop()
{
if (m_ptr !is null)
return cast(bool)sfSoundStream_GetLoop(m_ptr);
return false;
}
/**
* Set the stream loop state.
*
* Disabled by default.
*
* Params:
* loop = true to play in loop, false to play once
*/
void loop(bool loop)
{
if (m_ptr !is null)
sfSoundStream_SetLoop(m_ptr, loop);
}
} // of @property
protected:
/**
* Protected constructor
*
* Params:
* channelsCount = number of channel
* sampleRate = sample rate of the stream
*
*/
this(uint channelsCount, uint sampleRate)
{
m_channelsCount = channelsCount;
m_sampleRate = sampleRate;
super(sfSoundStream_Create(&externalOnGetData, &externalOnSeek, channelsCount, sampleRate, &m_id));
m_mutex = new Mutex();
m_samples = new LinkedList!(Data);
m_t = new Thread(&this.threadPoll);
m_id = ++s_seed;
s_instances[m_id] = this;
}
/**
* Called each time the stream is seeked
*/
abstract void onSeek(float timeOffset);
/**
* Called each time the stream needs new data.
* This method will be call by an other thread, take care of possible synchronisation issues.
*
* Params:
* data = array of samples to stream
*
* Returns:
* true to continue streaming, false to stop
*/
abstract bool onGetData(out short[] data);
private:
// Called sync when user calling play()
// TODO: check if it's correct that way
extern(C) static void externalOnSeek(float t, void* user)
{
int id;
if ((id = *cast(int*) user) in s_instances)
{
SoundStream temp = s_instances[id];
return (temp.onSeek(t));
}
}
// C Thread callback (no allocation can be done)
extern (C) static int externalOnGetData(sfSoundStreamChunk* data, void* user)
{
int id, flag = false;
// Get calling soundStream
if ((id = *cast(int*) user) in s_instances)
{
SoundStream temp = s_instances[id];
//if no samples are available but streaming is not stopped, we sleep the thread
while (temp.m_samples.empty && temp.m_flag)
Thread.sleep(10_000_0); // 10ms
scope Lock l = new Lock(temp.m_mutex);
if (!temp.m_samples.empty)
{
if (temp.m_dummy !is null)
delete temp.m_dummy;
temp.m_dummy = temp.m_samples.dequeue;
if ((flag = temp.m_dummy.Flag) == true)
{
data.Samples = temp.m_dummy.Samples.ptr;
data.NbSamples = temp.m_dummy.Samples.length;
}
else
{
data.Samples = null;
data.NbSamples = 0;
}
}
}
return flag;
}
// Managed thread loop
void threadPoll()
{
short[] data;
bool ret = true;
// while streaming is active ...
while (ret && m_flag)
{
{
scope Lock l = new Lock(m_mutex);
// see how many samples are available (keep always 2 samples ready)
if (m_samples.getCount < 2)
{
// if we need new samples, lock and call derived class
ret = onGetData(data);
m_samples.enqueue(new Data(data, ret));
}
}
Thread.sleep(100_000_0); // 100ms
}
}
private class Data
{
short[] Samples;
bool Flag;
mixin Alloc;
this (short[] samples, bool flag)
{
this.Samples = samples;
this.Flag = flag;
}
}
Thread m_t;
Mutex m_mutex;
LinkedList!(Data) m_samples;
Data m_dummy;
bool m_flag;
uint m_channelsCount;
uint m_sampleRate;
int m_id;
static SoundStream[int] s_instances;
static int s_seed = 0;
// External ====================================================================
extern (C)
{
struct sfSoundStreamChunk{ short* Samples; uint NbSamples; }
alias void function(float, void*) sfSoundStreamSeekCallback;
alias int function (sfSoundStreamChunk*, void*) sfSoundStreamGetDataCallback;
alias SFMLClass function(sfSoundStreamGetDataCallback, sfSoundStreamSeekCallback, uint, uint, void*) pf_sfSoundStream_Create;
alias void function(SFMLClass) pf_sfSoundStream_Destroy;
alias void function(SFMLClass) pf_sfSoundStream_Play;
alias void function(SFMLClass) pf_sfSoundStream_Pause;
alias void function(SFMLClass) pf_sfSoundStream_Stop;
alias uint function(SFMLClass) pf_sfSoundStream_GetChannelsCount;
alias uint function(SFMLClass) pf_sfSoundStream_GetSampleRate;
alias float function(SFMLClass) pf_sfSoundStream_GetPlayingOffset;
alias void function(SFMLClass, float) pf_sfSoundStream_SetPlayingOffset;
alias int function(SFMLClass) pf_sfSoundStream_GetLoop;
alias void function(SFMLClass, int) pf_sfSoundStream_SetLoop;
static pf_sfSoundStream_Create sfSoundStream_Create;
static pf_sfSoundStream_Destroy sfSoundStream_Destroy;
static pf_sfSoundStream_Play sfSoundStream_Play;
static pf_sfSoundStream_Pause sfSoundStream_Pause;
static pf_sfSoundStream_Stop sfSoundStream_Stop;
static pf_sfSoundStream_GetChannelsCount sfSoundStream_GetChannelsCount;
static pf_sfSoundStream_GetSampleRate sfSoundStream_GetSampleRate;
static pf_sfSoundStream_GetPlayingOffset sfSoundStream_GetPlayingOffset;
static pf_sfSoundStream_SetPlayingOffset sfSoundStream_SetPlayingOffset;
static pf_sfSoundStream_GetLoop sfSoundStream_GetLoop;
static pf_sfSoundStream_SetLoop sfSoundStream_SetLoop;
}
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-audio-d");
else
DllLoader dll = DllLoader.load("csfml-audio");
sfSoundStream_Create = cast(pf_sfSoundStream_Create)dll.getSymbol("sfSoundStream_Create");
sfSoundStream_Destroy = cast(pf_sfSoundStream_Destroy)dll.getSymbol("sfSoundStream_Destroy");
sfSoundStream_Play = cast(pf_sfSoundStream_Play)dll.getSymbol("sfSoundStream_Play");
sfSoundStream_Pause = cast(pf_sfSoundStream_Pause)dll.getSymbol("sfSoundStream_Pause");
sfSoundStream_Stop = cast(pf_sfSoundStream_Stop)dll.getSymbol("sfSoundStream_Stop");
sfSoundStream_GetChannelsCount = cast(pf_sfSoundStream_GetChannelsCount)dll.getSymbol("sfSoundStream_GetChannelsCount");
sfSoundStream_GetSampleRate = cast(pf_sfSoundStream_GetSampleRate)dll.getSymbol("sfSoundStream_GetSampleRate");
sfSoundStream_GetPlayingOffset = cast(pf_sfSoundStream_GetPlayingOffset)dll.getSymbol("sfSoundStream_GetPlayingOffset");
sfSoundStream_SetPlayingOffset = cast(pf_sfSoundStream_SetPlayingOffset)dll.getSymbol("sfSoundStream_SetPlayingOffset");
sfSoundStream_GetLoop = cast(pf_sfSoundStream_GetLoop)dll.getSymbol("sfSoundStream_GetLoop");
sfSoundStream_SetLoop = cast(pf_sfSoundStream_SetLoop)dll.getSymbol("sfSoundStream_SetLoop");
}
}

View file

@ -0,0 +1,41 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.all;
public import
dsfml.graphics.blendmode,
dsfml.graphics.color,
dsfml.graphics.font,
dsfml.graphics.idrawable,
dsfml.graphics.image,
dsfml.graphics.shader,
dsfml.graphics.rect,
dsfml.graphics.renderwindow,
dsfml.graphics.shape,
dsfml.graphics.sprite,
dsfml.graphics.text,
dsfml.graphics.view;

View file

@ -0,0 +1,38 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.blendmode;
/**
* Enumerate the blending modes for drawable objects.
*/
enum BlendMode
{
ALPHA, /// Pixel = Src * a + Dest * (1 - a)
ADD, /// Pixel = Src + Dest
MULTIPLY, /// Pixel = Src * Dest
NONE /// No blending
}

View file

@ -0,0 +1,123 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.color;
import std.string;
alias RGBA Color; // standard Color is RGBA
/**
* Color is an utility structure for manipulating colors
*/
struct RGBA
{
align(1):
ubyte r; /// Red component
ubyte g; /// Green component
ubyte b; /// Blue component
ubyte a = 255; /// Alpha (transparency) component, 255 = opaque
/**
* Operator == and != overload to compare two colors
*/
const bool opEquals(ref const(Color) color2)
{
return
(r == color2.r)
&& (g == color2.g)
&& (b == color2.b)
&& (a == color2.a);
}
/**
* Operator + overload to add two colors
*/
Color opAdd(Color color2)
{
ubyte r = this.r + color2.r > 255 ? 255 : cast(ubyte) (this.r + color2.r);
ubyte g = this.g + color2.g > 255 ? 255 : cast(ubyte) (this.g + color2.g);
ubyte b = this.b + color2.b > 255 ? 255 : cast(ubyte) (this.b + color2.b);
ubyte a = this.a + color2.a > 255 ? 255 : cast(ubyte) (this.a + color2.a);
return Color(r, g, b, a);
}
/**
* Operator += overload
*/
Color opAddAssign(Color color2)
{
this.r = this.r + color2.r > 255 ? 255 : cast(ubyte) (this.r + color2.r);
this.g = this.g + color2.g > 255 ? 255 : cast(ubyte) (this.g + color2.g);
this.b = this.b + color2.b > 255 ? 255 : cast(ubyte) (this.b + color2.b);
this.a = this.a + color2.a > 255 ? 255 : cast(ubyte) (this.a + color2.a);
return this;
}
/**
* Operator * overload to modulate colors
*/
Color opMul(Color color2)
{
ubyte r = cast(ubyte) (this.r * color2.r / 255);
ubyte g = cast(ubyte) (this.g * color2.g / 255);
ubyte b = cast(ubyte) (this.b * color2.b / 255);
ubyte a = cast(ubyte) (this.a * color2.a / 255);
return Color(r, g, b, a);
}
/**
* Operator *= overload
*/
Color opMulAssign(Color color2)
{
this.r = cast(ubyte) (this.r * color2.r / 255);
this.g = cast(ubyte) (this.g * color2.g / 255);
this.b = cast(ubyte) (this.b * color2.b / 255);
this.a = cast(ubyte) (this.a * color2.a / 255);
return this;
}
string toString()
{
return std.string.format("(%d,%d,%d,%d)", r,g,b,a);
}
static immutable
{
Color BLACK = Color(0, 0, 0); /// Black predefined color
Color WHITE = Color(255, 255, 255); /// White predefined color
Color RED = Color(255, 0, 0); /// Red predefined color
Color GREEN = Color(0, 255, 0); /// Green predefined color
Color BLUE = Color(0, 0, 255); /// Blue predefined color
Color YELLOW = Color(255, 0, 255); /// Yellow predefined color
Color MAGENTA = Color(255, 0, 255); /// Magenta predefined color
Color CYAN = Color(0, 255, 255); /// Cyan predefined color
}
}

View file

@ -0,0 +1,268 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.drawableimpl;
public import dsfml.system.common;
import dsfml.system.vector;
import dsfml.graphics.irendertarget;
import dsfml.graphics.idrawable,
dsfml.graphics.color,
dsfml.graphics.blendmode,
dsfml.graphics.renderwindow,
dsfml.graphics.renderimage,
dsfml.graphics.shader;
/*
* Package base class of all drawable.
* Provide implementation of IDrawable and functions aliases.
*/
package class DrawableImpl(string derivedClassName) : DSFMLObject, IDrawable
{
protected:
this()
{
super(sfDrawable_Create());
}
this(SFMLClass ptr)
{
super(ptr, true);
}
override void dispose()
{
sfDrawable_Destroy(m_ptr);
}
public:
override void rotate(float angle)
{
sfDrawable_Rotate(m_ptr, angle);
}
override void move(float offsetX, float offsetY)
{
sfDrawable_Move(m_ptr, offsetX, offsetY);
}
override void move(Vector2f offset)
{
sfDrawable_Move(m_ptr, offset.x, offset.y);
}
override Vector2f transformToLocal(Vector2f point) const
{
Vector2f ret;
sfDrawable_TransformToLocal(m_ptr, point.x, point.y, &ret.x, &ret.y);
return ret;
}
override Vector2f transformToGlobal(Vector2f point) const
{
Vector2f ret;
sfDrawable_TransformToLocal(m_ptr, point.x, point.y, &ret.x, &ret.y);
return ret;
}
override void render(IRenderTarget window)
{
sfRenderWindow_DrawThis((cast(DSFMLObject)window).nativePointer, m_ptr);
}
override void renderWithShader(IRenderTarget window, Shader shader)
{
sfRenderWindow_DrawThisWithShader((cast(DSFMLObject)window).nativePointer, m_ptr, shader.nativePointer);
}
override void setPosition(float x, float y)
{
sfDrawable_SetPosition(m_ptr, x, y);
}
override void setScale(float scaleX, float scaleY)
{
sfDrawable_SetScale(m_ptr, scaleX, scaleY);
}
override void setOrigin(float originX, float originY)
{
sfDrawable_SetOrigin(m_ptr, originX, originY);
}
@property
{
override void x(float x)
{
sfDrawable_SetX(m_ptr, x);
}
override void y(float y)
{
sfDrawable_SetY(m_ptr, y);
}
override void position(Vector2f vec)
{
sfDrawable_SetPosition(m_ptr, vec.x, vec.y);
}
override void scaleX(float scale)
{
if (scale > 0)
sfDrawable_SetScaleX(m_ptr, scale);
}
override void scaleY(float scale)
{
if (scale > 0)
sfDrawable_SetScaleY(m_ptr, scale);
}
override void scale(Vector2f scale)
{
if (scale.x > 0 && scale.y > 0)
sfDrawable_SetScale(m_ptr, scale.x, scale.y);
}
override void origin(Vector2f origin)
{
sfDrawable_SetOrigin(m_ptr, origin.x, origin.y);
}
override void rotation(float angle)
{
sfDrawable_SetRotation(m_ptr, angle);
}
override void color(Color c)
{
sfDrawable_SetColor(m_ptr, c);
}
override void blendMode(BlendMode mode)
{
sfDrawable_SetBlendMode(m_ptr, mode);
}
override Vector2f position() const
{
return Vector2f(sfDrawable_GetX(m_ptr), sfDrawable_GetY(m_ptr));
}
override Vector2f scale() const
{
return Vector2f(sfDrawable_GetScaleX(m_ptr), sfDrawable_GetScaleY(m_ptr));
}
override Vector2f origin() const
{
return Vector2f(sfDrawable_GetOriginX(m_ptr), sfDrawable_GetOriginY(m_ptr));
}
override float rotation() const
{
return sfDrawable_GetRotation(m_ptr);
}
override Color color() const
{
return sfDrawable_GetColor(m_ptr);
}
override BlendMode blendMode() const
{
return cast(BlendMode)(sfDrawable_GetBlendMode(m_ptr));
}
override void scale(Vector2f scale)
{
sfDrawable_SetScale(m_ptr, scale.x, scale.y);
}
}
private:
static extern(C)
{
SFMLClass function() sfDrawable_Create;
void function(SFMLClass) sfDrawable_Destroy;
void function(SFMLClass, float) sfDrawable_SetX;
void function(SFMLClass, float) sfDrawable_SetY;
void function(SFMLClass, float, float) sfDrawable_SetPosition;
void function(SFMLClass, float) sfDrawable_SetScaleX;
void function(SFMLClass, float) sfDrawable_SetScaleY;
void function(SFMLClass, float, float) sfDrawable_SetScale;
void function(SFMLClass, float) sfDrawable_SetRotation;
void function(SFMLClass, float, float) sfDrawable_SetOrigin;
void function(SFMLClass, Color) sfDrawable_SetColor;
void function(SFMLClass, BlendMode) sfDrawable_SetBlendMode;
float function(SFMLClass) sfDrawable_GetX;
float function(SFMLClass) sfDrawable_GetY;
float function(SFMLClass) sfDrawable_GetScaleX;
float function(SFMLClass) sfDrawable_GetScaleY;
float function(SFMLClass) sfDrawable_GetRotation;
float function(SFMLClass) sfDrawable_GetOriginX;
float function(SFMLClass) sfDrawable_GetOriginY;
Color function(SFMLClass) sfDrawable_GetColor;
BlendMode function(SFMLClass) sfDrawable_GetBlendMode;
void function(SFMLClass, float, float) sfDrawable_Move;
void function(SFMLClass, float, float) sfDrawable_Scale;
void function(SFMLClass, float) sfDrawable_Rotate;
void function(SFMLClass, float, float, float*, float*) sfDrawable_TransformToLocal;
void function(SFMLClass, float, float, float*, float*) sfDrawable_TransformToGlobal;
typedef void function(SFMLClass, SFMLClass) pf_sfRenderWindow_DrawThis;
typedef void function(SFMLClass, SFMLClass, SFMLClass) pf_sfRenderWindow_DrawThisWithShader;
typedef void function(SFMLClass, SFMLClass) pf_sfRenderImage_DrawThis;
typedef void function(SFMLClass, SFMLClass, SFMLClass) pf_sfRenderImage_DrawThisWithShader;
pf_sfRenderWindow_DrawThis sfRenderWindow_DrawThis;
pf_sfRenderWindow_DrawThisWithShader sfRenderWindow_DrawThisWithShader;
pf_sfRenderImage_DrawThis sfRenderImage_DrawThis;
pf_sfRenderImage_DrawThisWithShader sfRenderImage_DrawThisWithShader;
}
mixin(loadDerivedFromSharedLib("csfml-graphics", "sfDrawable", derivedClassName,
"Create", "Destroy", "SetX", "SetY", "SetPosition", "SetScaleX", "SetScaleY", "SetScale", "SetRotation", "SetOrigin", "SetColor", "SetBlendMode",
"GetX", "GetY", "GetScaleX", "GetScaleY", "GetRotation", "GetOriginX", "GetOriginY", "GetColor", "GetBlendMode", "Move",
"Scale", "Rotate", "TransformToLocal", "TransformToGlobal"));
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-graphics-d");
else
DllLoader dll = DllLoader.load("csfml-graphics");
sfRenderWindow_DrawThis = cast(pf_sfRenderWindow_DrawThis)dll.getSymbol("sfRenderWindow_Draw" ~ derivedClassName[2..$]);
sfRenderWindow_DrawThisWithShader = cast(pf_sfRenderWindow_DrawThisWithShader)dll.getSymbol("sfRenderWindow_Draw" ~ derivedClassName[2..$] ~ "WithShader");
sfRenderImage_DrawThis = cast(pf_sfRenderImage_DrawThis)dll.getSymbol("sfRenderImage_Draw" ~ derivedClassName[2..$]);
sfRenderImage_DrawThisWithShader = cast(pf_sfRenderImage_DrawThisWithShader)dll.getSymbol("sfRenderImage_Draw" ~ derivedClassName[2..$] ~ "WithShader");
}
}

View file

@ -0,0 +1,193 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.font;
import dsfml.system.common,
dsfml.system.exception,
dsfml.system.stringutil;
import dsfml.graphics.rect,
dsfml.graphics.image;
/// Glyph describes a glyph (a visual character)
struct Glyph
{
int Advance; /// Offset to move horizontically to the next character
IntRect Bounds; /// Bounding rectangle of the glyph, in coordinates relative to the baseline
IntRect SubRect; /// Texture coordinates of the glyph inside the font's image
}
/**
* Font is the low-level class for loading and
* manipulating character fonts.
*/
class Font : DSFMLObject
{
private:
static Font s_default;
public:
/**
* Get SFML default built-in font (Arial)
*/
static Font getDefaultFont()
{
if (s_default is null)
s_default = new Font(sfFont_GetDefaultFont());
return s_default;
}
/**
* construct the Font from a file
*
* Params:
* filename = font file to load
*/
this(string filename)
{
if (filename is null || filename.length == 0)
throw new LoadingException("LoadingException : Filename is invalid.");
super(sfFont_CreateFromFile(toStringz(filename)));
}
/**
* construct the Font from a file in memory
*
* Params:
* data = data to load
*/
this(ubyte[] data)
{
if (data is null || data.length == 0)
throw new Exception("LoadingException : Memory stream is invalid.");
super(sfFont_CreateFromMemory(data.ptr, data.length));
}
override void dispose()
{
sfFont_Destroy(m_ptr);
}
/**
* get a glyph in a font
*
* Params:
* codePoint = Unicode code point of the character to get
* charSize = Reference character size
* bold = Retrieve the bold version or the regular one?
* Returns:
* The glyph corresponding to codePoint and charSize
*/
Glyph getGlyph(uint codePoint, uint charSize, bool bold)
{
return sfFont_GetGlyph(m_ptr, codePoint, charSize, bold);
}
/**
* Get the kerning offset of two glyphs
*
* Params:
* first = Unicode code point of the first character
* second = Unicode code point of the second character
* charSize = Reference character size
*
* Returns:
* Kerning value for first and second, in pixels
*/
int getKerning(uint first, uint second, uint charSize)
{
return sfFont_GetKerning(m_ptr, first, second, charSize);
}
/**
* Get the vertical offset to apply between two consecutive lines of text.
*
* Params:
* charSize = Reference character size
*
* Returns:
* Line spacing, in pixels
*/
int getLineSpacing(uint charSize)
{
return sfFont_GetLineSpacing(m_ptr, charSize);
}
Image getImage(uint charSize)
{
return new Image(sfFont_GetImage(m_ptr, charSize));
}
package:
this(SFMLClass ptr)
{
super(ptr, true);
}
private:
static extern(C)
{
// sfFont
SFMLClass function() sfFont_Create;
SFMLClass function(cchar*) sfFont_CreateFromFile;
SFMLClass function(ubyte*, size_t) sfFont_CreateFromMemory;
void function(SFMLClass) sfFont_Destroy;
SFMLClass function() sfFont_GetDefaultFont;
// DSFML2
Glyph function(SFMLClass, uint, uint, bool) sfFont_GetGlyph;
int function(SFMLClass, uint, uint, uint) sfFont_GetKerning;
int function(SFMLClass, uint) sfFont_GetLineSpacing;
SFMLClass function(SFMLClass, uint) sfFont_GetImage;
}
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-graphics-d");
else
DllLoader dll = DllLoader.load("csfml-graphics");
// sfFont
mixin(loadFromSharedLib("sfFont_CreateFromFile"));
mixin(loadFromSharedLib("sfFont_CreateFromMemory"));
mixin(loadFromSharedLib("sfFont_Destroy"));
mixin(loadFromSharedLib("sfFont_GetDefaultFont"));
// DSFML2
mixin(loadFromSharedLib("sfFont_GetGlyph"));
mixin(loadFromSharedLib("sfFont_GetKerning"));
mixin(loadFromSharedLib("sfFont_GetLineSpacing"));
mixin(loadFromSharedLib("sfFont_GetImage"));
}
}

View file

@ -0,0 +1,285 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.idrawable;
import dsfml.system.vector;
import dsfml.graphics.irendertarget;
import dsfml.graphics.color,
dsfml.graphics.blendmode,
dsfml.graphics.renderwindow,
dsfml.graphics.renderimage,
dsfml.graphics.shader;
/**
* Interface for drawable object
*
* Shape, Text and Sprite implement IDrawable
*/
interface IDrawable
{
/**
* Set the position of the object
*
* Params:
* x = New left coordinate
* y = New top coordinate
*/
void setPosition(float x, float y);
/**
* Set the scale of the object
*
* Params:
* scaleX = New horizontal scale > 0
* scaleY = New vertical scale > 0
*/
void setScale(float scalex, float scaley);
// in {assert(scalex > 0 && scalex > 0);} // TODO: add in again when interface contracts work
/**
* Set the origin of the object, in coordinates relative to the
* top-left of the object (take 2 values).
* The default origin is (0, 0)
*
* Params:
* originX : X coordinate of the origin
* originY : Y coordinate of the origin
*/
void setOrigin(float originX, float originY);
@property
{
/**
* Set the left position of the object
*
* Params:
* x = New left coordinate
*/
void x(float x);
/**
* Set the top position of the object
*
* Params:
* y = New top coordinate
*/
void y(float y);
/**
* Set the position of the object
*
* Params:
* vec = new position
*/
void position(Vector2f vec);
/**
* Set the horizontal scale of the object
*
* Params:
* scale = New horizontal scale (Strictly positive)
*/
void scaleX(float scale);
/**
* Set the vertical scale of the object
*
* Params:
* scale = New vertical scale (Strictly positive)
*/
void scaleY(float scale);
/**
* Set the scale of the object
*
* Params:
* scale = new scale
*/
void scale(Vector2f scale);
// in {assert(scale.x > 0 && scale.y > 0);} // TODO
/**
* Set the origin of the object, in coordinates relative to the
* top-left of the object (take a 2D vector).
* The default origin is (0, 0)
*
* Params:
* origin : New origin
*/
void origin(Vector2f origin);
/**
* Set the rotation of the object
*
* Params:
* angle = Angle of rotation, in degree
*/
void rotation(float angle);
/**
* Set the color
*
* Params:
* c = New color
*/
void color(Color c);
/**
* Set the blending mode for the object.
* The default blend mode is Blend.Alpha
*
* Params:
* mode = New blending mode
*/
void blendMode(BlendMode mode);
const
{
/**
* Get the position of the object
*
* Returns:
* Current position
*
*/
Vector2f position();
/**
* Get the current scale of the object
*
* Returns:
* Current scale
*/
Vector2f scale();
/**
* Get the origin of the object
*
* Returns:
* Current position of the origin
*
*/
Vector2f origin();
/**
* Get the rotation angle of the object
*
* Returns:
* Angle of rotation, in degree
*/
float rotation();
/**
* Get the color of the string
*
* Returns:
* Current color
*/
Color color();
/**
* Get the current blending mode
*
* Returns:
* Current blending mode
*/
BlendMode blendMode();
} // const
} // @property
/**
* Rotate the object
* Angle is added to the current orientation of the objet
*
* Params:
* angle = Angle of rotation in degree
*/
void rotate(float angle);
/**
* Move the object
* New offset is added to object current position
*
* Params:
* offsetX = Offset on the X axis
* offsetY = Offset on the Y axis
*/
void move(float offsetX, float offsetY);
/**
* Move the object
* New offset is added to object current position
*
* Params:
* offset = Amount of units to move the object of
*/
void move(Vector2f offset);
/**
* Transform a point from global coordinates into local coordinates
* (ie it applies the inverse of object's origin, translation, rotation and scale to the point)
*
* Params:
* point = Point to transform
*
* Returns:
* Transformed point
*/
Vector2f transformToLocal(Vector2f point) const;
/**
* Transform a point from local coordinates into global coordinates
* (ie it applies the inverse of object's origin, translation, rotation and scale to the point)
*
* Params:
* point = Point to transform
*
* Returns:
* Transformed point
*/
Vector2f transformToGlobal(Vector2f point) const;
/**
* Render the specific geometry of the object
*
* Params:
* window = Target into which render the object
*/
void render(IRenderTarget window);
/**
* Render the specific geometry of the object with a shader
*
* Params:
* window = Render target
* shader = Shader to use
*/
void renderWithShader(IRenderTarget window, Shader shader);
}

View file

@ -0,0 +1,352 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.image;
import dsfml.graphics.color,
dsfml.graphics.rect;
// dsfml.graphics.renderwindow;
import dsfml.system.common,
dsfml.system.exception,
dsfml.system.stringutil;
/**
* Image is the low-level class for loading and
* manipulating images
*/
class Image : DSFMLObject
{
package:
this(SFMLClass ptr)
{
super(ptr, true);
}
public:
/**
* Default constructor
*/
this()
{
super(sfImage_Create());
}
/**
* Construct an empty image
*
* Params:
* width = Image width
* height = Image height
* col = Image color (black by default)
*/
this(uint width, uint height, Color col = Color.BLACK)
{
super(sfImage_CreateFromColor(width, height, col));
}
/**
* Construct the image from a file
*
* Params:
* filename = Path of the image file to load
*
* Throws:
* LoadingException if filename is empty or null.
*/
this(string filename)
{
if (filename is null || filename.length == 0)
throw new LoadingException("LoadingException : Filename is invalid.");
super(sfImage_CreateFromFile(toStringz(filename)));
}
/**
* Construct the image from a file in memory
*
* Params:
* data = array of data in memory
* Throws:
* LoadingException if data is empty or null.
*/
this(ubyte[] data)
{
if (data is null || data.length == 0)
throw new LoadingException("Memory stream is invalid.");
super(sfImage_CreateFromMemory(data.ptr, data.length));
}
/**
* Construct the image directly from an array of pixels
*
* Params:
* width = Image width
* height = Image height
* data = array of pixels in memory (assumed format is RGBA)
*
* Throws:
* LoadingException if data length doesn't match Width * Height * 4
*/
this(uint width, uint height, ubyte[] data)
{
if (width * height * 4 != data.length)
throw new LoadingException("Pixels array length doesn't match the specified size.");
super(sfImage_CreateFromPixels(width, height, data.ptr));
}
override void dispose()
{
sfImage_Destroy(m_ptr);
}
/**
* Save the content of the image to a file
*
* Params:
* filename = Path of the file to save (overwritten if already exist)
*
* Returns:
* True if saving was successful
*/
bool saveToFile(string filename)
{
return cast(bool)sfImage_SaveToFile(m_ptr, toStringz(filename));
}
/**
* Create an empty image
*
* Params:
* width = Image width
* height = Image height
* col = Image color (black by default)
*
* Returns:
* True if creation was successful
*/
bool create(uint width, uint height, Color col = Color.BLACK)
{
m_ptr = sfImage_CreateFromColor(width, height, col);
return (m_ptr !is null);
}
/**
* Create transparency mask from a specified colorkey
*
* Params:
* colorKey = Color to become transparent
* alpha = Alpha value to use for transparent pixels (0 by default)
*/
void createMaskFromColor(Color colorKey, ubyte alpha = 0)
{
sfImage_CreateMaskFromColor(m_ptr, colorKey, alpha);
}
/+
/**
* Create the image from the current contents of the
* given window
*
* Params:
* window = Window to capture
* sourceRect = Sub-rectangle of the screen to copy (empty by default - entire image)
*
* Returns:
* True if copy was successful
*/
bool copyScreen(RenderWindow window, IntRect sourceRect = IntRect())
{
return cast(bool)sfImage_CopyScreen(m_ptr, window.nativePointer, sourceRect);
}
+/
/**
* Copy pixels from another image onto this one.
* This function does a slow pixel copy and should only
* be used at initialization time
*
* Params:
* 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
*/
void copyImage(Image source, uint destX, uint destY, IntRect sourceRect = IntRect())
{
sfImage_CopyImage(m_ptr, source.nativePointer, destX, destY, sourceRect);
}
/**
* Change the color of a pixel
* Don't forget to call Update when you end modifying pixels
*
* Params:
* x = X coordinate of pixel in the image
* y = Y coordinate of pixel in the image
* col = New color for pixel (X, Y)
*/
void setPixel(uint x, uint y, Color col)
{
sfImage_SetPixel(m_ptr, x, y, col);
}
/**
* Get a pixel from the image
*
* Params:
* x = X coordinate of pixel in the image
* y = Y coordinate of pixel in the image
*
* Returns:
* Color of pixel (x, y)
*/
Color getPixel(uint x, uint y)
{
return sfImage_GetPixel(m_ptr, x, y);
}
/**
* Get an array of pixels (8 bits integers RGBA)
* Array size is GetWidth() x GetHeight() x 4
* This array becomes invalid if you reload or resize the image
*
* Returns:
* array of pixels
*/
ubyte[] getPixelsArray()
{
return sfImage_GetPixelsPtr(m_ptr)[0..width() * height() * 4];
}
/**
* Bind the image for rendering
*/
void bind()
{
sfImage_Bind(m_ptr);
}
/**
* Update a sub-rectangle of the image from an array of pixels
*
* Warning: for performances reasons, this function doesn't
* perform any check; thus you're responsible of ensuring that
* rectangle does not exceed the image size, and that
* pixels contains enough elements.
*
* Params:
* rectangle = sub rectangle of the image to update
* pixels = array of pixels to write to the image
*/
void updatePixels(ubyte[] pixels, IntRect rectangle)
{
sfImage_UpdatePixels(m_ptr, pixels.ptr, rectangle);
}
@property
{
/**
* Enable or disable image smooth filter.
* This parameter is enabled by default
*
* Params:
* s = True to enable smoothing filter, false to disable it
*/
void smooth(bool s)
{
sfImage_SetSmooth(m_ptr, s);
}
/**
* Return the width of the image
*
* Returns:
* Width in pixels
*/
uint width()
{
return sfImage_GetWidth(m_ptr);
}
/**
* Return the height of the image
*
* Returns:
* Height in pixels
*/
uint height()
{
return sfImage_GetHeight(m_ptr);
}
/**
* Tells whether the smooth filtering is enabled or not
*
* Returns:
* True if image smoothing is enabled
*/
bool smooth()
{
return cast(bool)sfImage_IsSmooth(m_ptr);
}
}
private:
static extern (C)
{
SFMLClass function() sfImage_Create;
SFMLClass function(uint, uint, Color) sfImage_CreateFromColor;
SFMLClass function(uint, uint, ubyte*) sfImage_CreateFromPixels;
SFMLClass function(cchar*) sfImage_CreateFromFile;
SFMLClass function(ubyte* ,size_t) sfImage_CreateFromMemory;
void function(SFMLClass) sfImage_Destroy;
int function(SFMLClass, cchar*) sfImage_SaveToFile;
void function(SFMLClass, Color, ubyte) sfImage_CreateMaskFromColor;
SFMLClass function(SFMLClass) sfImage_Copy;
int function(SFMLClass, SFMLClass, IntRect) sfImage_CopyScreen;
void function(SFMLClass, SFMLClass, uint, uint, IntRect) sfImage_CopyImage;
void function(SFMLClass, uint, uint, Color) sfImage_SetPixel;
Color function(SFMLClass, uint, uint) sfImage_GetPixel;
ubyte* function(SFMLClass) sfImage_GetPixelsPtr;
void function(SFMLClass) sfImage_Bind;
void function(SFMLClass, int) sfImage_SetSmooth;
uint function(SFMLClass) sfImage_GetWidth;
uint function(SFMLClass) sfImage_GetHeight;
int function(SFMLClass) sfImage_IsSmooth;
void function(SFMLClass, ubyte*, IntRect) sfImage_UpdatePixels;
}
mixin(loadFromSharedLib2("csfml-graphics", "sfImage",
"Create", "CreateFromColor", "CreateFromPixels", "CreateFromFile", "CreateFromMemory", "Destroy", "SaveToFile",
"CreateMaskFromColor", "Copy", "CopyScreen", "CopyImage", "SetPixel", "GetPixel", "GetPixelsPtr", "Bind", "SetSmooth", "GetWidth",
"GetHeight", "IsSmooth", "UpdatePixels"));
}

View file

@ -0,0 +1,138 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.irendertarget;
import dsfml.system.vector;
import dsfml.graphics.idrawable;
import dsfml.graphics.rect;
import dsfml.graphics.shader;
import dsfml.graphics.view;
import dsfml.graphics.color;
interface IRenderTarget
{
/**
* Clear the entire target with a single color
*
* \param color : Color to use to clear the render target
*
*/
void clear(Color color = Color());
/**
* Draw something into the target
*
* \param object : Object to draw
*
*/
void draw(IDrawable object);
/**
* Draw something into the target with a shader
*
* \param object : Object to draw
* \param shader : Shader to apply
*
*/
void draw(IDrawable object, Shader shader);
/**
* Convert a point in target coordinates into view coordinates
*
* \param x : X coordinate of the point to convert, relative to the target
* \param y : Y coordinate of the point to convert, relative to the target
* \param view : Target view to convert the point to, null to use the currently associated view
*
* \return Converted point
*
*/
Vector2f convertCoords(uint x, uint y, View view = null);
/**
* Save the current OpenGL render states and matrices
*
*/
void saveGLStates();
/**
* Restore the previously saved OpenGL render states and matrices
*
*/
void restoreGLStates();
@property
{
/**
* Get the width of the rendering region of the target
*
* \return Width in pixels
*
*/
uint width();
/**
* Get the height of the rendering region of the target
*
* \return Height in pixels
*
*/
uint height();
/**
* Change the current active view.
*
* \param view : New view to use (pass GetDefaultView() to set the default view)
*
*/
void view(View view);
/**
* Get the current view
*
* \return Current view active in the window
*
*/
View view();
/**
* Get the default view of the window
*
* \return Default view
*
*/
View defaultView();
/**
* Get the viewport of a view applied to this target
*
* \param view Target view
*
* \return Viewport rectangle, expressed in pixels in the current target
*
*/
IntRect viewport(View view);
}
}

View file

@ -0,0 +1,149 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.rect;
version (Tango)
{
import tango.core.Traits;
}
else
{
template isIntegerType(T)
{
const bool isIntegerType =
is (T == byte) ||
is (T == short) ||
is (T == int) ||
is (T == long);
}
template isRealType(T)
{
const bool isRealType =
is (T == float) ||
is (T == double) ||
is (T == real);
}
}
/**
* Rect is an utility class for manipulating rectangles.
* Template parameter defines the type of coordinates (integer float, ...)
*/
struct Rect(T)
{
T left; // Left coordinate of the rectangle
T top; // Top coordinate of the rectangle
T width; // width
T height; // height
static if (!isIntegerType!(T) && !isRealType!(T))
{
static assert (0, "This type is not supported by Rectangle");
}
T min(T)(T i, T j)
{
return i < j ? i : j;
}
T max(T)(T i, T j)
{
return i > j ? i : j;
}
/**
* Get the right coordinate of the rectangle
*/
T right()
{
return left + width;
}
/**
* Get the bottom coordinate of the rectangle
*/
T bottom()
{
return top + height;
}
/**
* Check if a point is inside the rectangle's area
*
* Params:
* x = X coordinate of the point to test
* y = Y coordinate of the point to test
*
* Returns:
* True if the point is inside
*/
bool contains(T x, T y)
{
return (x >= left) && (x < right) && (y >= top) && (y < bottom);
}
/**
* Check intersection between two rectangles
*
* Params:
* rectangle = Rectangle to test
* overlappingRect = Rectangle to be filled with overlapping rect (NULL by default)
*
* Returns:
* True if rectangles overlap
*/
bool intersects(Rect!(T) rectangle, out Rect!(T) overlappingRect = Rect!(T)())
{
// Compute overlapping rect
auto overlapping = Rect!(T)(
max(left, rectangle.left),
max(top, rectangle.top),
min(right, rectangle.right),
min(bottom, rectangle.bottom)
);
// If overlapping rect is valid, then there is intersection
if ((overlapping.left < overlapping.right) && (overlapping.top < overlapping.bottom))
{
overlappingRect = overlapping;
return true;
}
else
{
overlappingRect = Rect!(T)();
return false;
}
}
//bool opEquals
}
///Alias
alias Rect!(int) IntRect;
///ditto
alias Rect!(float) FloatRect;

View file

@ -0,0 +1,316 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.renderimage;
import dsfml.system.common,
dsfml.system.exception,
dsfml.system.stringutil,
dsfml.system.vector;
import dsfml.graphics.idrawable,
dsfml.graphics.image,
dsfml.graphics.color,
dsfml.graphics.rect,
dsfml.graphics.shader,
dsfml.graphics.view,
dsfml.graphics.irendertarget;
/**
* Target for 2D rendering into an image that can be reused in a sprite
*/
class RenderImage : DSFMLObject, IRenderTarget
{
private:
Image _image = null;
View _view = null;
View _defaultView = null;
package:
this(SFMLClass ptr)
{
super(ptr, true);
}
override void dispose()
{
sfRenderImage_Destroy(m_ptr);
}
public:
/**
* Construct a new renderimage
*
* Params:
* width = Width of the renderimage
* height = Height of the renderimage
* depthBuffer = Do you want a depth-buffer attached? (useful only if you're doing 3D OpenGL on the renderimage)
*/
this(uint width, uint height, bool depthBuffer = false)
{
super(sfRenderImage_Create(width, height, depthBuffer));
}
/**
* Update the contents of the target image
*/
void display()
{
sfRenderImage_Display(m_ptr);
}
/**
* Draw something on a renderimage
*
* Params:
* drawable = object to draw
*/
void draw(IDrawable drawable)
{
drawable.render(this);
}
/**
*
* Params:
* drawable = Object to draw
* shader = Shader to use
*/
void draw(IDrawable drawable, Shader shader)
{
drawable.renderWithShader(this, shader);
}
/**
* Clear the renderimage with the given color
*
* Params:
* color = Fill color
*/
void clear(Color color)
{
sfRenderImage_Clear(m_ptr, color);
}
/**
* Convert a point in image coordinates into view coordinates
*
* Params:
* imageX = X coordinate of the point to convert, relative to the image
* imageY = Y coordinate of the point to convert, relative to the image
* targetView = Target view to convert the point to (pass NULL to use the current view)
*
* Returns:
* Converted point
*/
Vector2f convertCoords(uint imageX, uint imageY, View targetView = null)
{
Vector2f vec;
sfRenderImage_ConvertCoords(m_ptr, imageX, imageY, &vec.x, &vec.y, targetView is null ? null : targetView.nativePointer);
return vec;
}
/**
* Save the current OpenGL render states and matrices
*/
void saveGLStates()
{
sfRenderImage_SaveGLStates(m_ptr);
}
/**
* Restore the previously saved OpenGL render states and matrices
*/
void restoreGLStates()
{
sfRenderImage_RestoreGLStates(m_ptr);
}
@property
{
/**
* Return the width of the rendering region of a renderimage
*
* Returns:
* Width in pixels
*/
uint width()
{
return sfRenderImage_GetWidth(m_ptr);
}
/**
* Return the height of the rendering region of a renderimage
*
* Returns:
* Height in pixels
*/
uint height()
{
return sfRenderImage_GetHeight(m_ptr);
}
/**
* Activate or deactivate a renderimage as the current target for rendering
*
* Params:
* active = true to activate, false to deactivate
* Returns:
* true if operation was successful, false otherwise
*/
bool active(bool activ)
{
return sfRenderImage_SetActive(m_ptr, activ);
}
/**
* Change the current active view of a renderimage
*
* Params:
* view = Pointer to the new view
*/
void view(View v)
{
if (_view !is null)
{
_view.setHandled(false);
}
sfRenderImage_SetView(m_ptr, v.nativePointer);
_view = v;
_view.setHandled(true);
}
/**
* Get the current active view rectangle
*
* Returns:
* current view rectangle, in global coordinates
*/
View view()
{
if (_view is null)
{
SFMLClass cView = sfRenderImage_GetView(m_ptr);
_view = new View(cView, true);
}
return _view;
}
/**
* Get the default view
*
* Returns:
* default view
*/
View defaultView()
{
if (_defaultView is null)
{
SFMLClass cView = sfRenderImage_GetDefaultView(m_ptr);
_defaultView = new View(cView, true);
}
return _defaultView;
}
IntRect viewport(View v = null) // TODO: is there a need to accept other Views than the currently assigned one?
{
return sfRenderImage_GetViewport(m_ptr, v is null ? _view.nativePointer : v.nativePointer);
}
/**
* Get the target image
*
* Returns:
* target image
*/
Image image()
{
if (_image is null)
{
SFMLClass cImage = sfRenderImage_GetImage(m_ptr);
_image = new Image(cImage);
}
return _image;
}
/**
* Check whether the system supports render images or not
*
* Returns:
* true if the RenderImage class can be used
*/
bool isAvailable()
{
return sfRenderImage_IsAvailable();
}
}
private:
static extern(C)
{
SFMLClass function(uint, uint, bool) sfRenderImage_Create;
void function(SFMLClass) sfRenderImage_Destroy;
uint function(SFMLClass) sfRenderImage_GetWidth;
uint function(SFMLClass) sfRenderImage_GetHeight;
bool function(SFMLClass, bool) sfRenderImage_SetActive;
void function(SFMLClass) sfRenderImage_Display;
void function(SFMLClass, void*) sfRenderImage_DrawSprite;
void function(SFMLClass, void*) sfRenderImage_DrawShape;
void function(SFMLClass, void*) sfRenderImage_DrawText;
void function(SFMLClass, void*, void*) sfRenderImage_DrawSpriteWithShader;
void function(SFMLClass, void*, void*) sfRenderImage_DrawShapeWithShader;
void function(SFMLClass, void*, void*) sfRenderImage_DrawTextWithShader;
void function(SFMLClass, Color) sfRenderImage_Clear;
void function(SFMLClass, SFMLClass) sfRenderImage_SetView;
SFMLClass function(SFMLClass) sfRenderImage_GetView;
SFMLClass function(SFMLClass) sfRenderImage_GetDefaultView;
IntRect function(SFMLClass, SFMLClass) sfRenderImage_GetViewport;
void function(SFMLClass, uint, uint, float*, float*, SFMLClass) sfRenderImage_ConvertCoords;
SFMLClass function(SFMLClass) sfRenderImage_GetImage;
bool function() sfRenderImage_IsAvailable;
// DSFML2
void function(SFMLClass) sfRenderImage_SaveGLStates;
void function(SFMLClass) sfRenderImage_RestoreGLStates;
}
mixin(loadFromSharedLib2("csfml-graphics", "sfRenderImage", "Create", "Destroy", "GetWidth", "GetHeight",
"SetActive", "Display", "Clear", "SetView", "GetView", "GetDefaultView", "GetViewport", "ConvertCoords",
"GetImage", "IsAvailable",
// DSFML2
"SaveGLStates", "RestoreGLStates"));
}

View file

@ -0,0 +1,339 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.renderwindow;
import dsfml.graphics.color,
dsfml.graphics.sprite,
dsfml.graphics.shape,
dsfml.graphics.text,
dsfml.graphics.rect,
dsfml.graphics.shader,
dsfml.graphics.view,
dsfml.graphics.idrawable,
dsfml.graphics.irendertarget;
import dsfml.window.event,
dsfml.window.input,
dsfml.window.videomode,
dsfml.window.window,
dsfml.window.windowhandle;
import dsfml.system.common,
dsfml.system.stringutil,
dsfml.system.vector;
/**
* Simple wrapper for Window that allows easy 2D rendering.
*/
class RenderWindow : Window, IRenderTarget
{
private:
View m_view = null;
View m_defaultView = null;
public:
/**
* Construct the window
*
* Params:
* mode = Video mode to use
* title = Title of the window
* windowStyle = Window style (Resize | Close by default)
* settings = Context settings (default is default ContextSettings values)
*/
this(VideoMode mode, string title, Style windowStyle = Style.Default, ContextSettings settings = ContextSettings())
{
super(sfRenderWindow_Create(mode, toStringz(title), windowStyle, &settings));
m_input = new Input(sfRenderWindow_GetInput(m_ptr));
}
/**
* Construct the window from an existing control
*
* Params:
* handle = Platform-specific handle of the control
* settings = Context settings (default is default ContextSettings values)
*/
this(WindowHandle handle, ContextSettings settings = ContextSettings())
{
super(sfRenderWindow_CreateFromHandle(handle, &settings));
m_input = new Input(sfRenderWindow_GetInput(m_ptr));
}
override void dispose()
{
sfRenderWindow_Destroy(m_ptr);
}
/**
* Create (or recreate) the window
*
* Input created with getInput will become invalid.
*
* Params:
* mode = Video mode to use
* title = Title of the window
* windowStyle = Window style (Resize | Close by default)
* settings = Context settings (default is default ContextSettings values)
*
*/
override void create(VideoMode mode, string title, Style windowStyle = Style.Default, ContextSettings settings = ContextSettings())
{
if (m_ptr !is null)
dispose();
m_ptr = sfRenderWindow_Create(mode, toStringz(title), windowStyle, &settings);
m_input = new Input(sfRenderWindow_GetInput(m_ptr));
}
/**
* Create (or recreate) the window from an existing control
*
* Input created with getInput become invalid.
*
* Params:
* handle = Platform-specific handle of the control
* settings = Context settings (default is default ContextSettings values)
*
*/
override void create(WindowHandle handle, ContextSettings settings = ContextSettings())
{
if (m_ptr !is null)
dispose();
m_ptr = sfRenderWindow_CreateFromHandle(handle, &settings);
m_input = new Input(sfRenderWindow_GetInput(m_ptr));
}
/**
* Draw a sprite, shape or text on the window with a shader
*
* Params:
* drawable = IDrawable to draw
* shader = Shader to use
*/
void draw(IDrawable drawable, Shader shader)
{
drawable.renderWithShader(this, shader);
}
/**
* Draw a sprite, shape or text
*
* Params:
* drawable = IDrawable to draw
*/
void draw(IDrawable drawable)
{
drawable.render(this);
}
/**
* Clear the screen with the given color.
*
* Params:
* col = Fill color
*/
void clear(Color col = Color.BLACK)
{
sfRenderWindow_Clear(m_ptr, col);
}
/**
* Convert a point in window coordinates into view coordinates
*
* Params:
* windowX = X coordinate of the point to convert, relative to the window
* windowY = Y coordinate of the point to convert, relative to the window
* targetView = Target view to convert the point to (pass NULL to use the current view)
*
* Returns:
* Converted point
*/
Vector2f convertCoords(uint windowX, uint windowY, View targetView = null)
{
Vector2f vec;
sfRenderWindow_ConvertCoords(m_ptr, windowX, windowY, &vec.x, &vec.y, targetView is null ? null : targetView.nativePointer);
return vec;
}
/**
* Save the current OpenGL render states and matrices
*/
void saveGLStates()
{
sfRenderWindow_SaveGLStates(m_ptr);
}
/**
* Restore the previously saved OpenGL render states and matrices
*/
void restoreGLStates()
{
sfRenderWindow_RestoreGLStates(m_ptr);
}
@property
{
/**
* Change the current active view.
* The current view is defined with the initial size of the window
*
* Params:
* newView = Pointer to the new view (pass getDefaultView to set the default view)
*/
void view(View newView)
{
if (m_view !is null)
{
m_view.setHandled(false);
}
sfRenderWindow_SetView(m_ptr, newView.nativePointer);
m_view = newView;
m_view.setHandled(true);
}
/**
* Get the current view rectangle
*
* Returns:
* current view rectangle, in global coordinates
*/
View view()
{
if (m_view is null)
{
SFMLClass cView = sfRenderWindow_GetView(m_ptr);
m_view = new View(cView, true);
}
return m_view;
}
/**
* Get the default view
*
* Returns:
* default view
*/
View defaultView()
{
if (m_defaultView is null)
{
SFMLClass cView = sfRenderWindow_GetDefaultView(m_ptr);
m_defaultView = new View(cView, true);
}
return m_defaultView;
}
/**
* Return the width of the rendering region of a renderwindow
*
* Returns:
* Width in pixels
*/
override uint width()
{
return sfRenderWindow_GetWidth(m_ptr);
}
/**
* Return the height of the rendering region of a renderwindow
*
* Returns:
* Height in pixels
*/
override uint height()
{
return sfRenderWindow_GetHeight(m_ptr);
}
/**
* Get the viewport of a view applied to this target
*
* Params:
* view = Target view
* Returns:
* Viewport rectangle, expressed in pixels in the current target
*/
IntRect viewport(View v = null) // TODO: is there a need to accept other Views than the currently assigned one?
{
return sfRenderWindow_GetViewport(m_ptr, v is null ? m_view.nativePointer : v.nativePointer);
}
}
private:
static extern(C)
{
SFMLClass function(VideoMode, cchar*, Style, ContextSettings*)sfRenderWindow_Create;
SFMLClass function(WindowHandle, ContextSettings*) sfRenderWindow_CreateFromHandle;
void function(SFMLClass) sfRenderWindow_Destroy;
SFMLClass function(SFMLClass) sfRenderWindow_GetInput;
bool function(SFMLClass) sfRenderWindow_IsOpened;
uint function(SFMLClass) sfRenderWindow_GetWidth;
uint function(SFMLClass) sfRenderWindow_GetHeight;
/*
void function(SFMLClass, SFMLClass) sfRenderWindow_DrawSprite;
void function(SFMLClass, SFMLClass) sfRenderWindow_DrawShape;
void function(SFMLClass, SFMLClass) sfRenderWindow_DrawText;
void function(SFMLClass, SFMLClass, SFMLClass) sfRenderWindow_DrawSpriteWithShader;
void function(SFMLClass, SFMLClass, SFMLClass) sfRenderWindow_DrawShapeWithShader;
void function(SFMLClass, SFMLClass, SFMLClass) sfRenderWindow_DrawTextWithShader;
*/
SFMLClass function(SFMLClass) sfRenderWindow_Capture;
void function(SFMLClass, Color) sfRenderWindow_Clear;
void function(SFMLClass, SFMLClass) sfRenderWindow_SetView;
SFMLClass function(SFMLClass) sfRenderWindow_GetView;
SFMLClass function(SFMLClass) sfRenderWindow_GetDefaultView;
void function(SFMLClass, uint, uint, float*, float*, SFMLClass) sfRenderWindow_ConvertCoords;
// DSFML2
void function(SFMLClass) sfRenderWindow_SaveGLStates;
void function(SFMLClass) sfRenderWindow_RestoreGLStates;
IntRect function(SFMLClass, SFMLClass) sfRenderWindow_GetViewport;
}
mixin(loadFromSharedLib2("csfml-graphics", "sfRenderWindow", "Create", "CreateFromHandle",
"Destroy", "GetInput", "Clear", "SetView", "GetView", "GetDefaultView", "ConvertCoords",
"GetWidth", "GetHeight",
// DSFML2
"SaveGLStates", "RestoreGLStates", "GetViewport"));
static ~this()
{
}
}

View file

@ -0,0 +1,177 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.shader;
import dsfml.graphics.image;
import dsfml.system.common;
import dsfml.system.exception;
import dsfml.system.stringutil;
/**
* Define loading methods for effect
*/
enum LoadingType
{
FROMFILE, /// string represents a file path
FROMSTRING /// string represents effect code
}
/**
* Shader is used to apply a post effect to a window
*
* See_Also:
* $(LINK2 http://www.sfml-dev.org/tutorials/graphics-postfx.php, SFML post FX tutorial) from more informations about Post effects and GLSL fragment shaders syntax.
*/
class Shader : DSFMLObject
{
private:
Image m_texture;
public:
/**
* construct the effect
*
* Params:
* effect = Path of a file or string containing the effect.
* type = type of the effect (default is FROMFILE)
*/
this(string effect, LoadingType type = LoadingType.FROMFILE)
{
if (effect is null || effect.length == 0)
throw new LoadingException("LoadingException : Effect is invalid.");
if (type == LoadingType.FROMFILE)
super(sfShader_CreateFromFile(toStringz(effect)));
else
super(sfShader_CreateFromMemory(toStringz(effect)));
}
override void dispose()
{
sfShader_Destroy(m_ptr);
}
/**
* Change parameters of the effect
*
* Params:
* name = Parameter name in the effect
*/
void setParameter(string name, float x)
{
sfShader_SetParameter1(m_ptr, toStringz(name), x);
}
/**
* ditto
*/
void setParameter(string name, float x, float y)
{
sfShader_SetParameter2(m_ptr, toStringz(name), x, y);
}
/**
* ditto
*/
void setParameter(string name, float x, float y, float z)
{
sfShader_SetParameter3(m_ptr, toStringz(name), x, y, z);
}
/**
* ditto
*/
void setParameter(string name, float x, float y, float z, float w)
{
sfShader_SetParameter4(m_ptr, toStringz(name), x, y, z, w);
}
/**
* Set a texture parameter
*
* Params:
* name = Texture name in the effect
* texture = Image to set (pass NULL to use content of current framebuffer)
*/
void setTexture(string name, Image texture)
{
m_texture = texture;
sfShader_SetTexture(m_ptr, toStringz(name), texture is null ? null : texture.nativePointer);
}
/**
* Tell whether or not the system supports shaders
*
* Returns:
* True if the system can use shaders
*/
static bool isAvailable()
{
return cast(bool)sfShader_IsAvailable();
}
private:
static extern(C)
{
SFMLClass function(cchar*) sfShader_CreateFromFile;
SFMLClass function(cchar*) sfShader_CreateFromMemory;
void function(SFMLClass) sfShader_Destroy;
void function(SFMLClass, cchar*, float) sfShader_SetParameter1;
void function(SFMLClass, cchar*, float, float) sfShader_SetParameter2;
void function(SFMLClass, cchar*, float, float, float) sfShader_SetParameter3;
void function(SFMLClass, cchar*, float, float, float, float) sfShader_SetParameter4;
void function(SFMLClass, cchar*, SFMLClass) sfShader_SetTexture;
int function() sfShader_IsAvailable;
void function(SFMLClass) sfShader_Bind;
void function(SFMLClass) sfShader_Unbind;
}
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-graphics-d");
else
DllLoader dll = DllLoader.load("csfml-graphics");
mixin(loadFromSharedLib("sfShader_CreateFromFile"));
mixin(loadFromSharedLib("sfShader_CreateFromMemory"));
mixin(loadFromSharedLib("sfShader_Destroy"));
mixin(loadFromSharedLib("sfShader_SetParameter1"));
mixin(loadFromSharedLib("sfShader_SetParameter2"));
mixin(loadFromSharedLib("sfShader_SetParameter3"));
mixin(loadFromSharedLib("sfShader_SetParameter4"));
mixin(loadFromSharedLib("sfShader_SetTexture"));
mixin(loadFromSharedLib("sfShader_IsAvailable"));
mixin(loadFromSharedLib("sfShader_Bind"));
mixin(loadFromSharedLib("sfShader_Unbind"));
}
}

View file

@ -0,0 +1,306 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.shape;
import dsfml.system.vector;
import dsfml.graphics.blendmode;
import dsfml.graphics.color;
import dsfml.graphics.drawableimpl;
/**
* Shape defines a drawable convex shape ; it also defines
* helper functions to draw simple shapes like
* lines, rectangles, circles, etc.
*/
class Shape : DrawableImpl!("sfShape")
{
private:
this (SFMLClass ptr)
{
super(ptr);
}
public:
this()
{
super();
}
/**
* Add a point to the shape
*
* Params:
* x = X position of the point
* y = Y position of the point
* col = Color of the point (white by default)
* outlineCol = Outline color of the point (black by default)
*/
void addPoint(float x, float y, Color col = Color.WHITE, Color outlineCol = Color.BLACK)
{
sfShape_AddPoint(m_ptr, x, y, col, outlineCol);
}
/**
* Add a point to the shape
*
* Params:
* position = position of the point
* col = Color of the point (white by default)
* outlineCol = Outline color of the point (black by default)
*/
void addPoint(Vector2f position, Color col = Color.WHITE, Color outlineCol = Color.BLACK)
{
sfShape_AddPoint(m_ptr, position.x, position.x, col, outlineCol);
}
@property
{
/**
* Enable or disable filling the shape.
* Fill is enabled by default.
*
* Params:
* enable = True to enable, false to disable
*/
void enableFill(bool enable)
{
sfShape_EnableFill(m_ptr, enable);
}
/**
* Enable or disable drawing a shape outline.
* Outline is enabled by default
*
* Params:
* enable = True to enable, false to disable
*/
void enableOutline(bool enable)
{
sfShape_EnableOutline(m_ptr, enable);
}
/**
* Change the width of a shape outline
*
* Params:
* width = New width
*/
void outlineWidth(float width)
{
sfShape_SetOutlineWidth(m_ptr, width);
}
/**
* Get the width of the shape outline
*
* Returns:
* Current outline width
*
*/
float outlineWidth()
{
return sfShape_GetOutlineWidth(m_ptr);
}
/**
* Get the number of points composing a shape
*
* Returns:
* Total number of points
*/
uint pointsCount()
{
return sfShape_GetPointsCount(m_ptr);
}
}
/**
* Get a point of the shape
*
* Params:
* index = Index of the point
*
* Returns:
* position of the point
*/
Vector2f getPointPosition(uint index)
{
float x, y;
sfShape_GetPointPosition(m_ptr, index, &x, &y);
return Vector2f(x, y);
}
/**
* Set the position of a shape point
*
* Params:
* index = Index of the point
* position = New position of the point
*/
void setPointPosition(uint index, Vector2f position)
{
sfShape_SetPointPosition(m_ptr, index, position.x, position.y);
}
/**
* Get the color of a shape's point
*
* Params:
* index = Index of the point
*
* Returns:
* Color of the point
*/
Color getPointColor(uint index)
{
return sfShape_GetPointColor(m_ptr, index);
}
/**
* Set the color of a shape's point
*
* Params:
* index = Index of the point
* color = new color of the point
*/
void setPointColor(uint index, Color color)
{
sfShape_SetPointColor(m_ptr, index, color);
}
/**
* Get the outline color of a shape's point
*
* Params:
* index = Index of the point
*
* Returns:
* Color of the outline
*/
Color getPointOutlineColor(uint index)
{
return sfShape_GetPointOutlineColor(m_ptr, index);
}
/**
* Set the outline color of a shape's point
*
* Params:
* index = Index of the point
* color = new color of the point
*/
void setPointOutlineColor(uint index, Color color)
{
sfShape_SetPointOutlineColor(m_ptr, index, color);
}
/**
* Create a shape made of a single line
*
* Params:
* p1X, p1Y = Position of the first point
* p2X, p2Y = Position second point
* thickness = Line thickness
* col = Color used to draw the line
* outline = Outline width (0 by default)
* outlineCol = Color used to draw the outline (black by default)
*
* Returns:
* New line shape
*/
static Shape line(float p1X, float p1Y, float p2X, float p2Y, float thickness, Color col, float outline = 0.f, Color outlineCol = Color.BLACK)
{
return new Shape(sfShape_CreateLine(p1X, p1Y, p2X, p2Y, thickness, col, outline, outlineCol));
}
/**
* Create a shape made of a single rectangle
*
* Params:
* left, top = Top-left corner of the rectangle
* width, height = Size of the rectangle
* col = Color used to fill the rectangle
* outline = Outline width (0 by default)
* outlineCol = Color used to draw the outline (black by default)
*
* Returns:
* new rectangle shape
*/
static Shape rectangle(float left, float top, float width, float height, Color col, float outline = 0.f, Color outlineCol = Color.BLACK)
{
return new Shape(sfShape_CreateRectangle(left, top, width, height, col, outline, outlineCol));
}
/**
* Create a shape made of a single circle
*
* Params:
* x = X position of the center
* y = Y position of the center
* radius = Radius
* col = Color used to fill the circle
* outline = Outline width (0 by default)
* outlineCol = Color used to draw the outline (black by default)
*
* Returns:
* new circle shape
*/
static Shape circle(float x, float y, float radius, Color col, float outline = 0.f, Color outlineCol = Color.BLACK)
{
return new Shape(sfShape_CreateCircle(x, y, radius, col, outline, outlineCol));
}
private:
static extern(C)
{
SFMLClass function(float, float, float, float, float, Color, float, Color) sfShape_CreateLine;
SFMLClass function(float, float, float, float, Color, float, Color) sfShape_CreateRectangle;
SFMLClass function(float, float, float, Color, float, Color) sfShape_CreateCircle;
void function(SFMLClass, float, float, Color, Color) sfShape_AddPoint;
void function(SFMLClass, int) sfShape_EnableFill;
void function(SFMLClass, int) sfShape_EnableOutline;
void function(SFMLClass, float Width) sfShape_SetOutlineWidth;
float function(SFMLClass) sfShape_GetOutlineWidth;
uint function(SFMLClass) sfShape_GetPointsCount;
void function(SFMLClass, uint Index, float* X, float* Y) sfShape_GetPointPosition;
void function(SFMLClass, uint Index, float X, float Y) sfShape_SetPointPosition;
Color function(SFMLClass, uint index) sfShape_GetPointColor;
void function(SFMLClass, uint index, Color color) sfShape_SetPointColor;
Color function(SFMLClass, uint index) sfShape_GetPointOutlineColor;
void function(SFMLClass, uint index, Color color) sfShape_SetPointOutlineColor;
}
mixin(loadFromSharedLib2("csfml-graphics", "sfShape",
"CreateLine", "CreateRectangle", "CreateCircle", "AddPoint", "EnableFill", "EnableOutline", "SetOutlineWidth", "GetOutlineWidth",
"GetPointsCount", "GetPointPosition", "SetPointPosition", "GetPointColor", "SetPointColor", "GetPointOutlineColor",
"SetPointOutlineColor"));
}

View file

@ -0,0 +1,238 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.sprite;
import dsfml.graphics.blendmode;
import dsfml.graphics.color;
import dsfml.graphics.drawableimpl;
import dsfml.graphics.image;
import dsfml.graphics.rect;
import dsfml.system.vector;
/**
* Sprite defines a sprite : texture, transformations,
* color, and draw on screen
* See_Also:
* IDrawable
*/
class Sprite : DrawableImpl!("sfSprite")
{
private:
Image m_image; //< Image used to draw the sprite
IntRect m_subRect; //< Sub-rectangle of source image to assign to the sprite
public:
/**
* Default constructor
*/
this()
{
super();
}
/**
* Construct the sprite from a source image
*
* Params:
* img = Image of the sprite
* left = Left coordinate of the sprite (0 by default)
* top = Top coordinate of the sprite (0 by default)
* scalex = Horizontal scale (1 by default)
* scaley = Vertical scale (1 by default)
* rot = Orientation, in degrees (0 by default)
* col = Color of the sprite (white by default)
*/
this(Image img, float left = 0.f, float top = 0.f, float scalex = 1.f, float scaley = 1.f, float rot = 0.f, Color col = Color.WHITE)
{
super();
m_image = img;
sfSprite_SetImage(m_ptr, img.nativePointer, true);
x = left;
y = top;
scaleX = scalex;
scaleY = scaley;
rotation = rot;
color = col;
}
/**
* Change the image of the sprite
*
* Params:
* img = New image
* adjustToNewSize = adjust sprite subrect to new image size
*/
void setImage(Image img, bool adjustToNewSize = false)
{
assert(img !is null, "Trying to set a null image.");
sfSprite_SetImage(m_ptr, img.nativePointer, adjustToNewSize);
m_image = img;
}
@property void image(Image img)
{
setImage(img, false);
}
/**
* Resize the sprite (by changing its scale factors).
* The default size is defined by the subrect
*
* Params:
* width = New width (must be strictly positive)
* height = New height (must be strictly positive)
*/
void resize(float width, float height)
{
if (width > 0 && height > 0)
sfSprite_Resize(m_ptr, width, height);
}
/**
* Resize the sprite (by changing its scale factors).
* The default size is defined by the subrect
*
* Params:
* size = New size (both coordinates must be strictly positive)
*/
void resize(Vector2f size)
{
if (size.x > 0 && size.y > 0)
sfSprite_Resize(m_ptr, size.x, size.y);
}
/**
* Flip the sprite horizontally
*
* Params:
* flipped = True to flip the sprite
*/
void flipX(bool flipped)
{
sfSprite_FlipX(m_ptr, flipped);
}
/**
* Flip the sprite vertically
*
* Params:
* flipped = True to flip the sprite
*/
void flipY(bool flipped)
{
sfSprite_FlipY(m_ptr, flipped);
}
/**
* Get the color of a given pixel in the sprite
*
* Params:
* x = X coordinate
* y = Y coordinate
*
* Returns:
* Color of pixel
*/
Color getPixel(uint x, uint y) const
{
return sfSprite_GetPixel(m_ptr, x, y);
}
@property
{
/**
* Set the sub-rectangle of a sprite inside the source image.
*
* Params:
* rect = New sub-rectangle
*/
void subRect(IntRect rect)
{
sfSprite_SetSubRect(m_ptr, rect);
m_subRect = rect;
}
/**
* Get the source image of the sprite
*
* Returns:
* Pointer to the image (can be NULL)
*/
Image image()
{
return m_image;
}
/**
* Get the sub-rectangle of the sprite inside the source image
*
* Returns:
* Sub-rectangle
*/
IntRect subRect()
{
if (m_subRect == IntRect())
m_subRect = sfSprite_GetSubRect(m_ptr);
//m_subRect = IntRect(0, 0, m_image.getWidth(), m_image.getHeight());
return m_subRect;
}
/**
* Get the sprite size
*
* Returns:
* Size of the sprite
*/
Vector2f size() const
{
return Vector2f(sfSprite_GetWidth(m_ptr), sfSprite_GetHeight(m_ptr));
}
}
private:
static extern(C)
{
void function(SFMLClass, SFMLClass, bool) sfSprite_SetImage;
void function(SFMLClass, IntRect) sfSprite_SetSubRect;
void function(SFMLClass, float, float) sfSprite_Resize;
void function(SFMLClass, int) sfSprite_FlipX;
void function(SFMLClass, int) sfSprite_FlipY;
SFMLClass function(SFMLClass) sfSprite_GetImage;
IntRect function(SFMLClass) sfSprite_GetSubRect;
float function(SFMLClass) sfSprite_GetWidth;
float function(SFMLClass) sfSprite_GetHeight;
Color function(SFMLClass, uint, uint) sfSprite_GetPixel;
}
mixin(loadFromSharedLib2("csfml-graphics", "sfSprite",
"SetImage", "SetSubRect", "Resize", "FlipX", "FlipY", "GetImage", "GetSubRect", "GetWidth", "GetHeight", "GetPixel"));
}

View file

@ -0,0 +1,277 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.text;
import dsfml.graphics.blendmode;
import dsfml.graphics.color;
import dsfml.graphics.font;
import dsfml.graphics.drawableimpl;
import dsfml.graphics.rect;
import dsfml.system.stringutil;
import dsfml.system.vector;
/**
* Enumerate the text drawing styles
*/
enum TextStyle
{
REGULAR = 0, /// Regular characters, no style
BOLD = 1 << 0, /// Characters are bold
ITALIC = 1 << 1, /// Characters are in italic
UNDERLINED = 1 << 2 /// Characters are underlined
}
/**
* Text defines a graphical 2D text, that can be drawn on screen
*
* All string litterals used must be prefixed with c for utf-8
* and d for utf-32 string.
*
* Examples :
* ---------------------------------------------------------------
* Text s = new Text("Hello"c);
* //this(string, Font, float)
* s = new Text("Hello"d);
* //this(dstring, Font, float)
* ---------------------------------------------------------------
*
* See_Also:
* IDrawable
*/
class Text : DrawableImpl!("sfText")
{
private:
Font m_font;
public:
/**
* Construct the string from a text
*
* Prefixs string litterals with c
*
* Params:
* s = Text assigned to the string
* f = Font used to draw the string (use default font)
* size = Characters size, in pixels (32 by default)
*/
this(string s, Font f = Font.getDefaultFont(), uint size = 30)
{
super();
font = f;
text = s;
characterSize = size;
}
/**
* Construct the string from a unicode text
*
* Prefixs string litterals with d
*
* Params:
* s = Text assigned to the string
* f = Font used to draw the string (use default font)
* size = Characters size, in pixels (32 by default)
*/
this(dstring s, Font f = Font.getDefaultFont(), uint size = 30)
{
super();
font = f;
text = s;
characterSize = size;
}
@property
{
/**
* Set the text (from a multibyte string)
*
* Params:
* text = New text
*/
void text(string text)
{
sfText_SetString(m_ptr, toStringz(text));
}
/**
* Set the text (from a unicode string)
*
* Params:
* text = New text
*/
void text(dstring text)
{
sfText_SetUnicodeString(m_ptr, toStringz(text));
}
/**
* Get the text (returns a multibyte string)
*
* Returns:
* Text
*/
string text()
{
return fromStringz(sfText_GetString(m_ptr));
}
/**
* Set the font of the string
*
* Params:
* f = Font
*/
void font(Font f)
{
m_font = f;
sfText_SetFont(m_ptr, f.nativePointer);
}
/**
* Set the size of the string
*
* Params:
* size = New size, in pixels
*/
void characterSize(uint size)
{
sfText_SetCharacterSize(m_ptr, size);
}
/**
* Set the style of the text
* The default style is Regular
*
* Params:
* TextStyle = New text style, (combination of Style enum values)
*
*/
void style(TextStyle tstyle)
{
sfText_SetStyle(m_ptr, tstyle);
}
/**
* Get the text (returns a unicode string)
*
* Returns:
* Text
*/
dstring unicodeText()
{
return fromStringz(sfText_GetUnicodeString(m_ptr));
}
/**
* Get the font used by the string
*
* Returns:
* Font name
*/
Font font()
{
return m_font;
}
/**
* Get the size of the characters
*
* Returns:
* Size of the characters
*/
uint characterSize()
{
return sfText_GetCharacterSize(m_ptr);
}
/**
* Get the current font style
*
* Returns:
* Font style
*/
TextStyle style()
{
return sfText_GetStyle(m_ptr);
}
/**
* Get the string rectangle on screen
*
* Returns:
* Rectangle contaning the string in screen coordinates
*/
FloatRect rect()
{
return sfText_GetRect(m_ptr);
}
}
/**
* Return the visual position of the Index-th character of the string,
* in coordinates relative to the string
* (note : translation, center, rotation and scale are not applied)
*
* Params:
* index = Index of the character
*
* Returns:
* Position of the Index-th character (end of string of Index is out of range)
*/
Vector2f getCharacterPos(size_t index)
{
Vector2f ret;
sfText_GetCharacterPos(m_ptr, index, &ret.x, &ret.y);
return ret;
}
private:
static extern(C)
{
void function(SFMLClass, cchar*) sfText_SetString;
void function(SFMLClass, cdchar*) sfText_SetUnicodeString;
void function(SFMLClass, SFMLClass) sfText_SetFont;
void function(SFMLClass, uint) sfText_SetCharacterSize;
void function(SFMLClass, TextStyle) sfText_SetStyle;
idchar* function(SFMLClass) sfText_GetUnicodeString;
ichar* function(SFMLClass) sfText_GetString;
SFMLClass function(SFMLClass) sfText_GetFont;
uint function(SFMLClass) sfText_GetCharacterSize;
TextStyle function (SFMLClass) sfText_GetStyle;
void function(SFMLClass, size_t, float*, float*) sfText_GetCharacterPos;
FloatRect function(SFMLClass) sfText_GetRect;
}
mixin(loadFromSharedLib2("csfml-graphics", "sfText",
"SetString", "SetUnicodeString", "SetFont", "SetCharacterSize", "SetStyle", "GetUnicodeString", "GetString", "GetFont",
"GetCharacterSize", "GetStyle", "GetCharacterPos", "GetRect"));
}

View file

@ -0,0 +1,347 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.graphics.view;
import dsfml.graphics.rect;
import dsfml.system.common,
dsfml.system.vector;
/**
* This class defines a view (position, size and zoom) ;
* you can consider it as a camera
*/
class View : DSFMLObject
{
private:
FloatRect _rect; // a view defines a source area of the scene to display, and a destination area into the rendertarget where to map the source area
FloatRect _viewport; // the viewport is the destination area in the rendertarget
bool m_isModified = true;
public:
/**
* Constructor
*
* Default view (1000 x 1000)
*/
this()
{
super(sfView_Create());
}
/**
* Constructor
*
* Params:
* center = center of the view
* size = size of the view (width, height)
*/
this(Vector2f center, Vector2f size)
{
super(sfView_CreateFromRect(FloatRect(center.x - size.x / 2, center.y - size.y / 2, size.x, size.y) ));
}
/**
* Constructor
*
* Params:
* rect = Rectangle defining the position and size of the view
*/
this(FloatRect rect)
{
super(sfView_CreateFromRect(rect));
}
override void dispose()
{
sfView_Destroy(m_ptr);
}
/**
* Change the center of the view
*
* Params:
* x = X coordinates of the new center
* y = Y coordinates of the new center
*/
void setCenter(float x, float y)
{
sfView_SetCenter(m_ptr, x, y);
m_isModified = true;
}
/**
* Change the center of the view
*
* Params:
* center = New center
*/
void setCenter(Vector2f center)
{
sfView_SetCenter(m_ptr, center.x, center.y);
m_isModified = true;
}
/**
* Change the size of the view (take 2 values)
*
* Params:
* width = New width
* height = New height
*/
void setSize(float width, float height)
{
sfView_SetSize(m_ptr, width, height);
m_isModified = true;
}
/**
* Change the size of the view (take 2 values)
*
* Params:
* size = New size
*/
void setSize(Vector2f size)
{
sfView_SetSize(m_ptr, size.x, size.y);
m_isModified = true;
}
/**
* Rebuild the view from a rectangle
*
* Params:
* viewport : Rectangle defining the position and size of the view
*/
void setViewport(FloatRect viewport)
{
sfView_SetViewport(m_ptr, viewport);
_viewport = viewport;
}
/**
* Get the center of the view
*
* Returns:
* Center of the view
*/
Vector2f getCenter()
{
return Vector2f(sfView_GetCenterX(m_ptr), sfView_GetCenterY(m_ptr));
}
/**
* Get the size of the view
*
* Returns:
* size of the view
*/
Vector2f getSize()
{
return Vector2f(sfView_GetWidth(m_ptr), sfView_GetHeight(m_ptr));
}
/**
* Get the width of the view
*
* Returns:
* width of the view
*/
float getWidth()
{
return sfView_GetWidth(m_ptr);
}
/**
* Get the height of the view
*
* Returns:
* height of the view
*/
float getHeight()
{
return sfView_GetHeight(m_ptr);
}
/**
* Get the bounding retangle of the view
*/
FloatRect getViewport()
{
if (m_isModified)
{
m_isModified = false;
_viewport = sfView_GetViewport(m_ptr);
}
return _viewport;
}
/**
* Move the view
*
* Params:
* offsetX = Offset to move the view, on X axis
* offsetY = Offset to move the view, on Y axis
*/
View move(float offsetX, float offsetY)
{
sfView_Move(m_ptr, offsetX, offsetY);
m_isModified = true;
return this;
}
/**
* Move the view
*
* Params:
* offset = offsetto move the view
*/
View move(Vector2f offset)
{
sfView_Move(m_ptr, offset.x, offset.y);
m_isModified = true;
return this;
}
/**
* Resize the view rectangle to simulate a zoom / unzoom effect
*
* Params:
* factor = Zoom factor to apply, relative to the current zoom
*/
View zoom(float factor)
{
sfView_Zoom(m_ptr, factor);
m_isModified = true;
return this;
}
/**
* Rotate the view relatively to its current orientation.
*
* Params:
* angle = Angle to rotate, in degree
*/
View rotate(float angle)
{
sfView_Rotate(m_ptr, angle);
return this;
}
/**
* Set the orientation of the view
* The default rotation of a view is 0 degree
*
* Params:
* angle = New angle, in degrees
*/
View setRotation(float angle)
{
sfView_SetRotation(m_ptr, angle);
return this;
}
/**
* Get the current orientation of the view
*
* Returns:
* Rotation angle of the view, in degrees
*/
float getRotation()
{
return sfView_GetRotation(m_ptr);
}
void reset(FloatRect rect)
{
sfView_Reset(m_ptr, rect);
_rect = rect;
}
package:
this(SFMLClass ptr, bool preventDelete)
{
super(ptr, preventDelete);
}
private:
static extern(C)
{
SFMLClass function() sfView_Create;
SFMLClass function(FloatRect) sfView_CreateFromRect;
void function(SFMLClass) sfView_Destroy;
void function(SFMLClass, float, float) sfView_SetCenter;
void function(SFMLClass, float, float) sfView_SetSize;
void function(SFMLClass, FloatRect) sfView_SetViewport;
float function(SFMLClass) sfView_GetCenterX;
float function(SFMLClass) sfView_GetCenterY;
float function(SFMLClass) sfView_GetWidth;
float function(SFMLClass) sfView_GetHeight;
FloatRect function(SFMLClass) sfView_GetViewport;
void function(SFMLClass, float, float) sfView_Move;
void function(SFMLClass, float) sfView_Zoom;
// DSFML2
void function(SFMLClass, float) sfView_SetRotation;
float function(SFMLClass) sfView_GetRotation;
void function(SFMLClass, float) sfView_Rotate;
void function(SFMLClass, FloatRect) sfView_Reset;
}
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-graphics-d");
else
DllLoader dll = DllLoader.load("csfml-graphics");
mixin(loadFromSharedLib("sfView_Create"));
mixin(loadFromSharedLib("sfView_CreateFromRect"));
mixin(loadFromSharedLib("sfView_Destroy"));
mixin(loadFromSharedLib("sfView_SetCenter"));
mixin(loadFromSharedLib("sfView_SetSize"));
mixin(loadFromSharedLib("sfView_SetViewport"));
mixin(loadFromSharedLib("sfView_GetCenterX"));
mixin(loadFromSharedLib("sfView_GetCenterY"));
mixin(loadFromSharedLib("sfView_GetWidth"));
mixin(loadFromSharedLib("sfView_GetHeight"));
mixin(loadFromSharedLib("sfView_GetViewport"));
mixin(loadFromSharedLib("sfView_Move"));
mixin(loadFromSharedLib("sfView_Zoom"));
// DSFML2
mixin(loadFromSharedLib("sfView_SetRotation"));
mixin(loadFromSharedLib("sfView_GetRotation"));
mixin(loadFromSharedLib("sfView_Rotate"));
mixin(loadFromSharedLib("sfView_Reset"));
}
}

View file

@ -0,0 +1,38 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.network.all;
public import
dsfml.network.ftp,
dsfml.network.http,
dsfml.network.ipaddress,
dsfml.network.packet,
dsfml.network.socketselector,
dsfml.network.socketstatus,
dsfml.network.tcpsocket,
dsfml.network.udpsocket,
dsfml.network.tcplistener ;

View file

@ -0,0 +1,602 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.network.ftp;
import dsfml.system.common;
import dsfml.system.stringutil;
import dsfml.network.ipaddress;
/**
* Enumeration of transfer mode
*/
enum FtpTransferMode
{
BINARY, ///< Binary mode (file is transfered as a sequence of bytes)
ASCII, ///< Text mode using ASCII encoding
EBCDIC ///< Text mode using EBCDIC encoding
}
/**
* Enumerate all the valid status codes returned in
* a FTP response
*/
enum FtpStatus
{
// 1xx: the requested action is being initiated,
// expect another reply before proceeding with a new command
RESTARTMARKERREPLY = 110, ///< Restart marker reply
SERVICEREADYSOON = 120, ///< Service ready in N minutes
DATACONNECTIONALREADYOPENED = 125, ///< Data connection already opened, transfer starting
OPENINGDATACONNECTION = 150, ///< File status ok, about to open data connection
// 2xx: the requested action has been successfully completed
OK = 200, ///< Command ok
POINTLESSCOMMAND = 202, ///< Command not implemented
SYSTEMSTATUS = 211, ///< System status, or system help reply
DIRECTORYSTATUS = 212, ///< Directory status
FILESTATUS = 213, ///< File status
HELPMESSAGE = 214, ///< Help message
SYSTEMTYPE = 215, ///< NAME system type, where NAME is an official system name from the list in the Assigned Numbers document
SERVICEREADY = 220, ///< Service ready for new user
CLOSINGCONNECTION = 221, ///< Service closing control connection
DATACONNECTIONOPENED = 225, ///< Data connection open, no transfer in progress
CLOSINGDATACONNECTION = 226, ///< Closing data connection, requested file action successful
ENTERINGPASSIVEMODE = 227, ///< Entering passive mode
LOGGEDIN = 230, ///< User logged in, proceed. Logged out if appropriate
FILEACTIONOK = 250, ///< Requested file action ok
DIRECTORYOK = 257, ///< PATHNAME created
// 3xx: the command has been accepted, but the requested action
// is dormant, pending receipt of further information
NEEDPASSWORD = 331, ///< User name ok, need password
NEEDACCOUNTTOLOGIN = 332, ///< Need account for login
NEEDINFORMATION = 350, ///< Requested file action pending further information
// 4xx: the command was not accepted and the requested action did not take place,
// but the error condition is temporary and the action may be requested again
SERVICEUNAVAILABLE = 421, ///< Service not available, closing control connection
DATACONNECTIONUNAVAILABLE = 425, ///< Can't open data connection
TRANSFERABORTED = 426, ///< Connection closed, transfer aborted
FILEACTIONABORTED = 450, ///< Requested file action not taken
LOCALERROR = 451, ///< Requested action aborted, local error in processing
INSUFFICIENTSTORAGESPACE = 452, ///< Requested action not taken; insufficient storage space in system, file unavailable
// 5xx: the command was not accepted and
// the requested action did not take place
COMMANDUNKNOWN = 500, ///< Syntax error, command unrecognized
PARAMETERSUNKNOWN = 501, ///< Syntax error in parameters or arguments
COMMANDNOTIMPLEMENTED = 502, ///< Command not implemented
BADCOMMANDSEQUENCE = 503, ///< Bad sequence of commands
PARAMETERNOTIMPLEMENTED = 504, ///< Command not implemented for that parameter
NOTLOGGEDIN = 530, ///< Not logged in
NEEDACCOUNTTOSTORE = 532, ///< Need account for storing files
FILEUNAVAILABLE = 550, ///< Requested action not taken, file unavailable
PAGETYPEUNKNOWN = 551, ///< Requested action aborted, page type unknown
NOTENOUGHMEMORY = 552, ///< Requested file action aborted, exceeded storage allocation
FILENAMENOTALLOWED = 553, ///< Requested action not taken, file name not allowed
// 10xx: SFML custom codes
INVALIDRESPONSE = 1000, ///< Response is not a valid FTP one
CONNECTIONFAILED = 1001, ///< Connection with server failed
CONNECTIONCLOSED = 1002, ///< Connection with server closed
INVALIDFILE = 1003 ///< Invalid file to upload / download
}
/**
* This class provides methods for manipulating the FTP protocol (described in RFC 959).
* It provides easy access and transfers to remote directories and files on a FTP server.
*/
class Ftp : DSFMLObject
{
/**
* This class wraps a FTP response, which is basically :
* - a status code
* - a message
*/
static class FtpResponse : DSFMLObject
{
override void dispose()
{
sfFtpResponse_Destroy(m_ptr);
}
/**
* Convenience function to check if the response status code
* means a success
*
* Returns:
* True if status is success (code < 400)
*/
bool isOk()
{
return cast(bool)sfFtpResponse_IsOk(m_ptr);
}
/**
* Get the response status code
*
* Returns:
* Status code
*/
FtpStatus getStatus()
{
return sfFtpResponse_GetStatus(m_ptr);
}
/**
* Get the full message contained in the response
*
* Returns:
* The response message
*/
string getMessage()
{
return fromStringz(sfFtpResponse_GetMessage(m_ptr));
}
private:
this(SFMLClass ptr)
{
super(ptr);
}
// External ================================================================
extern (C)
{
typedef void function(SFMLClass) pf_sfFtpResponse_Destroy;
typedef int function(SFMLClass) pf_sfFtpResponse_IsOk;
typedef FtpStatus function(SFMLClass) pf_sfFtpResponse_GetStatus;
typedef ichar* function(SFMLClass) pf_sfFtpResponse_GetMessage;
static pf_sfFtpResponse_Destroy sfFtpResponse_Destroy;
static pf_sfFtpResponse_IsOk sfFtpResponse_IsOk;
static pf_sfFtpResponse_GetStatus sfFtpResponse_GetStatus;
static pf_sfFtpResponse_GetMessage sfFtpResponse_GetMessage;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfFtpResponse_Destroy = cast(pf_sfFtpResponse_Destroy)dll.getSymbol("sfFtpResponse_Destroy");
sfFtpResponse_IsOk = cast(pf_sfFtpResponse_IsOk)dll.getSymbol("sfFtpResponse_IsOk");
sfFtpResponse_GetStatus = cast(pf_sfFtpResponse_GetStatus)dll.getSymbol("sfFtpResponse_GetStatus");
sfFtpResponse_GetMessage = cast(pf_sfFtpResponse_GetMessage)dll.getSymbol("sfFtpResponse_GetMessage");
}
}
/**
* Specialization of FTP response returning a directory
*/
static class FtpDirectoryResponse : FtpResponse
{
override void dispose()
{
sfFtpDirectoryResponse_Destroy(m_ptr);
}
/**
* Get the directory returned in the response.
*
* Returns:
* Directory name
*/
string getDirectory()
{
return fromStringz(sfFtpDirectoryResponse_GetDirectory(m_ptr));
}
private:
this(SFMLClass ptr)
{
super(ptr);
}
// External ================================================================
extern (C)
{
typedef void function(SFMLClass) pf_sfFtpDirectoryResponse_Destroy;
typedef ichar* function(SFMLClass) pf_sfFtpDirectoryResponse_GetDirectory;
static pf_sfFtpDirectoryResponse_Destroy sfFtpDirectoryResponse_Destroy;
static pf_sfFtpDirectoryResponse_GetDirectory sfFtpDirectoryResponse_GetDirectory;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfFtpDirectoryResponse_Destroy = cast(pf_sfFtpDirectoryResponse_Destroy)dll.getSymbol("sfFtpDirectoryResponse_Destroy");
sfFtpDirectoryResponse_GetDirectory = cast(pf_sfFtpDirectoryResponse_GetDirectory)dll.getSymbol("sfFtpDirectoryResponse_GetDirectory");
}
}
/**
* Specialization of FTP response returning a filename listing.
*/
static class FtpListingResponse : FtpResponse
{
override void dispose()
{
sfFtpListingResponse_Destroy(m_ptr);
}
/**
* Get the number of files in the listing
*
* Returns:
* Total number of files
*/
size_t getCount()
{
return sfFtpListingResponse_GetCount(m_ptr);
}
/**
* Get the index-th filename in the directory
*
* Params:
* index = Index of the filename to get
*
* Returns:
* Filename
*/
string opIndex(size_t index)
{
return fromStringz(sfFtpListingResponse_GetFilename(m_ptr, index));
}
/**
* Foreach implementation
*/
int opApply(int delegate(string) dg)
{
size_t count = getCount();
int result;
for(int i = 0; i < count; i++)
{
result = dg(this[i]);
if (result)
break;
}
return result;
}
private:
this(SFMLClass ptr)
{
super(ptr);
}
// External ================================================================
extern (C)
{
typedef void function(SFMLClass) pf_sfFtpListingResponse_Destroy;
typedef size_t function(SFMLClass) pf_sfFtpListingResponse_GetCount;
typedef ichar* function(SFMLClass, size_t) pf_sfFtpListingResponse_GetFilename;
static pf_sfFtpListingResponse_Destroy sfFtpListingResponse_Destroy;
static pf_sfFtpListingResponse_GetCount sfFtpListingResponse_GetCount;
static pf_sfFtpListingResponse_GetFilename sfFtpListingResponse_GetFilename;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfFtpListingResponse_Destroy = cast(pf_sfFtpListingResponse_Destroy)dll.getSymbol("sfFtpListingResponse_Destroy");
sfFtpListingResponse_GetCount = cast(pf_sfFtpListingResponse_GetCount)dll.getSymbol("sfFtpListingResponse_GetCount");
sfFtpListingResponse_GetFilename = cast(pf_sfFtpListingResponse_GetFilename)dll.getSymbol("sfFtpListingResponse_GetFilename");
}
}
/**
* Default constructor
*/
this()
{
super(sfFtp_Create());
}
override void dispose()
{
sfFtp_Destroy(m_ptr);
}
/**
* Connect to the specified FTP server
*
* Params:
* server = FTP server to connect to
* port = Port used for connection (21 by default, standard FTP port)
* timeout = Maximum time to wait, in seconds (0 by default, means no timeout)
*
* Returns:
* Server response to the request
*/
FtpResponse connect(IPAddress server, ushort port = 21, float timeout = 0.f)
{
return new FtpResponse(sfFtp_Connect(m_ptr, server, port, timeout));
}
/**
* Log in using anonymous account
*
* Returns:
* Server response to the request
*/
FtpResponse login()
{
return new FtpResponse(sfFtp_LoginAnonymous(m_ptr));
}
/**
* Log in using a username and a password
*
* Params:
* username = User name
* password = password
*
* Returns:
* Server response to the request
*/
FtpResponse login(string username, string password)
{
return new FtpResponse(sfFtp_Login(m_ptr, toStringz(username), toStringz(password)));
}
/**
* Close the connection with FTP server
*
* Returns:
* Server response to the request
*/
FtpResponse disconnect()
{
return new FtpResponse(sfFtp_Disconnect(m_ptr));
}
/**
* Send a null command to prevent from being disconnected.
*
* Returns:
* Server response to the request
*/
FtpResponse keepAlive()
{
return new FtpResponse(sfFtp_KeepAlive(m_ptr));
}
/**
* Get the current working directory
*
* Returns:
* Server response to the request
*/
FtpDirectoryResponse getWorkingDirectory()
{
return new FtpDirectoryResponse(sfFtp_GetWorkingDirectory(m_ptr));
}
/**
* Get the content of the given directory (subdirectories and files).
*
* Params:
* directory = directory to list (null by default, the current one)
*
* Returns:
* Server response to the request
*/
FtpListingResponse getDirectoryListing(string directory = null)
{
return new FtpListingResponse(sfFtp_GetDirectoryListing(m_ptr, toStringz(directory)));
}
/**
* Change the current working directory
*
* Params:
* directory = New directory, relative to the current one.
*
* Returns:
* Server response to the request
*/
FtpResponse changeDirectory(string directory)
{
return new FtpResponse(sfFtp_ChangeDirectory(m_ptr, toStringz(directory)));
}
/**
* Go to the parent directory of the current one
*
* Returns:
* Server response to the request
*/
FtpResponse parentDirectory()
{
return new FtpResponse(sfFtp_ParentDirectory(m_ptr));
}
/**
* Create a new directory
*
* Params:
* name = name of the directory to create
*
* Returns:
* Server response to the request
*/
FtpResponse createDirectory(string name)
{
return new FtpResponse(sfFtp_CreateDirectory(m_ptr, toStringz(name)));
}
/**
* remove an existing directory
*
* Params:
* name = name of the directory to remove
*
* Returns:
* Server response to the request
*/
FtpResponse deleteDirectory(string name)
{
return new FtpResponse(sfFtp_DeleteDirectory(m_ptr, toStringz(name)));
}
/**
* Rename a file
*
* Params:
* name = file to rename
* newName = new name
*
* Returns:
* Server response to the request
*/
FtpResponse renameFile(string name, string newName)
{
return new FtpResponse(sfFtp_RenameFile(m_ptr, toStringz(name), toStringz(newName)));
}
/**
* Remove an existing file
*
* Params:
* name = file to remove
*
* Returns:
* Server response to the request
*/
FtpResponse deleteFile(string name)
{
return new FtpResponse(sfFtp_DeleteFile(m_ptr, toStringz(name)));
}
/**
* Download a file from the server
*
* Params:
* distantFile = Path of the distant file to download
* destFile = Where to put the file on the local computer
* mode = transfer mode (binary by default)
*
* Returns:
* Server response to the request
*/
FtpResponse download(string distantFile, string destFile, FtpTransferMode mode = FtpTransferMode.BINARY)
{
return new FtpResponse(sfFtp_Download(m_ptr, toStringz(distantFile), toStringz(destFile), mode));
}
/**
* Upload a file to the server
*
* Params:
* localFile = Path of the local file to upload
* destPath = Where to put the file on the server
* mode = transfer mode (binary by default)
* Returns:
* Server response to the request
*/
FtpResponse upload(string localFile, string destFile, FtpTransferMode mode = FtpTransferMode.BINARY)
{
return new FtpResponse(sfFtp_Upload(m_ptr, toStringz(localFile), toStringz(destFile), mode));
}
private:
// External ====================================================================
extern (C)
{
typedef SFMLClass function() pf_sfFtp_Create;
typedef void function(SFMLClass) pf_sfFtp_Destroy;
typedef SFMLClass function(SFMLClass, IPAddress, ushort, float) pf_sfFtp_Connect;
typedef SFMLClass function(SFMLClass) pf_sfFtp_LoginAnonymous;
typedef SFMLClass function(SFMLClass, cchar*, cchar*) pf_sfFtp_Login;
typedef SFMLClass function(SFMLClass) pf_sfFtp_Disconnect;
typedef SFMLClass function(SFMLClass) pf_sfFtp_KeepAlive;
typedef SFMLClass function(SFMLClass) pf_sfFtp_GetWorkingDirectory;
typedef SFMLClass function(SFMLClass, cchar*) pf_sfFtp_GetDirectoryListing;
typedef SFMLClass function(SFMLClass, cchar*) pf_sfFtp_ChangeDirectory;
typedef SFMLClass function(SFMLClass) pf_sfFtp_ParentDirectory;
typedef SFMLClass function(SFMLClass, cchar*) pf_sfFtp_CreateDirectory;
typedef SFMLClass function(SFMLClass, cchar*) pf_sfFtp_DeleteDirectory;
typedef SFMLClass function(SFMLClass, cchar*, cchar*) pf_sfFtp_RenameFile;
typedef SFMLClass function(SFMLClass, cchar*) pf_sfFtp_DeleteFile;
typedef SFMLClass function(SFMLClass, cchar*, cchar*, FtpTransferMode) pf_sfFtp_Download;
typedef SFMLClass function(SFMLClass, cchar*, cchar*, FtpTransferMode) pf_sfFtp_Upload;
static pf_sfFtp_Create sfFtp_Create;
static pf_sfFtp_Destroy sfFtp_Destroy;
static pf_sfFtp_Connect sfFtp_Connect;
static pf_sfFtp_LoginAnonymous sfFtp_LoginAnonymous;
static pf_sfFtp_Login sfFtp_Login;
static pf_sfFtp_Disconnect sfFtp_Disconnect;
static pf_sfFtp_KeepAlive sfFtp_KeepAlive;
static pf_sfFtp_GetWorkingDirectory sfFtp_GetWorkingDirectory;
static pf_sfFtp_GetDirectoryListing sfFtp_GetDirectoryListing;
static pf_sfFtp_ChangeDirectory sfFtp_ChangeDirectory;
static pf_sfFtp_ParentDirectory sfFtp_ParentDirectory;
static pf_sfFtp_CreateDirectory sfFtp_CreateDirectory;
static pf_sfFtp_DeleteDirectory sfFtp_DeleteDirectory;
static pf_sfFtp_RenameFile sfFtp_RenameFile;
static pf_sfFtp_DeleteFile sfFtp_DeleteFile;
static pf_sfFtp_Download sfFtp_Download;
static pf_sfFtp_Upload sfFtp_Upload;
}
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-network-d");
else
DllLoader dll = DllLoader.load("csfml-network");
sfFtp_Create = cast(pf_sfFtp_Create)dll.getSymbol("sfFtp_Create");
sfFtp_Destroy = cast(pf_sfFtp_Destroy)dll.getSymbol("sfFtp_Destroy");
sfFtp_Connect = cast(pf_sfFtp_Connect)dll.getSymbol("sfFtp_Connect");
sfFtp_LoginAnonymous = cast(pf_sfFtp_LoginAnonymous)dll.getSymbol("sfFtp_LoginAnonymous");
sfFtp_Login = cast(pf_sfFtp_Login)dll.getSymbol("sfFtp_Login");
sfFtp_Disconnect = cast(pf_sfFtp_Disconnect)dll.getSymbol("sfFtp_Disconnect");
sfFtp_KeepAlive = cast(pf_sfFtp_KeepAlive)dll.getSymbol("sfFtp_KeepAlive");
sfFtp_GetWorkingDirectory = cast(pf_sfFtp_GetWorkingDirectory)dll.getSymbol("sfFtp_GetWorkingDirectory");
sfFtp_GetDirectoryListing = cast(pf_sfFtp_GetDirectoryListing)dll.getSymbol("sfFtp_GetDirectoryListing");
sfFtp_ChangeDirectory = cast(pf_sfFtp_ChangeDirectory)dll.getSymbol("sfFtp_ChangeDirectory");
sfFtp_ParentDirectory = cast(pf_sfFtp_ParentDirectory)dll.getSymbol("sfFtp_ParentDirectory");
sfFtp_sfFtp_CreateDirectoryDirectory = cast(pf_sfFtp_CreateDirectory)dll.getSymbol("sfFtp_CreateDirectory");
sfFtp_DeleteDirectory = cast(pf_sfFtp_DeleteDirectory)dll.getSymbol("sfFtp_DeleteDirectory");
sfFtp_RenameFile = cast(pf_sfFtp_RenameFile)dll.getSymbol("sfFtp_RenameFile");
sfFtp_DeleteFile = cast(pf_sfFtp_DeleteFile)dll.getSymbol("sfFtp_DeleteFile");
sfFtp_Download = cast(pf_sfFtp_Download)dll.getSymbol("sfFtp_Download");
sfFtp_Upload = cast(pf_sfFtp_Upload)dll.getSymbol("sfFtp_Upload");
}
}

View file

@ -0,0 +1,398 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.network.http;
import dsfml.system.stringutil;
import dsfml.system.common;
/**
* HTTP methods enumeration
*/
enum HttpMethod
{
GET, ///< Request in get mode, standard method to retrieve a page
POST, ///< Request in post mode, usually to send data to a page
HEAD ///< Request a page's header only
}
/**
* HTTP response status code
*/
enum HttpStatus
{
// 2xx: success
OK = 200, ///< Most common code returned when operation was successful
CREATED = 201, ///< The resource has successfully been created
ACCEPTED = 202, ///< The request has been accepted, but will be processed later by the server
NOCONTENT = 204, ///< Sent when the server didn't send any data in return
// 3xx: redirection
MULTIPLECHOICES = 300, ///< The requested page can be accessed from several locations
MOVEDPERMANENTLY = 301, ///< The requested page has permanently moved to a new location
MOVEDTEMPORARILY = 302, ///< The requested page has temporarily moved to a new location
NOTMODIFIED = 304, ///< For conditionnal requests, means the requested page hasn't changed and doesn't need to be refreshed
// 4xx: client error
BADREQUEST = 400, ///< The server couldn't understand the request (syntax error)
UNAUTHORIZED = 401, ///< The requested page needs an authentification to be accessed
FORBIDDEN = 403, ///< The requested page cannot be accessed at all, even with authentification
NOTFOUND = 404, ///< The requested page doesn't exist
// 5xx: server error
INTERNALSERVERERROR = 500, ///< The server encountered an unexpected error
NOTIMPLEMENTED = 501, ///< The server doesn't implement a requested feature
BADGATEWAY = 502, ///< The gateway server has received an error from the source server
SERVICENOTAVAILABLE = 503, ///< The server is temporarily unavailable (overloaded, in maintenance, ...)
// 10xx: SFML custom codes
INVALIDRESPONSE = 1000, ///< Response is not a valid HTTP one
CONNECTIONFAILED = 1001 ///< Connection with server failed
}
/**
* This class provides methods for manipulating the HTTP protocol (described in
* RFC 1945).
* It can connect to a website, get files, send requests
*/
class Http : DSFMLObject
{
/**
* Wrapper for a http request, which is basically :
* - a header with a method, a target URI and a set of field/value pairs
* - an optional body (for POST requests)
*/
static class Response : DSFMLObject
{
override void dispose()
{
sfHttpResponse_Destroy(m_ptr);
}
/**
* Get the value of a field
*
* Params:
* field = Name of the field to get (case-insensitive)
* Returns:
* Value of the field, or enpty string if not found
*/
string getField(string field)
{
return fromStringz(sfHttpResponse_GetField(m_ptr, toStringz(field)));
}
/**
* Get the header status code
*
* Returns:
* header status code
*/
HttpStatus getStatus()
{
return sfHttpResponse_GetStatus(m_ptr);
}
/**
* Get the major HTTP version number of the response
*
* Returns:
* Major version number
*/
uint getMajorHTTPVersion()
{
return sfHttpResponse_GetMajorVersion(m_ptr);
}
/**
* Get the minor HTTP version number of the response
*
* Returns:
* Minor version number
*/
uint getMinorHTTPVersion()
{
return sfHttpResponse_GetMinorVersion(m_ptr);
}
/**
* Get the body of the response. The body can contain :
* - the requested page (for GET requests)
* - a response from the server (for POST requests)
* - nothing (for HEAD requests)
* - an error message (in case of an error)
*
* Returns:
* the response body
*/
string getBody()
{
return fromStringz(sfHttpResponse_GetBody(m_ptr));
}
private:
this(SFMLClass ptr)
{
super(ptr);
}
// External ================================================================
extern (C)
{
typedef void function(SFMLClass) pf_sfHttpResponse_Destroy;
typedef ichar* function(SFMLClass, cchar*) pf_sfHttpResponse_GetField;
typedef HttpStatus function(SFMLClass) pf_sfHttpResponse_GetStatus;
typedef uint function(SFMLClass) pf_sfHttpResponse_GetMajorVersion;
typedef uint function(SFMLClass) pf_sfHttpResponse_GetMinorVersion;
typedef ichar* function(SFMLClass) pf_sfHttpResponse_GetBody;
static pf_sfHttpResponse_Destroy sfHttpResponse_Destroy;
static pf_sfHttpResponse_GetField sfHttpResponse_GetField;
static pf_sfHttpResponse_GetStatus sfHttpResponse_GetStatus;
static pf_sfHttpResponse_GetMajorVersion sfHttpResponse_GetMajorVersion;
static pf_sfHttpResponse_GetMinorVersion sfHttpResponse_GetMinorVersion;
static pf_sfHttpResponse_GetBody sfHttpResponse_GetBody;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfHttpResponse_Destroy = cast(pf_sfHttpResponse_Destroy)dll.getSymbol("sfHttpResponse_Destroy");
sfHttpResponse_GetField = cast(pf_sfHttpResponse_GetField)dll.getSymbol("sfHttpResponse_GetField");
sfHttpResponse_GetStatus = cast(pf_sfHttpResponse_GetStatus)dll.getSymbol("sfHttpResponse_GetStatus");
sfHttpResponse_GetMajorVersion = cast(pf_sfHttpResponse_GetMajorVersion)dll.getSymbol("sfHttpResponse_GetMajorVersion");
sfHttpResponse_GetMinorVersion = cast(pf_sfHttpResponse_GetMinorVersion)dll.getSymbol("sfHttpResponse_GetMinorVersion");
sfHttpResponse_GetBody = cast(pf_sfHttpResponse_GetBody)dll.getSymbol("sfHttpResponse_GetBody");
}
}
/**
* Wrapper for a HTTP response which is basically :
* - a header with a status code and a set of field/value pairs
* - a body (the content of the requested resource)
*/
static class Request : DSFMLObject
{
/**
* Constructor
*
* Params:
* requestMethod = Method to use for the request (Get by default)
* uri = Target URI ("/" by default -- index page)
* requestBody = Content of the request's body (empty by default)
*/
this(HttpMethod requestMethod = HttpMethod.GET, string uri = "/", string requestBody = "")
{
super(sfHttpRequest_Create());
sfHttpRequest_SetMethod(m_ptr, requestMethod);
sfHttpRequest_SetUri(m_ptr, toStringz(uri));
sfHttpRequest_SetBody(m_ptr, toStringz(requestBody));
}
/**
* Set the value of a field. Field is created if it doesn't exists.
*
* Params:
* field = name of the field to set (case-insensitive)
* value = value of the field
*/
void setField(string field, string value)
{
sfHttpRequest_SetField(m_ptr, toStringz(field), toStringz(value));
}
/**
* Set the request method.
*
* Params:
* requestMethod = Method to use for the request.
*/
void setMethod(HttpMethod requestMethod)
{
sfHttpRequest_SetMethod(m_ptr, requestMethod);
}
/**
* Set the target URI of the request.
*
* Params:
* uri = URI to request, local to the host.
* Returns:
*/
void setUri(string uri)
{
sfHttpRequest_SetUri(m_ptr, toStringz(uri));
}
/**
* Set the HTTP version of the request.
*
* Params:
* major = Major version number
* minor = Minor version number
*/
void setHttpVersion(uint major, uint minor)
{
sfHttpRequest_SetHttpVersion(m_ptr, major, minor);
}
/**
* Set the body of the request. This parameter is optionnal and make sense
* only for POST requests.
*
* Params:
* requestBody = Content of the request body.
*/
void setBody(string requestBody)
{
sfHttpRequest_SetBody(m_ptr, toStringz(requestBody));
}
private:
// External ================================================================
extern (C)
{
typedef SFMLClass function() pf_sfHttpRequest_Create;
typedef void function(SFMLClass) pf_sfHttpRequest_Destroy;
typedef void function(SFMLClass, cchar*, cchar*) pf_sfHttpRequest_SetField;
typedef void function(SFMLClass, HttpMethod) pf_sfHttpRequest_SetMethod;
typedef void function(SFMLClass, cchar*) pf_sfHttpRequest_SetUri;
typedef void function(SFMLClass, uint, uint) pf_sfHttpRequest_SetHttpVersion;
typedef void function(SFMLClass, cchar*) pf_sfHttpRequest_SetBody;
static pf_sfHttpRequest_Create sfHttpRequest_Create;
static pf_sfHttpRequest_Destroy sfHttpRequest_Destroy;
static pf_sfHttpRequest_SetField sfHttpRequest_SetField;
static pf_sfHttpRequest_SetMethod sfHttpRequest_SetMethod;
static pf_sfHttpRequest_SetUri sfHttpRequest_SetUri;
static pf_sfHttpRequest_SetHttpVersion sfHttpRequest_SetHttpVersion;
static pf_sfHttpRequest_SetBody sfHttpRequest_SetBody;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfHttpRequest_Create = cast(pf_sfHttpRequest_Create)dll.getSymbol("sfHttpRequest_Create");
sfHttpRequest_Destroy = cast(pf_sfHttpRequest_Destroy)dll.getSymbol("sfHttpRequest_Destroy");
sfHttpRequest_SetField = cast(pf_sfHttpRequest_SetField)dll.getSymbol("sfHttpRequest_SetField");
sfHttpRequest_SetMethod = cast(pf_sfHttpRequest_SetMethod)dll.getSymbol("sfHttpRequest_SetMethod");
sfHttpRequest_SetUri = cast(pf_sfHttpRequest_SetUri)dll.getSymbol("sfHttpRequest_SetUri");
sfHttpRequest_SetHttpVersion = cast(pf_sfHttpRequest_SetHttpVersion)dll.getSymbol("sfHttpRequest_SetHttpVersion");
sfHttpRequest_SetBody = cast(pf_sfHttpRequest_SetBody)dll.getSymbol("sfHttpRequest_SetBody");
}
}
/**
* Constructor
*/
this()
{
super(sfHttp_Create());
}
/**
* Constructor
*
* Params:
* host = Web server to connect to
* port = port to use for connection (0 by default -- use the standard port of the protocol)
*/
this(string host, ushort port = 0)
{
super(sfHttp_Create());
sfHttp_SetHost(m_ptr, toStringz(host), port);
}
override void dispose()
{
sfHttp_Destroy(m_ptr);
}
/**
* Set the target host.
*
* Params:
* host = Web server to connect to
* port = port to use for connection (0 by default -- use the standard port of the protocol)
*/
void setHost(string host, ushort port = 0)
{
sfHttp_SetHost(m_ptr, toStringz(host), port);
}
/**
* Send a HTTP request and return the server's response.
* You must be connected to a host before sending requests.
* Any missing mandatory header field 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.
*
* Params:
* req = Request to send
*
* Returns:
* Server's response
*/
Response sendRequest(Request req)
{
return new Response( sfHttp_SendRequest(m_ptr, req.nativePointer) );
}
private:
// External ====================================================================
extern (C)
{
typedef SFMLClass function() pf_sfHttp_Create;
typedef void function(SFMLClass) pf_sfHttp_Destroy;
typedef void function(SFMLClass, cchar*, ushort) pf_sfHttp_SetHost;
typedef SFMLClass function(SFMLClass, SFMLClass) pf_sfHttp_SendRequest;
static pf_sfHttp_Create sfHttp_Create;
static pf_sfHttp_Destroy sfHttp_Destroy;
static pf_sfHttp_SetHost sfHttp_SetHost;
static pf_sfHttp_SendRequest sfHttp_SendRequest;
}
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-network-d");
else
DllLoader dll = DllLoader.load("csfml-network");
sfHttp_Create = cast(pf_sfHttp_Create)dll.getSymbol("sfHttp_Create");
sfHttp_Destroy = cast(pf_sfHttp_Destroy)dll.getSymbol("sfHttp_Destroy");
sfHttp_SetHost = cast(pf_sfHttp_SetHost)dll.getSymbol("sfHttp_SetHost");
sfHttp_SendRequest = cast(pf_sfHttp_SendRequest)dll.getSymbol("sfHttp_SendRequest");
}
}

View file

@ -0,0 +1,148 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.network.ipaddress;
import dsfml.system.common;
import dsfml.system.stringutil;
/**
* IPAddress provides easy manipulation of IP v4 addresses
*/
struct IPAddress
{
byte[16] Address;
/**
* Construct the address from a string
*
* Params:
* address = IP address ("xxx.xxx.xxx.xxx") or network name
*
*/
static opCall(string address)
{
return sfIpAddress_FromString(toStringz(address));
}
/**
* Construct the address from 4 bytes
*
* Params:
* byte0 = First byte of the address
* byte1 = Second byte of the address
* byte2 = Third byte of the address
* byte3 = Fourth byte of the address
*
*/
static opCall(ubyte byte0, ubyte byte1, ubyte byte2, ubyte byte3)
{
return sfIpAddress_FromBytes(byte0, byte1, byte2, byte3);
}
/**
* Construct the address from a 32 bits integer
*
* Params:
* address = 4 bytes of the address packed into a 32 bits integer
*
*/
static opCall(uint address)
{
return sfIpAddress_FromInteger(address);
}
/**
* Get the empty/invalid address
*
* Returns:
* Empty object that represents invalid addresses
*/
static IPAddress None()
{
return sfIpAddress_None();
}
@property
{
/**
* Get the computer's local IP address (from the LAN point of view)
*
* Returns:
* Local IP address
*
*/
static IPAddress localAddress()
{
return sfIpAddress_GetLocalAddress();
}
/**
* Get the computer's public IP address (from the web point of view).
* The only way to get a public address is to ask it to a
* distant website ; as a consequence, this function may be
* very slow -- use it as few as possible !
*
* Returns:
* Public IP address
*
*/
static IPAddress publicAddress()
{
return sfIpAddress_GetPublicAddress();
}
/**
* Local host address (to connect to the same computer).
*/
static IPAddress localHost()
{
return sfIpAddress_LocalHost();
}
}
const bool opEquals(ref const(IPAddress) other)
{
return Address == other.Address;
}
}
private:
static extern(C)
{
IPAddress function(cchar*) sfIpAddress_FromString;
IPAddress function(ubyte, ubyte, ubyte, ubyte)sfIpAddress_FromBytes;
IPAddress function(uint) sfIpAddress_FromInteger;
IPAddress function() sfIpAddress_None;
IPAddress function() sfIpAddress_GetLocalAddress;
IPAddress function() sfIpAddress_GetPublicAddress;
IPAddress function() sfIpAddress_LocalHost;
}
mixin(loadFromSharedLib2("csfml-network", "sfIpAddress",
"FromBytes", "FromString", "FromInteger", "GetLocalAddress", "GetPublicAddress", "None", "LocalHost"));

View file

@ -0,0 +1,417 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.network.packet;
import dsfml.system.common;
import dsfml.system.stringutil;
/**
* Packet wraps data to send / to receive through the network
*
* The order of insertion and extraction must be the same.
*
* You can derive from Packet and override onSend and onReceive to do custom operations before send or after reception.
*
* Litterals integer are promoted to int.
* Litterals floating point are promoted to float.
*
* Extraction or insertion can be specified with explicit template.
* Examples:
* ------------------------------------------------------------
* Packet p = new Packet();
*
* int i = 32, j = 42;
* string k = hello;
*
* p.set(i, k, j); //Set the data in the packet
*
* int a, b;
* string c;
* p.get(a, c, b); //Get data from the packet
*
* //...
*
* Packet p = new Packet();
* p.set!(byte)(5); // Litteral are inserted with byte type
* ------------------------------------------------------------
*
* See_Also:
* $(LINK2 http://www.digitalmars.com/d/1.0/lex.html, D litterals Specification) for more informations.
*/
class Packet : DSFMLObject
{
/**
* Default constructor
*
*/
this()
{
super(sfPacket_Create());
}
override void dispose()
{
sfPacket_Destroy(m_ptr);
}
/**
* Append data to the end of the packet.
*
* Params:
* data = Array of data to append
*
*/
void append(byte[] data)
{
if (data !is null)
sfPacket_Append(m_ptr, data.ptr, data.length);
}
/**
* Clear the packet data
*
*/
void clear()
{
sfPacket_Clear(m_ptr);
}
/**
* Get an array to the data contained in the packet
* $(B the returned array may be invalid after you
* append data to the packet)
*
* Returns:
* array of data
*
* Remarks:
* return an array of $(B all) data in the packet.
*
* ----------
* Packet p = new Packet();
*
* string str1 = "Hi";
* string str2 = "Hello";
*
* p.set(str1, str2);
*
* // Retrieve str1 from packet
* string str3;
* p.get(str3);
*
* // Returns an array containing str1 and str2.
* byte[] ptr = p.getData();
* ----------
*/
byte[] getData()
{
if (canRead)
return sfPacket_GetData(m_ptr)[0..getDataSize()];
else
return null;
}
/**
* Get the size of the data contained in the packet
*
* Returns:
* Data size, in bytes
*/
uint getDataSize()
{
return sfPacket_GetDataSize(m_ptr);
}
/**
* Tell if the reading position has reached the end of the packet
*
* Returns:
* true if all data have been read.
*/
bool endOfPacket()
{
return cast(bool)sfPacket_EndOfPacket(m_ptr);
}
/**
* Tell if the packet is valid for reading
*
* Returns:
* True if data can be extracted from the packet
*
*/
bool canRead()
{
return cast(bool)sfPacket_CanRead(m_ptr);
}
/**
* Add new variables to the packet
* Accept (u)byte, (u)short, (u)int, float, double, string and wstring types
*/
Packet set(T...)(T t)
{
foreach (v; t)
internalSet(t);
return this;
}
/**
* Retrieve data from the packet
* Accept (u)byte, (u)short, (u)int, float, double, string and wstring types
*/
Packet get(T...)(ref T t)
{
foreach (v; t)
internalGet(t);
return this;
}
/**
* Called before packet is send
*
* Params:
* size = Variable to fill with the size of the data to send
* Returns:
* Array of byte to send
*/
byte[] onSend()
{
return getData();
}
/**
* Called after a packet has been received
*
* Params:
* data = Array of byte received
*/
void onReceive(byte[] data)
{
append(data);
}
private:
void internalGet(ref bool data)
{
data = cast(bool)sfPacket_ReadInt32(m_ptr);
}
void internalGet(ref byte data)
{
data = sfPacket_ReadInt8(m_ptr);
}
void internalGet(ref ubyte data)
{
data = sfPacket_ReadUint8(m_ptr);
}
void internalGet(ref short data)
{
data = sfPacket_ReadInt16(m_ptr);
}
void internalGet(ref ushort data)
{
data = sfPacket_ReadUint16(m_ptr);
}
void internalGet(ref int data)
{
data = sfPacket_ReadInt32(m_ptr);
}
void internalGet(ref uint data)
{
data = sfPacket_ReadUint32(m_ptr);
}
void internalGet(ref float data)
{
data = sfPacket_ReadFloat(m_ptr);
}
void internalGet(ref double data)
{
data = sfPacket_ReadDouble(m_ptr);
}
void internalGet(ref string data)
{
scope char[] temp = new char[sfPacket_GetDataSize(m_ptr)];
sfPacket_ReadString(m_ptr, temp.ptr);
size_t l = fromStringz(temp.ptr).length;
data = cast(string) temp[0 .. l];
}
void internalGet(ref wstring data)
{
scope wchar[] temp = new wchar[sfPacket_GetDataSize(m_ptr)];
sfPacket_ReadWideString(m_ptr, temp.ptr);
size_t l = fromStringz(temp.ptr).length;
data = cast(wstring) temp[0 .. l];
}
void internalSet(bool data)
{
sfPacket_WriteInt32(m_ptr, cast(int)data);
}
void internalSet(byte data)
{
sfPacket_WriteInt8(m_ptr, data);
}
void internalSet(ubyte data)
{
sfPacket_WriteUint8(m_ptr, data);
}
void internalSet(short data)
{
sfPacket_WriteInt16(m_ptr, data);
}
void internalSet(ushort data)
{
sfPacket_WriteUint16(m_ptr, data);
}
void internalSet(int data)
{
sfPacket_WriteInt32(m_ptr, data);
}
void internalSet(uint data)
{
sfPacket_WriteUint32(m_ptr, data);
}
void internalSet(float data)
{
sfPacket_WriteFloat(m_ptr, data);
}
void internalSet(double data)
{
sfPacket_WriteDouble(m_ptr, data);
}
void internalSet(string data)
{
sfPacket_WriteString(m_ptr, toStringz(data));
}
void internalSet(wstring data)
{
sfPacket_WriteWideString(m_ptr, toStringz(data));
}
// External ====================================================================
extern (C)
{
typedef SFMLClass function() pf_sfPacket_Create;
typedef void function(SFMLClass) pf_sfPacket_Destroy;
typedef void function(SFMLClass, const(void)*, size_t) pf_sfPacket_Append;
typedef void function(SFMLClass) pf_sfPacket_Clear;
typedef byte* function(SFMLClass) pf_sfPacket_GetData;
typedef uint function(SFMLClass) pf_sfPacket_GetDataSize;
typedef int function(SFMLClass) pf_sfPacket_EndOfPacket;
typedef int function(SFMLClass) pf_sfPacket_CanRead;
typedef byte function(SFMLClass) pf_sfPacket_ReadInt8;
typedef ubyte function(SFMLClass) pf_sfPacket_ReadUint8;
typedef short function(SFMLClass) pf_sfPacket_ReadInt16;
typedef ushort function(SFMLClass) pf_sfPacket_ReadUint16;
typedef int function(SFMLClass) pf_sfPacket_ReadInt32;
typedef uint function(SFMLClass) pf_sfPacket_ReadUint32;
typedef float function(SFMLClass) pf_sfPacket_ReadFloat;
typedef double function(SFMLClass) pf_sfPacket_ReadDouble;
typedef void function(SFMLClass, char*) pf_sfPacket_ReadString;
typedef void function(SFMLClass, wchar*) pf_sfPacket_ReadWideString;
typedef void function(SFMLClass, byte) pf_sfPacket_WriteInt8;
typedef void function(SFMLClass, ubyte) pf_sfPacket_WriteUint8;
typedef void function(SFMLClass, short) pf_sfPacket_WriteInt16;
typedef void function(SFMLClass, ushort) pf_sfPacket_WriteUint16;
typedef void function(SFMLClass, int) pf_sfPacket_WriteInt32;
typedef void function(SFMLClass, uint) pf_sfPacket_WriteUint32;
typedef void function(SFMLClass, float) pf_sfPacket_WriteFloat;
typedef void function(SFMLClass, double) pf_sfPacket_WriteDouble;
typedef void function(SFMLClass, cchar*) pf_sfPacket_WriteString;
typedef void function(SFMLClass, cwchar*) pf_sfPacket_WriteWideString;
static pf_sfPacket_Create sfPacket_Create;
static pf_sfPacket_Destroy sfPacket_Destroy;
static pf_sfPacket_Append sfPacket_Append;
static pf_sfPacket_Clear sfPacket_Clear;
static pf_sfPacket_GetData sfPacket_GetData;
static pf_sfPacket_GetDataSize sfPacket_GetDataSize;
static pf_sfPacket_EndOfPacket sfPacket_EndOfPacket;
static pf_sfPacket_CanRead sfPacket_CanRead;
static pf_sfPacket_ReadInt8 sfPacket_ReadInt8;
static pf_sfPacket_ReadUint8 sfPacket_ReadUint8;
static pf_sfPacket_ReadInt16 sfPacket_ReadInt16;
static pf_sfPacket_ReadUint16 sfPacket_ReadUint16;
static pf_sfPacket_ReadInt32 sfPacket_ReadInt32;
static pf_sfPacket_ReadUint32 sfPacket_ReadUint32;
static pf_sfPacket_ReadFloat sfPacket_ReadFloat;
static pf_sfPacket_ReadDouble sfPacket_ReadDouble;
static pf_sfPacket_ReadString sfPacket_ReadString;
static pf_sfPacket_ReadWideString sfPacket_ReadWideString;
static pf_sfPacket_WriteInt8 sfPacket_WriteInt8;
static pf_sfPacket_WriteUint8 sfPacket_WriteUint8;
static pf_sfPacket_WriteInt16 sfPacket_WriteInt16;
static pf_sfPacket_WriteUint16 sfPacket_WriteUint16;
static pf_sfPacket_WriteInt32 sfPacket_WriteInt32;
static pf_sfPacket_WriteUint32 sfPacket_WriteUint32;
static pf_sfPacket_WriteFloat sfPacket_WriteFloat;
static pf_sfPacket_WriteDouble sfPacket_WriteDouble;
static pf_sfPacket_WriteString sfPacket_WriteString;
static pf_sfPacket_WriteWideString sfPacket_WriteWideString;
}
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-network-d");
else
DllLoader dll = DllLoader.load("csfml-network");
sfPacket_Append = cast(pf_sfPacket_Append)dll.getSymbol("sfPacket_Append");
sfPacket_CanRead = cast(pf_sfPacket_CanRead)dll.getSymbol("sfPacket_CanRead");
sfPacket_Clear = cast(pf_sfPacket_Clear)dll.getSymbol("sfPacket_Clear");
sfPacket_Create = cast(pf_sfPacket_Create)dll.getSymbol("sfPacket_Create");
sfPacket_Destroy = cast(pf_sfPacket_Destroy)dll.getSymbol("sfPacket_Destroy");
sfPacket_EndOfPacket = cast(pf_sfPacket_EndOfPacket)dll.getSymbol("sfPacket_EndOfPacket");
sfPacket_GetData = cast(pf_sfPacket_GetData)dll.getSymbol("sfPacket_GetData");
sfPacket_GetDataSize = cast(pf_sfPacket_GetDataSize)dll.getSymbol("sfPacket_GetDataSize");
sfPacket_ReadDouble = cast(pf_sfPacket_ReadDouble)dll.getSymbol("sfPacket_ReadDouble");
sfPacket_ReadFloat = cast(pf_sfPacket_ReadFloat)dll.getSymbol("sfPacket_ReadFloat");
sfPacket_ReadInt16 = cast(pf_sfPacket_ReadInt16)dll.getSymbol("sfPacket_ReadInt16");
sfPacket_ReadInt32 = cast(pf_sfPacket_ReadInt32)dll.getSymbol("sfPacket_ReadInt32");
sfPacket_ReadInt8 = cast(pf_sfPacket_ReadInt8)dll.getSymbol("sfPacket_ReadInt8");
sfPacket_ReadString = cast(pf_sfPacket_ReadString)dll.getSymbol("sfPacket_ReadString");
sfPacket_ReadWideString = cast(pf_sfPacket_ReadWideString)dll.getSymbol("sfPacket_ReadWideString");
sfPacket_ReadUint16 = cast(pf_sfPacket_ReadUint16)dll.getSymbol("sfPacket_ReadUint16");
sfPacket_ReadUint32 = cast(pf_sfPacket_ReadUint32)dll.getSymbol("sfPacket_ReadUint32");
sfPacket_ReadUint8 = cast(pf_sfPacket_ReadUint8)dll.getSymbol("sfPacket_ReadUint8");
sfPacket_WriteDouble = cast(pf_sfPacket_WriteDouble)dll.getSymbol("sfPacket_WriteDouble");
sfPacket_WriteFloat = cast(pf_sfPacket_WriteFloat)dll.getSymbol("sfPacket_WriteFloat");
sfPacket_WriteInt16 = cast(pf_sfPacket_WriteInt16)dll.getSymbol("sfPacket_WriteInt16");
sfPacket_WriteInt32 = cast(pf_sfPacket_WriteInt32)dll.getSymbol("sfPacket_WriteInt32");
sfPacket_WriteInt8 = cast(pf_sfPacket_WriteInt8)dll.getSymbol("sfPacket_WriteInt8");
sfPacket_WriteString = cast(pf_sfPacket_WriteString)dll.getSymbol("sfPacket_WriteString");
sfPacket_WriteWideString = cast(pf_sfPacket_WriteWideString)dll.getSymbol("sfPacket_WriteWideString");
sfPacket_WriteUint16 = cast(pf_sfPacket_WriteUint16)dll.getSymbol("sfPacket_WriteUint16");
sfPacket_WriteUint32 = cast(pf_sfPacket_WriteUint32)dll.getSymbol("sfPacket_WriteUint32");
sfPacket_WriteUint8 = cast(pf_sfPacket_WriteUint8)dll.getSymbol("sfPacket_WriteUint8");
}
}

View file

@ -0,0 +1,153 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.network.socketselector;
import dsfml.network.tcpsocket;
import dsfml.network.udpsocket;
import dsfml.system.common;
/**
* Multiplexer that allows to read from multiple sockets
*/
class SocketSelector : DSFMLObject
{
/**
* Default constructor
*/
this()
{
super(sfSocketSelector_Create());
}
override void dispose()
{
sfSocketSelector_Destroy(m_ptr);
}
/**
* Add a socket to watch
*
* Params:
* socket = A tcp or udp socket
*/
void add(T socket)
{
if (!(socket.nativePointer in m_watchedSockets))
{
sfSocketSelector_Add(m_ptr, socket.nativePointer);
m_watchedSockets[socket.nativePointer] = socket;
m_numSocketsWatched++;
}
}
/**
* Remove a previously added socket
*
* Params:
* socket = A tcp or udp socket
*/
void remove(T socket)
{
if (socket.nativePointer in m_watchedSockets)
{
sfSocketSelector_Remove(m_ptr, socket.nativePointer);
m_watchedSockets.remove(socket.nativePointer);
m_numSocketsWatched--;
}
}
/**
* Clear all sockets being watched
*/
void clear()
{
sfSocketSelector_Clear(m_ptr);
foreach(key; m_watchedSockets.keys)
m_watchedSockets.remove(key);
m_numSocketsWatched = 0;
}
/**
* Wait and collect sockets which are ready for reading.
* This functions will return either when at least one socket
* is ready, or when the given time is out
*
* Params:
* timeout = Maximum time to wait, in seconds (0 to disable timeout)
*
* Returns:
* Number of sockets ready
*/
uint wait(float timeout = 0.f)
{
return sfSocketSelector_Wait(m_ptr, timeout);
}
/**
* After a call to Wait(), get the Index-th socket which is
* ready for reading. The total number of sockets ready
* is the integer returned by the previous call to Wait()
*
* Params:
* index = Index of the socket to get
*
* Returns:
* The Index-th socket
*/
T GetSocketsReady(uint index)
{
return m_watchedSockets[sfSocketSelector_GetSocketReady(m_ptr, index)];
}
private:
// size_t m_numSocketsWatched;
// T[void*] m_watchedSockets;
// External ====================================================================
static extern(C)
{
SFMLClass function() sfSocketSelector_Create;
void function(SFMLClass) sfSocketSelector_Destroy;
void function(SFMLClass, SFMLClass) sfSocketSelector_AddTcpListener;
void function(SFMLClass, SFMLClass) sfSocketSelector_AddTcpSocket;
void function(SFMLClass, SFMLClass) sfSocketSelector_AddUdpSocket;
void function(SFMLClass, SFMLClass) sfSocketSelector_RemoveTcpListener;
void function(SFMLClass, SFMLClass) sfSocketSelector_RemoveTcpSocket;
void function(SFMLClass, SFMLClass) sfSocketSelector_RemoveUdpSocket;
void function(SFMLClass) sfSocketSelector_Clear;
bool function(SFMLClass, float) sfSocketSelector_Wait;
bool function(SFMLClass, SFMLClass) sfSocketSelector_IsTcpListenerReady;
bool function(SFMLClass, SFMLClass) sfSocketSelector_IsTcpSocketReady;
bool function(SFMLClass, SFMLClass) sfSocketSelector_IsUdpSocketReady;
}
mixin(loadFromSharedLib2("csfml-network", "sfSocketSelector",
"Create", "Destroy", "AddTcpListener", "AddTcpSocket", "AddUdpSocket", "RemoveTcpListener", "RemoveTcpSocket", "RemoveUdpSocket",
"Clear", "Wait", "IsTcpListenerReady", "IsTcpSocketReady", "IsUdpSocketReady"));
}

View file

@ -0,0 +1,38 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.network.socketstatus;
/**
* Enumeration of status returned by socket functions
*/
enum SocketStatus
{
DONE, ///
NOTREADY, ///
DISCONNECTED, ///
UNEXPECTEDERROR ///
}

View file

@ -0,0 +1,49 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.network.tcplistener;
import dsfml.network.socketstatus;
import dsfml.system.common;
class TcpListener : DSFMLObject
{
private:
public:
private:
static extern(C)
{
SFMLClass function() sfTcpListener_Create;
void function(SFMLClass) sfTcpListener_Destroy;
void function(SFMLClass, bool) sfTcpListener_SetBlocking;
bool function(SFMLClass) sfTcpListener_IsBlocking;
SocketStatus function(SFMLClass, ushort) sfTcpListener_Listen;
SocketStatus function(SFMLClass, SFMLClass*) sfTcpListener_Accept;
}
mixin(loadFromSharedLib2("csfml-network", "sfTcpListener",
"Create", "Destroy", "SetBlocking", "IsBlocking", "Listen", "Accept"));
}

View file

@ -0,0 +1,273 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.network.tcpsocket;
import dsfml.network.ipaddress;
import dsfml.network.packet;
import dsfml.network.socketstatus;
import dsfml.system.common;
/**
* TcpSocket wraps a socket using TCP protocol to send data safely (but a bit slower)
*/
class TcpSocket : DSFMLObject
{
/**
* Default constructor
*/
this()
{
super(sfTcpSocket_Create());
m_intermediatePacket = new Packet();
}
override void dispose()
{
sfTcpSocket_Destroy(m_ptr);
}
/**
* Connect to another computer on a specified port
*
* Params:
* port = Port to use for transfers (warning : ports < 1024 are reserved)
* hostAddress = IP Address of the host to connect to
* timeout = Maximum time to wait in seconds (0 by default : no timeout)
*
* Returns:
* True if operation has been successful
*/
bool connect(ushort port, IPAddress hostAddress, float timeout = 0.f)
{
return cast(bool) !sfTcpSocket_Connect(m_ptr, port, hostAddress, timeout);
}
/**
* Listen to a specified port for incoming data or connections
*
* Params:
* port = Port to listen to
*
* Returns:
* True if operation has been successful
*/
bool listen(ushort port)
{
return cast(bool)sfTcpSocket_Listen(m_ptr, port);
}
/**
* Wait for a connection (must be listening to a port).
* This function is blocking.
*
* Params:
* connected = Socket containing the connection with the connected client
*
* Returns:
* Status code
*/
SocketStatus accept(TcpSocket connected)
{
SFMLClass temp = null;
SocketStatus ret = sfTcpSocket_Accept(m_ptr, &temp, null);
connected.m_ptr = temp;
return ret;
}
/**
* Wait for a connection (must be listening to a port).
* This function is blocking.
*
* Params:
* connected = Socket containing the connection with the connected client
* address = Pointer to an address to fill with client infos
*
* Returns:
* Status code
*/
SocketStatus accept(TcpSocket connected, out IPAddress address)
{
SFMLClass temp = null;
SocketStatus ret = sfTcpSocket_Accept(m_ptr, &temp, &address);
connected.m_ptr = temp;
return ret;
}
/**
* Send an array of bytes to the host (must be connected first)
*
* Params:
* data = array of bytes to send
*
* Returns:
* Status code
*/
SocketStatus send(byte[] data)
in
{
assert(data && data.length);
}
body
{
return cast(SocketStatus)sfTcpSocket_Send(m_ptr, data.ptr, data.length);
}
/**
* Receive an array of bytes from the host (must be connected first).
* This function will block until a connection was accepted
*
* Params:
* data = array to fill (make sure it is big enough)
* sizeReceived = Number of bytes received
*
* Returns:
* Status code
*
* Remarks:
* Assert if data is null or length == 0
*
*/
SocketStatus receive(byte[] data, out size_t sizeReceived)
in
{
assert(data && data.length);
}
body
{
return cast(SocketStatus)sfTcpSocket_Receive(m_ptr, data.ptr, data.length, &sizeReceived);
}
/**
* Send a packet of data to the host (must be connected first)
*
* Params:
* packetToSend = Packet to send
*
* Returns:
* Status code
*
*/
SocketStatus send(Packet packetToSend)
{
byte[] dataArray = packetToSend.onSend();
m_intermediatePacket.append(dataArray);
SocketStatus stat = cast(SocketStatus)sfTcpSocket_SendPacket(m_ptr, m_intermediatePacket.nativePointer);
m_intermediatePacket.clear();
return stat;
}
/**
* Receive a packet from the host (must be connected first).
* This function will block if the socket is blocking
*
* Params:
* packetToReceive = Packet to fill with received data
*
* Returns:
* Status code
*
*/
SocketStatus receive(Packet packetToReceive)
{
SocketStatus stat = cast(SocketStatus)sfTcpSocket_ReceivePacket(m_ptr, m_intermediatePacket.nativePointer);
packetToReceive.onReceive(m_intermediatePacket.getData);
m_intermediatePacket.clear();
return stat;
}
/**
* Check if the socket is in a valid state ; this function
* can be called any time to check if the socket is OK
*
* Returns:
* True if the socket is valid
*
*/
bool isValid()
{
return cast(bool)sfTcpSocket_IsValid(m_ptr);
}
package:
this (SFMLClass ptr)
{
super(ptr);
m_intermediatePacket = new Packet();
}
private:
Packet m_intermediatePacket;
// External ====================================================================
extern (C)
{
typedef SFMLClass function() pf_sfTcpSocket_Create;
typedef void function(SFMLClass) pf_sfTcpSocket_Destroy;
typedef int function(SFMLClass, ushort, IPAddress, float) pf_sfTcpSocket_Connect;
typedef int function(SFMLClass, ushort) pf_sfTcpSocket_Listen;
typedef SocketStatus function(SFMLClass, SFMLClass*, IPAddress*) pf_sfTcpSocket_Accept;
typedef SocketStatus function(SFMLClass, const(byte)*, size_t) pf_sfTcpSocket_Send;
typedef SocketStatus function(SFMLClass, byte*, size_t, size_t*) pf_sfTcpSocket_Receive;
typedef SocketStatus function(SFMLClass, SFMLClass) pf_sfTcpSocket_SendPacket;
typedef SocketStatus function(SFMLClass, SFMLClass) pf_sfTcpSocket_ReceivePacket;
typedef int function(SFMLClass) pf_sfTcpSocket_IsValid;
static pf_sfTcpSocket_Create sfTcpSocket_Create;
static pf_sfTcpSocket_Destroy sfTcpSocket_Destroy;
static pf_sfTcpSocket_Connect sfTcpSocket_Connect;
static pf_sfTcpSocket_Listen sfTcpSocket_Listen;
static pf_sfTcpSocket_Accept sfTcpSocket_Accept;
static pf_sfTcpSocket_Send sfTcpSocket_Send;
static pf_sfTcpSocket_Receive sfTcpSocket_Receive;
static pf_sfTcpSocket_SendPacket sfTcpSocket_SendPacket;
static pf_sfTcpSocket_ReceivePacket sfTcpSocket_ReceivePacket;
static pf_sfTcpSocket_IsValid sfTcpSocket_IsValid;
}
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-network-d");
else
DllLoader dll = DllLoader.load("csfml-network");
sfTcpSocket_Accept = cast(pf_sfTcpSocket_Accept)dll.getSymbol("sfTcpSocket_Accept");
sfTcpSocket_Connect = cast(pf_sfTcpSocket_Connect)dll.getSymbol("sfTcpSocket_Connect");
sfTcpSocket_Create = cast(pf_sfTcpSocket_Create)dll.getSymbol("sfTcpSocket_Create");
sfTcpSocket_Destroy = cast(pf_sfTcpSocket_Destroy)dll.getSymbol("sfTcpSocket_Destroy");
sfTcpSocket_IsValid = cast(pf_sfTcpSocket_IsValid)dll.getSymbol("sfTcpSocket_IsValid");
sfTcpSocket_Listen = cast(pf_sfTcpSocket_Listen)dll.getSymbol("sfTcpSocket_Listen");
sfTcpSocket_Receive = cast(pf_sfTcpSocket_Receive)dll.getSymbol("sfTcpSocket_Receive");
sfTcpSocket_ReceivePacket = cast(pf_sfTcpSocket_ReceivePacket)dll.getSymbol("sfTcpSocket_ReceivePacket");
sfTcpSocket_Send = cast(pf_sfTcpSocket_Send)dll.getSymbol("sfTcpSocket_Send");
sfTcpSocket_SendPacket = cast(pf_sfTcpSocket_SendPacket)dll.getSymbol("sfTcpSocket_SendPacket");
}
}

View file

@ -0,0 +1,241 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.network.udpsocket;
import dsfml.network.ipaddress;
import dsfml.network.packet;
import dsfml.network.socketstatus;
import dsfml.system.common;
/**
* UdpSocket wraps a socket using UDP protocol to
* send data fastly (but with less safety)
*/
class UdpSocket : DSFMLObject
{
/**
* Default constructor
*/
this()
{
super(sfUdpSocket_Create());
m_intermediatePacket = new Packet();
}
override void dispose()
{
sfUdpSocket_Destroy(m_ptr);
}
/**
* Bind the socket to a specific port
*
* Params:
* port = Port to bind the socket to
*
* Returns:
* True if operation has been successful
*
*/
bool bind(ushort port)
{
m_port = port;
return cast(bool)sfUdpSocket_Bind(m_ptr, port);
}
/**
* Unbind the socket from its previous port, if any
*
* Returns: True if operation has been successful
*
*/
bool unbind()
{
m_port = 0;
return cast(bool)sfUdpSocket_Unbind(m_ptr, m_port);
}
/**
* Send an array of bytes
*
* Params:
* data = bytes array to send
* address = Address of the computer to send the packet to
* port = Port to send the data to
*
* Returns:
* Status code
*
*/
SocketStatus send(byte[] data, IPAddress address, ushort port)
{
return cast(SocketStatus) sfUdpSocket_Send(m_ptr, data.ptr, data.length, address, port);
}
/**
* Receive an array of bytes.
* This function is blocking.
*
* Params:
* data = Pointer to a byte array to fill (make sure it is big enough)
* sizeReceived = Number of bytes received
* address = Address of the computer which sent the data
*
* Returns:
* Status code
*
* Remarks:
* Assert if data is null or length == 0
*
*/
SocketStatus receive(byte[] data, out size_t sizeReceived, out IPAddress address)
{
SocketStatus ret = sfUdpSocket_Receive(m_ptr, data.ptr, data.length, &sizeReceived, &address);
return ret;
}
/**
* Send a packet of data
*
* Params:
* packetToSend = Packet to send
* address = Address of the computer to send the packet to
* port = Port to send the data to
*
* Returns:
* Status code
*
*/
SocketStatus send(Packet packetToSend, IPAddress address, ushort port)
{
byte[] dataArray = packetToSend.onSend();
m_intermediatePacket.append(dataArray);
SocketStatus stat = cast(SocketStatus)sfUdpSocket_SendPacket(m_ptr, m_intermediatePacket.nativePointer, address, port);
m_intermediatePacket.clear();
return stat;
}
/**
* Receive a packet.
* This function is blocking.
*
* Params:
* packetToReceive = Packet to fill with received data
* address = Address of the computer which sent the packet
*
* Returns:
* Status code
*
*/
SocketStatus receive(Packet packetToReceive, out IPAddress address)
{
SocketStatus ret = sfUdpSocket_ReceivePacket(m_ptr, m_intermediatePacket.nativePointer, &address);
packetToReceive.onReceive(m_intermediatePacket.getData);
m_intermediatePacket.clear();
return ret;
}
/**
* Check if the socket is in a valid state ; this function
* can be called any time to check if the socket is OK
*
* Returns:
* True if the socket is valid
*
*/
bool isValid()
{
return cast(bool)sfUdpSocket_IsValid(m_ptr);
}
/**
* Get the port the socket is currently bound to
*
* Returns:
* Current port (0 means the socket is not bound)
*/
ushort getPort()
{
return m_port;
}
package:
this (SFMLClass ptr)
{
super(ptr);
m_intermediatePacket = new Packet();
}
private:
Packet m_intermediatePacket;
ushort m_port;
// External ====================================================================
extern (C)
{
typedef SFMLClass function() pf_sfUdpSocket_Create;
typedef void function(SFMLClass) pf_sfUdpSocket_Destroy;
typedef int function(SFMLClass, ushort) pf_sfUdpSocket_Bind;
typedef int function(SFMLClass, ushort) pf_sfUdpSocket_Unbind;
typedef SocketStatus function(SFMLClass, byte*, size_t, IPAddress, ushort) pf_sfUdpSocket_Send;
typedef SocketStatus function(SFMLClass, byte*, size_t, size_t*, IPAddress*) pf_sfUdpSocket_Receive;
typedef SocketStatus function(SFMLClass, SFMLClass, IPAddress, ushort) pf_sfUdpSocket_SendPacket;
typedef SocketStatus function(SFMLClass, SFMLClass, IPAddress*) pf_sfUdpSocket_ReceivePacket;
typedef int function(SFMLClass) pf_sfUdpSocket_IsValid;
static pf_sfUdpSocket_Create sfUdpSocket_Create;
static pf_sfUdpSocket_Destroy sfUdpSocket_Destroy;
static pf_sfUdpSocket_Bind sfUdpSocket_Bind;
static pf_sfUdpSocket_Unbind sfUdpSocket_Unbind;
static pf_sfUdpSocket_Send sfUdpSocket_Send;
static pf_sfUdpSocket_Receive sfUdpSocket_Receive;
static pf_sfUdpSocket_SendPacket sfUdpSocket_SendPacket;
static pf_sfUdpSocket_ReceivePacket sfUdpSocket_ReceivePacket;
static pf_sfUdpSocket_IsValid sfUdpSocket_IsValid;
}
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-network-d");
else
DllLoader dll = DllLoader.load("csfml-network");
sfUdpSocket_Bind = cast(pf_sfUdpSocket_Bind)dll.getSymbol("sfUdpSocket_Bind");
sfUdpSocket_Create = cast(pf_sfUdpSocket_Create)dll.getSymbol("sfUdpSocket_Create");
sfUdpSocket_Destroy = cast(pf_sfUdpSocket_Destroy)dll.getSymbol("sfUdpSocket_Destroy");
sfUdpSocket_IsValid = cast(pf_sfUdpSocket_IsValid)dll.getSymbol("sfUdpSocket_IsValid");
sfUdpSocket_Receive = cast(pf_sfUdpSocket_Receive)dll.getSymbol("sfUdpSocket_Receive");
sfUdpSocket_ReceivePacket = cast(pf_sfUdpSocket_ReceivePacket)dll.getSymbol("sfUdpSocket_ReceivePacket");
sfUdpSocket_Send = cast(pf_sfUdpSocket_Send)dll.getSymbol("sfUdpSocket_Send");
sfUdpSocket_SendPacket = cast(pf_sfUdpSocket_SendPacket)dll.getSymbol("sfUdpSocket_SendPacket");
sfUdpSocket_Unbind = cast(pf_sfUdpSocket_Unbind)dll.getSymbol("sfUdpSocket_Unbind");
}
}

View file

@ -0,0 +1,47 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.system.all;
version (linux)
{
version (build)
{
pragma(link, "dl"); //Link libdl.so (dlopen, dlsym)
}
}
version (darwin)
{
version (build)
{
pragma(link, "dl"); //Link libdl.dylib (dlopen, dlsym)
}
}
public import
dsfml.system.lock,
dsfml.system.vector;

View file

@ -0,0 +1,84 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.system.alloc;
version (Tango)
{
public import tango.core.Memory;
}
else
{
public import core.memory;
}
/*
struct GC
{
static void* malloc(uint size)
{
return std.c.stdlib.malloc(size);
}
static void free(void* ptr)
{
std.c.stdlib.free(ptr);
}
static void addRange(void* ptr, uint size)
{
std.gc.addRange(ptr, ptr + size);
}
static void removeRange(void* ptr)
{
std.gc.removeRange(ptr);
}
}
*/
/*
* Template for native non-GCed allocation for interaction between C and D threads.
*/
template Alloc()
{
new (size_t size)
{
void* p = GC.malloc(size);
if (!p)
assert(0, "Memory allocation failed");
GC.addRange(p, size);
return p;
}
delete(void* p)
{
GC.removeRange(p);
GC.free(p);
}
}

View file

@ -0,0 +1,141 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.system.common;
public import dsfml.system.dllloader;
// type aliases for D2
package
{
alias const(char) cchar;
alias const(wchar) cwchar;
alias const(dchar) cdchar;
alias immutable(char) ichar;
alias immutable(wchar) iwchar;
alias immutable(dchar) idchar;
alias const(char)[] cstring;
// alias immutable(void) ivoid;
alias const(void) cvoid;
typedef immutable(void)* SFMLClass;
}
// used to mixin code function
string loadFromSharedLib(string fname)
{
return fname ~ " = " ~ "cast(typeof(" ~ fname ~ ")) dll.getSymbol(\"" ~ fname ~ "\");";
}
//used to mixin code function
string loadFromSharedLib2(S...)(string lib, string className, S fnames)
{
string res = `static this()
{
debug
DllLoader dll = DllLoader.load("` ~ lib ~ `-d");
else
DllLoader dll = DllLoader.load("` ~ lib ~ `");
`;
foreach(fname; fnames)
{
res ~= "\t" ~ className ~ "_" ~ fname ~ " = " ~ "cast(typeof(" ~ className ~ "_" ~ fname ~ ")) dll.getSymbol(\"" ~ className ~ "_" ~ fname ~ "\");\n";
}
return res ~ "}\n";
}
string loadDerivedFromSharedLib(S...)(string lib, string baseClass, string derivedClass, S fnames)
{
string res = `static this()
{
debug
DllLoader dll = DllLoader.load("` ~ lib ~ `-d");
else
DllLoader dll = DllLoader.load("` ~ lib ~ `");
`;
foreach(fname; fnames)
{
res ~= "\t" ~ baseClass ~ "_" ~ fname ~ " = " ~ "cast(typeof(" ~ baseClass ~ "_" ~ fname ~ ")) dll.getSymbol(\"" ~ derivedClass ~ "_" ~ fname ~ "\");\n";
}
return res ~ "}\n";
}
/**
* Base class for all DSFML classes.
*/
class DSFMLObject
{
private:
bool m_preventDelete;
protected:
SFMLClass m_ptr;
abstract void dispose();
public:
/// get the underlying C pointer
@property final SFMLClass nativePointer()
{
return m_ptr;
}
public:
this(SFMLClass ptr, bool preventDelete = false)
{
m_ptr = ptr;
m_preventDelete = preventDelete;
}
~this()
{
if (!m_preventDelete)
dispose();
m_ptr = m_ptr.init;
}
final void setHandled(bool handled)
{
m_preventDelete = handled;
}
override bool opEquals(Object o)
{
return (m_ptr == (cast(DSFMLObject)o).nativePointer);
}
protected invariant()
{
assert(m_ptr !is null, "Problem occurs with a null pointer in " ~ this.toString);
}
}

View file

@ -0,0 +1,238 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.system.dllloader;
import dsfml.system.stringutil;
version (Tango)
{
import tango.io.Console;
import tango.sys.SharedLib;
}
else
{
import std.stdio;
version (Windows)
{
import std.c.windows.windows;
import std.windows.syserror; // for error strings
alias HMODULE MODULEHANDLE;
}
else version (linux)
{
import std.c.linux.linux;
alias void* MODULEHANDLE;
const int RTLD_NOW = 0x00002;
const int RTLD_GLOBAL = 0x00100;
}
else version (darwin)
{
alias void* MODULEHANDLE;
const int RTLD_NOW = 0x2;
const int RTLD_GLOBAL = 0x8;
extern (C)
{
void* dlopen(char* file, int mode);
int dlclose(void* handle);
void* dlsym(void* handle, char* name);
char* dlerror();
}
}
}
static this()
{
version (Tango)
{
SharedLib.throwExceptions = false;
}
}
static ~this()
{
// DllLoader.closeAll();
}
private void report(string msg, string lib, string symb)
{
string str = "Loading error. Reason : " ~ msg ~ " (library : " ~ lib ~ ", symbol : " ~ symb ~ ")";
version (Tango)
{
Cerr(str).newline;
}
else
{
stderr.writeln(str);
}
}
/**
* Simple Dll loader.
*/
class DllLoader
{
static DllLoader load(string library)
{
version (Windows)
{
string libraryName = library ~ ".dll";
}
else version (linux)
{
string libraryName = "lib" ~ library ~ ".so";
}
else version (darwin)
{
string libraryName = "lib" ~ library ~ ".dylib";
}
if (libraryName in alreadyLoaded)
{
return alreadyLoaded[libraryName];
}
else
{
DllLoader temp = new DllLoader(libraryName);
alreadyLoaded[libraryName] = temp;
return temp;
}
}
void* getSymbol(string symbolName)
{
void* symb;
version (Tango)
{
symb = m_lib.getSymbol(toStringz(symbolName));
}
else
{
version (Windows)
{
symb = GetProcAddress(m_lib, toStringz(symbolName));
}
else version (linux)
{
symb = dlsym(m_lib, toStringz(symbolName));
}
else version (darwin)
{
symb = dlsym(m_lib, toStringz(symbolName));
}
}
if (symb is null)
debug report( "Symbol cannot be found in specified library", m_libPath, symbolName);
return symb;
}
void close()
{
version (Tango)
{
m_lib.unload();
}
else
{
version (Windows)
{
FreeLibrary(m_lib);
}
else version (linux)
{
dlclose(m_lib);
}
else version (darwin)
{
dlclose(m_lib);
}
alreadyLoaded.remove(this.m_libPath);
}
}
static void closeAll()
{
foreach(lib; alreadyLoaded.values)
{
lib.close();
}
}
private:
this(string libraryPath)
{
m_libPath = libraryPath;
version (Tango)
{
m_lib = SharedLib.load(libraryPath);
}
else
{
version (Windows)
{
m_lib = LoadLibraryA(toStringz(libraryPath));
}
else version (linux)
{
m_lib = dlopen(toStringz(libraryPath), RTLD_NOW | RTLD_GLOBAL);
}
else version (darwin)
{
m_lib = dlopen(toStringz(libraryPath), RTLD_NOW | RTLD_GLOBAL);
if (m_lib is null)
m_lib = dlopen(toStringz("@executable_path/" ~ libraryPath), RTLD_NOW | RTLD_GLOBAL);
}
}
if (m_lib is null)
{
debug report("Cannot open library", m_libPath, null);
version (Windows)
{
debug report("Windows error message: " ~ sysErrorString(GetLastError()), m_libPath, null);
}
}
}
version (Tango)
{
SharedLib m_lib;
}
else
{
MODULEHANDLE m_lib;
}
static DllLoader[string] alreadyLoaded;
string m_libPath;
}

View file

@ -0,0 +1,43 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.system.exception;
class LoadingException : Exception
{
this(string msg)
{
super(msg);
}
}
class NullParameterException : Exception
{
this(string msg)
{
super(msg);
}
}

View file

@ -0,0 +1,103 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.system.linkedlist;
/*
* Trivial implementation of Queue linked list (for internal use)
*/
class LinkedList(T)
{
Node!(T) head;
Node!(T) tail;
private size_t m_count;
void enqueue(T object)
{
if (empty)
head = tail = new Node!(T)(object);
else
{
tail.Next = new Node!(T)(object);
tail = tail.Next;
}
m_count++;
}
T dequeue()
{
T o;
if (empty)
o = T.init;
else
{
o = head.Data;
head = head.Next;
m_count--;
}
return o;
}
bool empty()
{
return (head is null);
}
size_t getCount()
{
return m_count;
}
void clear()
{
T data;
while ((data = dequeue()) !is T.init) {}
}
int opApply(int delegate(ref T) dg)
{
T data;
int result;
while ((data = dequeue) !is T.init)
{
if ((result = dg(data)) != 0)
break;
}
return result;
}
}
private class Node(T)
{
Node Next;
T Data;
this(T data)
{
Data = data;
}
}

View file

@ -0,0 +1,66 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.system.lock;
import core.sync.mutex;
/**
* Encapsulation of an critical section. Unlocking is guaranteed when the Lock goes out of scope, even on exception.
*
* Remarks:
* Lock is a scope class, you need to mark Lock object as scope :
*
* -----------------
* Mutex m = new Mutex;
* //..
* {
* scope Lock l = new Lock(m);
* // Critical section
* } // End of critical (Destructor called and mutex unlocked)
* //..
*
* -----------------
*/
scope class Lock
{
/**
* Construct the lock and lock the mutex
*/
this(Mutex m)
{
m_mutex = m;
m_mutex.lock();
}
~this()
{
m_mutex.unlock();
}
private:
Mutex m_mutex;
}

View file

@ -0,0 +1,82 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.system.stringutil;
import std.traits; // for Unqual
/*
version (Tango)
{
public import tango.stdc.stringz;
}
else
{
public import std.string;
}
*/
T* toStringz(T)(T[] str)
{
if (str is null)
return null;
else if (str.length && str[$ - 1] is T.init)
return str.ptr;
auto ret = new Unqual!(T)[str.length + 1];
ret[0 .. str.length] = str[0 .. $];
ret[str.length] = 0;
return cast(T*) ret.ptr;
}
size_t stringLength(T)(T* p)
{
if (p is null || *p == T.init)
return 0;
size_t length;
while (*(p + length))
{
length++;
}
return length;
}
T[] fromStringz(T)(T* ptr)
{
auto ret = new Unqual!(T)[stringLength(ptr)];
ret[0..$] = ptr[0..ret.length];
return cast(T[]) ret;
}

View file

@ -0,0 +1,467 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.system.vector;
import std.conv;
import std.math;
import std.traits : isFloatingPoint;
import std.typetuple;
/**
* generic fixed-size Vector struct
*
* Params:
* T = element type
* dim = vector dimension
*/
struct Vector(T, int dim)
{
static assert (dim >= 2 && dim <= 4);
// vectors of 3 floats are extended to 4 to make it possible to use SSE optimizations
private const realdim = (is(T == float) && dim == 3 && sseAvailable) ? 4 : dim;
// vectors of (3)4 floats or 2 doubles will use SSE
private const bool useSSE = (is(T == float) && realdim == 4 /* || is(T == double) && dim == 2 */ ) && sseAvailable;
private alias LengthReturnType!(T) LengthType; // the type returned by length
union
{
/// normal struct element access
struct
{
static if (dim >= 1) T x;
static if (dim >= 2) T y;
static if (dim >= 3) T z;
static if (dim >= 4) T w;
}
struct
{
static if (dim >= 1) T r;
static if (dim >= 2) T g;
static if (dim >= 3) T b;
static if (dim >= 4) T a;
}
// only the array has the hidden 4th value in case of vec3f
// this is to be able to foreach over tuple without computing w unnecessarily
T[realdim] cell; /// array access
Repeat!(T, dim) tuple; /// for tuple access
}
// zero vectors
static if (2 == dim) const static Vector zero = Vector(0, 0);
static if (3 == dim) const static Vector zero = Vector(0, 0, 0);
static if (4 == dim) const static Vector zero = Vector(0, 0, 0, 0);
static if (2 == dim) const static Vector one = Vector(1, 1);
static if (3 == dim) const static Vector one = Vector(1, 1, 1);
static if (4 == dim) const static Vector one = Vector(1, 1, 1, 1);
static if (2 == dim) const static Vector unitX = Vector(1, 0);
static if (3 == dim) const static Vector unitX = Vector(1, 0, 0);
static if (4 == dim) const static Vector unitX = Vector(1, 0, 0, 0);
static if (2 == dim) const static Vector unitY = Vector(0, 1);
static if (3 == dim) const static Vector unitY = Vector(0, 1, 0);
static if (4 == dim) const static Vector unitY = Vector(0, 1, 0, 0);
static if (3 == dim) const static Vector unitZ = Vector(0, 0, 1);
static if (4 == dim) const static Vector unitZ = Vector(0, 0, 1, 0);
static if (4 == dim) const static Vector unitW = Vector(0, 0, 0, 1);
/// ensure that no component is a NaN
invariant()
{
assert(isValid());
}
// checks if the elements aren't NaNs
private bool isValid() const
{
static if (dim >= 1) if (isNaN(x)) return false;
static if (dim >= 2) if (isNaN(y)) return false;
static if (dim >= 3) if (isNaN(z)) return false;
static if (dim >= 4) if (isNaN(w)) return false;
return true;
}
/************************************************************************************
* Operator overloading
***********************************************************************************/
/// negate the vector
Vector opUnary(string op : "-")()
{
static if (dim == 2) return Vector(-x, -y);
else static if (dim == 3) return Vector(-x, -y, -z);
else static if (dim == 4) return Vector(-x, -y, -z, -w);
}
/// dot product
T opBinary(string op : "*")(typeof(this) v)
if (is(typeof(T+T)) && is(typeof(T*T)))
{
static if (dim == 2) return x*v.x + y*v.y;
else static if (dim == 3) return x*v.x + y*v.y + z*v.z;
else static if (dim == 4) return x*v.x + y*v.y + z*v.z + w*v.w;
}
/// element-wise operations, +, -,
Vector opBinary(string op, U:typeof(this))(U v)
// check if the operation is supported on the type T
if (op != "*" && (op == "+" && is(typeof(T+T)) || op == "-" && is(typeof(T-T)) || op == "*" && is(typeof(T*T))
|| op == "/" && is(typeof(T/T)) || op == "%" && is(typeof(T%T))))
{
Vector res = void;
foreach (i, x; tuple)
mixin("res.tuple[i] = tuple[i] " ~ op ~ " v.tuple[i];");
return res;
}
/// operations with a scalar
// TODO: make this usable with arbitrary scalars (not only Vector element type T), including necessary checks etc.
typeof(this) opBinary(string op)(T s)
{
Vector res = void;
foreach(i, x; tuple)
mixin("res.tuple[i] = tuple[i] " ~ op ~ " s;");
return res;
}
/// element-wise assign operations, +=, -=, ...
Vector opOpAssign(string op, U:Vector)(U v)
{
foreach (i, _; tuple)
mixin("tuple[i] " ~ op ~ "= v.tuple[i];");
return this;
}
/// (*=) overload
Vector opOpAssign(string op)(T s)
{
foreach (i, _; tuple)
mixin("tuple[i] " ~ op ~ "= s;");
return this;
}
/// return length*length
@property LengthType sqLength()
{
static if (2 == dim) return (x * x + y * y);
else static if (3 == dim) return (x * x + y * y + z * z);
else static if (4 == dim) return (x * x + y * y + z * z + w * w);
else static assert (false);
}
/// return the vector length
@property LengthType length()
{
static if (useSSE)
{
static if (is(t == float) && dim == 3) // make sure that w is 0
assert(w == 0);
float res;
auto p = cell.ptr;
asm
{
// movups XMM0, &cell;
mov EAX, p;
movups XMM0, [EAX];
mulps XMM0, XMM0; // v0 = vec(x*x, y*y, z*z, w*w)
movaps XMM1, XMM0; // v1 = v0
shufps XMM0, XMM1, 0x4e; // v0 = vec(z*z, w*w, x*x, y*y)
addps XMM0, XMM1; // v0 = vec(x*x + z*z, y*y + w*w, z*z + x*x, w*w + y*y)
movaps XMM1, XMM0; // v1 = v0
shufps XMM1, XMM1, 0x11; // v1 = vec(w*w + y*y, z*z + x*x, w*w + y*y, z*z + x*x)
addps XMM0, XMM1; // v0 = |vec|^2 at all 4 positions
rsqrtss XMM0, XMM0; // v0 = 1/sqrt(v0)
rcpss XMM0, XMM0; // v= = 1/v0
movss res, XMM0;
}
return res;
}
else
{
// compute squared length
auto ret = sqLength();
// compute sqrt
version(useFastSqrt)
{
static if (is(T == float))
return fastSqrt(ret);
}
return sqrt(ret);
}
}
void normalize()
{
static if (useSSE)
{
static if (is(t == float) && dim == 3) // make sure that w is 0
assert (w == 0, "vector component w isn't 0!");
auto p = cell.ptr;
asm
{
mov EAX, p;
movups XMM0, [EAX];
movaps XMM2, XMM0; // save it for later
mulps XMM0, XMM0; // v0 = vec(x*x, y*y, z*z, w*w)
movaps XMM1, XMM0; // v1 = v0
shufps XMM0, XMM1, 0x4e; // v0 = vec(z*z, w*w, x*x, y*y)
addps XMM0, XMM1; // v0 = vec(x*x + z*z, y*y + w*w, z*z + x*x, w*w + y*y)
movaps XMM1, XMM0; // v1 = v0
shufps XMM1, XMM1, 0x11; // v1 = vec(w*w + y*y, z*z + x*x, w*w + y*y, z*z + x*x)
addps XMM0, XMM1; // v0 = |vec|^2 at all 4 positions
rsqrtps XMM0, XMM0; // v0 = 1/sqrt(v0)
mulps XMM2, XMM0; // v2 = vec * v0
movups [EAX], XMM0;
}
}
else
{
auto len = length();
foreach(i, _; tuple) // bug 2411 workaround, foreach ref on tuples doesn't work
tuple[i] /= len;
}
}
/// return normalized version of this vector
Vector normalized()
{
Vector res = this;
res.normalize();
return res;
}
///
string toString()
{
string res = "[";
res ~= to!(string)(x);
static if (dim >= 2) res ~= ", " ~ to!(string)(y);
static if (dim >= 3) res ~= ", " ~ to!(string)(z);
static if (dim >= 4) res ~= ", " ~ to!(string)(w);
return res ~ "]";
}
static if (is(T == float))
{
/// do a quick normalize using fast approximate inverse sqrt
void quickNormalize()
{
T inv = invSqrt(sqLength);
this *= inv;
}
/// return a normalized version of this vector
Vector quickNormalized()
{
auto res = this;
res.quickNormalize();
return res;
}
}
/// return a pointer to the vector data
@property T* ptr()
{
return &x;
}
/// calculate distance to other vector
LengthType distance(Vector!(T,dim) other)
{
assert (isValid);
assert (other.isValid);
other -= this;
return other.length;
}
///
bool opEquals(ref const Vector v) const
{
assert (isValid);
assert (v.isValid);
static if (dim >= 1) if (x != v.x) return false;
static if (dim >= 2) if (y != v.y) return false;
static if (dim >= 3) if (z != v.z) return false;
static if (dim >= 4) if (w != v.w) return false;
return true;
}
/// swizzling
@property Vector!(T,n.length) opDispatch(string n)() const
if (allCharsValid(n,"xyzw"[0..dim]))
{
static if (n.length == 2) return
Vector!(T,n.length)(cell[n[0]-'x'], cell[n[1]-'x']);
static if (n.length == 3) return
Vector!(T,n.length)(cell[n[0]-'x'], cell[n[1]-'x'], cell[n[2]-'x']);
static if (n.length == 4) return
Vector!(T,n.length)(cell[n[0]-'x'], cell[n[1]-'x'], cell[n[2]-'x'], cell[n[3]-'x']);
}
// helper function
static private bool allCharsValid( string s, string valid )
{
foreach ( e1; s )
{
bool b = false;
foreach (e2; valid)
b |= e1 == e2;
if (!b)
return false;
}
return true;
}
///
bool isUnit()
{
real sql = cast(real)sqLength();
return abs(sql - 1.0) < 0.001;
}
}
/******* useful alias declarations *******/
alias Vector!(float, 2) Vector2f; ///
alias Vector!(float, 3) Vector3f; ///
alias Vector!(float, 4) Vector4f; ///
alias Vector!(double, 2) Vector2d; ///
alias Vector!(double, 3) Vector3d; ///
alias Vector!(double, 4) Vector4d; ///
alias Vector!(int, 2) Vector2i; ///
alias Vector!(int, 3) Vector3i; ///
alias Vector!(int, 4) Vector4i; ///
alias Vector!(uint, 2) Vector2ui; ///
alias Vector!(uint, 3) Vector3ui; ///
alias Vector!(uint, 4) Vector4ui; ///
alias Vector!(ushort, 2) Vector2us; ///
alias Vector!(ushort, 3) Vector3us; ///
alias Vector!(ushort, 4) Vector4us; ///
alias Vector!(ubyte, 2) Vector2ub; ///
alias Vector!(ubyte, 3) Vector3ub; ///
alias Vector!(ubyte, 4) Vector4ub; ///
// TODO: do all kinds of unittesting
unittest
{
Vector3f v = {1.5f, 1.f, 0.5f};
Vector3f w = {-1.f, 2.f, -0.5f};
assert(v.length - sqrt(3.5f) < 0.0001, sseAvailable ? "SSE length calculation failed" : "normal length calculation failed");
assert(w.length - sqrt(5.25f) < 0.0001, sseAvailable ? "SSE length calculation failed" : "normal length calculation failed");
assert(v+w == Vector3f(0.5f, 3.f, 0.f));
assert(v-w == Vector3f(2.5f, -1.f, 1.f));
auto r = v.xy;
writeln(r);
}
/**
* compute 1/sqrt(x)
* assumes x > 0
*
* Copyright (C) 2002-2006 Chris Lomont
* explanation on www.lomont.org
*/
float invSqrt(float x)
{
assert(x > 0);
float xhalf = 0.5f * x;
int i = *cast(int*)&x; // get bits for floating value
i = 0x5f375a86 - (i >> 1); // gives initial guess y0 with magic number
x = *cast(float*)&i; // convert bits back to float
x = x*(1.5f - xhalf * x * x); // Newton step, repeating increases accuracy
return x;
}
/**
* compute sqrt(x)
* assumes x >= 0
*/
float fastSqrt(float x)
{
assert(x >= 0);
int i = *cast(int*) &x;
if (0 == ((i >> 23)&255))
return 0; // close
return x * invSqrt(x);
}
// get the correct return type for the length function
private template LengthReturnType(T)
{
static if (is(T == float) || is(T == double) || is(T == real))
alias T LengthReturnType;
else
alias float LengthReturnType;
}
/// repeat a type count times
template Repeat(T, int count)
{
static if (!count)
alias TypeTuple!() Repeat;
else
alias TypeTuple!(T, Repeat!(T, count-1)) Repeat;
}
// determine SSE usability
// TODO: make more sophisticated
version(X86)
version(D_InlineAsm_X86)
const bool sseAvailable = is(typeof({void* foo; asm { mov EAX, foo; movups XMM0, [EAX]; } }));
version(X86_64)
version(D_InlineAsm_X86_64)
const bool sseAvailable = false; // TODO: add this

View file

@ -0,0 +1,34 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.window.all;
public import
dsfml.window.event,
dsfml.window.input,
dsfml.window.videomode,
dsfml.window.window,
dsfml.window.windowhandle;

View file

@ -0,0 +1,77 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.window.context;
import dsfml.system.common;
/**
*
*/
class Context : DSFMLObject
{
/**
*
*/
this()
{
super(sfContext_Create());
}
override void dispose()
{
sfContext_Destroy(m_ptr);
}
/**
*
* Params:
* active =
*/
void setActive(bool active)
{
sfContext_SetActive(m_ptr, active);
}
private:
static extern(C)
{
SFMLClass function() sfContext_Create;
void function(SFMLClass) sfContext_Destroy;
void function(SFMLClass, bool) sfContext_SetActive;
}
static this()
{
debug
DllLoader dll = DllLoader.load("csfml-window-d");
else
DllLoader dll = DllLoader.load("csfml-window");
mixin(loadFromSharedLib("sfContext_Create"));
mixin(loadFromSharedLib("sfContext_Destroy"));
mixin(loadFromSharedLib("sfContext_SetActive"));
}
}

View file

@ -0,0 +1,326 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.window.event;
/**
* Definition of key codes for keyboard events
*
* $(B Possibles values:)$(BR)
* Except letters and numbers, you can use :$(BR)
* * LCONTROL, LSHIFT, LALT, LSYSTEM, RCONTROL, RSHIFT, RALT, RSYSTEM.$(BR)
* * LBRACKET, RBRACKET, SEMICOLON, COMMA, PERIOD, QUOTE, SLASH, BACKSLASH, TILDE, EQUAL, DASH.$(BR)
* * SPACE, RETURN, BACK, TAB, PAGEUP, PAGEDOWN, END, HOME, INSERT, DELETE.$(BR)
* * ADD, SUBTRACT, MULTIPLY, DIVIDE, LEFT, RIGHT, UP, DOWN.$(BR)
* * Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9.$(BR)
* * F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15.$(BR)
*/
enum KeyCode
{
A = 'a',
B = 'b',
C = 'c',
D = 'd',
E = 'e',
F = 'f',
G = 'g',
H = 'h',
I = 'i',
J = 'j',
K = 'k',
L = 'l',
M = 'm',
N = 'n',
O = 'o',
P = 'p',
Q = 'q',
R = 'r',
S = 's',
T = 't',
U = 'u',
V = 'v',
W = 'w',
X = 'x',
Y = 'y',
Z = 'z',
Num0 = '0',
Num1 = '1',
Num2 = '2',
Num3 = '3',
Num4 = '4',
Num5 = '5',
Num6 = '6',
Num7 = '7',
Num8 = '8',
Num9 = '9',
Escape = 256,
LControl,
LShift,
LAlt,
LSystem,
RControl,
RShist,
RAlt,
RSystem,
Menu,
LBracket,
RBracket,
Semicolon,
Comma,
Period,
Quote,
Slash,
Backslash,
Tilde,
Equal,
Dash,
Space,
Return,
Back,
Tab,
PageUp,
PageDown,
End,
Home,
Insert,
Delete,
Add,
Subtract,
Multiply,
Divide,
Left,
Right,
Up,
Down,
Numpad0,
Numpad1,
Numpad2,
Numpad3,
Numpad4,
Numpad5,
Numpad6,
Numpad7,
Numpad8,
Numpad9,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
Pause,
}
/**
* Definition of button codes for mouse events
*/
enum MouseButtons
{
Left, ///
Right, ///
Middle, ///
XButton1, ///
XButton2 ///
}
/**
* Definition of joystick axis for joystick events
*/
enum JoyAxis
{
AxisX, ///
AxisY, ///
AxisZ, ///
AxisR, ///
AxisU, ///
AxisV, ///
AxisPOV ///
}
/// EventType
enum EventType
{
Closed,
Resized,
LostFocus,
GainedFocus,
TextEntered,
KeyPressed,
KeyReleased,
MouseWheelMoved,
MouseButtonPressed,
MouseButtonReleased,
MouseMoved,
MouseEntered,
MouseLeft,
JoyButtonPressed,
JoyButtonReleased,
JoyMoved
}
/**
* Event defines a system event and its parameters
*/
align(1) struct Event
{
/**
* Enumeration of the different types of events. Accessing a value of another event that the one received (e.g. Event.Size.Width when receiving an KEYPRESSED event) will result in undefined behavior.
* $(UL
* $(LI CLOSED)
* $(LI LOSTFOCUS)
* $(LI GAINEDFOCUS)
* $(LI RESIZED
* $(UL
* $(LI Event.Size.Width : new Width, in pixels.)
* $(LI Event.Size.Height : new height, in pixels.)
* )
* )
* $(LI TEXTENTERED
* $(UL
* $(LI Event.Text.Unicode : dchar entered.)
* )
* )
* $(LI KEYPRESSED, KEYRELEASED
* $(UL
* $(LI Event.Key.Code : Key code of the key.)
* $(LI Event.Key.Alt : Alt pressed ?)
* $(LI Event.Key.Control : Control pressed ?)
* $(LI Event.Key.Shift : Shift pressed ?)
* )
* )
* $(LI MOUSEWHEELMOVED
* $(UL
* $(LI Event.MouseWheel.Delta : Wheel move (positive if forward, negative else.) )
* )
* )
* $(LI MOUSEBUTTONPRESSED, MOUSEBUTTONRELEASED
* $(UL
* $(LI Event.MouseButton.Button : Mouse button pressed.)
* $(LI Event.MouseButton.X : Cursor X position.)
* $(LI Event.MouseButton.Y : Cursor X position.)
* )
* )
* $(LI MOUSEMOVED
* $(UL
* $(LI Event.MouseMove.X : Cursor X position. Local coordinates.)
* $(LI Event.MouseMove.Y : Cursor Y position. Local coordinates.)
* )
* )
* $(LI MOUSEENTERED)
* $(LI MOUSELEFT)
* $(LI JOYBUTTONPRESSED, JOYBUTTONRELEASED
* $(UL
* $(LI Event.JoyButton.JoystickId : Id of the joystick.)
* $(LI Event.JoyButton.Button : Joystick button pressed.)
* )
* )
* $(LI JOYMOVED
* $(UL
* $(LI Event.JoyMove.JoystickId : Id of the joystick.)
* $(LI Event.JoyMove.Axis : Moved axis.)
* $(LI Event.JoyMove.Position : Actual position of the axis [-100, 100], except for POV [0, 360].)
* )
* )
* )
*/
EventType Type;
union
{
struct SText
{
dchar Unicode;
}
SText Text;
struct SKey
{
align(4): // cause bool is size 1
KeyCode Code;
bool Alt;
bool Control;
bool Shift;
}
SKey Key;
struct SMouseMove
{
int X;
int Y;
}
SMouseMove MouseMove;
struct SMouseButton
{
MouseButtons Button;
int X;
int Y;
}
SMouseButton MouseButton;
struct SMouseWheel
{
int Delta;
}
SMouseWheel MouseWheel;
struct SJoyMove
{
uint JoystickId;
JoyAxis Axis;
float Position;
}
SJoyMove JoyMove;
struct SJoyButton
{
uint JoystickId;
uint Button;
}
SJoyButton JoyButton;
struct SSize
{
uint Width;
uint Height;
}
SSize Size;
}
}

View file

@ -0,0 +1,152 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.window.input;
import dsfml.system.common;
import dsfml.window.event;
/**
* Input handles real-time input from keyboard and mouse.
* Use it instead of events to handle continuous moves and more
* game-friendly inputs
*/
class Input : DSFMLObject
{
public: // TODO: try to fix this, doesn't work with package
this(SFMLClass input)
{
super(input, true);
}
override void dispose()
{
// nothing to do
}
public:
/**
* Get the state of a key
*
* Params:
* key = Key to check
*
* Returns:
* True if key is down, false if key is up
*/
bool isKeyDown(KeyCode key)
{
return cast(bool)sfInput_IsKeyDown(m_ptr, key);
}
/**
* Get the state of a mouse button
*
* Params:
* button = Button to check
*
* Returns:
* True if button is down, false if button is up
*/
bool isMouseButtonDown(MouseButtons button)
{
return cast(bool)sfInput_IsMouseButtonDown(m_ptr, button);
}
/**
* Get the state of a joystick button
*
* Params:
* joyId = Identifier of the joystick to check (0 or 1)
* button = Button to check
*
* Returns:
* True if button is down, false if button is up
*/
bool isJoystickButtonDown(uint joyId, uint button)
{
return cast(bool)sfInput_IsJoystickButtonDown(m_ptr, joyId, button);
}
/**
* Get a joystick axis position
*
* Params:
* joyId = Identifier of the joystick to check (0 or 1)
* axis = Axis to get
*
* Returns:
* Current axis position, in the range [-100, 100] (except for POV, which is [0, 360])
*/
float getJoystickAxis(uint joyId, JoyAxis axis)
{
return sfInput_GetJoystickAxis(m_ptr, joyId, axis);
}
@property
{
/**
* Get the mouse X position
*
* Returns:
* Current mouse left position, relative to owner window
*/
int mouseX()
{
return sfInput_GetMouseX(m_ptr);
}
/**
* Get the mouse Y position
*
* Returns:
* Current mouse top position, relative to owner window
*
*/
int mouseY()
{
return sfInput_GetMouseY(m_ptr);
}
}
private:
// External ====================================================================
static extern (C)
{
int function(SFMLClass, KeyCode) sfInput_IsKeyDown;
int function(SFMLClass, MouseButtons) sfInput_IsMouseButtonDown;
int function(SFMLClass, uint, uint) sfInput_IsJoystickButtonDown;
int function(SFMLClass) sfInput_GetMouseX;
int function(SFMLClass) sfInput_GetMouseY;
float function(SFMLClass, uint, JoyAxis) sfInput_GetJoystickAxis;
}
mixin(loadFromSharedLib2("csfml-window", "sfInput",
"IsKeyDown", "IsMouseButtonDown", "IsJoystickButtonDown", "GetMouseX", "GetMouseY", "GetJoystickAxis"));
}

View file

@ -0,0 +1,105 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.window.videomode;
import dsfml.system.common;
/**
* VideoMode defines a video mode (width, height, bpp, frequency)
* and provides static functions for getting modes supported
* by the display device
*/
struct VideoMode
{
uint Width; /// Video mode width, in pixels
uint Height; /// Video mode height, in pixels
uint BitsPerPixel = 32; /// Video mode pixel depth, in bits per pixels
@property
{
/**
* Get the current desktop video mode
*
* Returns:
* Current desktop video mode
*/
static VideoMode getDesktopMode()
{
return sfVideoMode_GetDesktopMode();
}
/**
* Get all the supported video modes for fullscreen mode.
* Modes are sorted from best to worst.
*
* Returns:
* video mode array
*/
static VideoMode[] getFullscreenModes()
{
size_t arraySize;
VideoMode* array = sfVideoMode_GetFullscreenModes(&arraySize); // TODO: check pointer?
return array[0 .. arraySize];
}
/**
* Tell whether or not the video mode is supported
*
* Returns:
* True if video mode is supported, false otherwise
*/
bool isValid()
{
return cast(bool)sfVideoMode_IsValid(this);
}
}
/**
* Comparison operator overload -- tell if two video modes are equal
*
* Params:
* Other : Video mode to compare
*
* Returns:
* True if modes are equal
*/
const bool opEquals(ref const(VideoMode) other)
{
return ((other.Width == Width) && (other.Height == Height) && (other.BitsPerPixel == BitsPerPixel));
}
}
extern (C)
{
VideoMode function() sfVideoMode_GetDesktopMode;
VideoMode* function(size_t*) sfVideoMode_GetFullscreenModes;
int function(VideoMode) sfVideoMode_IsValid;
}
mixin(loadFromSharedLib2("csfml-window", "sfVideoMode",
"GetDesktopMode", "GetFullscreenModes", "IsValid"));

View file

@ -0,0 +1,454 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.window.window;
import dsfml.window.event;
import dsfml.window.input;
import dsfml.window.videomode;
import dsfml.window.windowhandle;
import dsfml.system.common;
import dsfml.system.stringutil;
/**
* Window style
*/
enum Style : uint
{
None = 0, /// No border / title bar (this flag and all others are mutually exclusive)
Titlebar = 1 << 0, /// Title bar + fixed border
Resize = 1 << 1, /// Titlebar + resizable border + maximize button
Close = 1 << 2, /// Titlebar + close button
Fullscreen = 1 << 3, /// Fullscreen mode (this flag and all others are mutually exclusive)
Default = Titlebar | Resize | Close /// Default window style
}
/**
* Structure defining the creation settings of windows
*/
struct ContextSettings
{
uint DepthBits = 24; /// Bits of the depth buffer
uint StencilBits = 8; /// Bits of the stencil buffer
uint AntialiasingLevel = 0; /// Level of antialiasing
uint MajorVersion = 3; /// Major number of the context version to create
uint MinorVersion = 0; /// Minor number of the context version to create
}
/**
* Window is a rendering window ; it can create a new window
* or connect to an existing one
*/
class Window : DSFMLObject
{
protected:
this(SFMLClass ptr)
{
super(ptr);
}
Input m_input;
override void dispose()
{
m_input = null;
sfWindow_Destroy(m_ptr);
}
public:
/**
* Construct a new window
*
* Params:
* mode = Video mode to use
* title = Title of the window
* windowStyle = Window style (Resize | Close by default)
* settings = Context settings (default is default ContextSettings values)
*/
this(VideoMode mode, string title, Style windowStyle = Style.Default, ContextSettings settings = ContextSettings())
{
super(sfWindow_Create(mode, toStringz(title), windowStyle, &settings));
}
/**
* Construct the window from an existing control
*
* Params:
* handle = Platform-specific handle of the control
* settings = Context settings (default is default ContextSettings values)
*/
this(WindowHandle handle, ContextSettings settings = ContextSettings())
{
super(sfWindow_CreateFromHandle(handle, &settings));
}
/**
* Create (or recreate) the window
*
* Input created with getInput becomes invalid.
*
* Params:
* mode = Video mode to use
* title = Title of the window
* windowStyle = Window style (Resize | Close by default)
* settings = Context settings (default is default ContextSettings values)
*/
void create(VideoMode mode, string title, Style windowStyle = Style.Default, ContextSettings settings = ContextSettings())
{
if (m_ptr !is null)
dispose();
m_ptr = sfWindow_Create(mode, toStringz(title), windowStyle, &settings);
}
/**
* Create (or recreate) the window from an existing control
*
* Input created with getInput becomes invalid.
*
* Params:
* handle = Platform-specific handle of the control
* settings = Context settings (default is default ContextSettings values)
*/
void create(WindowHandle handle, ContextSettings settings = ContextSettings())
{
if (m_ptr !is null)
dispose();
m_ptr = sfWindow_CreateFromHandle(handle, &settings);
}
/**
* Close (destroy) the window.
* You can call create to recreate a valid window
*/
void close()
{
sfWindow_Close(m_ptr);
}
/**
* Get the event on top of events stack, if any, and pop it
*
* Params:
* eventReceived = Event to fill, if any
*
* Returns:
* True if an event was returned, false if events stack was empty
*/
bool getEvent(out Event eventReceived)
{
return cast(bool) sfWindow_GetEvent(m_ptr, &eventReceived);
}
/**
* 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 occured), the \a 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.
*
* Params:
* e Event to be returned
*
* Returns:
* false if any error occured
*/
bool waitEvent(out Event e)
{
return sfWindow_WaitEvent(m_ptr, &e);
}
/**
* Show or hide the window
*
* Params:
* state = True to show, false to hide
*
*/
void show(bool state)
{
sfWindow_Show(m_ptr, state);
}
/**
* Display the window on screen
*/
void display()
{
sfWindow_Display(m_ptr);
}
@property
{
/**
* Tell whether or not a window is opened
*
* Returns:
* True if window is currently open.
*/
bool isOpened()
{
return cast(bool) sfWindow_IsOpened(m_ptr);
}
/**
* Get the width of the rendering region of the window
*
* Returns:
* Width in pixels
*/
uint width()
{
return sfWindow_GetWidth(m_ptr);
}
/**
* Get the height of the rendering region of the window
*
* Returns:
* Height in pixels
*/
uint height()
{
return sfWindow_GetHeight(m_ptr);
}
/**
* Get the creation settings of a window
*
* Returns:
* Settings used to create the window
*/
ContextSettings settings()
{
return sfWindow_GetSettings(m_ptr);
}
/**
* Enable / disable vertical synchronization
*
* Params:
* enabled : True to enable v-sync, false to deactivate
*/
void useVerticalSync(bool enabled)
{
sfWindow_UseVerticalSync(m_ptr, enabled);
}
/**
* Show or hide the mouse cursor
*
* Params:
* show : True to show, false to hide
*/
void showMouseCursor(bool show)
{
sfWindow_ShowMouseCursor(m_ptr, show);
}
/**
* Enable or disable automatic key-repeat for keydown events.
* Automatic key-repeat is enabled by default.
*
* Params:
* enabled = true to enable, false to disable
*/
void enableKeyRepeat(bool enabled)
{
sfWindow_EnableKeyRepeat(m_ptr, enabled);
}
/**
* Set the window as the current target for rendering
*
* Params:
* active = True to activate, false to deactivate
* Returns:
* True if operation was successful, false otherwise
*/
bool active(bool active)
{
return cast(bool)sfWindow_SetActive(m_ptr, active);
}
/**
* Get the input manager of the window
*
* Returns:
* An input manager
* See_Also :
* Input
*/
Input input()
{
if (m_input is null)
m_input = new Input(sfWindow_GetInput(m_ptr));
return m_input;
}
/**
* Limit the framerate to a maximum fixed frequency
*
* Params:
* limit : Framerate limit, in frames per seconds (use 0 to disable limit)
*/
void framerateLimit(uint limit)
{
sfWindow_SetFramerateLimit(m_ptr, limit);
}
/**
* Get the time the last frame took
*
* Returns:
* time in seconds
*/
float frameTime()
{
return sfWindow_GetFrameTime(m_ptr);
}
/**
* Change the joystick threshold, ie. the value below which
* no move event will be generated
*
* Params:
* threshold : New threshold, in range [0, 100]
*/
void joystickThreshold(float threshold)
{
sfWindow_SetJoystickThreshold(m_ptr, threshold);
}
/**
* Retrieve the Os-specific handle of a window
*
* Params:
* renderWindow = Renderwindow object
*/
WindowHandle windowHandle()
{
return sfWindow_GetSystemHandle(m_ptr);
}
}
/**
* Change the position of the mouse cursor
*
* Params:
* left = Left coordinate of the cursor, relative to the window
* top = Top coordinate of the cursor, relative to the window
*/
void setCursorPosition(uint left, uint top)
{
sfWindow_SetCursorPosition(m_ptr, left, top);
}
/**
* Change the position of the window on screen.
* Only works for top-level windows
*
* Params:
* left = Left position
* top = Top position
*/
void setPosition(int left, int top)
{
sfWindow_SetPosition(m_ptr, left, top);
}
/**
* change the size of the rendering region of the window
*
* Params:
* width : new width
* height : new height
*/
void setSize(uint width, uint height)
{
sfWindow_SetSize(m_ptr, width, height);
}
/**
* Change the window's icon
*
* Params:
* width = Icon's width, in pixels
* height = Icon's height, in pixels
* data = array of pixels in memory, format must be RGBA 32 bits
*
*/
void setIcon(size_t width, size_t height, ubyte[] data)
{
sfWindow_SetIcon(m_ptr, width, height, data.ptr);
}
private:
// External ====================================================================
static extern(C)
{
SFMLClass function(VideoMode, cchar*, Style, ContextSettings*)sfWindow_Create;
SFMLClass function(WindowHandle, ContextSettings*) sfWindow_CreateFromHandle;
void function(SFMLClass) sfWindow_Destroy;
void function(SFMLClass) sfWindow_Close;
int function(SFMLClass) sfWindow_IsOpened;
uint function(SFMLClass) sfWindow_GetWidth;
uint function(SFMLClass) sfWindow_GetHeight;
ContextSettings function(SFMLClass Window) sfWindow_GetSettings;
int function(SFMLClass, Event*) sfWindow_GetEvent;
void function(SFMLClass, int) sfWindow_UseVerticalSync;
void function(SFMLClass, int) sfWindow_ShowMouseCursor;
void function(SFMLClass, uint, uint) sfWindow_SetCursorPosition;
void function(SFMLClass, int, int) sfWindow_SetPosition;
void function(SFMLClass, uint, uint) sfWindow_SetSize;
void function(SFMLClass, int) sfWindow_Show;
void function(SFMLClass, int) sfWindow_EnableKeyRepeat;
void function(SFMLClass, size_t, size_t, ubyte*) sfWindow_SetIcon;
int function(SFMLClass, int) sfWindow_SetActive;
void function(SFMLClass) sfWindow_Display;
SFMLClass function(SFMLClass) sfWindow_GetInput;
void function(SFMLClass, uint) sfWindow_SetFramerateLimit;
float function(SFMLClass) sfWindow_GetFrameTime;
void function(SFMLClass, float) sfWindow_SetJoystickThreshold;
// DSFML2
bool function(SFMLClass, void*) sfWindow_WaitEvent;
WindowHandle function(SFMLClass) sfWindow_GetSystemHandle;
}
mixin(loadFromSharedLib2("csfml-window", "sfWindow",
"Create", "CreateFromHandle", "Destroy", "Close", "IsOpened", "GetWidth", "GetHeight", "GetSettings", "GetEvent", "UseVerticalSync",
"ShowMouseCursor", "SetCursorPosition", "SetPosition", "SetSize", "Show", "EnableKeyRepeat", "SetIcon", "SetActive", "Display",
"GetInput", "SetFramerateLimit", "GetFrameTime", "SetJoystickThreshold", "WaitEvent", "GetSystemHandle"));
}

View file

@ -0,0 +1,47 @@
/*
* DSFML - SFML Library wrapper for the D programming language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@gmail.com)
* Copyright (C) 2010 Andreas Hollandt
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
module dsfml.window.windowhandle;
/**
* Define a low-level window handle type, specific to
* each platform
*/
version(Windows)
{
// Windows defines a void* handle (HWND)
typedef void* WindowHandle;
}
else version(linux)
{
// Unix - X11 defines an unsigned integer handle (Window)
typedef ulong WindowHandle;
}
else version(darwin)
{
// Mac OS X defines a void* handle (NSWindow)
typedef void* WindowHandle;
}