public void GenerateUVSphere(float parallels, float meridians) { ObjectVertex top = null, bottom = null; var vertices = new ObjectVertex[(int)Ceiling(parallels) - 1, (int)Ceiling(meridians)]; for (int parallel = 0; parallel < parallels + 1; parallel++) { double p = parallel * (PI / parallels); for (int meridian = 0; meridian < meridians; meridian++) { double m = 2 * meridian * (PI / meridians); float x = (float)(Sin(p) * Cos(m)); float y = (float)Cos(p); float z = (float)(Sin(p) * Sin(m)); var vertex = new ObjectVertex(x, y, z); if (parallel <= 0) top = vertex; else if (parallel >= parallels) bottom = vertex; else vertices[parallel - 1, meridian] = vertex; } } for (int parallel = 0; parallel < parallels; parallel++) { for (int meridian = 0; meridian < meridians; meridian++) { bool last = meridian >= meridians - 1; if (parallel <= 0) { var a = vertices[parallel, meridian]; var b = vertices[parallel, last ? 0 : meridian + 1]; Faces.Add(new ObjectFace(this, top, b, a)); } else if (parallel >= parallels - 1) { var a = vertices[parallel - 1, meridian]; var b = vertices[parallel - 1, last ? 0 : meridian + 1]; Faces.Add(new ObjectFace(this, bottom, a, b)); } else { var a = vertices[parallel - 1, meridian]; var b = vertices[parallel - 1, last ? 0 : meridian + 1]; var c = vertices[parallel, meridian]; var d = vertices[parallel, last ? 0 : meridian + 1]; AddQuad(a, b, c, d, false); } } } }
10 April 2019
Math - Generate a UV sphere
The following code generates the vertices and faces of a UV sphere. It is based on this CodeProject article. The code is written in C#, but it's really about the math. It first generates the vertices in a two-dimensional array, and then the faces from that array. The top and bottom are treated separately, because they are only one single vertex. Because of this, the first and final parallel are finished with triangles instead of a quads.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment