Let’s write a comprehensive case using what we learned about OpenGL at the front door

First, the effect drawing

Ii. Flow chart

Three, the source code

#include "GLTools.h"
#include "GLShaderManager.h"
#include "GLFrustum.h"
#include "GLBatch.h"
#include "GLMatrixStack.h"
#include "GLGeometryTransform.h"
#include "StopWatch.h"//定时

#include <math.h>
#include <stdio.h>

#ifdef __APPLE__
#include <glut/glut.h>
#else
#define FREEGLUT_STATIC
#include <GL/glut.h>
#endif


GLShaderManager        shaderManager;            // 着色器管理器
GLMatrixStack        modelViewMatrix;        // 模型视图矩阵
GLMatrixStack        projectionMatrix;        // 投影矩阵
GLFrustum            viewFrustum;            // 视景体
GLGeometryTransform    transformPipeline;        // 几何图形变换管道

GLTriangleBatch        torusBatch;             //大球
GLTriangleBatch     sphereBatch;            //小球
GLBatch                floorBatch;          //地板


GLFrame             cameraFrame;

//添加50个随机小球
#define NUM_SPHERES 50
GLFrame spheres[NUM_SPHERES];


//纹理标记数组
GLuint uiTextures[3];


bool LoadTGATexture(const char *szFileName, GLenum minFilter, GLenum magFilter, GLenum wrapMode)
{
    
    //初始化需要用到的参数
    GLbyte *pBits;
    int nWidth,nHeight,nComponents;
    GLenum eFormat;
    
    
    //读取到上面的数据
    pBits = gltReadTGABits(szFileName, &nWidth, &nHeight, &nComponents, &eFormat);
    if (pBits == NULL) {
        return false;
    }
    
    
    //设置纹理
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);
    
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);
    
    
    //载入纹理
    /*
     参数1:纹理维度
     参数2:mip贴图层次
     参数3:纹理单元存储的颜色成分(从读取像素图是获得)-将内部参数nComponents改为了通用压缩纹理格式GL_COMPRESSED_RGB
     参数4:加载纹理宽
     参数5:加载纹理高
     参数6:加载纹理的深度
     参数7:像素数据的数据类型(GL_UNSIGNED_BYTE,每个颜色分量都是一个8位无符号整数)
     参数8:指向纹理图像数据的指针
     */
    
    glTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGB, nWidth, nHeight, 0,eFormat, GL_UNSIGNED_BYTE, pBits);
    
    
    //释放pBits
    free(pBits);
    
    //如果是以下4种过滤方式,才生产MIP贴图
    if(
       minFilter == GL_LINEAR_MIPMAP_LINEAR ||
       minFilter == GL_LINEAR_MIPMAP_NEAREST ||
       minFilter == GL_NEAREST_MIPMAP_LINEAR ||
       minFilter == GL_NEAREST_MIPMAP_NEAREST
       ){
        
        //加载Mip,纹理生成所有的Mip层
        glGenerateMipmap(GL_TEXTURE_2D);
        
        
    }
    
    
    return true;
}
void SetupRC()
{
    //1、设置背景色
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    
    //2、初始化着色器
    shaderManager.InitializeStockShaders();
    
    //3、开始深度测试、正背面剔除
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    
    //4、初始化地板(添加顶点数据和纹理坐标)
    GLfloat texSize = 10.0f;
    floorBatch.Begin(GL_TRIANGLE_FAN, 4,1);
    floorBatch.MultiTexCoord2f(0, 0.0f, 0.0f);
    floorBatch.Vertex3f(-20.f, -0.41f, 20.0f);
    
    floorBatch.MultiTexCoord2f(0, texSize, 0.0f);
    floorBatch.Vertex3f(20.0f, -0.41f, 20.f);
    
    floorBatch.MultiTexCoord2f(0, texSize, texSize);
    floorBatch.Vertex3f(20.0f, -0.41f, -20.0f);
    
    floorBatch.MultiTexCoord2f(0, 0.0f, texSize);
    floorBatch.Vertex3f(-20.0f, -0.41f, -20.0f);
    floorBatch.End();
    
    //5、初始化自转大球
    gltMakeSphere(torusBatch, 0.4f, 40, 80);
    
    
    //6、初始化自转+公转的小球
    gltMakeSphere(sphereBatch, 0.1f, 12, 24);
    
    
    //7、设置50个随机位置的小球
    for (int i=0; i<NUM_SPHERES; i++) {
        //因为都在一个平面,Y值是不变的。X和Z是随机的
        GLfloat x = ((GLfloat)((rand() % 400) - 200 ) * 0.1f);
        GLfloat z = ((GLfloat)((rand() % 400) - 200 ) * 0.1f);
        
        //对spheres数组中的每一个顶点,设置顶点数据(SetOrigin设置位置)
        spheres[i].SetOrigin(x, 0.0f, z);
    }
    
    
    //8、初始化纹理-申请3个纹理
    glGenTextures(3, uiTextures);
    
    //9、绑定各个纹理,并且读取TGA文件参数并进行设置
    glBindTexture(GL_TEXTURE_2D, uiTextures[0]);
    LoadTGATexture("marble.tga",
                   GL_LINEAR_MIPMAP_LINEAR,
                   GL_LINEAR,
                   GL_REPEAT);
    
    
    glBindTexture(GL_TEXTURE_2D, uiTextures[1]);
    LoadTGATexture("marslike.tga",
                   GL_LINEAR_MIPMAP_LINEAR,
                   GL_LINEAR,
                   GL_CLAMP_TO_EDGE);
    
    
    glBindTexture(GL_TEXTURE_2D, uiTextures[2]);
    LoadTGATexture("moonlike.tga",
                   GL_LINEAR_MIPMAP_LINEAR,
                   GL_LINEAR,
                   GL_CLAMP_TO_EDGE);
}

//删除纹理
void ShutdownRC(void)
{
    glDeleteTextures(3, uiTextures);
}



void drawSomething(GLfloat yRot)
{
    //1、定义光源位置和漫反射颜色
    static GLfloat vWhite[] = { 1.0f, 1.0f, 1.0f, 1.0f };
    static GLfloat vLightPos[] = { 0.0f, 3.0f, 0.0f, 1.0f };
    
    //2、绘制50个随机小球
    //先设置纹理-2号纹理
    glBindTexture(GL_TEXTURE_2D, uiTextures[2]);
    //循环把每个小球位置放进栈中,并绘制出来
    //因为小球是几何模型,所以不需要绑定纹理坐标
    for(int i = 0; i < NUM_SPHERES; i++) {
        modelViewMatrix.PushMatrix();
        modelViewMatrix.MultMatrix(spheres[i]);
        /*
        参数1: 存储着⾊器种类-纹理光源着⾊器 GLT_SHADER_TEXTURE_POINT_LIGHT_DIEF
        参数2: 模型4*4矩阵
        参数3: 投影4*4矩阵
        参数4: 点光源位置
        参数5: 颜⾊值(⼏何图形的基本⾊)
        参数6: 纹理单元
        */
        shaderManager.UseStockShader(GLT_SHADER_TEXTURE_POINT_LIGHT_DIFF,
                                     modelViewMatrix.GetMatrix(),
                                     transformPipeline.GetProjectionMatrix(),
                                     vLightPos,
                                     vWhite,
                                     0);
        sphereBatch.Draw();
        modelViewMatrix.PopMatrix();
    }
    
    
    
    //把所有图案都平移一下。先Y轴平移一点点,再Z轴平移一点点
    modelViewMatrix.Translate(0.0f, 0.2f, -2.5f);
    //3、绘制大球
    modelViewMatrix.PushMatrix();
    modelViewMatrix.Rotate(yRot, 0.0f, 1.0f, 0.0f);
    glBindTexture(GL_TEXTURE_2D, uiTextures[1]);
    shaderManager.UseStockShader(GLT_SHADER_TEXTURE_POINT_LIGHT_DIFF,
                                 modelViewMatrix.GetMatrix(),
                                 transformPipeline.GetProjectionMatrix(),
                                 vLightPos,
                                 vWhite,
                                 0);
    torusBatch.Draw();
    modelViewMatrix.PopMatrix();
    
    
    //4、绘制公转自转小球
    modelViewMatrix.PushMatrix();
    modelViewMatrix.Rotate(yRot * -2.0f, 0.0f, 1.0f, 0.0f);
    modelViewMatrix.Translate(0.8f, 0.0f, 0.0f);
    glBindTexture(GL_TEXTURE_2D, uiTextures[2]);
    shaderManager.UseStockShader(GLT_SHADER_TEXTURE_POINT_LIGHT_DIFF,
                                 modelViewMatrix.GetMatrix(),
                                 transformPipeline.GetProjectionMatrix(),
                                 vLightPos,
                                 vWhite,
                                 0);
    sphereBatch.Draw();
    modelViewMatrix.PopMatrix();
    
}
void RenderScene(void)
{
    //1、设置必要的参数
    //地板颜色
    static GLfloat vFloorColor[] = {1.0f,1.0f,0.0f,0.75f};
    //基于时间的旋转角度
    static CStopWatch rotTimer;
    float yRot = rotTimer.GetElapsedSeconds() * 60.f;
    //清空颜色缓冲区和深度缓冲区
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    

    //2、压栈,是为了保证整个画面绘制完之后,清空,不影响下一次绘制
    modelViewMatrix.PushMatrix();
    
    //3、压入观察者,因为观察者一旦变化,所有东西都会变化。其他的变化其实是基于观察者变化之上的。
    M3DMatrix44f mCamera;
    cameraFrame.GetCameraMatrix(mCamera);
    modelViewMatrix.MultMatrix(mCamera);
    
    //4、画镜面部分。这里也要加一次push、pop。因为镜面部分和镜面之上是分开的,没有联动,不能让镜面对其他地方造成影响
    //镜面push (这里push的是观察者矩阵)
    modelViewMatrix.PushMatrix();
    
    //围绕Y轴翻转,所以顶点都发生了改变
    modelViewMatrix.Scale(1.0f, -1.0f, 1.0f);
    //为了效果逼真,把镜面与镜面之上隔开距离,沿着Y轴偏移一下
    modelViewMatrix.Translate(0.0f, 0.8f, 0.0f);
    //因为镜面和正常是反的,所以要声明一下,让顺时针成为正面
    glFrontFace(GL_CW);
    //开始绘制镜面所显示的东西
    drawSomething(yRot);
    //镜面画完之后要把正面恢复成逆时针
    glFrontFace(GL_CCW);
    //镜面pop
    modelViewMatrix.PopMatrix();
    
    //5、画地板部分,然后和镜面部分混合一下(是为了能够看到地板以下的镜面部分)。 因为地板从始至终没有发生变化,所以不需要压栈出栈
    //开启混合
    glEnable(GL_BLEND);
    //指定颜色混合方程式
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    //绑定地板纹理
    glBindTexture(GL_TEXTURE_2D, uiTextures[0]);
    //使用着色器
    /*
    参数1: 存储着⾊器种类-纹理调整着⾊器 GLT_SHADER_TEXTURE_MODULATE
    参数2: 模型4*4矩阵
    参数3: 颜⾊值
    参数4: 纹理单元
    */
    shaderManager.UseStockShader(GLT_SHADER_TEXTURE_MODULATE,transformPipeline.GetModelViewProjectionMatrix(),vFloorColor,0);
    //绘制
    floorBatch.Draw();
    //关闭混合
    glDisable(GL_BLEND);
    
    
    //6、画地板之上的正常区域
    //其实这个地方是要加push、pop的,但是因为,这一块是最后绘制的,它对其他地方没有影响,就可以省略了
    drawSomething(yRot);
    
    //7、出栈
    modelViewMatrix.PopMatrix();
    
    //8、交换缓冲区
    glutSwapBuffers();
    
    //9、因为开启了定时器,我们要不断刷新渲染
    glutPostRedisplay();
    
}


