-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtextures.cpp
More file actions
73 lines (67 loc) · 2.32 KB
/
textures.cpp
File metadata and controls
73 lines (67 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include "textures.h"
#include <SDL2/SDL_image.h>
#include <algorithm>
#include <iostream>
#include <string>
namespace {
SDL_Surface* loadSurface(const std::string& path) {
SDL_Surface* loaded = IMG_Load(path.c_str());
if (!loaded) {
std::cerr << "Failed to load texture " << path << ": " << IMG_GetError() << "\n";
return nullptr;
}
SDL_Surface* converted = SDL_ConvertSurfaceFormat(loaded, SDL_PIXELFORMAT_ARGB8888, 0);
SDL_FreeSurface(loaded);
if (!converted) {
std::cerr << "Failed to convert texture " << path << ": " << SDL_GetError() << "\n";
}
return converted;
}
} // namespace
TextureManager loadTextures() {
TextureManager tm{};
tm.textures.resize(6, nullptr);
tm.textures[1] = loadSurface("resources/textures/redbrick.png");
tm.textures[2] = loadSurface("resources/textures/greystone.png");
tm.textures[3] = loadSurface("resources/textures/wood.png");
tm.textures[4] = loadSurface("resources/textures/bluestone.png");
tm.textures[DOOR_TILE] = loadSurface("resources/textures/door.png");
tm.spriteTextures.push_back(loadSurface("resources/textures/sprite_barrel.png"));
tm.spriteTextures.push_back(loadSurface("resources/textures/sprite_pillar.png"));
tm.spriteTextures.push_back(loadSurface("resources/textures/sprite_greenlight.png"));
return tm;
}
void freeTextures(TextureManager& tm) {
for (auto* surf : tm.textures) {
if (surf) {
SDL_FreeSurface(surf);
}
}
for (auto* surf : tm.spriteTextures) {
if (surf) {
SDL_FreeSurface(surf);
}
}
tm.textures.clear();
tm.spriteTextures.clear();
}
Uint32 sampleTextureRaw(SDL_Surface* surf, int x, int y) {
if (!surf) {
return 0;
}
x = std::max(0, std::min(x, surf->w - 1));
y = std::max(0, std::min(y, surf->h - 1));
Uint8* pixelBase = static_cast<Uint8*>(surf->pixels);
Uint32* pixels = reinterpret_cast<Uint32*>(pixelBase);
int stride = surf->pitch / static_cast<int>(sizeof(Uint32));
return pixels[y * stride + x];
}
Color sampleTexture(SDL_Surface* surf, int x, int y) {
if (!surf) {
return {255, 0, 255}; // magenta fallback
}
Uint32 pixel = sampleTextureRaw(surf, x, y);
Uint8 r, g, b, a;
SDL_GetRGBA(pixel, surf->format, &r, &g, &b, &a);
return {r, g, b};
}