Chunk.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include "Chunk.h"
  2. #include "Constants.h"
  3. #include "Globals.h"
  4. #include "Registries.h"
  5. Chunk::Chunk( Framework::Punkt location, int dimensionId )
  6. : ReferenceCounter(),
  7. dimensionId( dimensionId ),
  8. location( location )
  9. {}
  10. Chunk::Chunk( Framework::Punkt location, int dimensionId, Framework::StreamReader* zReader )
  11. : Chunk( location, dimensionId )
  12. {
  13. load( zReader );
  14. }
  15. Chunk::~Chunk()
  16. {}
  17. Block* Chunk::zBlockAt( Framework::Vec3<int> location ) const
  18. {
  19. for( Block* b : blocks )
  20. {
  21. if( (Framework::Vec3<int>)b->getPos() == location )
  22. return b;
  23. }
  24. return 0;
  25. }
  26. void Chunk::setBlock( Block* block )
  27. {
  28. Framework::Vec3<int> pos = (Framework::Vec3<int>)block->getPos();
  29. for( Framework::Iterator<Block*> iterator = blocks.begin(); iterator; iterator++ )
  30. {
  31. if( pos == (Framework::Vec3<int>)iterator->getPos() )
  32. {
  33. iterator->release();
  34. iterator.set( block );
  35. return;
  36. }
  37. }
  38. blocks.add( block );
  39. }
  40. void Chunk::load( Framework::StreamReader* zReader )
  41. {
  42. Framework::Vec3<int> pos = { 0, 0, 0 };
  43. unsigned short id;
  44. zReader->lese( (char*)&id, 2 );
  45. while( id )
  46. {
  47. zReader->lese( (char*)&pos.x, 4 );
  48. zReader->lese( (char*)&pos.y, 4 );
  49. zReader->lese( (char*)&pos.z, 4 );
  50. bool d;
  51. zReader->lese( (char*)&d, 1 );
  52. if( d )
  53. {
  54. Block* block = STATIC_REGISTRY( BlockType ).zElement( id )->loadBlock( { pos.x + location.x - CHUNK_SIZE / 2, pos.y + location.y - CHUNK_SIZE / 2, pos.z }, zReader );
  55. if( block )
  56. setBlock( block );
  57. }
  58. else if( STATIC_REGISTRY( BlockType ).zElement( id )->needsInstance() )
  59. setBlock( STATIC_REGISTRY( BlockType ).zElement( id )->createBlock( { pos.x + location.x - CHUNK_SIZE / 2, pos.y + location.y - CHUNK_SIZE / 2, pos.z } ) );
  60. zReader->lese( (char*)&id, 2 );
  61. }
  62. }
  63. int Chunk::getDimensionId() const
  64. {
  65. return dimensionId;
  66. }
  67. Framework::Punkt Chunk::getCenter() const
  68. {
  69. return location;
  70. }
  71. Framework::Vec3<int> Chunk::getMin() const
  72. {
  73. return { location.x - CHUNK_SIZE / 2, location.y - CHUNK_SIZE / 2, 0 };
  74. }
  75. Framework::Vec3<int> Chunk::getMax() const
  76. {
  77. return { location.x + CHUNK_SIZE / 2, location.y + CHUNK_SIZE / 2, WORLD_HEIGHT };
  78. }
  79. void Chunk::forAll( std::function<void( Model3D* )> f )
  80. {
  81. for( Block* b : blocks )
  82. f( b );
  83. }