关键的向量运算:求两个点连线上的中点: 其实高中的向量就学过、两个向量加起来是平行四边形的对角线、那么其实数乘 1/2 就能得到中点了!
代码如下:
1 #pragma once 2 #include"Math.h" 3 #include"Shader.h" 4 #include<glew.h> 5 #include<string> 6 7 class SierpinskiGasket 8 { 9 public: 10 // 默认的三角形的三个顶点 11 SierpinskiGasket() { 12 this->initVertices[0] = Vector3(0.0f ,0.5f ,0.0f); 13 this->initVertices[1] = Vector3(-0.5f ,0.0f ,0.0f); 14 this->initVertices[2] = Vector3(0.5f ,0.0f ,0.0f); 15 }; 16 void genPoints(int nums) { 17 this->numsToDraw = nums; 18 Vector3* data = new Vector3[nums]; 19 data[0] = Vector3(0.0f, 0.0f, 0.0f); 20 21 for (size_t i = 1; i < nums; i++) 22 { 23 int j = rand() % 3; 24 auto v1 = initVertices[j]; 25 // 求两点 a和b之间的中点的公式: (A+B)/2 : 平行四边形对角线的一般 26 data[i] = (v1 + data[i - 1])*0.5f; 27 } 28 glGenVertexArrays(1, &vao); 29 glBindVertexArray(vao); 30 GLuint vbo; 31 glGenBuffers(1, &vbo); 32 glBindBuffer(GL_ARRAY_BUFFER, vbo); 33 glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3)*nums, data, GL_STATIC_DRAW); 34 glEnableVertexArrayAttrib(vao, 0); 35 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); 36 37 glBindVertexArray(0); 38 }; 39 40 void initShader(std::string vs, std::string fs) { 41 42 this->myShader = new Shader(); 43 myShader->initShader(vs.c_str(), fs.c_str()); 44 }; 45 46 void draw() { 47 myShader->start(); 48 glBindVertexArray(vao); 49 glDrawArrays(GL_POINTS, 0, numsToDraw); 50 glBindVertexArray(0); 51 myShader->end(); 52 }; 53 54 private: 55 // 模型 vao 56 GLuint vao; 57 // 使用的着色器 58 Shader* myShader; 59 // 总共要绘制多少个点 60 int numsToDraw; 61 // 开始的三个三角形顶点 62 Vector3 initVertices[3]; 63 64 };
懒得分开写了、比较简单、当然还有别的封装方法
其中的vector自己封装一下、做个运算符重载就行
这个类最神奇的地方就在于是不依赖于具体的窗口的
不管是SDL、glfw还是啥窗口、都适用。
浙公网安备 33010602011771号