1
0
Fork 0
mirror of https://git.coom.tech/drummyfish/small3dlib.git synced 2024-12-22 01:26:17 +01:00

Add vector normalization

This commit is contained in:
Miloslav Číž 2019-06-05 00:49:00 +02:00
parent f4a4ca06b4
commit 3d78f32ff3
2 changed files with 56 additions and 23 deletions

View file

@ -276,9 +276,10 @@ typedef struct
} S3L_Vec4;
static inline void S3L_initVec4(S3L_Vec4 *v);
static inline void S3L_vec3Add(S3L_Vec4 *result, S3L_Vec4 added);
static inline void S3L_vec3Sub(S3L_Vec4 *result, S3L_Vec4 substracted);
S3L_Unit S3L_vec3Length(S3L_Vec4 v);
void S3L_normalizeVec3(S3L_Vec4 *v);
#define S3L_logVec4(v)\
printf("Vec4: %d %d %d %d\n",((v).x),((v).y),((v).z),((v).w))
@ -444,6 +445,9 @@ static inline S3L_Unit S3L_nonZero(S3L_Unit value);
S3L_Unit S3L_sin(S3L_Unit x);
static inline S3L_Unit S3L_cos(S3L_Unit x);
S3L_Unit S3L_vec3Length(S3L_Vec4 v);
S3L_Unit S3L_sqrt(S3L_Unit value);
/** Interpolated between two values, v1 and v2, in the same ratio as t is to
tMax. Does NOT prevent zero division. */
static inline S3L_Unit S3L_interpolate(
@ -964,6 +968,55 @@ void S3L_makeRotationMatrixZXY(
#undef S
}
S3L_Unit S3L_sqrt(S3L_Unit value)
{
int8_t sign = 1;
if (value < 0)
{
sign = -1;
value *= -1;
}
uint32_t result = 0;
uint32_t a = value;
uint32_t b = 1u << 30;
while (b > a)
b >>= 2;
while (b != 0)
{
if (a >= result + b)
{
a -= result + b;
result = result + 2 * b;
}
b >>= 2;
result >>= 1;
}
return result * sign;
}
S3L_Unit S3L_vec3Length(S3L_Vec4 v)
{
return S3L_sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
void S3L_normalizeVec3(S3L_Vec4 *v)
{
S3L_Unit l = S3L_vec3Length(*v);
if (l == 0)
return;
v->x = (v->x * S3L_FRACTIONS_PER_UNIT) / l;
v->y = (v->y * S3L_FRACTIONS_PER_UNIT) / l;
v->z = (v->z * S3L_FRACTIONS_PER_UNIT) / l;
}
void S3L_initTransoform3D(S3L_Transform3D *t)
{
S3L_initVec4(&(t->translation));

View file

@ -266,26 +266,7 @@ void recomputeLight()
for (int i = 0; i < 127; ++i)
{
S3L_Vec4 v;
int index = i * 3;
v.x = houseVertices[index];
v.y = houseVertices[index + 1];
v.z = houseVertices[index + 2];
S3L_vec3Xmat4(&v,m);
S3L_Unit d = S3L_distanceManhattan(v,scene.camera.transform.translation);
d = radius - d;
int l = 0;
if (d >= 0)
l = 255 - S3L_interpolateFrom0(255,d,radius);
houseVertexLighting[i] = l;
houseVertexLighting[i] = 255;
}
}
@ -302,8 +283,7 @@ void draw()
if (f % 16 == 0)
recomputeLight();
//scene.models[0].transform.rotation.z = f * 0.1;
//scene.models[0].transform.rotation.x = f * 0.3;
scene.models[0].transform.translation.x = sin(f / 16.0) * S3L_FRACTIONS_PER_UNIT;
S3L_drawScene(scene);