美文网首页
Three.js源码解读三:CircleGeometry

Three.js源码解读三:CircleGeometry

作者: federerchou | 来源:发表于2017-09-27 17:55 被阅读111次

    (一)直观了解CircleGeometry

    CircleGeometry(扇形几何体)是Three.js体系中最简单的一种几何体。可以通过阅读它的源码来强化理解Geometry的几大要素:

    • 顶点
    • 法向量
    • 纹理

    • 一个最简单的扇形几何体:
    三个三角形组成的扇形

    这个扇形的边缘弧度似乎不够平滑,可以为他加入更多的三角形,来模拟一个平滑的弧度扇形。

    三十个三角形组成的扇形
    现在你对CircleGeometry已经有了一个直观的了解,接下来,我们来做源码解读。

    (二)源码解读

    1. 顶点(vertex)

    CircleGeometry由一定数量的三角形组成,它的几何形状由一下参数决定:

    /**
      * radius: 扇形的半径,也是三角形的等边长度
      * segments: 组成扇形的三角形的数量,segments越大,三角形越多,扇形边缘  越平滑
      * thetaStart: 扇形的起始角度
      * thetaLength:扇形的圆心角,
      **/
    CircleBufferGeometry( radius, segments, thetaStart, thetaLength )
    

    如何计算这行三角形的顶点呢?

    计算顶点坐标

    用红色的圈标出了所有的顶点。根据传入的segments,可以计算出顶点的数量:

    vertices.length = 1(圆心) + (segments + 1)
    
    //将圆形加入顶点缓存中
    vertices.push( 0, 0, 0 );
    

    根据上面的示意图,可以计算出每个顶点的X,Y值

    //Θ等于每个三角形的所经过的圆心角度数
    Θ = thetaStart + (thetaLength / segments) * index
    X = radius * cos(Θ)
    Y = radius * sin(Θ)
    

    因此,在CirlcleGeometry中会有以下代码:

    for(s =0; s<= segments;s++) {
      var segment = thetaStart + s / segments * thetaLength;
      vertex.x = radius * Math.cos( segment );
      vertex.y = radius * Math.sin( segment );
      vertex.z = 0;
      vertices.push(vertex.x,vertex.y,vertex.z = 0)
    }
    

    2.面

    在之前的文章中,我们知道面是顶点的索引。在CircleGeometry中,indices就是用来存储顶点索引的缓存数组。

    //保存顶点索引
    //(1,2,0),(2,3,0),(3,4,0)...
    for ( i = 1; i <= segments; i ++ ) {
        indices.push( i, i + 1, 0 );
    }
    

    3.贴图(uv)

    uvs用于指定顶点对应的贴图坐标。图片和WebGL其实属于两个不同的坐标系,图片坐标系(uv坐标)的范围是[0,1],WebGL的坐标系范围是[-1,1]。为了关联起这两种坐标系,需要将他们进行统一。

    贴图原理

    只要简单的平移和缩放,就能将[-1,-1]坐标系统一到[0,1]坐标系中。

    x = (x + 1)/2
    y = (y + 1)/2
    
    统一坐标系
    for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
            var segment = thetaStart + s / segments * thetaLength;
            // vertex
            vertex.x = radius * Math.cos( segment );
            vertex.y = radius * Math.sin( segment );
            vertices.push( vertex.x, vertex.y, vertex.z );
            // normal
            normals.push( 0, 0, 1 );
                    //统一WebGL和贴图坐标系
                    //现在,你应该能理解下面代码的含义了
            uv.x = ( vertices[ i ] / radius + 1 ) / 2;
            uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
            uvs.push( uv.x, uv.y );
        }
    

    最终贴图效果如下(为了便于展示,将扇形的圆形角调整为360):


    UV贴图

    相关文章

      网友评论

          本文标题:Three.js源码解读三:CircleGeometry

          本文链接:https://www.haomeiwen.com/subject/kbjuextx.html