You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.3 KiB
C++

#ifndef COMPONENTS_SOLID_HPP
#define COMPONENTS_SOLID_HPP
#include "components/point.hpp"
#include "window.hpp"
#include <algorithm>
#include <cstdint>
#include <string>
class Solid {
public:
Solid(std::string path) {
bitmap = sdl2LoadSolid(path.c_str());
}
~Solid() {
if (bitmap != nullptr)
SDL_FreeSurface(bitmap);
}
float collision(Vec2 p) const noexcept {
float dy = 0.f;
if (at(p)) {
auto up = p;
while (up.y > 0 && at(up))
up.y--;
auto down = p;
while (down.y < bitmap->h && at(down))
down.y++;
if (down.y - p.y > p.y - up.y)
dy = -(p.y - up.y);
else
dy = down.y - p.y;
}
return dy;
}
private:
SDL_Surface *bitmap;
bool at(Vec2 p) const noexcept {
const auto bm = reinterpret_cast<std::uint8_t *>(bitmap->pixels);
const int x = std::clamp(static_cast<int>(p.x), 0, bitmap->w);
const int y = std::clamp(static_cast<int>(p.y), 0, bitmap->h);
const int i = y * bitmap->w + x;
const auto val = bm[i * bitmap->format->BytesPerPixel];
return val > 0;
}
};
#endif // COMPONENTS_SOLID_HPP