NasNas
An intuitive and beginner friendly 2D game framework for C++
SpriteBatch.hpp
1 
5 #pragma once
6 
7 #include <list>
8 #include <memory>
9 #include <vector>
10 
11 #include <SFML/Graphics/Drawable.hpp>
12 #include <SFML/Graphics/Color.hpp>
13 #include <SFML/Graphics/RenderTarget.hpp>
14 #include <SFML/Graphics/Texture.hpp>
15 #include <SFML/Graphics/Transformable.hpp>
16 #include <SFML/Graphics/Vertex.hpp>
17 #include <SFML/Graphics/VertexBuffer.hpp>
18 
19 #include <NasNas/core/graphics/Renderable.hpp>
20 #include <NasNas/core/graphics/Sprite.hpp>
21 
22 namespace ns {
23 
24  class SpriteBatch : public sf::Drawable, ns::Renderable {
25 
26  struct SpriteBatchLayer {
27  explicit SpriteBatchLayer(const sf::Texture* tex);
28  const sf::Texture* texture;
29  sf::VertexBuffer buffer;
30  std::vector<const ns::Sprite*> sprites;
31  std::vector<sf::Vertex> vertices;
32  };
33 
34  public:
35  enum class DrawOrder {Front, Back};
36 
37  SpriteBatch();
38  void clear();
39 
40  void start(sf::VertexBuffer::Usage usage);
41 
42  void setDrawOrder(DrawOrder order);
43 
44  void draw(const ns::Sprite* sprite);
45  void draw(const sf::Texture* texture, const sf::Vector2f& pos, const sf::IntRect& rect, const sf::Color& color = sf::Color::White);
46  void draw(const sf::Texture* texture, const sf::IntRect& rect, const sf::Transformable& tr, const sf::Color& color = sf::Color::White);
47 
48  void erase(const ns::Sprite* sprite);
49 
50  void end();
51 
52  auto getDepth() const -> unsigned ;
53  auto getUsage() const -> sf::VertexBuffer::Usage;
54  auto getPosition() const -> sf::Vector2f;
55  auto getGlobalBounds() const -> ns::FloatRect;
56 
57  private:
58  void render() override;
59  void draw(sf::RenderTarget& target, sf::RenderStates states) const override;
60 
61  ns::FloatRect m_global_bounds;
62  sf::VertexBuffer::Usage m_usage;
63  DrawOrder m_draw_order = DrawOrder::Front;
64 
65  std::list<SpriteBatchLayer> m_layers;
66  std::vector<std::unique_ptr<const ns::Sprite>> m_gc;
67 
68  bool m_need_end = false;
69  bool m_need_render = false;
70  };
71 
72 }