chunk.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include "chunk.h"
  2. // STD
  3. #include <algorithm>
  4. #include <iostream>
  5. #include "coral_device.h"
  6. using namespace coral_3d;
  7. chunk::chunk(coral_3d::coral_device& device)
  8. {
  9. load(device);
  10. }
  11. void chunk::load(coral_device& device)
  12. {
  13. for (int y = 0; y < chunk_height_; y++)
  14. for (int x = 0; x < chunk_width_; x++)
  15. for (int z = 0; z < chunk_width_; z++)
  16. voxel_map_[{ x,y,z }] = true;
  17. for (int y = 0; y < chunk_height_; y++)
  18. for (int x = 0; x < chunk_width_; x++)
  19. for (int z = 0; z < chunk_width_; z++)
  20. add_block({ x,y,z });
  21. build_mesh(device);
  22. std::cout << "Built chunk with:\n\t"
  23. << num_faces_ << " faces\n\t"
  24. << num_faces_ * 2 << " triangles\n\t"
  25. << blocks_.size() << " blocks\n";
  26. position_ = glm::vec3{ 0.f };
  27. }
  28. void chunk::add_block(glm::vec3 position)
  29. {
  30. auto block = voxel_data::get_block();
  31. int num_deleted_faces{ 0 };
  32. auto it = block.faces.begin();
  33. while (it != block.faces.end())
  34. {
  35. // Check if there is a voxel adjecent to this face
  36. if (voxel_map_.contains(position + it->vertices[0].normal))
  37. {
  38. // If there is, delete this face
  39. it = block.faces.erase(it);
  40. num_deleted_faces++;
  41. continue;
  42. }
  43. // Else, add this face to the chunk
  44. for (auto& vertex : it->vertices)
  45. {
  46. vertex.position += position;
  47. }
  48. for (auto& index : it->indices)
  49. {
  50. index += (num_faces_ * 4) - (num_deleted_faces * 4);
  51. }
  52. ++it;
  53. }
  54. atlas_generator_.calculate_uvs(block);
  55. num_faces_ += block.faces.size();
  56. blocks_.emplace_back(block);
  57. }
  58. void chunk::build_mesh(coral_device& device)
  59. {
  60. std::vector<Vertex> vertices;
  61. std::vector<uint32_t> indices;
  62. for (const auto& block : blocks_)
  63. {
  64. for (const auto& face : block.faces)
  65. {
  66. vertices.insert(vertices.end(), face.vertices.begin(), face.vertices.end());
  67. indices.insert(indices.end(), face.indices.begin(), face.indices.end());
  68. }
  69. }
  70. mesh_ = coral_mesh::create_mesh_from_vertices(device, vertices, indices);
  71. }