void ChangeSize(int w, int h)
{
 
    if (h == 0) {
        h = 1;
    }
    glViewport(0, 0, w, h);
    
    viewFrustum.SetPerspective(35.0f, float(w)/float(h), 1.0f, 150.0f);
    
    projectionMatrix.LoadMatrix(viewFrustum.GetProjectionMatrix());
    
    transformPipeline.SetMatrixStacks(modelViewMatrix, projectionMatrix);
    
}


void SpeacialKeys(int key,int x,int y)
{
    
    if (key == GLUT_KEY_UP) {
        //MoveForward 平移
        cameraFrame.MoveForward(0.1f);
    }
    if (key == GLUT_KEY_DOWN) {
        cameraFrame.MoveForward(-0.1f);
    }
    
    if (key == GLUT_KEY_LEFT) {
        //RotateWorld 旋转
        cameraFrame.RotateWorld(m3dDegToRad(5.0f), 0.0f, 1.0f, 0.0f);
    }
    
    if (key == GLUT_KEY_RIGHT) {
        cameraFrame.RotateWorld(m3dDegToRad(-5.0f), 0.0f, 1.0f, 0.0f);
    }
    
    
    
    //本里这里需要移动后重新渲染的,但是因为渲染方法中,因为定时器问题本身就一直再重新渲染,这里就不用再写一遍了,啰嗦
//    glutPostRedisplay();
    
}

int main(int argc, char* argv[])
{
    
    gltSetWorkingDirectory(argv[0]);
   
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(800,600);
    glutCreateWindow("球体世界");

    GLenum err = glewInit();
    if (GLEW_OK != err) {
       fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
       return 1;
    }

    glutReshapeFunc(ChangeSize);
    glutDisplayFunc(RenderScene);
    glutSpecialFunc(SpeacialKeys);


    SetupRC();
    glutMainLoop();
    
    
    ShutdownRC();
    
    return 0;
    
    
    
}

Copy the code

Four, notes

  • Shader use: large ball ball – texture point light shader; Floor – Texture adjustment shader.
  • Big ball rotation: To visualize the big ball, we need to translate it. Then push the stack and rotate (if you put a translation in the stack, it will be shifted with each turn).
  • Ball rotation + revolution: pressing, must pay attention to the rotationTranslation. Because pushing doesn’t satisfy the commutative law. If it’s a translationRotation is another effect.
  • Mirror floor: in fact, the bottom of the thing is written again, and then mixed with the floor texture formed.
  • Since there are two draws and renderings for all balls, we encapsulate a drawSomething method and call it directly twice to save code
  • The position of the graphics changes with each move, so the first thing to do in RenderSence after pushing is to put the Camera name in.
  • Remember to pop every push.
  • In fact, we can see the full picture of the case if we zoom out: