Dav1dde/gl3n

Casting between Vector's with different types but the same length does not work

Opened this issue · 3 comments

vec3 a = cast(vec3)vec3i(1, 2, 3);

That can be don with simple constructing it.

vec3 a = vec3(vec3i(1,2,3));
Or because of D magic simple
vec3 a = vec3i(1,2,3);

float to int though is not that easy.

That kind of cast which you are trying to do is not intended to work. You need to cast the elements of the vector into a new vector not cast the vector.

Here are the functions I used for casting these vectors (and array cast functions):

Vector!(NT,L) vecCast(NT,OT,size_t L)(Vector!(OT,L) xs) {
	return Vector!(NT,L)(xs.vector.arrayCast!NT);
}

NT[] arrayCast(NT,OT)(OT[] xs) {
	return xs.map!(cst!(NT,OT)).array();
}
NT[L] arrayCast(NT,OT,size_t L)(OT[L] xs) {
	NT[L] nxs;
	foreach (i,e; xs) {
		nxs[i] = e.cst!NT;
	}
	return nxs;
}

The cst is just a template function version of the cast primitive. It is from the cst library on dub.

Here are 4 examples of using it:

vec3 a = vecCast!float(vec3i(1, 2, 3));
vec3i a = vecCast!int(vec3(1, 2, 3));
vec3 a = vec3i(1, 2, 3).vecCast!float;
vec3i a = vec3(1, 2, 3).vecCast!int;

Thanks for answering, I'll assume this has been answered now.

Maybe worth adding an opCast, mh...