Skip to content

Instantly share code, notes, and snippets.

@hamsham

hamsham/cuda_math.h

Created Aug 18, 2015
Embed
What would you like to do?
Basic Linear Algebra functions for CUDA
#include <math.h>
__device__ inline float clampf(const float n, const float minVal, const float maxVal)
{
return (n < minVal ? minVal : n) > maxVal ? maxVal : n;
}
__device__ inline float3 fill_vec3f(const float n)
{
const float3 ret = {.x=n, .y=n, .z=n};
return ret;
}
__device__ inline float2 fill2_vec2f(const float n1, const float n2)
{
const float2 ret = {.x=n1, .y=n2};
return ret;
}
__device__ inline float3 fill3_vec3f(const float n1, const float n2, const float n3)
{
const float3 ret = {.x=n1, .y=n2, .z=n3};
return ret;
}
__device__ inline float3 add_vec3f(const float3 n1, const float3 n2)
{
const float3 ret = {.x=n1.x+n2.x, .y=n1.y+n2.y, .z=n1.z+n2.z};
return ret;
}
__device__ inline float3 sub_vec3f(const float3 n1, const float3 n2)
{
const float3 ret = {.x=n1.x-n2.x, .y=n1.y-n2.y, .z=n1.z-n2.z};
return ret;
}
__device__ inline float3 mul_vec3f(const float3 n1, const float3 n2)
{
const float3 ret = {.x=n1.x*n2.x, .y=n1.y*n2.y, .z=n1.z*n2.z};
return ret;
}
__device__ float3 cross_vec3f(const float3 n1, const float3 n2)
{
const float3 ret = {
.x=(n1.y * n2.z) - (n1.z * n2.y),
.y=(n1.z * n2.x) - (n1.x * n2.z),
.z=(n1.x * n2.y) - (n1.y * n2.x)
};
return ret;
}
__device__ inline float dot_vec2f(const float2 n1, const float2 n2)
{
return (n1.x*n2.x) + (n1.y*n2.y);
}
__device__ inline float dot_vec3f(const float3 n1, const float3 n2)
{
return (n1.x*n2.x) + (n1.y*n2.y) + (n1.z*n2.z);
}
__device__ inline float length_vec2f(const float2 n)
{
return sqrtf(dot_vec2f(n, n));
}
__device__ inline float length_vec3f(const float3 n)
{
return sqrtf(dot_vec3f(n, n));
}
__device__ inline float2 normalize_vec2f(const float2 n)
{
const float mag = 1.f / length_vec2f(n);
const float2 ret = {.x=n.x*mag, .y=n.y*mag};
return ret;
}
__device__ inline float3 normalize_vec3f(const float3 n)
{
const float mag = 1.f / length_vec3f(n);
const float3 ret = {.x=n.x*mag, .y=n.y*mag, .z=n.z*mag};
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment