多次生成一个插入的对象

时间:2017-10-24 23:17:28

标签: c++ opengl glm-math coordinate-transformation

我正在尝试为我的游戏创建5x5x5多维数据集。现在,我有这个代码,在相机视图中只显示一个立方体。显然,它已被插入"只有一次。

void onIdle() override {

        // Animate using time when activated
        if (animationEnabled) time = (float) glfwGetTime();

        // Set gray background
        glClearColor(.5f, .5f, .5f, 0);

        // Clear depth and color buffers
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Create object matrices
        auto cubeMat = rotate(mat4{}, time, {1.0f, 1.0f, 0.0f});
        //auto cubeMat = mat4(1.0f);
        auto sphereMat = rotate(mat4{}, (float)time, {0.5f, 1.0f, 0.0f});
        cubeMat = scale(cubeMat, {0.2f, 0.2f, 0.2f});

        // Camera position/rotation - for example, translate camera a bit backwards (positive value in Z axis), so we can see the objects
        auto cameraMat = translate(mat4{}, {0, 0, -4.0f});

        program.setUniform("ViewMatrix", cameraMat);

        // Update camera position with perspective projection
        program.setUniform("ProjectionMatrix", perspective((PI / 180.f) * 60.0f, 1.0f, 0.1f, 10.0f));

        program.setUniform("LightDirection", normalize(vec3{1.0f, -1.0f, 1.0f}));
        // Render objects

        // Central box
        program.setUniform("Texture", cubeTexture);
        for (int i = 0; i < 5*5*5; ++i)
        {
        program.setUniform("ModelMatrix", cubeMat[i]);
        cube.render();
        }
    }
};

如何生成5x5x5立方体,这样我就不必多次手动插入它们?此外,每次插入都应该为每个立方体提供特定的位置,以创建一个充满5x5x5小立方体的大型3D立方体(如rubik&#39; s立方体),甚至更好,这里是一个很好的example

1 个答案:

答案 0 :(得分:2)

您需要一个为单个多维数据集生成模型矩阵的函数:

mat4 CubeMat( int x, int y, int z )
{
    mat4 cubeMat;
    //cubeMat = rotate(cubeMat, time, {1.0f, 1.0f, 0.0f});
    //cubeMat = scale(cubeMat, {0.2f, 0.2f, 0.2f});
    cubeMat = translate(cubeMat, {1.5f*(float)x-4.0f, 1.5f*(float)y-4.0f, 1.5f*(float)z-4.0f});
    return cubeMat;
}

你必须拨打cube.render(); 5 * 5 * 5次,你必须设置5 * 5 * 5个人模型矩阵:

for (int x = 0; x < 5; ++x)
{
    for (int y = 0; y < 5; ++y)
    {
        for (int z = 0; z < 5; ++z)
        {
            mat4 cubeMat = CubeMat(x, y, z);
            program.setUniform("ModelMatrix", cubeMat);
            cube.render();
        }
    }
}