Moved all bindings to the "bindings" sub-directory

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

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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