|
| 1 | +#include "TileMapComponent.h" |
| 2 | +#include "Actor.h" |
| 3 | +#include <fstream> |
| 4 | +#include <sstream> |
| 5 | +#include <iostream> |
| 6 | + |
| 7 | +TileMapComponent::TileMapComponent(Actor* owner, int drawOrder) |
| 8 | +:SpriteComponent(owner, drawOrder) |
| 9 | +{ |
| 10 | +} |
| 11 | + |
| 12 | +void TileMapComponent::Draw(SDL_Renderer* renderer) |
| 13 | +{ |
| 14 | + if (mTexture) |
| 15 | + { |
| 16 | + SDL_Rect dsrect; |
| 17 | + dsrect.w = mTileSize; |
| 18 | + dsrect.h = mTileSize; |
| 19 | + for (int i = 0; i < mLoadedCSV.size(); i++) |
| 20 | + { |
| 21 | + dsrect.y = i * mTileSize; |
| 22 | + for (int j = 0; j < mLoadedCSV[i].size(); j++) |
| 23 | + { |
| 24 | + if (mLoadedCSV[i][j] > -1) |
| 25 | + { |
| 26 | + dsrect.x = j * mTileSize; |
| 27 | + |
| 28 | + // Draw (have to convert angle from radians to degrees, and clockwise to counter) |
| 29 | + SDL_RenderCopyEx(renderer, |
| 30 | + mTexture, |
| 31 | + &mTileRects[mLoadedCSV[i][j]], |
| 32 | + &dsrect, |
| 33 | + -Math::ToDegrees(mOwner->GetRotation()), |
| 34 | + nullptr, |
| 35 | + SDL_FLIP_NONE); |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +void TileMapComponent::LoadTilemap(std::string&& CSVPath, SDL_Texture* tilemapTexture, int tileSize) |
| 43 | +{ |
| 44 | + mTexture = tilemapTexture; |
| 45 | + mTileSize = tileSize; |
| 46 | + |
| 47 | + SDL_QueryTexture(tilemapTexture, nullptr, nullptr, &mTexWidth, &mTexHeight); |
| 48 | + |
| 49 | + // Split the texture in to tiles to use with a csv tilemap. |
| 50 | + int tilesW = mTexWidth / tileSize; |
| 51 | + int tilesH = mTexHeight / tileSize; |
| 52 | + for (int i = 0; i < tilesH; i++) |
| 53 | + { |
| 54 | + for (int j = 0; j < tilesW; j++) |
| 55 | + { |
| 56 | + SDL_Rect tilerect; |
| 57 | + tilerect.x = j * tileSize; |
| 58 | + tilerect.y = i * tileSize; |
| 59 | + tilerect.w = tileSize; |
| 60 | + tilerect.h = tileSize; |
| 61 | + |
| 62 | + mTileRects.emplace_back(std::move(tilerect)); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + std::cout << "Tiles loaded: " << mTileRects.size() << std::endl; |
| 67 | + |
| 68 | + // Load desired tiles from csv file. |
| 69 | + std::ifstream fin(std::move(CSVPath)); |
| 70 | + std::string s; |
| 71 | + char cstring[4]; |
| 72 | + while (std::getline(fin, s)) |
| 73 | + { |
| 74 | + std::istringstream ss; |
| 75 | + ss.str(s); |
| 76 | + std::vector<int> CSVLine; |
| 77 | + while (ss.getline(cstring, 4, ',')) |
| 78 | + { |
| 79 | + CSVLine.emplace_back(stoi(std::string(cstring))); |
| 80 | + } |
| 81 | + mLoadedCSV.emplace_back(std::move(CSVLine)); |
| 82 | + } |
| 83 | + |
| 84 | + // Print loaded tilemap to console. |
| 85 | + for (auto& intvec : mLoadedCSV) |
| 86 | + { |
| 87 | + for (int i : intvec) |
| 88 | + { |
| 89 | + std::cout << i; |
| 90 | + } |
| 91 | + std::cout << std::endl; |
| 92 | + } |
| 93 | +} |
0 commit comments