* simply replacing spaces with tabs in the example files

git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/branches/sfml2@1440 4e206d99-4929-0410-ac5d-dfc041789085
This commit is contained in:
trass3r 2010-03-04 02:23:27 +00:00
parent 8390807b08
commit 4a19225764
9 changed files with 670 additions and 670 deletions

View File

@ -13,218 +13,218 @@ import Derelict.opengl.glu;
// An enum for each controls methods
enum ControlMethod
{
MOUSE,
KEYBOARD
MOUSE,
KEYBOARD
}
void main()
{
DerelictGL.load();
DerelictGLU.load();
//Start the message loop
Application.run(new MyForm());
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();
}
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);
}
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();
}
//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);
}
//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 onTick(Timer t, EventArgs ea)
{
draw();
}
protected void onPaint(PaintEventArgs pea)
{
super.onPaint(pea);
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 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();
}
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);
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);
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();
}
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

@ -8,110 +8,110 @@ 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.");
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);
// 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 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 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]];
// 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);
// 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
String curFXStr = new String("Current effect is " ~ EFFECTS[actualIndex]);
curFXStr.setFont(f);
curFXStr.setPosition(20.f, 0.f);
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
String infoStr = new String("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();
// 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]);
}
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]);
}
}
}
// 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();
// 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);
// 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 background and apply the post-fx
app.draw(background);
app.draw(currentEffect);
// Draw interface strings
app.draw(curFXStr);
app.draw(infoStr);
// Draw interface strings
app.draw(curFXStr);
app.draw(infoStr);
// Finally, display the rendered frame on screen
app.display();
}
// Finally, display the rendered frame on screen
app.display();
}
}

View File

@ -5,62 +5,62 @@ import dsfml.network.all;
version (Tango)
{
import tango.io.Console;
import tango.io.Stdout;
}
import tango.io.Console;
import tango.io.Stdout;
}
else
{
import std.stdio;
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();
//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);
}
version (Tango)
{
Stdout(c).newline;
}
else
{
writefln("%s", c);
}
}
void read()
{
version (Tango)
{
Cin.get();
}
else
{
readln();
}
version (Tango)
{
Cin.get();
}
else
{
readln();
}
}

View File

@ -5,79 +5,79 @@ import dsfml.network.all;
version (Tango)
{
import tango.io.Console;
import tango.io.Stdout;
import tango.io.Console;
import tango.io.Stdout;
}
else
{
import std.stdio;
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);
//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();
//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
* Multilib string display
*/
void display(wchar[] c)
{
version (Tango)
{
Stdout(c).newline;
}
else
{
writefln("%s", c);
}
version (Tango)
{
Stdout(c).newline;
}
else
{
writefln("%s", c);
}
}
/**
* Dummy function to prevent console closing on windows
* Dummy function to prevent console closing on windows
*/
void read()
{
version (Tango)
{
Cin.get();
}
else
{
readln();
}
version (Tango)
{
Cin.get();
}
else
{
readln();
}
}

View File

@ -5,12 +5,12 @@ import dsfml.audio.all;
version (Tango)
{
import tango.io.Console;
import tango.io.Stdout;
import tango.io.Console;
import tango.io.Stdout;
}
else
{
import std.stdio;
import std.stdio;
}
// SoundStream is an abstract class.
@ -18,74 +18,74 @@ else
// 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.getSamples[0..m_buff.getSamplesCount];
}
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.getSamples[0..m_buff.getSamplesCount];
}
protected:
bool onStart()
{
// No specifics things to do, just return true.
return true;
}
bool onGetData(out short[] data)
{
// We ensure that we have enough data to send
if (m_cursor + this.getSampleRate > m_data.length)
return false;
// Assign data in the buffer ...
data = m_data[m_cursor..m_cursor + this.getSampleRate];
// ... and increment the cursor
m_cursor += this.getSampleRate;
return true;
}
bool onStart()
{
// No specifics things to do, just return true.
return true;
}
bool onGetData(out short[] data)
{
// We ensure that we have enough data to send
if (m_cursor + this.getSampleRate > m_data.length)
return false;
// Assign data in the buffer ...
data = m_data[m_cursor..m_cursor + this.getSampleRate];
// ... and increment the cursor
m_cursor += this.getSampleRate;
return true;
}
}
void main()
{
MySoundStream stream = new MySoundStream();
display("Playing sound !\n Press enter to stop playback.");
stream.play();
read();
stream.stop();
MySoundStream stream = new MySoundStream();
display("Playing sound !\n Press enter to stop playback.");
stream.play();
read();
stream.stop();
}
void display(char[] c)
{
version (Tango)
version (Tango)
{
Stdout(c).newline;
Stdout(c).newline;
}
else
else
{
writefln("%s", c);
writefln("%s", c);
}
}
/**
* Dummy function to prevent console closing on windows
* Dummy function to prevent console closing on windows
*/
void read()
{
version (Tango)
version (Tango)
{
Cin.get();
Cin.get();
}
else
else
{
readln();
readln();
}
}

View File

@ -9,64 +9,64 @@ class NetworkRecorder : SoundRecorder
{
public:
// Constructor
this(SocketTCP Socket)
{
mySocket = Socket;
}
// Constructor
this(SocketTCP Socket)
{
mySocket = Socket;
}
~this()
{
delete mySocket;
}
~this()
{
delete mySocket;
}
protected:
override bool onStart()
{
return true;
}
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;
}
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
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();
// Create a TCP socket for communicating with server
SocketTCP Socket = new SocketTCP();
// Connect to the specified server
if (!Socket.connect(port, adr))
return;
// 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();
// 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);
// 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();
// 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);
// Send a "end-of-stream" packet
Packet PacketOut = new Packet();
PacketOut.set(EndOfStream);
Socket.send(PacketOut);
}

View File

@ -6,41 +6,41 @@ 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]));
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;
}
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;
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

@ -5,130 +5,130 @@ import util;
class NetworkAudioStream : SoundStream
{
public:
static this()
{
s_sync = new Object();
}
static this()
{
s_sync = new Object();
}
// Default constructor
this()
{
myListener = new SocketTCP();
myClient = new SocketTCP();
// Set the sound parameters
super(1, 44100);
}
// 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;
}
// 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();
// 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();
}
}
// Start receiving audio data
receiveLoop();
}
else
{
// Start playback
play();
}
}
protected:
override bool onStart()
{
// Reset the playing offset
myOffset = 0;
override bool onStart()
{
// Reset the playing offset
myOffset = 0;
return true;
}
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;
}
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;
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);
// 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++;
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;
}
}
}
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;
SocketTCP myListener;
SocketTCP myClient;
short[] mySamples;
short[] myTempBuffer;
size_t myOffset;
bool myHasFinished;
static Object s_sync;
};
@ -137,26 +137,26 @@ private:
// 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);
// 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);
}
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);
}
// 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,6 +1,6 @@
module util;
const ubyte AudioData = 1;
const ubyte AudioData = 1;
const ubyte EndOfStream = 2;
public import dsfml.system.all;
@ -9,41 +9,41 @@ public import dsfml.network.all;
version(Tango)
{
public import tango.io.Console;
public import tango.text.convert.Integer;
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()
{
}
}
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();
}
}
class Cin
{
static char[] get()
{
return readln();
}
}
public import std.string : atoi;
alias atoi parse;
public import std.string : atoi;
alias atoi parse;
}