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 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include "WorldPlane.h"
  2. #include "World.h"
  3. #include "Timer.h"
  4. namespace Swan {
  5. static ChunkPos chunkPos(TilePos pos) {
  6. int chx = pos.x_ / CHUNK_WIDTH;
  7. if (pos.x_ < 0 && pos.x_ % CHUNK_WIDTH != 0) chx -= 1;
  8. int chy = pos.y_ / CHUNK_HEIGHT;
  9. if (pos.y_ < 0 && pos.y_ % CHUNK_HEIGHT != 0) chy -= 1;
  10. return ChunkPos(chx, chy);
  11. }
  12. static Chunk::RelPos relPos(TilePos pos) {
  13. int rx = pos.x_ % CHUNK_WIDTH;
  14. if (rx < 0) rx += CHUNK_WIDTH;
  15. int ry = pos.y_ % CHUNK_HEIGHT;
  16. if (ry < 0) ry += CHUNK_HEIGHT;
  17. return Chunk::RelPos(rx, ry);
  18. }
  19. Entity &WorldPlane::spawnEntity(const std::string &name, const Vec2 &pos) {
  20. if (world_->ents_.find(name) == world_->ents_.end()) {
  21. fprintf(stderr, "Tried to spawn non-existant entity %s!",
  22. name.c_str());
  23. abort();
  24. }
  25. Entity *ent = world_->ents_[name]->create(*world_, pos);
  26. entities_.push_back(std::unique_ptr<Entity>(ent));
  27. fprintf(stderr, "Spawned %s at %f,%f.\n", name.c_str(), pos.x_, pos.y_);
  28. return *ent;
  29. }
  30. bool WorldPlane::hasChunk(ChunkPos pos) {
  31. return chunks_.find(pos) != chunks_.end();
  32. }
  33. Chunk &WorldPlane::getChunk(ChunkPos pos) {
  34. auto iter = chunks_.find(pos);
  35. if (iter == chunks_.end()) {
  36. iter = chunks_.emplace(pos, new Chunk(pos)).first;
  37. gen_->genChunk(*this, *iter->second);
  38. iter->second->redraw(world_->tile_map_);
  39. }
  40. return *iter->second;
  41. }
  42. void WorldPlane::setTileID(TilePos pos, Tile::ID id) {
  43. getChunk(chunkPos(pos)).setTileID(world_->tile_map_, relPos(pos), id);
  44. }
  45. Tile &WorldPlane::getTile(TilePos pos) {
  46. return getChunk(chunkPos(pos)).getTile(world_->tile_map_, relPos(pos));
  47. }
  48. Entity &WorldPlane::spawnPlayer() {
  49. return gen_->spawnPlayer(*this);
  50. }
  51. void WorldPlane::draw(Win &win) {
  52. for (auto &ch: chunks_)
  53. ch.second->draw(win);
  54. for (auto &ent: entities_)
  55. ent->draw(win);
  56. }
  57. void WorldPlane::update(float dt) {
  58. for (auto &ent: entities_)
  59. ent->update(*this, dt);
  60. }
  61. void WorldPlane::tick() {
  62. for (auto &ent: entities_)
  63. ent->tick();
  64. }
  65. }