1 /** 2 Copyright: Copyright (c) 2013-2016 Andrey Penechko. 3 License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0). 4 Authors: Andrey Penechko. 5 */ 6 7 module voxelman.core.chunkmesh; 8 9 import voxelman.math; 10 import voxelman.model.vertex; 11 import derelict.opengl3.gl3; 12 import voxelman.core.config : DimentionId; 13 import voxelman.graphics; 14 15 struct Attribute 16 { 17 uint location; 18 uint elementNum;///number of 19 uint elementType;///GL_FLOAT etc 20 uint elementSize;///in bytes 21 uint offset;///offset from the begining of buffer 22 bool normalized; 23 } 24 25 struct ChunkMesh 26 { 27 vec3 position; 28 DimentionId dimention; 29 MeshVertex[] data; 30 31 bool isDataDirty = true; 32 static int numBuffersAllocated; 33 34 private GLuint vao; 35 private GLuint vbo; 36 private bool hasBuffers = false; 37 38 private void genBuffers() 39 { 40 glGenBuffers(1, &vbo); 41 glGenVertexArrays(1, &vao); 42 ++numBuffersAllocated; 43 hasBuffers = true; 44 } 45 46 void deleteBuffers() 47 { 48 if (!hasBuffers) return; 49 glDeleteBuffers(1, &vbo); 50 glDeleteVertexArrays(1, &vao); 51 --numBuffersAllocated; 52 hasBuffers = false; 53 } 54 55 void uploadBuffer() 56 { 57 glBindBuffer(GL_ARRAY_BUFFER, vbo); 58 glBufferData(GL_ARRAY_BUFFER, data.length*MeshVertex.sizeof, data.ptr, GL_STATIC_DRAW); 59 MeshVertex.setAttributes(); 60 glBindBuffer(GL_ARRAY_BUFFER, 0); 61 } 62 63 void bind() 64 { 65 if (!hasBuffers) 66 genBuffers(); 67 glBindVertexArray(vao); 68 } 69 70 static void unbind() 71 { 72 glBindVertexArray(0); 73 } 74 75 void render(bool trianlges) 76 { 77 assert(hasBuffers); 78 79 if (isDataDirty) 80 { 81 uploadBuffer(); 82 isDataDirty = false; 83 } 84 if (trianlges) 85 glDrawArrays(GL_TRIANGLES, 0, cast(uint)numVertexes());//data.length/12); 86 else 87 glDrawArrays(GL_LINES, 0, cast(uint)numVertexes());//data.length/12); 88 } 89 90 bool empty() { return data.length == 0; } 91 92 ulong numVertexes() {return data.length;} 93 ulong numTris() {return data.length/3;} 94 ulong dataBytes() { return data.length * MeshVertex.sizeof; } 95 } 96 97 alias MeshVertex = VertexPosColor!(float, ubyte); 98