Reverse Spherifying A Cube

I have [what I believe is] a relatively simple geometry question - how can I take a cube that has been transformed into a sphere (normalize the vertices of it and multiply by them by a value - the radius of the resulting sphere) and transform that sphere back into the original cube without any information from the original cube, except for the original cube’s dimensions? Essentially:

I’m not sure why someone would need that, but the easiest way would be a two step approach:

  1. figure out to which side a vertex belongs. that’s quite easy as you just have to find out which component of the vertex is the largest (absolute value)
  2. Once you have the normal vector of the face you can use Unitys mathematical Plane struct to project each vertex onto the surface of your cube

Something like that:

void DeSpherify(Vector3[] aVertices, float aHalfCubeSize)
{
    for(int i = 0; i < aVertices.Length; i++)
    {
        Vector3 v = aVertices*;*

Vector3 n;
if (Mathf.Abs(v.x) > Mathf.Abs(v.y))
{
if (Mathf.Abs(v.x) > Mathf.Abs(v.z))
n = new Vector3(Mathf.Sign(v.x),0,0);
else
n = new Vector3(0,0,Mathf.Sign(v.z));
}
else
{
if (Mathf.Abs(v.y) > Mathf.Abs(v.z))
n = new Vector3(0,Mathf.Sign(v.y),0);
else
n = new Vector3(0,0,Mathf.Sign(v.z));
}
var plane = new Plane(n * aHalfCubeSize, -n);
float dist;
var ray = new Ray(Vector3.zero, v.normalized);
if (plane.Raycast(ray, out dist))
{
aVertices = ray.GetPoint(dist);
}
}
}
Wrote from scratch, haven’t testet (yet) :wink:
edit
Actually there’s a much easier approach :wink: I just thought about. You still need to find out which component is the largest, but then all you have to do is bringing that componwnt to your desired length (either normalized or your halfcubesize)
Vector3 Cubify(Vector3 aVertex)
{
float x = Mathf.Abs(aVertex.x);
float y = Mathf.Abs(aVertex.y);
float z = Mathf.Abs(aVertex.z);
if (x > y)
{
if (x > z)
return aVertex * 1f/x;
else
return aVertex * 1f/z;
}
else
{
if (y > z)
return aVertex * 1f/y;
else
return aVertex * 1f/z;
}
}