Search code examples
c++openglglm-mathcoordinate-transformation

Generate one inserted object multiple times


I am trying to create 5x5x5 cubes for my game. Right now, I have this code which shows only one cube in the camera view. Obviously, it is "inserted" only one time.

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

How can I generate 5x5x5 cubes so I don't have to manually insert them so many times? Also, every insertion should give each cube its specific location to create a big 3D cube full of little 5x5x5 cubes (like rubik's cube) or even better, here is a good example.


Solution

  • You need a function which generates a model matrix for an individual cube:

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

    You have to call cube.render(); 5*5*5 times and you have to set 5*5*5 idividual model matrices:

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