A 2D tile-based sandbox game.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

WorldPlane.cc 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. int chx = pos.x / CHUNK_WIDTH;
  13. if (pos.x < 0 && pos.x % CHUNK_WIDTH != 0) chx -= 1;
  14. int chy = pos.y / CHUNK_HEIGHT;
  15. if (pos.y < 0 && pos.y % CHUNK_HEIGHT != 0) chy -= 1;
  16. return ChunkPos(chx, chy);
  17. }
  18. static Chunk::RelPos relPos(TilePos pos) {
  19. int rx = pos.x % CHUNK_WIDTH;
  20. if (rx < 0) rx += CHUNK_WIDTH;
  21. int ry = pos.y % CHUNK_HEIGHT;
  22. if (ry < 0) ry += CHUNK_HEIGHT;
  23. return Chunk::RelPos(rx, ry);
  24. }
  25. Context WorldPlane::getContext() {
  26. return {
  27. .game = *world_->game_,
  28. .world = *world_,
  29. .plane = *this,
  30. .resources = world_->resources_
  31. };
  32. }
  33. WorldPlane::WorldPlane(
  34. ID id, World *world, std::unique_ptr<WorldGen> gen,
  35. std::vector<std::unique_ptr<EntityCollection>> &&colls):
  36. id_(id), world_(world), gen_(std::move(gen)), ent_colls_(std::move(colls)) {
  37. for (auto &coll: ent_colls_) {
  38. ent_colls_by_type_[coll->type()] = coll.get();
  39. ent_colls_by_name_[coll->name()] = coll.get();
  40. }
  41. }
  42. EntityRef WorldPlane::spawnEntity(const std::string &name, const Entity::PackObject &obj) {
  43. return ent_colls_by_name_.at(name)->spawn(getContext(), obj);
  44. }
  45. void WorldPlane::despawnEntity(Entity &ent) {
  46. // TODO: this
  47. info << "Despawned entity.";
  48. }
  49. bool WorldPlane::hasChunk(ChunkPos pos) {
  50. return chunks_.find(pos) != chunks_.end();
  51. }
  52. // This function will be a bit weird because it's a really fucking hot function.
  53. Chunk &WorldPlane::getChunk(ChunkPos pos) {
  54. ZoneScopedN("WorldPlane getChunk");
  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. ZoneScopedN("WorldPlane getTileID");
  96. return getChunk(chunkPos(pos)).getTileID(relPos(pos));
  97. }
  98. Tile &WorldPlane::getTile(TilePos pos) {
  99. return world_->getTileByID(getTileID(pos));
  100. }
  101. Iter<Entity *> WorldPlane::getEntsInArea(Vec2 center, float radius) {
  102. return Iter<Entity *>([] { return std::nullopt; });
  103. // TODO: this
  104. /*
  105. return mapFilter(entities_.begin(), entities_.end(), [=](std::unique_ptr<Entity> &ent)
  106. -> std::optional<Entity *> {
  107. // Filter out things which don't have bodies
  108. auto *has_body = dynamic_cast<BodyTrait::HasBody *>(ent.get());
  109. if (has_body == nullptr)
  110. return std::nullopt;
  111. // Filter out things which are too far away from 'center'
  112. auto &body = has_body->getBody();
  113. auto bounds = body.getBounds();
  114. Vec2 entcenter = bounds.pos + (bounds.size / 2);
  115. auto dist = (entcenter - center).length();
  116. if (dist > radius)
  117. return std::nullopt;
  118. return ent.get();
  119. });
  120. */
  121. }
  122. EntityRef WorldPlane::spawnPlayer() {
  123. return gen_->spawnPlayer(getContext());
  124. }
  125. void WorldPlane::breakTile(TilePos pos) {
  126. // If the block is already air, do nothing
  127. Tile::ID id = getTileID(pos);
  128. Tile::ID air = world_->getTileID("@::air");
  129. if (id == air)
  130. return;
  131. // Change tile to air and emit event
  132. setTileID(pos, air);
  133. world_->evt_tile_break_.emit(getContext(), pos, world_->getTileByID(id));
  134. }
  135. SDL_Color WorldPlane::backgroundColor() {
  136. return gen_->backgroundColor(world_->player_->getBody().getBounds().pos);
  137. }
  138. void WorldPlane::draw(Win &win) {
  139. ZoneScopedN("WorldPlane draw");
  140. auto ctx = getContext();
  141. auto pbounds = world_->player_->getBody().getBounds();
  142. gen_->drawBackground(ctx, win, pbounds.pos);
  143. ChunkPos pcpos = ChunkPos(
  144. (int)floor(pbounds.pos.x / CHUNK_WIDTH),
  145. (int)floor(pbounds.pos.y / CHUNK_HEIGHT));
  146. // Just init one chunk per frame
  147. if (chunk_init_list_.size() > 0) {
  148. Chunk *chunk = chunk_init_list_.front();
  149. info << "render chunk " << chunk->pos_;
  150. chunk_init_list_.pop_front();
  151. chunk->render(ctx, win.renderer_);
  152. }
  153. for (int x = -1; x <= 1; ++x) {
  154. for (int y = -1; y <= 1; ++y) {
  155. auto iter = chunks_.find(pcpos + ChunkPos(x, y));
  156. if (iter != chunks_.end())
  157. iter->second.draw(ctx, win);
  158. }
  159. }
  160. for (auto &coll: ent_colls_)
  161. coll->draw(ctx, win);
  162. if (debug_boxes_.size() > 0) {
  163. for (auto &pos: debug_boxes_) {
  164. win.drawRect(pos, Vec2(1, 1));
  165. }
  166. }
  167. }
  168. void WorldPlane::update(float dt) {
  169. ZoneScopedN("WorldPlane update");
  170. auto ctx = getContext();
  171. debug_boxes_.clear();
  172. for (auto &coll: ent_colls_)
  173. coll->update(ctx, dt);
  174. }
  175. void WorldPlane::tick(float dt) {
  176. ZoneScopedN("WorldPlane tick");
  177. auto ctx = getContext();
  178. // Any chunk which has been in use since last tick should be kept alive
  179. for (std::pair<ChunkPos, Chunk *> &ch: tick_chunks_)
  180. ch.second->keepActive();
  181. tick_chunks_.clear();
  182. for (auto &coll: ent_colls_)
  183. coll->tick(ctx, dt);
  184. // Tick all chunks, figure out if any of them should be deleted or compressed
  185. auto iter = active_chunks_.begin();
  186. auto last = active_chunks_.end();
  187. while (iter != last) {
  188. auto &chunk = *iter;
  189. auto action = chunk->tick(dt);
  190. switch (action) {
  191. case Chunk::TickAction::DEACTIVATE:
  192. info << "Compressing inactive modified chunk " << chunk->pos_;
  193. chunk->compress();
  194. iter = active_chunks_.erase(iter);
  195. last = active_chunks_.end();
  196. break;
  197. case Chunk::TickAction::DELETE:
  198. info << "Deleting inactive unmodified chunk " << chunk->pos_;
  199. chunks_.erase(chunk->pos_);
  200. iter = active_chunks_.erase(iter);
  201. last = active_chunks_.end();
  202. break;
  203. case Chunk::TickAction::NOTHING:
  204. ++iter;
  205. break;
  206. }
  207. }
  208. }
  209. void WorldPlane::debugBox(TilePos pos) {
  210. debug_boxes_.push_back(pos);
  211. }
  212. }