将立方体转换为opengl中的球体 [英] transform cube to sphere in opengl

查看:261
本文介绍了将立方体转换为opengl中的球体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用三角形法建立了一些立方体(每个立方体有24个立方体)。

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.

推荐答案

要使用简单的OpenGL来做到这一点,你需要使用更精细的tessellate立方体。而不是绘制每个面只有两个三角形,你将它细分成更小的片段。

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.

如果您将每个边缘分割为 n 件,你会得到每个面的 nxn 正方形或 2 * n * n 三角形。

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.

在顶点着色器中, InterpFract 为分数的插值(0用于绘制立方体,1用于绘制球体),代码可以看起来像这样:

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);
}

这是一个半径为1的球体。如果你需要一个不同的半径,你可以将 sphereCoord 乘以半径。

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.

使用更先进的OpenGL,您可以避免馈入更多的顶点,然后用曲面细分着色器对面进行细分。

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

这篇关于将立方体转换为opengl中的球体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