Removed the D and Python bindings

This commit is contained in:
Laurent Gomila 2011-07-06 23:10:53 +02:00
parent bdbfe2b0b5
commit 9441bd6e8c
175 changed files with 0 additions and 22354 deletions

View File

@ -1,2 +0,0 @@
SirJulio (Dagorn Julien) => sirjulio13@gmail.com
Insomniak => insomniak.fr@gmail.com

View File

@ -1,18 +0,0 @@
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.

View File

@ -1,36 +0,0 @@
/*
* 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

@ -1,185 +0,0 @@
/*
* 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-2");
else
DllLoader dll = DllLoader.load("csfml-audio-2");
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

@ -1,188 +0,0 @@
/*
* 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-2");
else
DllLoader dll = DllLoader.load("csfml-audio-2");
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

@ -1,224 +0,0 @@
/*
* 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-2");
else
DllLoader dll = DllLoader.load("csfml-audio-2");
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

@ -1,205 +0,0 @@
/*
* 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

@ -1,109 +0,0 @@
/*
* 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-2");
else
DllLoader dll = DllLoader.load("csfml-audio-2");
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

@ -1,316 +0,0 @@
/*
* 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

@ -1,311 +0,0 @@
/*
* 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

@ -1,384 +0,0 @@
/*
* 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-2");
else
DllLoader dll = DllLoader.load("csfml-audio-2");
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

@ -1,41 +0,0 @@
/*
* 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

@ -1,38 +0,0 @@
/*
* 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

@ -1,123 +0,0 @@
/*
* 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

@ -1,268 +0,0 @@
/*
* 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-2");
else
DllLoader dll = DllLoader.load("csfml-graphics-2");
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

@ -1,193 +0,0 @@
/*
* 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-2");
else
DllLoader dll = DllLoader.load("csfml-graphics-2");
// 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

@ -1,283 +0,0 @@
/*
* 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.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

@ -1,352 +0,0 @@
/*
* 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

@ -1,138 +0,0 @@
/*
* 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

@ -1,149 +0,0 @@
/*
* 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

@ -1,316 +0,0 @@
/*
* 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

@ -1,336 +0,0 @@
/*
* 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.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

@ -1,177 +0,0 @@
/*
* 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-2");
else
DllLoader dll = DllLoader.load("csfml-graphics-2");
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

@ -1,306 +0,0 @@
/*
* 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 thickness of a shape outline
*
* Params:
* thickness = New thickness
*/
void outlineThickness(float thickness)
{
sfShape_SetOutlineThickness(m_ptr, thickness);
}
/**
* Get the thickness of the shape outline
*
* Returns:
* Current outline thickness
*
*/
float outlineThickness()
{
return sfShape_GetOutlineThickness(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 thickness (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 thickness (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 thickness (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_SetOutlineThickness;
float function(SFMLClass) sfShape_GetOutlineThickness;
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", "SetOutlineThickness", "GetOutlineThickness",
"GetPointsCount", "GetPointPosition", "SetPointPosition", "GetPointColor", "SetPointColor", "GetPointOutlineColor",
"SetPointOutlineColor"));
}

View File

@ -1,238 +0,0 @@
/*
* 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

@ -1,277 +0,0 @@
/*
* 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

@ -1,347 +0,0 @@
/*
* 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-2");
else
DllLoader dll = DllLoader.load("csfml-graphics-2");
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

@ -1,38 +0,0 @@
/*
* 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

@ -1,602 +0,0 @@
/*
* 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-2");
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-2");
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-2");
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-2");
else
DllLoader dll = DllLoader.load("csfml-network-2");
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

@ -1,398 +0,0 @@
/*
* 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-2");
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-2");
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-2");
else
DllLoader dll = DllLoader.load("csfml-network-2");
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

@ -1,148 +0,0 @@
/*
* 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

@ -1,417 +0,0 @@
/*
* 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-2");
else
DllLoader dll = DllLoader.load("csfml-network-2");
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

@ -1,153 +0,0 @@
/*
* 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

@ -1,38 +0,0 @@
/*
* 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

@ -1,49 +0,0 @@
/*
* 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

@ -1,273 +0,0 @@
/*
* 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-2");
else
DllLoader dll = DllLoader.load("csfml-network-2");
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

@ -1,241 +0,0 @@
/*
* 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-2");
else
DllLoader dll = DllLoader.load("csfml-network-2");
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

@ -1,47 +0,0 @@
/*
* 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

@ -1,84 +0,0 @@
/*
* 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

@ -1,141 +0,0 @@
/*
* 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-2");
else
DllLoader dll = DllLoader.load("` ~ lib ~ `-2");
`;
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-2");
else
DllLoader dll = DllLoader.load("` ~ lib ~ `-2");
`;
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

@ -1,238 +0,0 @@
/*
* 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

@ -1,43 +0,0 @@
/*
* 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

@ -1,103 +0,0 @@
/*
* 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

@ -1,66 +0,0 @@
/*
* 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

@ -1,82 +0,0 @@
/*
* 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

@ -1,470 +0,0 @@
/*
* 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, uint 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 : "-")() const
{
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) const
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) const
// 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
Vector opBinary(string op, U)(U s) const
{
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, U)(U s)
if (!is(U:typeof(this))) // TODO: there's some dmd bug about this
{
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 other)
{
assert (isValid);
assert (other.isValid);
other -= this; // doable cause other is a struct not ref
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
import std.stdio;
unittest
{
writeln("unittests running");
Vector3f v = {1.5f, 1.f, 0.5f};
Vector3f w = {-1.f, 2.f, -0.5f};
writefln("v: %f w: %f", v.length - sqrt(3.5f), w.length - sqrt(5.25f));
// strangely calculating w.length is much less accurate
assert(v.length - sqrt(3.5f) < 0.001, sseAvailable ? "SSE length calculation failed" : "normal length calculation failed");
assert(w.length - sqrt(5.25f) < 0.001, 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

@ -1,34 +0,0 @@
/*
* 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

@ -1,68 +0,0 @@
/*
* 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;
}
mixin(loadFromSharedLib2("csfml-window", "sfContext",
"Create", "Destroy", "SetActive"));
}

View File

@ -1,326 +0,0 @@
/*
* 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

@ -1,152 +0,0 @@
/*
* 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

@ -1,105 +0,0 @@
/*
* 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

@ -1,454 +0,0 @@
/*
* 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);
}
/**
* Enable / disable vertical synchronization
*
* Params:
* enabled : True to enable v-sync, false to deactivate
*/
void enableVerticalSync(bool enabled)
{
sfWindow_EnableVerticalSync(m_ptr, enabled);
}
@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);
}
/**
* 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_EnableVerticalSync;
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", "EnableVerticalSync",
"ShowMouseCursor", "SetCursorPosition", "SetPosition", "SetSize", "Show", "EnableKeyRepeat", "SetIcon", "SetActive", "Display",
"GetInput", "SetFramerateLimit", "GetFrameTime", "SetJoystickThreshold", "WaitEvent", "GetSystemHandle"));
}

View File

@ -1,47 +0,0 @@
/*
* 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;
}

View File

@ -1,46 +0,0 @@
name=dsfml
[dsfml/audio]
type = library
target = dsfml-audio
version (Windows){
postbuild += copy "dsfml-audio.lib" "../lib/dsfml-audio.lib"
} else version (linux){
postbuild += cp -f "libdsfml-audio.a" "../lib/libdsfml-audio.a"
}
[dsfml/network]
type = library
target = dsfml-network
version (Windows){
postbuild += copy "dsfml-network.lib" "../lib/dsfml-network.lib"
} else version (linux){
postbuild += cp -f "libdsfml-network.a" "../lib/libdsfml-network.a"
}
[dsfml/graphics]
type = library
target = dsfml-graphics
version (Windows){
postbuild += copy "dsfml-graphics.lib" "../lib/dsfml-graphics.lib"
} else version (linux){
postbuild += cp -f "libdsfml-graphics.a" "../lib/libdsfml-graphics.a"
}
[dsfml/system]
type = library
target = dsfml-system
version (Windows){
postbuild += copy "dsfml-system.lib" "../lib/dsfml-system.lib"
} else version (linux){
postbuild += cp -f "libdsfml-system.a" "../lib/libdsfml-system.a"
}
[dsfml/window]
type = library
target = dsfml-window
version (Windows){
postbuild += copy "dsfml-window.lib" "../lib/dsfml-window.lib"
} else version (linux){
postbuild += cp -f "libdsfml-window.a" "../lib/libdsfml-window.a"
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

View File

@ -1,16 +0,0 @@
texture framebuffer
float offset
effect
{
vec2 offx = vec2(offset, 0.0);
vec2 offy = vec2(0.0, offset);
vec4 c0 = framebuffer(_in);
vec4 c1 = framebuffer(_in - offy);
vec4 c2 = framebuffer(_in + offy);
vec4 c3 = framebuffer(_in - offx);
vec4 c4 = framebuffer(_in + offx);
_out = c0 * 0.2 + c1 * 0.2 + c2 * 0.2 + c3 * 0.2 + c4 * 0.2;
}

View File

@ -1,10 +0,0 @@
texture framebuffer
vec3 color
effect
{
vec4 pixel = framebuffer(_in);
float gray = pixel.r * 0.39 + pixel.g * 0.50 + pixel.b * 0.11;
_out = vec4(gray * color, 1.0) * 0.6 + pixel * 0.4;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

View File

@ -1,12 +0,0 @@
texture framebuffer
vec2 mouse
effect
{
float len = distance(_in, mouse) * 7.0;
if (len < 1.0)
_out = framebuffer(_in + (_in - mouse) * len);
else
_out = framebuffer(_in);
}

View File

@ -1,6 +0,0 @@
texture framebuffer
effect
{
_out = framebuffer(_in);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 140 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

View File

@ -1,12 +0,0 @@
texture framebuffer
texture wave
vec2 offset
effect
{
vec2 texoffset = wave(_in * offset).xy;
texoffset -= vec2(0.5, 0.5);
texoffset *= 0.05;
_out = framebuffer(_in + texoffset);
}

View File

@ -1,230 +0,0 @@
module dflsample;
import dsfml.system.all;
import dsfml.window.all;
// DFL and Derelict must be present.
import dfl.all;
import Derelict.opengl.gl;
import Derelict.opengl.glu;
// An enum for each controls methods
enum ControlMethod
{
MOUSE,
KEYBOARD
}
void main()
{
DerelictGL.load();
DerelictGLU.load();
//Start the message loop
Application.run(new MyForm());
}
//A simple form with a groupbox to choose input method and the openGL control
class MyForm : Form
{
GLControl m_gl;
GroupBox m_gbx;
RadioButton m_rb1;
RadioButton m_rb2;
this()
{
m_gbx = new GroupBox();
m_gbx.dock = DockStyle.TOP;
m_gbx.height = 40;
m_gbx.text = "Choose your input";
this.controls.add(m_gbx);
m_rb1 = new RadioButton();
m_rb1.text = "Mouse";
m_rb1.location = Point(10, 15);
m_rb1.checked = true;
m_rb1.click ~= &radioButtonClick;
m_gbx.controls.add(m_rb1);
m_rb2 = new RadioButton();
m_rb2.text = "Keyboard";
m_rb2.location = Point(m_rb1.width + 10, 15);
m_rb2.click ~= &radioButtonClick;
m_gbx.controls.add(m_rb2);
m_gl = new GLControl();
m_gl.dock = DockStyle.FILL;
m_gl.controlMethod = ControlMethod.MOUSE;
this.controls.add(m_gl);
this.text = "DFL Opengl Integration Sample";
}
private void radioButtonClick(Control c, EventArgs ea)
{
m_gl.controlMethod(c.text == "Mouse" ? ControlMethod.MOUSE : ControlMethod.KEYBOARD);
m_gl.focus();
}
}
//Our OpenGL control
class GLControl : Control
{
Window m_win;
Input i;
Timer m_timer;
GLfloat rotx = 0.f, roty = 0.f;
ControlMethod m_method = ControlMethod.MOUSE;
this ()
{
super();
this.setStyle(ControlStyles.SELECTABLE | ControlStyles.ALL_PAINTING_IN_WM_PAINT | ControlStyles.WANT_ALL_KEYS, true);
//We set a timer to ensure periodic refresh of the window
m_timer = new Timer();
m_timer.interval(10);
m_timer.tick ~= &this.onTick;
}
public void controlMethod(ControlMethod m)
{
m_method = m;
}
//Override of the onHandleCreated method of Control
//integration of DSFML window in a control need a valid handle
protected void onHandleCreated(EventArgs ea)
{
super.onHandleCreated(ea);
//Construction of the window
m_win = new Window(cast(WindowHandle)this.handle);
//Get the input for further use
i = m_win.getInput();
//Now that the Window is instanciated, we can start the timer.
m_timer.start();
//Some opengl initializations functions
glClearDepth(1.f);
glClearColor(0.f, 0.f, 0.f, 0.f);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90.f, 1.f, 1.f, 500.f);
}
//We handle Mouse leaving and entering the control to hide or show the cursor
protected void onMouseEnter(MouseEventArgs mea)
{
super.onMouseEnter(mea);
Cursor.current.hide();
}
protected void onMouseLeave(MouseEventArgs mea)
{
super.onMouseLeave(mea);
Cursor.current.show();
}
//If the window is resize, we need to modify openGL view
protected void onResize(EventArgs ea)
{
super.onResize(ea);
glViewport(0, 0, this.width, this.height);
}
protected void onTick(Timer t, EventArgs ea)
{
draw();
}
protected void onPaint(PaintEventArgs pea)
{
super.onPaint(pea);
draw();
}
private void handleKeys()
{
if (i.isKeyDown(KeyCode.UP))
rotx += 1.f;
if (i.isKeyDown(KeyCode.DOWN))
rotx += -1.f;
if (i.isKeyDown(KeyCode.LEFT))
roty += -1.f;
if (i.isKeyDown(KeyCode.RIGHT))
roty += 1.f;
}
private void handleMousePos()
{
rotx = i.getMouseY() - (this.height / 2.0);
roty = i.getMouseX() - (this.width / 2.0);
}
private void draw()
{
if (m_method == ControlMethod.KEYBOARD)
handleKeys();
else
handleMousePos();
m_win.setActive(true);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.f, 0.f, -200.f);
glRotatef(rotx, 1.f, 0.f, 0.f);
glRotatef(roty, 0.f, 1.f, 0.f);
glBegin(GL_QUADS);
glColor3f(1.f, 0.f, 0.f);
glVertex3f(-50.f, -50.f, -50.f);
glVertex3f(-50.f, 50.f, -50.f);
glVertex3f( 50.f, 50.f, -50.f);
glVertex3f( 50.f, -50.f, -50.f);
glColor3f(0.f, 1.f, 0.f);
glVertex3f(-50.f, -50.f, 50.f);
glVertex3f(-50.f, 50.f, 50.f);
glVertex3f( 50.f, 50.f, 50.f);
glVertex3f( 50.f, -50.f, 50.f);
glColor3f(0.f, 0.f, 1.f);
glVertex3f(-50.f, -50.f, -50.f);
glVertex3f(-50.f, 50.f, -50.f);
glVertex3f(-50.f, 50.f, 50.f);
glVertex3f(-50.f, -50.f, 50.f);
glColor3f(1.f, 1.f, 0.f);
glVertex3f(50.f, -50.f, -50.f);
glVertex3f(50.f, 50.f, -50.f);
glVertex3f(50.f, 50.f, 50.f);
glVertex3f(50.f, -50.f, 50.f);
glColor3f(1.f, 0.f, 1.f);
glVertex3f(-50.f, -50.f, 50.f);
glVertex3f(-50.f, -50.f, -50.f);
glVertex3f( 50.f, -50.f, -50.f);
glVertex3f( 50.f, -50.f, 50.f);
glColor3f(0.f, 1.f, 1.f);
glVertex3f(-50.f, 50.f, 50.f);
glVertex3f(-50.f, 50.f, -50.f);
glVertex3f( 50.f, 50.f, -50.f);
glVertex3f( 50.f, 50.f, 50.f);
glEnd();
m_win.display();
}
}

View File

@ -1,33 +0,0 @@
[*]
buildflags += -I../../import -Ivoip
[pong/pong.d]
target = bin/pong
[postFX/postFX.d]
target = bin/postFX
[socket/socketclient.d]
target = bin/client
[socket/socketserver.d]
target = bin/server
[sound3d/sound3d.d]
target = bin/sound3d
[soundstream/soundstream.d]
target = bin/soundstream
[view/view.d]
target = bin/view
[voip/entry.d]
target = bin/voip
version (Windows){
version (DFL){
[dfl/dflsample.d]
target = bin/dflSample
}
}

View File

@ -1,155 +0,0 @@
module opengl;
import dsfml.system.all;
import dsfml.audio.all;
import dsfml.window.all;
import dsfml.graphics.all;
import std.perf;
import derelict.opengl.gl;
import derelict.opengl.glu;
void main()
{
// Create the main window
auto window = new RenderWindow(VideoMode(800, 600), "DSFML OpenGL", Style.Default, ContextSettings(24,8,0,3,1));
DerelictGL.load();
DerelictGLU.load();
// Create a sprite for the background
auto backgroundImage = new Image("Data/opengl/background.jpg");
auto background = new Sprite(backgroundImage);
// Load an OpenGL texture.
// We could directly use an Image as an OpenGL texture (with its Bind() member function),
// but here we want more control on it (generate mipmaps, ...) so we create a new one from the image pixels
GLuint texture = 0;
{
auto image = new Image("Data/opengl/texture.jpg");
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.width, image.height, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsArray().ptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
}
// Enable Z-buffer read and write
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glClearDepth(1.f);
// Setup a perspective projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90.f, 1.f, 1.f, 500.f);
// Bind our texture
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
glColor4f(1.f, 1.f, 1.f, 1.f);
// Create a clock for measuring the time elapsed
auto clock = new PerformanceCounter();
clock.start();
// Start game loop
while (window.isOpened())
{
// Process events
Event event;
while (window.getEvent(event))
{
// Close window : exit
if (event.Type == EventType.Closed)
window.close();
// Escape key : exit
if ((event.Type == EventType.KeyPressed) && (event.Key.Code == KeyCode.Escape))
window.close();
// Adjust the viewport when the window is resized
if (event.Type == EventType.Resized)
glViewport(0, 0, event.Size.Width, event.Size.Height);
}
// Draw the background
window.saveGLStates();
window.draw(background);
window.restoreGLStates();
// Activate the window before using OpenGL commands.
// This is useless here because we have only one window which is
// always the active one, but don't forget it if you use multiple windows
window.active = true;
// Clear the depth buffer
glClear(GL_DEPTH_BUFFER_BIT);
// We get the position of the mouse cursor, so that we can move the box accordingly
float x = window.input.mouseX * 200.f / window.width - 100.f;
float y = -window.input.mouseY * 200.f / window.height + 100.f;
// Apply some transformations
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(x, y, -100.f);
clock.stop();
glRotatef(clock.microseconds() * 0.000001 * 50, 1.f, 0.f, 0.f);
glRotatef(clock.microseconds() * 0.000001 * 30, 0.f, 1.f, 0.f);
glRotatef(clock.microseconds() * 0.000001 * 90, 0.f, 0.f, 1.f);
// Draw a cube
float size = 20.f;
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3f(-size, -size, -size);
glTexCoord2f(0, 1); glVertex3f(-size, size, -size);
glTexCoord2f(1, 1); glVertex3f( size, size, -size);
glTexCoord2f(1, 0); glVertex3f( size, -size, -size);
glTexCoord2f(0, 0); glVertex3f(-size, -size, size);
glTexCoord2f(0, 1); glVertex3f(-size, size, size);
glTexCoord2f(1, 1); glVertex3f( size, size, size);
glTexCoord2f(1, 0); glVertex3f( size, -size, size);
glTexCoord2f(0, 0); glVertex3f(-size, -size, -size);
glTexCoord2f(0, 1); glVertex3f(-size, size, -size);
glTexCoord2f(1, 1); glVertex3f(-size, size, size);
glTexCoord2f(1, 0); glVertex3f(-size, -size, size);
glTexCoord2f(0, 0); glVertex3f(size, -size, -size);
glTexCoord2f(0, 1); glVertex3f(size, size, -size);
glTexCoord2f(1, 1); glVertex3f(size, size, size);
glTexCoord2f(1, 0); glVertex3f(size, -size, size);
glTexCoord2f(0, 1); glVertex3f(-size, -size, size);
glTexCoord2f(0, 0); glVertex3f(-size, -size, -size);
glTexCoord2f(1, 0); glVertex3f( size, -size, -size);
glTexCoord2f(1, 1); glVertex3f( size, -size, size);
glTexCoord2f(0, 1); glVertex3f(-size, size, size);
glTexCoord2f(0, 0); glVertex3f(-size, size, -size);
glTexCoord2f(1, 0); glVertex3f( size, size, -size);
glTexCoord2f(1, 1); glVertex3f( size, size, size);
glEnd();
// Draw some text on top of our OpenGL object
window.saveGLStates();
Text text = new Text("DSFML / OpenGL demo"c);
text.position = Vector2f(250.f, 450.f);
text.color = Color(255, 255, 255, 170);
window.draw(text);
window.restoreGLStates();
// Finally, display the rendered frame on screen
window.display();
}
// Don't forget to destroy our texture
glDeleteTextures(1, &texture);
}

View File

@ -1,202 +0,0 @@
module pong;
import dsfml.system.all;
import dsfml.audio.all;
import dsfml.window.all;
import dsfml.graphics.all;
version (Tango)
{
import tango.io.Stdout;
import tango.math.Math;
}
else
{
import std.math;
import std.perf;
import std.random;
}
void main()
{
// Defines PI
const float PI = 3.14159f;
// Create the window of the application
RenderWindow app = new RenderWindow(VideoMode(800, 600, 32), "SFML Pong");
app.useVerticalSync(false);
Input i = app.input;
// Load the sounds used in the game
Sound BallSound = new Sound(new SoundBuffer("Data/ball.wav"));
// Load the images used in the game
Image PaddleImage = new Image("Data/paddle.tga");
Image BallImage = new Image("Data/ball.tga");
// Initialize the end text
Text End = new Text(""c);
Font font = new Font("Data/cheeseburger.ttf");
End.font = font;
End.characterSize = 60;
End.move(150.f, 200.f);
End.color = Color(50, 50, 250);
Text fps = new Text(""c, font, 30);
fps.move(50.f, 50.f);
fps.color = Color.BLACK;
// Create the sprites of the background, the paddles and the ball
Sprite LeftPaddle = new Sprite(PaddleImage);
Sprite RightPaddle = new Sprite(PaddleImage);
Sprite Ball = new Sprite(BallImage);
LeftPaddle.move(10, (app.view.getHeight() - LeftPaddle.size.y) / 2);
RightPaddle.move(app.view.getWidth() - RightPaddle.size.x - 10, (app.view.getHeight() - RightPaddle.size.y) / 2);
Ball.move((app.view.getWidth() - Ball.size.x) / 2, (app.view.getHeight() - Ball.size.y) / 2);
// Define the paddles properties
auto AITimer = new PerformanceCounter();
const long AITime = 100; // 100 ms
float LeftPaddleSpeed = 400.f;
float RightPaddleSpeed = 400.f;
// Define the ball properties
float BallSpeed = 400.f;
float BallAngle = 0.f;
do
{
// Make sure the ball initial angle is not too much vertical
BallAngle = uniform(0.f, 2 * PI);
} while (abs(cos(BallAngle)) < 0.7f);
bool IsPlaying = true;
Event evt;
uint iFps = 0;
auto fpsClock = new PerformanceCounter();
while (app.isOpened())
{
app.clear(Color(255, 255, 255, 255));
// Handle events
while (app.getEvent(evt))
{
// Window closed or escape key pressed : exit
if ((evt.Type == EventType.Closed) ||
((evt.Type == EventType.KeyPressed) && (evt.Key.Code == KeyCode.Escape)))
{
app.close();
break;
}
}
if (IsPlaying)
{
// Move the player's paddle
if (i.isKeyDown(KeyCode.Up) && (LeftPaddle.position.y > 5.f))
LeftPaddle.move(0.f, -LeftPaddleSpeed * app.frameTime);
if (i.isKeyDown(KeyCode.Down) && (LeftPaddle.position.y < app.view.getHeight() - LeftPaddle.size.y - 5.f))
LeftPaddle.move(0.f, LeftPaddleSpeed * app.frameTime);
// Move the computer's paddle
if (((RightPaddleSpeed < 0.f) && (RightPaddle.position.y > 5.f)) ||
((RightPaddleSpeed > 0.f) && (RightPaddle.position.y < app.view.getHeight() - RightPaddle.size.y - 5.f)))
{
RightPaddle.move(0.f, RightPaddleSpeed * app.frameTime);
}
// Update the computer's paddle direction according to the ball position
AITimer.stop();
if (AITimer.milliseconds > AITime)
{
AITimer.start();
if ((RightPaddleSpeed < 0) && (Ball.position.y + Ball.size.y > RightPaddle.position.y + RightPaddle.size.y))
RightPaddleSpeed = -RightPaddleSpeed;
if ((RightPaddleSpeed > 0) && (Ball.position.y < RightPaddle.position.y))
RightPaddleSpeed = -RightPaddleSpeed;
}
// Move the ball
float Factor = BallSpeed * app.frameTime;
Ball.move(cos(BallAngle) * Factor, sin(BallAngle) * Factor);
// Check collisions between the ball and the screen
if (Ball.position.x < 0.f)
{
IsPlaying = false;
End.text("You lost !\n(press escape to exit)"c);
}
if (Ball.position.x + Ball.size.x > app.view.getWidth())
{
IsPlaying = false;
End.text("You won !\n(press escape to exit)"c);
}
if (Ball.position.y < 0.f)
{
BallSound.play();
BallAngle = -BallAngle;
Ball.y = 0.1f;
}
if (Ball.position.y + Ball.size.y > app.view.getHeight())
{
BallSound.play();
BallAngle = -BallAngle;
Ball.y = app.view.getHeight() - Ball.size.y - 0.1f;
}
// Check the collisions between the ball and the paddles
// Left Paddle
if (Ball.position.x < LeftPaddle.position.x + LeftPaddle.size.x &&
Ball.position.x > LeftPaddle.position.x + (LeftPaddle.size.x / 2.0f) &&
Ball.position.y + Ball.size.y >= LeftPaddle.position.y &&
Ball.position.y <= LeftPaddle.position.y + LeftPaddle.size.y)
{
BallSound.play();
BallAngle = PI - BallAngle;
Ball.x = LeftPaddle.position.x + LeftPaddle.size.x + 0.1f;
}
// Right Paddle
if (Ball.position.x + Ball.size.x > RightPaddle.position.x &&
Ball.position.x + Ball.size.x < RightPaddle.position.x + (RightPaddle.size.x / 2.0f) &&
Ball.position.y + Ball.size.y >= RightPaddle.position.y &&
Ball.position.y <= RightPaddle.position.y + RightPaddle.size.y)
{
BallSound.play();
BallAngle = PI - BallAngle;
Ball.x = RightPaddle.position.x - Ball.size.x - 0.1f;
}
}
// Draw the background, paddles and ball sprites
app.draw(LeftPaddle);
app.draw(RightPaddle);
app.draw(Ball);
fpsClock.stop();
if(fpsClock.seconds >= 1)
{
fps.text = std.string.format("%d fps", iFps);
iFps = 0;
fpsClock.start();
}
++iFps;
app.draw(fps);
// If the game is over, display the end message
if (!IsPlaying)
app.draw(End);
// Display things on screen
app.display();
}
}

View File

@ -1,117 +0,0 @@
module postfx;
import dsfml.graphics.all;
import dsfml.system.all;
import dsfml.window.all;
const char[][5] EFFECTS = ["nothing", "blur", "colorize", "fisheye", "wave"];
void main()
{
int actualIndex;
// Check that the system can use post effects
if (PostFX.canUsePostFX() == false)
assert(0, "Your system doesn't support Post Effects.");
// Create the main window
RenderWindow app = new RenderWindow(VideoMode(800, 600), "SFML PostFX");
app.setFramerateLimit(100);
// Load a cute background image to display :)
Sprite background = new Sprite(new Image("Data/background.jpg"));
// Load the image needed for the wave effect
Image WaveImage = new Image("Data/wave.jpg");
// Load all effects
PostFX[char[]] Effects;
foreach(char[] c; EFFECTS)
{
Effects[c] = new PostFX("Data/" ~ c ~ ".sfx");
}
PostFX currentEffect = Effects[EFFECTS[actualIndex]];
// Do specific initializations
Effects["nothing"].setTexture("framebuffer", null);
Effects["blur"].setTexture("framebuffer", null);
Effects["blur"].setParameter("offset", 0.f);
Effects["colorize"].setTexture("framebuffer", null);
Effects["colorize"].setParameter("color", 1.f, 1.f, 1.f);
Effects["fisheye"].setTexture("framebuffer", null);
Effects["wave"].setTexture("framebuffer", null);
Effects["wave"].setTexture("wave", WaveImage);
Font f = new Font("Data/cheeseburger.ttf");
// Define a string for displaying current effect description
Text curFXStr = new Text("Current effect is " ~ EFFECTS[actualIndex]);
curFXStr.setFont(f);
curFXStr.setPosition(20.f, 0.f);
// Define a string for displaying help
Text infoStr = new Text("Move your mouse to change the effect parameters\nPress numpad + and - to change effect\nWarning : some effects may not work\ndepending on your graphics card"c);
infoStr.setFont(f);
infoStr.setPosition(20.f, 460.f);
infoStr.setColor(Color(200, 100, 150));
// Start the game loop
while (app.isOpened())
{
// Process events
Event evt;
while (app.getEvent(evt))
{
// Close window : exit
if (evt.Type == Event.EventType.CLOSED ||
evt.Type == Event.EventType.KEYPRESSED && evt.Key.Code == KeyCode.ESCAPE)
app.close();
if (evt.Type == Event.EventType.KEYPRESSED)
{
// Add key : next effect
if (evt.Key.Code == KeyCode.ADD)
{
if (actualIndex == 4)
actualIndex = 0;
else
actualIndex++;
currentEffect = Effects[EFFECTS[actualIndex]];
curFXStr.setText("Current effect is " ~ EFFECTS[actualIndex]);
}
// Subtract key : previous effect
if (evt.Key.Code == KeyCode.SUBTRACT)
{
if (actualIndex == 0)
actualIndex = 4;
else
actualIndex--;
currentEffect = Effects[EFFECTS[actualIndex]];
curFXStr.setText("Current effect is " ~ EFFECTS[actualIndex]);
}
}
}
// Get the mouse position in the range [0, 1]
float X = app.getInput().getMouseX() / cast(float) app.getWidth();
float Y = app.getInput().getMouseY() / cast(float) app.getHeight();
// Update the current effect
if (EFFECTS[actualIndex] == "blur") currentEffect.setParameter("offset", X * Y * 0.1f);
else if (EFFECTS[actualIndex] == "colorize") currentEffect.setParameter("color", 0.3f, X, Y);
else if (EFFECTS[actualIndex] == "fisheye") currentEffect.setParameter("mouse", X, 1.f - Y);
else if (EFFECTS[actualIndex] == "wave") currentEffect.setParameter("offset", X, Y);
// Draw background and apply the post-fx
app.draw(background);
app.draw(currentEffect);
// Draw interface strings
app.draw(curFXStr);
app.draw(infoStr);
// Finally, display the rendered frame on screen
app.display();
}
}

View File

@ -1,66 +0,0 @@
module socketclient;
import dsfml.system.all;
import dsfml.network.all;
version (Tango)
{
import tango.io.Console;
import tango.io.Stdout;
}
else
{
import std.stdio;
}
void main()
{
//The TCP socket
SocketTCP client = new SocketTCP();
//Try to connect to server (on localhost for this sample)
client.connect(9000, IPAddress.LOCALHOST);
display("Connected to server."w);
//Prepare a packet with a string
Packet p = new Packet();
p.set("Hello from the client !"w);
if (client.send(p) != SocketStatus.DONE) // Assert on error
assert(0);
//Clear the packet
p.clear();
//Wait for the response of the server and display it
if (client.receive(p) != SocketStatus.DONE)
assert(0);
wchar[] c;
p.get(c);
display("Packet received : "w ~ c);
read();
}
void display(wchar[] c)
{
version (Tango)
{
Stdout(c).newline;
}
else
{
writefln("%s", c);
}
}
void read()
{
version (Tango)
{
Cin.get();
}
else
{
readln();
}
}

View File

@ -1,83 +0,0 @@
module socketserver;
import dsfml.system.all;
import dsfml.network.all;
version (Tango)
{
import tango.io.Console;
import tango.io.Stdout;
}
else
{
import std.stdio;
}
void main()
{
//We create a TCP socket for listening incomming client
SocketTCP listener = new SocketTCP();
//Set a random port for the listener
if (!listener.listen(9000))
assert(0);
//Creation of TCP socket
SocketTCP client = new SocketTCP();
IPAddress ipClient;
display("Waiting for client."w);
if (listener.accept(client, ipClient) == SocketStatus.DONE) //This call blocks until client connection
{
display("New client connected."w);
//The packet for retrieving the client message
Packet p = new Packet();
display("Waiting for data"w);
if (client.receive(p) != SocketStatus.DONE) //Assert on reception error
assert(0);
//Display the string send by the client
wchar[] c;
p.get(c);
display("Packet received : "w ~ c);
//Clear the packet (We could use a new one)
p.clear();
//and send response to client
client.send(p.set("Hello from the server !"w));
}
read();
}
/**
* Multilib string display
*/
void display(wchar[] c)
{
version (Tango)
{
Stdout(c).newline;
}
else
{
writefln("%s", c);
}
}
/**
* Dummy function to prevent console closing on windows
*/
void read()
{
version (Tango)
{
Cin.get();
}
else
{
readln();
}
}

