summary refs log tree commit diff stats
path: root/src/renderer.cpp
blob: 931e699f460a5dac17a4f92c5ae126f9bc1858d3 (plain) (blame)
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
74
75
76
#include "renderer.h"
#include "consts.h"
#include "game.h"

Renderer::Renderer() {
  win_ = window_ptr(
    SDL_CreateWindow(
      "Tanetane",
      100,
      100,
      GAME_WIDTH,
      GAME_HEIGHT,
      SDL_WINDOW_SHOWN));

  if (!win_)
  {
    throw sdl_error();
  }

  ren_ = renderer_ptr(
    SDL_CreateRenderer(
      win_.get(),
      -1,
      SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC));

  if (!ren_)
  {
    throw sdl_error();
  }
}

void Renderer::render(Game& game) {
  texture_ptr canvas(
    SDL_CreateTexture(
      ren_.get(),
      SDL_PIXELFORMAT_RGBA8888,
      SDL_TEXTUREACCESS_TARGET,
      CANVAS_WIDTH,
      CANVAS_HEIGHT));

  if (!canvas)
  {
    throw sdl_error();
  }

  SDL_SetRenderTarget(ren_.get(), canvas.get());
  SDL_SetRenderDrawBlendMode(ren_.get(), SDL_BLENDMODE_NONE);
  SDL_SetRenderDrawColor(ren_.get(), 255, 255, 255, 255);
  SDL_RenderClear(ren_.get());

  for (const Sprite& sprite : game.getSpritesByY() | game.spriteView()) {
    const SpriteFrame& frame = sprite.getFrame();
    const SDL_Rect& src = frame.srcRect;
    SDL_Rect dest { sprite.loc().x() - frame.center.x(), sprite.loc().y() - frame.center.y(), frame.size.w(), frame.size.h() };
    SDL_RenderCopy(ren_.get(), textures_.at(sprite.getTextureId()).get(), &src, &dest);
  }

  SDL_SetRenderTarget(ren_.get(), nullptr);
  SDL_RenderCopy(ren_.get(), canvas.get(), nullptr, nullptr);
  SDL_RenderPresent(ren_.get());
}

int Renderer::loadImageFromFile(std::string_view filename) {
  surface_ptr pfs(IMG_Load(filename.data()));
  if (!pfs)
  {
    throw img_error();
  }

  texture_ptr tex = texture_ptr(SDL_CreateTextureFromSurface(ren_.get(), pfs.get()));

  int texId = textures_.size();
  textures_.push_back(std::move(tex));

  return texId;
}