A 2D tile-based sandbox game.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

WorldPlane.cc 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. #include "WorldPlane.h"
  2. #include <math.h>
  3. #include <iostream>
  4. #include <algorithm>
  5. #include "log.h"
  6. #include "World.h"
  7. #include "Game.h"
  8. #include "Clock.h"
  9. #include "Win.h"
  10. namespace Swan {
  11. static ChunkPos chunkPos(TilePos pos) {
  12. // This might look weird, but it reduces an otherwise complex series of operations
  13. // including conditional branches into like four x64 instructions.
  14. // Basically, the problem is that we want 'floor(pos.x / CHUNK_WIDTH)', but
  15. // integer division rounds towards zero, it doesn't round down.
  16. // Solution: Move the position far to the right in the number line, do the math there
  17. // with integer division which always rounds down (because the numbers are always >0),
  18. // then move the result back to something hovering around 0 again.
  19. return ChunkPos(
  20. ((long long)pos.x + (LLONG_MAX / 2) + 1) / CHUNK_WIDTH - ((LLONG_MAX / 2) / CHUNK_WIDTH) - 1,
  21. ((long long)pos.y + (LLONG_MAX / 2) + 1) / CHUNK_HEIGHT - ((LLONG_MAX / 2) / CHUNK_HEIGHT) - 1);
  22. }
  23. static Chunk::RelPos relPos(TilePos pos) {
  24. // This uses a similar trick to chunkPos to turn a mess of conditional moves
  25. // and math instructions into literally one movabs and one 'and'
  26. return Chunk::RelPos(
  27. (pos.x + (long long)CHUNK_WIDTH * ((LLONG_MAX / 2) / CHUNK_WIDTH)) % CHUNK_WIDTH,
  28. (pos.y + (long long)CHUNK_HEIGHT * ((LLONG_MAX / 2) / CHUNK_HEIGHT)) % CHUNK_HEIGHT);
  29. }
  30. Context WorldPlane::getContext() {
  31. return {
  32. .game = *world_->game_,
  33. .world = *world_,
  34. .plane = *this,
  35. .resources = world_->resources_
  36. };
  37. }
  38. WorldPlane::WorldPlane(
  39. ID id, World *world, std::unique_ptr<WorldGen> gen,
  40. std::vector<std::unique_ptr<EntityCollection>> &&colls):
  41. id_(id), world_(world), gen_(std::move(gen)), ent_colls_(std::move(colls)) {
  42. for (auto &coll: ent_colls_) {
  43. ent_colls_by_type_[coll->type()] = coll.get();
  44. ent_colls_by_name_[coll->name()] = coll.get();
  45. }
  46. }
  47. EntityRef WorldPlane::spawnEntity(const std::string &name, const Entity::PackObject &obj) {
  48. return ent_colls_by_name_.at(name)->spawn(getContext(), obj);
  49. }
  50. bool WorldPlane::hasChunk(ChunkPos pos) {
  51. return chunks_.find(pos) != chunks_.end();
  52. }
  53. // This function will be a bit weird because it's a really fucking hot function.
  54. Chunk &WorldPlane::getChunk(ChunkPos pos) {
  55. // First, look through all chunks which have been in use this tick
  56. for (auto [chpos, chunk]: tick_chunks_) {
  57. if (chpos == pos)
  58. return *chunk;
  59. }
  60. Chunk &chunk = slowGetChunk(pos);
  61. tick_chunks_.push_back({ pos, &chunk });
  62. return chunk;
  63. }
  64. Chunk &WorldPlane::slowGetChunk(ChunkPos pos) {
  65. ZoneScopedN("WorldPlane slowGetChunk");
  66. auto iter = chunks_.find(pos);
  67. // Create chunk if that turns out to be necessary
  68. if (iter == chunks_.end()) {
  69. iter = chunks_.emplace(pos, Chunk(pos)).first;
  70. Chunk &chunk = iter->second;
  71. gen_->genChunk(*this, chunk);
  72. active_chunks_.push_back(&chunk);
  73. chunk_init_list_.push_back(&chunk);
  74. // Otherwise, it might not be active, so let's activate it
  75. } else if (!iter->second.isActive()) {
  76. iter->second.keepActive();
  77. active_chunks_.push_back(&iter->second);
  78. chunk_init_list_.push_back(&iter->second);
  79. }
  80. return iter->second;
  81. }
  82. void WorldPlane::setTileID(TilePos pos, Tile::ID id) {
  83. Chunk &chunk = getChunk(chunkPos(pos));
  84. Chunk::RelPos rp = relPos(pos);
  85. Tile::ID old = chunk.getTileID(rp);
  86. if (id != old) {
  87. chunk.setTileID(rp, id, world_->getTileByID(id).image_.texture_.get());
  88. chunk.markModified();
  89. }
  90. }
  91. void WorldPlane::setTile(TilePos pos, const std::string &name) {
  92. setTileID(pos, world_->getTileID(name));
  93. }
  94. Tile::ID WorldPlane::getTileID(TilePos pos) {
  95. return getChunk(chunkPos(pos)).getTileID(relPos(pos));
  96. }
  97. Tile &WorldPlane::getTile(TilePos pos) {
  98. return world_->getTileByID(getTileID(pos));
  99. }
  100. Iter<Entity *> WorldPlane::getEntsInArea(Vec2 center, float radius) {
  101. return Iter<Entity *>([] { return std::nullopt; });
  102. // TODO: this
  103. /*
  104. return mapFilter(entities_.begin(), entities_.end(), [=](std::unique_ptr<Entity> &ent)
  105. -> std::optional<Entity *> {
  106. // Filter out things which don't have bodies
  107. auto *has_body = dynamic_cast<BodyTrait::HasBody *>(ent.get());
  108. if (has_body == nullptr)
  109. return std::nullopt;
  110. // Filter out things which are too far away from 'center'
  111. auto &body = has_body->getBody();
  112. auto bounds = body.getBounds();
  113. Vec2 entcenter = bounds.pos + (bounds.size / 2);
  114. auto dist = (entcenter - center).length();
  115. if (dist > radius)
  116. return std::nullopt;
  117. return ent.get();
  118. });
  119. */
  120. }
  121. EntityRef WorldPlane::spawnPlayer() {
  122. return gen_->spawnPlayer(getContext());
  123. }
  124. void WorldPlane::breakTile(TilePos pos) {
  125. // If the block is already air, do nothing
  126. Tile::ID id = getTileID(pos);
  127. Tile::ID air = world_->getTileID("@::air");
  128. if (id == air)
  129. return;
  130. // Change tile to air and emit event
  131. setTileID(pos, air);
  132. world_->evt_tile_break_.emit(getContext(), pos, world_->getTileByID(id));
  133. }
  134. SDL_Color WorldPlane::backgroundColor() {
  135. return gen_->backgroundColor(world_->player_->pos);
  136. }
  137. void WorldPlane::draw(Win &win) {
  138. ZoneScopedN("WorldPlane draw");
  139. auto ctx = getContext();
  140. auto &pbody = *(world_->player_);
  141. gen_->drawBackground(ctx, win, pbody.pos);
  142. ChunkPos pcpos = ChunkPos(
  143. (int)floor(pbody.pos.x / CHUNK_WIDTH),
  144. (int)floor(pbody.pos.y / CHUNK_HEIGHT));
  145. // Just init one chunk per frame
  146. if (chunk_init_list_.size() > 0) {
  147. Chunk *chunk = chunk_init_list_.front();
  148. info << "render chunk " << chunk->pos_;
  149. chunk_init_list_.pop_front();
  150. chunk->render(ctx, win.renderer_);
  151. }
  152. for (int x = -1; x <= 1; ++x) {
  153. for (int y = -1; y <= 1; ++y) {
  154. auto iter = chunks_.find(pcpos + ChunkPos(x, y));
  155. if (iter != chunks_.end())
  156. iter->second.draw(ctx, win);
  157. }
  158. }
  159. for (auto &coll: ent_colls_)
  160. coll->draw(ctx, win);
  161. if (debug_boxes_.size() > 0) {
  162. for (auto &pos: debug_boxes_) {
  163. win.drawRect(pos, Vec2(1, 1));
  164. }
  165. }
  166. }
  167. void WorldPlane::update(float dt) {
  168. ZoneScopedN("WorldPlane update");
  169. auto ctx = getContext();
  170. debug_boxes_.clear();
  171. for (auto &coll: ent_colls_)
  172. coll->update(ctx, dt);
  173. }
  174. void WorldPlane::tick(float dt) {
  175. ZoneScopedN("WorldPlane tick");
  176. auto ctx = getContext();
  177. // Any chunk which has been in use since last tick should be kept alive
  178. for (std::pair<ChunkPos, Chunk *> &ch: tick_chunks_)
  179. ch.second->keepActive();
  180. tick_chunks_.clear();
  181. for (auto &coll: ent_colls_)
  182. coll->tick(ctx, dt);
  183. // Tick all chunks, figure out if any of them should be deleted or compressed
  184. auto iter = active_chunks_.begin();
  185. auto last = active_chunks_.end();
  186. while (iter != last) {
  187. auto &chunk = *iter;
  188. auto action = chunk->tick(dt);
  189. switch (action) {
  190. case Chunk::TickAction::DEACTIVATE:
  191. info << "Compressing inactive modified chunk " << chunk->pos_;
  192. chunk->compress();
  193. iter = active_chunks_.erase(iter);
  194. last = active_chunks_.end();
  195. break;
  196. case Chunk::TickAction::DELETE:
  197. info << "Deleting inactive unmodified chunk " << chunk->pos_;
  198. chunks_.erase(chunk->pos_);
  199. iter = active_chunks_.erase(iter);
  200. last = active_chunks_.end();
  201. break;
  202. case Chunk::TickAction::NOTHING:
  203. ++iter;
  204. break;
  205. }
  206. }
  207. }
  208. void WorldPlane::debugBox(TilePos pos) {
  209. debug_boxes_.push_back(pos);
  210. }
  211. }