View File

@ -1,185 +0,0 @@
module sound3d;
import dsfml.system.all;
import dsfml.window.all;
import dsfml.graphics.all;
import dsfml.audio.all;
void main()
{
//We create our window with a limit of 100 and a white backcolor.
RenderWindow app = new RenderWindow (VideoMode(800, 600, 32), "Sound Spatialization Sample");
app.useVerticalSync(true);
Font f = new Font("Data/cheeseburger.ttf");
//Some instructions
Text s = new Text("Click anywhere on screen to change listener position.\nPress + or - to modify the speed of the car."c, f);
s.characterSize = 34;
s.setPosition(20, 30);
s.color = Color.BLACK;
//We prepare our images and the sound
string[2] images = ["Data/bluerallyecarleft.bmp", "Data/bluerallyecarright.bmp"];
Car c = new Car(images, "Data/car_idle.wav");
int carSpeed = 100;
//Set default position for the car and the listener
c.position = Vector2f(0, 300);
SoundListener.position = Vector2f(400, 300);
c.startPlaying();
//Start the main loop
while (app.isOpened())
{
app.clear(Color.WHITE);
Event evt;
//The event loop
while (app.getEvent(evt))
{
// if the window is closed, we can leave the game loop
if (evt.Type == EventType.Closed)
app.close();
// we handle the click event to change listener position
else if (evt.Type == EventType.MouseButtonPressed && evt.MouseButton.Button == MouseButtons.Left)
{
Input i = app.input;
SoundListener.position = Vector2f(i.mouseX, i.mouseY);
}
// and eventual keys press
else if (evt.Type == EventType.KeyPressed)
{
//Change the car speed
if (evt.Key.Code == KeyCode.Add)
{
carSpeed += 25;
}
else if (evt.Key.Code == KeyCode.Substract)
{
carSpeed -= 25;
}
}
}
//We move constantly our car.
c.move(Vector2f(app.frameTime * carSpeed, 0));
//Draw all the sprite and string on render window
app.draw(s);
app.draw(c.sprite);
app.draw(SoundListener.sprite);
//And finally display the window
app.display();
}
}
// Encapsulate the listener position and the visor sprite.
// There is only one listener so all the methods are statics.
class SoundListener
{
static Sprite s_crosshair;
static Vector2f s_p;
static this()
{
Image crosshairImg = new Image("Data/crosshair.tga");
crosshairImg.createMaskFromColor(Color.WHITE);
s_crosshair = new Sprite(crosshairImg);
s_crosshair.setOrigin(s_crosshair.size.x / 2, s_crosshair.size.y / 2);
//Listener.setTarget(1.f, 0.f, 0.f);
}
// Adjust position of the listener
@property static void position(Vector2f p)
{
Listener.setPosition(p.x, p.y, 5.f);
s_crosshair.setPosition(p.x, p.y);
}
@property static Sprite sprite()
{
return s_crosshair;
}
}
//! Class encapsulating all data for our car
class Car
{
Vector2f m_actual;
Sprite m_sprite;
Sound m_sound;
bool reverse;
Image[2] imgs;
//Constructor with with a fixed size string array of image path, and a string for the sound path
this (string[2] images, string soundFilename)
{
//load images and create filter
imgs[0] = new Image(images[0]); imgs[1] = new Image(images[1]);
foreach(img; imgs)
img.createMaskFromColor(Color(97, 68, 43));
m_sprite = new Sprite(imgs[0]);
m_sprite.setOrigin(m_sprite.size.x / 2, m_sprite.size.y / 2);
SoundBuffer buff = new SoundBuffer(soundFilename);
//load our sound with loop enabled
m_sound = new Sound(buff, true);
m_sound.attenuation = .05f;
}
// Begin the sound play
void startPlaying()
{
m_sound.play();
}
// Set the position of the car on the window
// Used to setup the begin car window and sound location
@property void position(Vector2f p)
{
m_sprite.setPosition(p.x, p.y);
m_sound.setPosition(p.x, 0, p.y);
}
//Move the car (visual and sound position)
//If the car leave the screen, we change the sprite image and reverse moving
void move(Vector2f vec)
{
// if the car is beyond the right screen limit
if (!reverse && m_sprite.position.x > 850)
{
m_sprite.setImage(imgs[1]);
reverse = true;
}
// same as above but for left limit
else if (reverse && vec.x + m_sprite.position.x < -50)
{
m_sprite.setImage(imgs[0]);
reverse = false;
}
if (reverse)
vec = -vec;
m_sprite.move(vec);
Vector2f pos = m_sprite.position;
m_sound.setPosition(pos.x , pos.y, 0);
}
@property Sprite sprite()
{
return m_sprite;
}
}

View File

@ -1,97 +0,0 @@
module soundstream;
import dsfml.system.all;
import dsfml.audio.all;
version (Tango)
{
import tango.io.Console;
import tango.io.Stdout;
}
else
{
import std.stdio;
}
// SoundStream is an abstract class.
// You need to implement onStart() and onGetData()
// Don't forget to call initialize() before any usage or playback will fail.
class MySoundStream : SoundStream
{
SoundBuffer m_buff;
short[] m_data;
size_t m_cursor;
this()
{
// We initialize the stream with some sound informations
super(1, 11025);
// We create a sound buffer to load samples from files
m_buff = new SoundBuffer("Data/car_idle.wav");
m_data = m_buff.samples[0..m_buff.samplesCount];
}
protected:
/*
bool onStart()
{
// No specifics things to do, just return true.
return true;
}
*/
override bool onGetData(out short[] data)
{
// We ensure that we have enough data to send
if (m_cursor + this.sampleRate > m_data.length)
return false;
// Assign data in the buffer ...
data = m_data[m_cursor..m_cursor + this.sampleRate];
// ... and increment the cursor
m_cursor += this.sampleRate;
return true;
}
override void onSeek(float timeOffset)
{
}
}
void main()
{
MySoundStream stream = new MySoundStream();
display("Playing sound !\n Press enter to stop playback.");
stream.play();
read(); // prevent console from closing
stream.stop();
}
void display(string c)
{
version (Tango)
{
Stdout(c).newline;
}
else
{
writeln(c);
}
}
/**
* Dummy function to prevent console closing on windows
*/
void read()
{
version (Tango)
{
Cin.get();
}
else
{
readln();
}
}

