Grid.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include "Grid.h"
  2. Mesh* createGridMesh(unsigned int lineCount)
  3. {
  4. // There needs to be an odd number of lines
  5. lineCount |= 1;
  6. const unsigned int pointCount = lineCount * 4;
  7. const unsigned int verticesSize = pointCount * (3 + 3);
  8. std::vector<float> vertices;
  9. vertices.resize(verticesSize);
  10. const float gridLength = (float)(lineCount / 2);
  11. float value = -gridLength;
  12. for (unsigned int i = 0; i < verticesSize; ++i)
  13. {
  14. // Default line color is dark grey
  15. Vector4 color(0.3f, 0.3f, 0.3f, 1.0f);
  16. // Very 10th line is brighter grey
  17. if (((int)value) % 10 == 0)
  18. {
  19. color.set(0.45f, 0.45f, 0.45f, 1.0f);
  20. }
  21. // The Z axis is blue
  22. if (value == 0.0f)
  23. {
  24. color.set(0.15f, 0.15f, 0.7f, 1.0f);
  25. }
  26. // Build the lines
  27. vertices[i] = value;
  28. vertices[++i] = 0.0f;
  29. vertices[++i] = -gridLength;
  30. vertices[++i] = color.x;
  31. vertices[++i] = color.y;
  32. vertices[++i] = color.z;
  33. vertices[++i] = value;
  34. vertices[++i] = 0.0f;
  35. vertices[++i] = gridLength;
  36. vertices[++i] = color.x;
  37. vertices[++i] = color.y;
  38. vertices[++i] = color.z;
  39. // The X axis is red
  40. if (value == 0.0f)
  41. {
  42. color.set(0.7f, 0.15f, 0.15f, 1.0f);
  43. }
  44. vertices[++i] = -gridLength;
  45. vertices[++i] = 0.0f;
  46. vertices[++i] = value;
  47. vertices[++i] = color.x;
  48. vertices[++i] = color.y;
  49. vertices[++i] = color.z;
  50. vertices[++i] = gridLength;
  51. vertices[++i] = 0.0f;
  52. vertices[++i] = value;
  53. vertices[++i] = color.x;
  54. vertices[++i] = color.y;
  55. vertices[++i] = color.z;
  56. value += 1.0f;
  57. }
  58. VertexFormat::Element elements[] =
  59. {
  60. VertexFormat::Element(VertexFormat::POSITION, 3),
  61. VertexFormat::Element(VertexFormat::COLOR, 3)
  62. };
  63. Mesh* mesh = Mesh::createMesh(VertexFormat(elements, 2), pointCount, false);
  64. if (mesh == NULL)
  65. {
  66. return NULL;
  67. }
  68. mesh->setPrimitiveType(Mesh::LINES);
  69. mesh->setVertexData(&vertices[0], 0, pointCount);
  70. return mesh;
  71. }
  72. Model* createGridModel(unsigned int lineCount)
  73. {
  74. Mesh* mesh = createGridMesh(lineCount);
  75. if (!mesh)
  76. return NULL;
  77. Model* model = Model::create(mesh);
  78. mesh->release();
  79. assert(model);
  80. return model;
  81. }