World.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include <cmath>
  2. #include "server/World.h"
  3. #include "utils/Logger.h"
  4. #include "utils/Random.h"
  5. World::World() : blocks(7, 7) {
  6. for(int x = 0; x < blocks.getSize(); x++) {
  7. for(int z = 0; z < blocks.getSize(); z++) {
  8. int height = sinf(x * 0.25f) * 2.0f + cosf(z * 0.25f) * 2.0f + 6.0f;
  9. for(int y = 0; y < height; y++) {
  10. blocks.set(x, y, z, 1);
  11. }
  12. }
  13. }
  14. }
  15. void World::addEntity(Entity* e) {
  16. entities.add(e);
  17. }
  18. void World::removeEntity(Entity* e) {
  19. for(int i = 0; i < entities.getLength(); i++) {
  20. if(entities[i] == e) {
  21. entities.removeBySwap(i);
  22. return;
  23. }
  24. }
  25. }
  26. List<Box> World::getBoxes(const Box& box) const {
  27. int minX = floorf(box.getMin()[0]);
  28. int minY = floorf(box.getMin()[1]);
  29. int minZ = floorf(box.getMin()[2]);
  30. int maxX = floorf(box.getMax()[0]);
  31. int maxY = floorf(box.getMax()[1]);
  32. int maxZ = floorf(box.getMax()[2]);
  33. List<Box> boxes;
  34. for(int x = minX; x <= maxX; x++) {
  35. for(int y = minY; y <= maxY; y++) {
  36. for(int z = minZ; z <= maxZ; z++) {
  37. Block::addBoxes(blocks.get(x, y, z), boxes,
  38. Vector3(static_cast<float>(x),
  39. static_cast<float>(y),
  40. static_cast<float>(z)));
  41. }
  42. }
  43. }
  44. return boxes;
  45. }
  46. void World::tick() {
  47. for(Entity* e : entities) {
  48. e->tick();
  49. if(!e->skip) {
  50. Vector3 move = limitMove(*e, e->getVelocity());
  51. e->move(move);
  52. }
  53. }
  54. }
  55. Vector3 World::limitMove(const Entity& e, Vector3 move) const {
  56. Box box = e.getBox();
  57. List<Box> boxes = getBoxes(box.expand(move));
  58. if(boxes.getLength() == 0) {
  59. return move;
  60. }
  61. Vector3 realMove;
  62. constexpr float step = 0.05f;
  63. while(move[0] != 0.0f || move[1] != 0.0f || move[2] != 0.0f) {
  64. for(int i = 0; i < 3; i++) {
  65. Vector3 old = realMove;
  66. if(move[i] > step) {
  67. realMove[i] += step;
  68. move[i] -= step;
  69. } else if(move[i] < -step) {
  70. realMove[i] -= step;
  71. move[i] += step;
  72. } else if(move[i] != 0.0f) {
  73. realMove[i] += move[i];
  74. move[i] = 0.0f;
  75. }
  76. Box moved = box.offset(realMove);
  77. for(const Box& box : boxes) {
  78. if(box.collidesWith(moved)) {
  79. move[i] = 0.0f;
  80. realMove = old;
  81. break;
  82. }
  83. }
  84. }
  85. }
  86. return realMove;
  87. }