Skip to content

Instantly share code, notes, and snippets.

@OrangeLightning219
Created March 3, 2025 15:02
Show Gist options
  • Save OrangeLightning219/be11aaad4accf6bea0b91d252b2270a3 to your computer and use it in GitHub Desktop.
Save OrangeLightning219/be11aaad4accf6bea0b91d252b2270a3 to your computer and use it in GitHub Desktop.
Sphere GJK weird results
#include "gjk.c"
#include <stdio.h>
#include <math.h>
struct Vector3
{
float x, y, z;
};
Vector3 operator+(Vector3 a, Vector3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
Vector3 operator-(Vector3 a, Vector3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
Vector3 operator*(Vector3 a, float b) { return {a.x * b, a.y * b, a.z * b}; }
Vector3 operator-(Vector3 a) { return {-a.x, -a.y, -a.z}; }
float dot(Vector3 a, Vector3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
Vector3 vec3(float v[3]) { return {v[0], v[1], v[2]}; }
struct Box
{
Vector3 center, dim;
};
struct Sphere
{
Vector3 center;
float radius;
};
int sphere_support(Sphere sphere, Vector3 dir, Vector3 *result)
{
*result = sphere.center;
return 0;
}
int box_support(Box box, Vector3 dir, Vector3 *result)
{
Vector3 dim = box.dim;
Vector3 v1 = box.center + dim * 0.5;
Vector3 v2 = v1 - Vector3{ dim.x, 0, 0 };
Vector3 v3 = v2 - Vector3{ 0, 0, dim.z };
Vector3 v4 = v1 - Vector3{ 0, 0, dim.z };
Vector3 v5 = v1 - Vector3{ 0, dim.y, 0 };
Vector3 v6 = v2 - Vector3{ 0, dim.y, 0 };
Vector3 v7 = v3 - Vector3{ 0, dim.y, 0 };
Vector3 v8 = v4 - Vector3{ 0, dim.y, 0 };
Vector3 vertices[8] = { v1, v2, v3, v4, v5, v6, v7, v8 };
float max_dot = -1000000.0;
int max_index = 0;
for (int i = 0; i < 8; ++i)
{
Vector3 v = vertices[i];
float dot_result = dot( v, dir );
if (dot_result > max_dot)
{
max_dot = dot_result;
max_index = i;
}
}
*result = vertices[ max_index ];
return max_index;
}
int main()
{
Sphere sphere = {{0, 0.26, 0}, 0.25};
Box box = {{0, -0.5, 0}, {10, 1, 10}};
Vector3 dir = box.center - sphere.center;
gjk_support s = {};
s.aid = sphere_support(sphere, dir, (Vector3*)s.a);
s.bid = box_support(box, -dir, (Vector3*)s.b);
gjk_simplex simplex = {};
while (gjk(&simplex, &s))
{
Vector3 da = vec3(s.da);
Vector3 db = vec3(s.db);
s.aid = sphere_support(sphere, da, (Vector3*)s.a);
s.bid = box_support(box, db, (Vector3*)s.b);
}
gjk_result result = {};
gjk_analyze(&result, &simplex);
gjk_quad(&result, sphere.radius, 0);
if (result.hit)
{
printf("hit\n");
}
else
{
printf("no hit\n");
printf("distance: %f\n", sqrt(result.distance_squared));
Vector3 a = vec3(result.p0);
Vector3 b = vec3(result.p1);
printf("point on a: (%f, %f, %f)\n", a.x, a.y, a.z);
printf("point on b: (%f, %f, %f)\n", b.x, b.y, b.z);
Vector3 ab = b - a;
float d = sqrt(dot(ab, ab));
printf("distance a to b: %f", d);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment