transform cube to sphere in opengl

六月ゝ 毕业季﹏ 提交于 2019-12-12 03:08:10

问题


I am built some Cubes with the triangle approach (24 verticies per cube).

Now I want to transform this cube to a sphere (maybe, I only want to have round corners) (later, I want to animate this transformation).

How can I realize this? Can I use texture coordinates or normals to do this? I found this thread, but it doesn't help me.


回答1:


To do this with simple OpenGL, you'll need to use a finer tessellate of the cube. Instead of drawing each face with only two triangles, you subdivide it into smaller pieces. The easiest tessellation is to split the faces into smaller squares, and drawing them with triangle strips.

If you split each edge into n pieces, you'll end up with n x n squares or 2 * n * n triangles for each face.

You can then interpolate between cube and sphere in the vertex shader. You draw the original cube. The sphere coordinates are obtained by simply normalizing the cube coordinates.

In the vertex shader, with InterpFract being the fraction of interpolation (0 for drawing the cube, 1 for drawing a sphere), the code could look something like this:

uniform float InterpFract;
attribute vec3 CubeCoord;

void main() {
    vec3 sphereCoord = normalize(CubeCoord);
    gl_Position = vec4(mix(CubeCoord, sphereCoord, InterpFract), 1.0);
}

This is for a sphere of radius 1. If you need a different radius, you can multiply sphereCoord by the radius.

If you also need normals, it takes some more math. Interpolating the normal of the cube and the normal of the sphere the same way the positions are interpolated does not produce correct normals. The correct solution is to interpolate the gradient vectors, and then calculate the normal as the cross product of the interpolated gradient vectors.

With more advanced OpenGL, you could avoid feeding in more vertices, and perform the subdivision of the faces with a tessellation shader instead.




回答2:


You could just scale each points to the sphere

let's say that your points are x[i], then to bring a point to the sphere, you do

x[i] = x[i] * radius / norm( x[i] )

assuming that your cube is centered on 0

if you want to interpolate this, it seems simple

I don't say that it works, but it looks to me like it should work



来源:https://stackoverflow.com/questions/28831424/transform-cube-to-sphere-in-opengl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!