View File

@ -1,69 +0,0 @@
module view;
import dsfml.system.all;
import dsfml.window.all;
import dsfml.graphics.all;
void main()
{
RenderWindow window = new RenderWindow(VideoMode(800, 600), "View sample");
window.framerateLimit = 100;
Input input = window.input;
Vector2f top;
FloatRect bound;
Shape s;
bool mousePressed;
Sprite background = new Sprite(new Image("Data/background.jpg"));
Font f = new Font("Data/cheeseburger.ttf");
Text str = new Text("Create a selection of the background with your mouse.\nPress Enter to zoom to this selection.\nPress Escape to return to the default view."c, f);
while (window.isOpened())
{
Event evt;
while (window.getEvent(evt))
{
if ( evt.Type == EventType.MouseButtonPressed &&
evt.MouseButton.Button == MouseButtons.Left)
{
top = window.convertCoords(input.mouseX, input.mouseY);
mousePressed = true;
}
else if ( evt.Type == EventType.MouseButtonReleased &&
evt.MouseButton.Button == MouseButtons.Left)
{
mousePressed = false;
}
else if ( evt.Type == EventType.MouseMoved &&
mousePressed)
{
Vector2f bottom = window.convertCoords(input.mouseX, input.mouseY);
bound = FloatRect(top.x, top.y, bottom.x-top.x, bottom.y-top.y);
s = Shape.rectangle(bound.left, bound.top, bound.width, bound.height, Color(0, 0, 0, 0), 1, Color.BLACK);
}
else if ( evt.Type == EventType.KeyPressed &&
evt.Key.Code == KeyCode.Return)
{
if (bound != FloatRect())
window.view = new View(bound);
s = null;
}
else if ( evt.Type == EventType.KeyPressed &&
evt.Key.Code == KeyCode.Escape)
{
window.view = window.defaultView;
}
else if ( evt.Type == EventType.Closed)
window.close();
}
window.draw(background);
window.draw(str);
if (s !is null) window.draw(s);
window.display();
}
}

View File

@ -1,72 +0,0 @@
module client;
import util;
// Specialization of audio recorder for sending recorded audio
// data through the network
class NetworkRecorder : SoundRecorder
{
public:
// Constructor
this(SocketTCP Socket)
{
mySocket = Socket;
}
~this()
{
delete mySocket;
}
protected:
override bool onStart()
{
return true;
}
override void onStop()
{
}
override bool onProcessSamples(short[] samples)
{
// Pack the audio samples into a network packet
Packet PacketOut = new Packet();
PacketOut.set(AudioData);
PacketOut.append((cast(byte*)samples.ptr)[0..samples.length * short.sizeof]);
// Send the audio packet to the server
return mySocket.send(PacketOut) == SocketStatus.DONE;
}
SocketTCP mySocket; ///< Socket used to communicate with the server
}
void runClient(IPAddress adr, int port)
{
// Create a TCP socket for communicating with server
SocketTCP Socket = new SocketTCP();
// Connect to the specified server
if (!Socket.connect(port, adr))
return;
// Wait for user input...
Cout("Press enter to start recording audio").newline;
Cin.get();
// Create a instance of our custom recorder
NetworkRecorder Recorder = new NetworkRecorder(Socket);
// Start capturing audio data
Recorder.start(44100);
Cout("Press enter to stop recording audio").newline;
Cin.get();
Recorder.stop();
// Send a "end-of-stream" packet
Packet PacketOut = new Packet();
PacketOut.set(EndOfStream);
Socket.send(PacketOut);
}

