Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved Cube To Sphere mapping #15

Open
Nighrix opened this issue Jul 21, 2024 · 0 comments
Open

Improved Cube To Sphere mapping #15

Nighrix opened this issue Jul 21, 2024 · 0 comments

Comments

@Nighrix
Copy link

Nighrix commented Jul 21, 2024

// TerrainFace.cs File
// Based of https://mathproofs.blogspot.com/2005/07/mapping-cube-to-sphere.html

Vector3 CubeToSphere(Vector3 cubePos)
    {
        float x2 = cubePos.x * cubePos.x;
        float y2 = cubePos.y * cubePos.y;
        float z2 = cubePos.z * cubePos.z;
        
        float x = cubePos.x * Mathf.Sqrt(1.0f - (y2 + z2) / 2.0f + (y2 * z2) / 3.0f);
        float y = cubePos.y * Mathf.Sqrt(1.0f - (z2 + x2) / 2.0f + (z2 * x2) / 3.0f);
        float z = cubePos.z * Mathf.Sqrt(1.0f - (x2 + y2) / 2.0f + (x2 * y2) / 3.0f);
        return new Vector3(x, y, z).normalized;
    }

public void ConstructMesh()
    {
        Vector3[] vertices = new Vector3[resolution * resolution];
        int[] triangles = new int[(resolution - 1) * (resolution - 1) * 6];
        int triIndex = 0;

        for (int y = 0; y < resolution; y++)
        {
            for (int x = 0; x < resolution; x++)
            {
                int i = x + y * resolution;
                Vector2 percent = new Vector2(x, y) / (resolution - 1);
                Vector3 pointOnUnitCube = localUp + (percent.x - .5f) * 2 * axisA + (percent.y - .5f) * 2 * axisB;
                Vector3 pointOnUnitSphere = pointOnUnitCube.normalized;
                vertices[i] = CubeToSphere(pointOnUnitCube); // pointOnUnitSphere;

                if (x != resolution - 1 && y != resolution - 1)
                {
                    triangles[triIndex] = i;
                    triangles[triIndex + 1] = i + resolution + 1;
                    triangles[triIndex + 2] = i + resolution;

                    triangles[triIndex + 3] = i;
                    triangles[triIndex + 4] = i + 1;
                    triangles[triIndex + 5] = i + resolution + 1;
                    triIndex += 6;
                }
            }
        }
        mesh.Clear();
        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.RecalculateNormals();
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant