summaryrefslogtreecommitdiffstats
path: root/src/glsphere.cpp
blob: 77cb7f75a9a6f3151a77a937fbe7caf75197fed5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include "glsphere.h"

GLSphere::GLSphere(double radius, int stacks, int slices)
    : GLBody(radius)
{
    // Force an even number
    m_stacks = stacks / 2 * 2;
    m_slices = slices / 2 * 2;
}

void GLSphere::makeSurface(QVector<GLPoint> *pointContainer,
                           QVector<GLshort> *indexContainer)
{
    GLBody::makeSurface(pointContainer, indexContainer);

    QVector3D t0 = QVector3D(0.0, 0.0, 0.0); //dummy texture

    QVector3D northpol = v_Y;
    QVector3D southpol = -v_Y;

    QVector<QVector3D> firstPointRow = calculateRow(0);

    QVector<QVector3D> sliceA = firstPointRow;
    QVector<QVector3D> sliceB;

    m_firstPoint = m_points->size();

    for (int slice = 1; slice < m_slices; slice += 2)
    {
        sliceB = calculateRow(slice);

        m_points->append(GLPoint(m_radius * northpol, northpol, t0, m_color));

        for (int i = 0; i < m_stacks - 1; i++)
        {
            m_points->append(GLPoint(m_radius * sliceA[i], sliceA[i],
                                     t0, m_color));

            m_points->append(GLPoint(m_radius * sliceB[i], sliceB[i],
                                     t0, m_color));
        }

        m_points->append(GLPoint(m_radius * southpol, southpol, t0, m_color));

        sliceA = calculateRow(slice + 1);

        for (int i = m_stacks - 2; i >= 0; i--)
        {
            m_points->append(GLPoint(m_radius * sliceA[i], sliceA[i],
                                     t0, m_color));

            m_points->append(GLPoint(m_radius * sliceB[i], sliceB[i],
                                     t0, m_color));
        }

        m_points->append(GLPoint(m_radius * northpol, northpol, t0, m_color));
    }

    m_nextPoint = m_points->size();
}

QVector<QVector3D> GLSphere::calculateRow(int slice)
{
    if(slice == m_stacks)
    {
        return firstRow;
    }

    QVector<QVector3D> longitude;

    for (int stack = 1; stack < m_stacks; stack++)
    {
        longitude.append(calculatePoint(2 * M_PI * slice / m_slices,
                                        stack * M_PI / m_stacks));
    }

    if (slice == 0)
    {
        firstRow = longitude;
    }

    return longitude;
}

QVector3D GLSphere::calculatePoint(double sliceRotation, double stackRotation)
{
    double x = sin(stackRotation) * sin(sliceRotation);
    double y = cos(stackRotation);
    double z = sin(stackRotation) * cos(sliceRotation);

    return QVector3D(x, y, z);
}