View File

@ -1,46 +0,0 @@
module entry;
import util;
import server;
import client;
int main(char[][] args)
{
char[][] argc = args.dup;
if (argc.length > 1)
{
if ( argc[1] == "-c" &&
argc.length == 4)
{
IPAddress adr = IPAddress(argc[2]);
if (adr.isValid() &&
parse(argc[3]) <= 60000 &&
parse(argc[3]) >= 1000)
{
runClient(adr, parse(argc[3]));
}
else
printUsage();
}
else if ( argc[1] == "-s" &&
argc.length == 3 &&
parse(argc[2]) <= 60000 &&
parse(argc[2]) >= 1000)
{
runServer(parse(argc[2]));
}
else
printUsage();
}
else
printUsage();
return 0;
}
void printUsage()
{
Cout("Usage :\n voip.exe [-c [ip address] | -s] [port] \n -c = run as client\n -s = run as server\n ip address = address of the server\n port = port between 1000 and 65000\n").newline;
}

View File

@ -1,162 +0,0 @@
module server;
import util;
class NetworkAudioStream : SoundStream
{
public:
static this()
{
s_sync = new Object();
}
// Default constructor
this()
{
myListener = new SocketTCP();
myClient = new SocketTCP();
// Set the sound parameters
super(1, 44100);
}
// Destructor
~this()
{
// Close the sockets
delete myClient;
delete myListener;
}
// Run the server, stream audio data from the client
void start(int Port)
{
if (!myHasFinished)
{
// Listen to the given port for incoming connections
if (!myListener.listen(Port))
return;
Cout("Listening").newline;
myListener.accept(myClient);
Cout("New Client").newline;
// Start playback
play();
// Start receiving audio data
receiveLoop();
}
else
{
// Start playback
play();
}
}
protected:
override bool onStart()
{
// Reset the playing offset
myOffset = 0;
return true;
}
override bool onGetData(out short[] data)
{
// We have reached the end of the buffer and all audio data have been played : we can stop playback
if ((myOffset == mySamples.length) && myHasFinished)
return false;
// No new data has arrived since last update : wait until we get some
while (myOffset == mySamples.length && !myHasFinished)
sleep(0.01f);
synchronized(s_sync)
{
myTempBuffer = mySamples[myOffset..mySamples.length];
// Update the playing offset
myOffset += myTempBuffer.length;
}
data = myTempBuffer;
return true;
}
private:
void receiveLoop()
{
while (!myHasFinished)
{
// Get waiting audio data from the network
Packet PacketIn = new Packet();
if (myClient.receive(PacketIn) != SocketStatus.DONE)
break;
// Extract the message ID
ubyte Id;
PacketIn.get(Id);
if (Id == AudioData)
{
// Extract audio samples from the packet, and append it to our samples buffer
synchronized(s_sync)
{
byte* temp = PacketIn.getData().ptr;
temp++;
mySamples ~= (cast(short*)temp)[0..(PacketIn.getDataSize - byte.sizeof ) / short.sizeof];
}
}
else if (Id == EndOfStream)
{
// End of stream reached : we stop receiving audio data
myHasFinished = true;
}
else
{
// Something's wrong...
myHasFinished = true;
}
}
}
SocketTCP myListener;
SocketTCP myClient;
short[] mySamples;
short[] myTempBuffer;
size_t myOffset;
bool myHasFinished;
static Object s_sync;
};
// Launch a server and wait for incoming audio data from
// a connected client
void runServer(int Port)
{
// Build an audio stream to play sound data as it is received through the network
NetworkAudioStream audioStream = new NetworkAudioStream;
audioStream.start(Port);
// Loop until the sound playback is finished
while (audioStream.getStatus() != SoundStatus.STOPPED)
{
// Leave some CPU time for other threads
sleep(0.1f);
}
Cout("Enter to replay").newline;
Cin.get();
// Replay the sound (just to make sure replaying the received data is OK)
audioStream.play();
// Loop until the sound playback is finished
while (audioStream.getStatus() != SoundStatus.STOPPED)
{
// Leave some CPU time for other threads
sleep(0.1f);
}
}

View File

@ -1,49 +0,0 @@
module util;
const ubyte AudioData = 1;
const ubyte EndOfStream = 2;
public import dsfml.system.all;
public import dsfml.audio.all;
public import dsfml.network.all;
version(Tango)
{
public import tango.io.Console;
public import tango.text.convert.Integer;
}
else
{
public import std.stdio;
//simple abstraction of Cout & Cin for phobos
class Cout
{
static Cout s_c;
static this()
{
s_c = new Cout();
}
static Cout opCall(char[] str)
{
writefln("%s", str);
return s_c;
}
void newline()
{
}
}
class Cin
{
static char[] get()
{
return readln();
}
}
public import std.string : atoi;
alias atoi parse;
}

View File

@ -1,5 +0,0 @@
graft src
graft scripts
graft doc
graft samples

View File

@ -1,2 +0,0 @@
__all__ = ['sf']

View File

@ -1,96 +0,0 @@
div#logo
{
margin-bottom : 1em;
background : url("http://www.sfml-dev.org/images/logo-bg.jpg") repeat-x;
}
div#logo a
{
display : block;
}
div.class_desc
{
margin-left:10px;
font-weight: bolder;
color:#168;
}
div.base_class
{
margin-top:8px;
margin-left:10px;
font-weight: bold;
color:#168;
}
div.attr_name
{
margin-top:20px;
margin-left:10px;
font-weight: bolder;
}
div.inherited
{
margin-left:20px;
font-size: smaller;
}
div.desc
{
margin-left:20px;
}
div.event_member
{
margin-left:30px;
font-weight: lighter;
}
p#footer
{
text-decoration : overline;
color : #606060;
padding-top : 1em;
text-align : center;
font-size : smaller;
}
p#footer a
{
color : #007298;
text-decoration : none;
}
H1 {
text-align : center;
margin-top : 0px;
color : #2090B0;
font-size : 160%;
}
H2 {
font-size: 120%;
}
H3 {
font-size: 100%;
}
a {
color: #2090B0;
}
a:visited {
color: #2090B0;
}
HR { height: 1px;
border: none;
border-top: 1px solid black;
}
BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV {
font-family: Geneva, Arial, Helvetica, sans-serif;
}
BODY,TD {
font-size: 90%;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 868 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -1,98 +0,0 @@
# coding=utf-8
from PySFML import sf
import random
# Simple class for an apple.
class Apple:
sprite = None
speed = (2, 2)
rotationstep = 1
def __init__( self, image ):
self.sprite = sf.Sprite( image )
self.sprite.SetOrigin( image.GetWidth() / 2, image.GetHeight() / 2 )
# Set resolution and create the window.
Resolution = (800, 600)
wnd = sf.RenderWindow( sf.VideoMode( Resolution[0], Resolution[1], 32 ), "Hello SFML!" )
wnd.UseVerticalSync( True )
# Load a fancy font.
cheese = sf.Font()
cheese.LoadFromFile( "data/cheeseburger.ttf" )
# Create a text.
text = sf.Text( u"Hello SFML from Python!", cheese, 50 )
text.SetOrigin( text.GetRect().GetSize()[0] / 2, text.GetRect().GetSize()[1] / 2 )
text.SetPosition( 400, 300 )
text.SetColor( sf.Color( 0, 100, 0, 100 ) )
# Create a text for FPS display.
fpstext = sf.Text( u"FPS: --", cheese )
fpstext.SetColor( sf.Color( 0, 0, 0 ) )
currentfps = 0
fpsclock = sf.Clock()
# Load apple image from file.
appleimage = sf.Image()
appleimage.LoadFromFile( "data/apple.png" )
# Create some apples with random position, speed, rotation and color.
apples = [Apple( appleimage ) for num in range( 0, 100 )]
for apple in apples:
apple.sprite.SetOrigin( appleimage.GetWidth() / 2, appleimage.GetHeight() / 2 )
apple.sprite.SetPosition(
random.randint( apple.sprite.GetOrigin()[0], Resolution[0] - apple.sprite.GetOrigin()[0] ),
random.randint( apple.sprite.GetOrigin()[1], Resolution[1] - apple.sprite.GetOrigin()[1] )
)
apple.sprite.SetColor( sf.Color( random.randint( 100, 255 ), random.randint( 100, 255 ), random.randint( 100, 255 ) ) )
randx = random.randint( -3, 3 )
randy = random.randint( -3, 3 )
apple.speed = (1 if randx == 0 else randx, 1 if randy == 0 else randy)
apple.rotationstep = random.uniform( 1.0, 20.0 ) - 10.0
event = sf.Event()
# Main loop.
while wnd.IsOpened():
# Fetch all pending events and process them.
while wnd.GetEvent( event ):
# Quit when window has been closed or Escape has been pressed.
if event.Type == sf.Event.Closed:
wnd.Close()
elif event.Type == sf.Event.KeyPressed and event.Key.Code == sf.Key.Escape:
wnd.Close()
# Clear window to white color.
wnd.Clear( sf.Color( 255, 255, 255 ) )
# Draw all apples and texts.
for apple in apples:
wnd.Draw( apple.sprite )
wnd.Draw( text )
wnd.Draw( fpstext )
wnd.Display() # Display everything.
# Count FPS.
currentfps += 1
if fpsclock.GetElapsedTime() >= 1.0:
fpsclock.Reset()
fpstext.SetString( u"FPS: " + unicode( currentfps ) )
currentfps = 0
# Update apples (for the "bounce effect").
for apple in apples:
apple.sprite.Move( apple.speed[0], apple.speed[1] )
apple.sprite.Rotate( apple.rotationstep )
realpos = (apple.sprite.GetPosition()[0] - apple.sprite.GetOrigin()[0], apple.sprite.GetPosition()[1] - apple.sprite.GetOrigin()[1])
if (apple.speed[0] > 0 and realpos[0] >= Resolution[0] - appleimage.GetWidth()) or (apple.speed[0] < 0 and realpos[0] <= 0):
apple.speed = (apple.speed[0] * -1, apple.speed[1])
if (apple.speed[1] > 0 and realpos[1] >= Resolution[1] - appleimage.GetWidth()) or (apple.speed[1] < 0 and realpos[1] <= 0):
apple.speed = (apple.speed[0], apple.speed[1] * -1)

View File

@ -1,165 +0,0 @@
#!/usr/bin/python
from PySFML import sf
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
def main():
# Create main window
App = sf.RenderWindow(sf.VideoMode(800, 600), "SFML OpenGL")
App.SetActive()
# Create a sprite for the background
BackgroundImage = sf.Image()
if not BackgroundImage.LoadFromFile("../../samples/bin/datas/opengl/background.jpg"):
return
Background = sf.Sprite(BackgroundImage)
# Load an OpenGL texture.
# We could directly use a sf.Image as an OpenGL texture (with its Bind() member function),
# but here we want more control on it (generate mipmaps, ...) so we create a new one
Image = sf.Image()
if not Image.LoadFromFile("../../samples/bin/datas/opengl/texture.jpg"):
return
# The next line is a bit different from the C++ version
Texture = glGenTextures(1) # instead of glGenTextures(1, &Texture);
glBindTexture(GL_TEXTURE_2D, Texture)
# It is almost the same line there, except in C++, the last argument was Image.GetPixelsPtr().
# In python, GetPixels simply returns a string.
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, Image.GetWidth(), Image.GetHeight(), GL_RGBA, GL_UNSIGNED_BYTE, Image.GetPixels())
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
# Enable Z-buffer read and write
glEnable(GL_DEPTH_TEST)
glDepthMask(GL_TRUE)
glClearDepth(1.)
# Setup a perspective projection
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(90., 1., 1., 500.)
# Bind our texture
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, Texture)
glColor4f(1., 1., 1., 1.)
# Create a clock for measuring the time elapsed
Clock = sf.Clock()
# Start game loop
while App.IsOpened():
# Process events
Event = sf.Event()
while App.GetEvent(Event):
# Close window : exit
if Event.Type == sf.Event.Closed:
App.Close()
# Escape key : exit
if (Event.Type == sf.Event.KeyPressed) and (Event.Key.Code == sf.Key.Escape):
App.Close()
# Adjust the viewport when the window is resized
if Event.Type == sf.Event.Resized:
glViewport(0, 0, Event.Size.Width, Event.Size.Height)
# Draw background
App.Draw(Background)
# Active window to be able to perform OpenGL commands.
App.SetActive()
# Clear depth buffer
glClear(GL_DEPTH_BUFFER_BIT)
# Apply some transformations
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef(0, 0, -200)
glRotatef(Clock.GetElapsedTime() * 50, 1, 0, 0)
glRotatef(Clock.GetElapsedTime() * 30, 0, 1, 0)
glRotatef(Clock.GetElapsedTime() * 90, 0, 0, 1)
# Draw a cube
glBegin(GL_QUADS)
glTexCoord2f(0, 0)
glVertex3f(-50., -50., -50.)
glTexCoord2f(0, 1)
glVertex3f(-50., 50., -50.)
glTexCoord2f(1, 1)
glVertex3f( 50., 50., -50.)
glTexCoord2f(1, 0)
glVertex3f( 50., -50., -50.)
glTexCoord2f(0, 0)
glVertex3f(-50., -50., 50.)
glTexCoord2f(0, 1)
glVertex3f(-50., 50., 50.)
glTexCoord2f(1, 1)
glVertex3f( 50., 50., 50.)
glTexCoord2f(1, 0)
glVertex3f( 50., -50., 50.)
glTexCoord2f(0, 0)
glVertex3f(-50., -50., -50.)
glTexCoord2f(0, 1)
glVertex3f(-50., 50., -50.)
glTexCoord2f(1, 1)
glVertex3f(-50., 50., 50.)
glTexCoord2f(1, 0)
glVertex3f(-50., -50., 50.)
glTexCoord2f(0, 0)
glVertex3f(50., -50., -50.)
glTexCoord2f(0, 1)
glVertex3f(50., 50., -50.)
glTexCoord2f(1, 1)
glVertex3f(50., 50., 50.)
glTexCoord2f(1, 0)
glVertex3f(50., -50., 50.)
glTexCoord2f(0, 1)
glVertex3f(-50., -50., 50.)
glTexCoord2f(0, 0)
glVertex3f(-50., -50., -50.)
glTexCoord2f(1, 0)
glVertex3f( 50., -50., -50.)
glTexCoord2f(1, 1)
glVertex3f( 50., -50., 50.)
glTexCoord2f(0, 1)
glVertex3f(-50., 50., 50.)
glTexCoord2f(0, 0)
glVertex3f(-50., 50., -50.)
glTexCoord2f(1, 0)
glVertex3f( 50., 50., -50.)
glTexCoord2f(1, 1)
glVertex3f( 50., 50., 50.)
glEnd()
# Draw some text on top of our OpenGL object
Text = sf.Text("This is a rotating cube")
Text.SetPosition(230., 300.)
Text.SetColor(sf.Color(128, 0, 128))
App.Draw(Text)
# Finally, display the rendered frame on screen
App.Display()
# Don't forget to destroy our texture
# In C++, the call to this function was a bit different
glDeleteTextures(Texture) # instead of glDeleteTextures(1, &Texture);
return
main()

View File

@ -1,43 +0,0 @@
#!/usr/bin/python
# You can notice that here we use PySFML.sf instead of just PySFML
# Therefore it won't be needed to put sf. in front of SFML classes
from PySFML import sf
def Main():
Buffer = sf.SoundBuffer()
if not Buffer.LoadFromFile("data/fart.wav"): # Loads the sound
return
Fart = sf.Sound(Buffer, False)
WindowWidth, WindowHeight = 640, 480
App = sf.RenderWindow(sf.VideoMode(WindowWidth,WindowHeight,32), "Sound with PySFML", sf.Style.Close, sf.ContextSettings(24,8,0))
App.SetFramerateLimit(30)
EventHandler = sf.Event()
InputHandler = App.GetInput()
Text = sf.Text("Turn the sound on.\nClick anywhere on the screen.\nMove the mouse. Click again.\nTry clicking in the corners.")
Text.SetX(30.)
Text.SetY(20.)
Text.SetColor(sf.Color(150, 100, 10, 255))
while App.IsOpened(): # Main loop
while App.GetEvent(EventHandler): # Event Handler
if EventHandler.Type == sf.Event.Closed:
App.Close()
if EventHandler.Type == sf.Event.KeyPressed and EventHandler.Key.Code == sf.Key.Escape:
App.Close()
if EventHandler.Type == sf.Event.MouseButtonPressed and EventHandler.MouseButton.Button == sf.Mouse.Left:
Fart.SetPitch(1.5 - 1.*InputHandler.GetMouseY()/WindowHeight)
Fart.SetPosition( 1.*(InputHandler.GetMouseX() - WindowWidth/2)/(WindowWidth/20), 2., -2.)
Fart.Play()
App.Draw(Text)
App.Display()
App.Clear(sf.Color.Black)
Main()

View File

@ -1,68 +0,0 @@
#!/usr/bin/env python
from PySFML import sf
def Main():
# Check that the device can capture audio
if sf.SoundRecorder.IsAvailable() == False:
print "Sorry, audio capture is not supported by your system"
return
# Choose the sample rate
SampleRate = 0
SampleRate = int(raw_input("Please choose the sample rate for sound capture (44100 is CD quality) : "))
# Wait for user input...
print "Press enter to start recording audio"
raw_input()
# Here we'll use an integrated custom recorder, which saves the captured data into a sfSoundBuffer
Recorder = sf.SoundBufferRecorder()
# Audio capture is done in a separate thread, so we can block the main thread while it is capturing
Recorder.Start(SampleRate)
print "Recording... press enter to stop"
raw_input()
Recorder.Stop()
# Get the buffer containing the captured data
Buffer = Recorder.GetBuffer()
# Display captured sound informations
print "Sound information :"
print " " + str(Buffer.GetDuration()) + " seconds"
print " " + str(Buffer.GetSampleRate()) + " samples / seconds"
print " " + str(Buffer.GetChannelsCount()) + " channels"
# Choose what to do with the recorded sound data
Choice = str(raw_input("What do you want to do with captured sound (p = play, s = save) ? "))
if Choice == 's':
# Choose the filename
Filename = str(raw_input("Choose the file to create : "))
# Save the buffer
Buffer.SaveToFile(Filename);
else:
# Create a sound instance and play it
Sound = sf.Sound(Buffer)
Sound.Play()
# Wait until finished
while Sound.GetStatus() == sf.Sound.Playing:
# Display the playing position - I don't know how to do this in python
# std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << Sound.GetPlayingOffset() << " sec";
# Leave some CPU time for other threads
sf.Sleep(0.1)
# Finished !
print "Done !"
# Wait until the user presses 'enter' key
print "Press enter to exit..."
raw_input()
return
Main()

View File

@ -1,67 +0,0 @@
#!/usr/bin/env python
from PySFML import sf
def Main():
# Check that the device can capture audio
if sf.SoundRecorder.CanCapture() == False:
print("Sorry, audio capture is not supported by your system")
return
# Choose the sample rate
SampleRate = int(input("Please choose the sample rate for sound capture (44100 is CD quality) : "))
# Wait for user input...
print("Press enter to start recording audio")
input()
# Here we'll use an integrated custom recorder, which saves the captured data into a sfSoundBuffer
Recorder = sf.SoundBufferRecorder()
# Audio capture is done in a separate thread, so we can block the main thread while it is capturing
Recorder.Start(SampleRate)
print("Recording... press enter to stop")
input()
Recorder.Stop()
# Get the buffer containing the captured data
Buffer = Recorder.GetBuffer()
# Display captured sound informations
print("Sound information :")
print(" " + str(Buffer.GetDuration()) + " seconds")
print(" " + str(Buffer.GetSampleRate()) + " samples / seconds")
print(" " + str(Buffer.GetChannelsCount()) + " channels")
# Choose what to do with the recorded sound data
Choice = str(input("What do you want to do with captured sound (p = play, s = save) ? "))
if Choice == 's':
# Choose the filename
Filename = str(input("Choose the file to create : "))
# Save the buffer
Buffer.SaveToFile(Filename);
else:
# Create a sound instance and play it
Sound = sf.Sound(Buffer)
Sound.Play()
# Wait until finished
while Sound.GetStatus() == sf.Sound.Playing:
# Display the playing position - I don't know how to do this in python
# std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << Sound.GetPlayingOffset() << " sec";
# Leave some CPU time for other threads
sf.Sleep(0.1)
# Finished !
print("Done !")
# Wait until the user presses 'enter' key
print("Press enter to exit...")
input()
return
Main()

Some files were not shown because too many files have changed in this diff Show More