camera.cpp 32.7 KB
Newer Older
1
#include <logging/logging.hpp>
2
#include <assets/assets_manager.hpp>
3
#include <gui/camera/camera.hpp>
4
#include <gui/screen/screen.hpp>
5
#include <gui/sprites/pic_sprite.hpp>
6
#include <gui/sprites/orange_blob.hpp>
louiz’'s avatar
louiz’ committed
7
#include <gui/sprites/tourbillon_sprite.hpp>
louiz’'s avatar
louiz’ committed
8
#include <gui/sprites/bullet_sprite.hpp>
louiz’'s avatar
louiz’ committed
9
#include <gui/sprites/emp_sprite.hpp>
10
#include <gui/effect.hpp>
11
#include <world/world.hpp>
12
#include <world/layer.hpp>
13
#include <world/entity.hpp>
louiz’'s avatar
louiz’ committed
14
#include <world/team.hpp>
louiz’'s avatar
louiz’ committed
15
#include <world/task.hpp>
16
#include <gui/utils.hpp>
louiz’'s avatar
louiz’ committed
17
#include <game/game_client.hpp>
18 19
#include <climits>
#include <cstdlib>
20
#include <gui/effects/explosion.hpp>
21 22 23 24 25
#include <gui/camera/mobility_sprites.hpp>

#include <world/works/path_work.hpp>

#include <gui/sprites/decoration_sprite.hpp>
26

louiz’'s avatar
louiz’ committed
27
#include <world/abilities.hpp>
louiz’'s avatar
louiz’ committed
28
#include <world/location.hpp>
29
#include <world/health.hpp>
louiz’'s avatar
louiz’ committed
30

31
#include <algorithm>
louiz’'s avatar
louiz’ committed
32 33
#include <iostream>

34 35
using namespace std::string_literals;

louiz’'s avatar
louiz’ committed
36 37
Camera::Camera(GameClient* game, Screen* screen):
  ScreenElement(screen),
38
  x(0),
39
  y(56),
40
  zoom(1),
41
  focused(true),
42
  movement_speed(1000),
43 44
  previous_position(0, 0),
  start_drag_position(0, 0),
louiz’'s avatar
louiz’ committed
45
  game(game),
louiz’'s avatar
louiz’ committed
46
  mouse_selection(),
47 48
  tileset(),
  fog(1920, 1080, this, &this->world())
49
{
louiz’'s avatar
louiz’ committed
50
  this->tileset.load_from_file("test6.tmx");
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

  if (!ParticleEffect::texture.loadFromFile(AssetsManager::full_name("images/particles.png")))
    {
      log_debug("Failed to load particle.png");
      exit(1);
    }

  this->decoration_sprites.push_back(std::make_unique<DecorationSprite<49>>(Position{800, 800},
                           AssetsManager::full_name("images/test/tree.png"),
                           sf::Vector2<int>{256, 400}, 35ms));
  this->decoration_sprites.push_back(std::make_unique<DecorationSprite<49>>(Position{900, 850},
                           AssetsManager::full_name("images/test/tree.png"),
                           sf::Vector2<int>{256, 400}, 35ms));

  MobilitySprites::init();
  OrangeBlob::init();
67 68 69 70 71 72
}

Camera::~Camera()
{
}

louiz’'s avatar
louiz’ committed
73 74 75 76 77
World& Camera::world() const
{
  return this->game->get_world();
}

louiz’'s avatar
louiz’ committed
78
Map& Camera::map() const
louiz’'s avatar
louiz’ committed
79
{
louiz’'s avatar
louiz’ committed
80
  return this->world().get_map();
louiz’'s avatar
louiz’ committed
81 82 83 84 85 86 87 88 89 90 91 92
}

sf::RenderWindow& Camera::win()
{
  return this->screen->window();
}

sf::RenderWindow& Camera::win() const
{
  return this->screen->window();
}

93
bool Camera::handle_event(const sf::Event& event)
94
{
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
  if (event.type == sf::Event::LostFocus)
    this->focused = false;
  else if (event.type == sf::Event::GainedFocus)
    this->focused = true;
  else if (event.type == sf::Event::MouseButtonPressed)
    {
      switch (event.mouseButton.button)
        {
        case sf::Mouse::Left:
          this->handle_left_click(event);
          break;
        case sf::Mouse::Middle:
          this->handle_middle_click(event);
          break;
        case sf::Mouse::Right:
          this->handle_right_click(event);
          break;
        default:
          log_debug("Mouse button not implemented.");
        }
    }
  else if (event.type == sf::Event::MouseButtonReleased)
    {
      switch (event.mouseButton.button)
        {
        case sf::Mouse::Left:
          this->handle_left_release(event);
          break;
        case sf::Mouse::Middle:
          this->handle_middle_release(event);
          break;
        default:
          log_debug("Mouse button not implemented.");
        }
    }
  this->fixup_camera_position();
  if (this->mouse_selection.ongoing == true)
    return true;
  return false;
}

louiz’'s avatar
louiz’ committed
136
void Camera::handle_middle_click(const sf::Event&)
137 138 139 140 141
{
}

void Camera::handle_right_click(const sf::Event& event)
{
142
  const Position pos = this->screen_to_world_position(event.mouseButton.x,
143
                                                      event.mouseButton.y);
louiz’'s avatar
louiz’ committed
144 145
  bool queue = sf::Keyboard::isKeyPressed(sf::Keyboard::LShift);
  log_debug("queue: " << queue);
146

147
  // A right click when there's an action associated with the left click
148
  // resets the default action of the right click.
149
  if (this->screen->get_left_click().callback)
150
    this->screen->reset_left_click();
151 152

  // else // otherwise it always does the move action.
louiz’'s avatar
louiz’ committed
153 154 155 156
    {
      std::vector<EntityId> ids;
      for (const auto& entity: this->game->get_selection().get_entities())
        ids.push_back(entity->get_id());
157 158 159 160 161 162
      if (ids.empty())
        return ;
      const Entity* entity_under_mouse = this->get_entity_under_mouse();
      if (entity_under_mouse)
        this->game->action_follow(ids, entity_under_mouse->get_id(), queue);
      else
louiz’'s avatar
louiz’ committed
163 164
        this->game->action_move(ids, pos, queue);
    }
165 166 167 168
}

void Camera::handle_left_click(const sf::Event& event)
{
louiz’'s avatar
louiz’ committed
169
  // TODO do nothing if the click is not in the camera zone.
170
  if (!this->screen->get_left_click().callback)
louiz’'s avatar
louiz’ committed
171 172 173 174 175 176 177 178
    {
      const sf::Vector2i pos(event.mouseButton.x + this->x,
                             event.mouseButton.y + this->y);

      this->mouse_selection.start(pos);
    }
  else
    {
179
      const Position pos = this->screen_to_world_position(event.mouseButton.x,
louiz’'s avatar
louiz’ committed
180
                                                          event.mouseButton.y);
181 182
      if (this->screen->get_left_click().callback(pos) == true)
        this->screen->reset_left_click();
louiz’'s avatar
louiz’ committed
183
    }
184 185
}

louiz’'s avatar
louiz’ committed
186
void Camera::handle_left_release(const sf::Event&)
187 188 189 190 191 192
{
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::RShift) ||
      sf::Keyboard::isKeyPressed(sf::Keyboard::LShift))
    this->add_mouse_selection_to_selection();
  else
    this->set_mouse_selection_to_selection();
193
  this->mouse_selection.end();
194 195 196 197
}

void Camera::set_mouse_selection_to_selection()
{
198 199
  sf::Vector2i mouse_pos = this->get_mouse_position();

louiz’'s avatar
louiz’ committed
200 201 202 203
  // Only the manipulable entities are considered
  std::vector<const Entity*> entities_in_mouse_selection;

  for (const auto& entity: this->world().entities)
204
    {
louiz’'s avatar
louiz’ committed
205 206 207 208 209 210 211 212 213
      Location* location = entity->get<Location>();
      Team* team = entity->get<Team>();
      if (!team || !location || !entity->is_manipulable())
        continue;
      if (this->mouse_selection.contains(mouse_pos,
                                         this->world_to_camera_position(location->position())))
        entities_in_mouse_selection.push_back(entity.get());
    }

214 215 216
  if (entities_in_mouse_selection.empty())
    return ;

louiz’'s avatar
louiz’ committed
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
  auto end_own_entities = std::partition(entities_in_mouse_selection.begin(),
                                         entities_in_mouse_selection.end(),
                                         [this](const Entity* entity) -> bool
                                         {
                                           Team* team = entity->get<Team>();
                                           if (team->get() == this->game->get_self_team())
                                             return true;
                                           return false;
                                         });
  if (end_own_entities == entities_in_mouse_selection.begin())
    { // 0 of the selected entities are the player's
      this->game->get_selection().assign(entities_in_mouse_selection.begin(),
                                         entities_in_mouse_selection.end());
    }
  else
    { // Only select entities owned by the player
      this->game->get_selection().assign(entities_in_mouse_selection.begin(),
                                         end_own_entities);
235 236 237 238 239
    }
}

void Camera::add_mouse_selection_to_selection()
{
240
  sf::Vector2i mouse_pos = this->get_mouse_position();
louiz’'s avatar
louiz’ committed
241 242

  for (const auto& entity: this->world().entities)
243
    {
louiz’'s avatar
louiz’ committed
244
      Location* location = entity->get<Location>();
louiz’'s avatar
louiz’ committed
245
      if (!location || !entity->is_manipulable())
louiz’'s avatar
louiz’ committed
246
        continue;
247
      if (this->mouse_selection.contains(mouse_pos,
248
                                         this->world_to_camera_position(location->position())))
249
        {
louiz’'s avatar
louiz’ committed
250 251
          if (this->game->is_entity_selected(entity.get()) == false)
            this->game->select_entity(entity.get());
252
        }
253 254 255 256
    }
  this->mouse_selection.end();
}

louiz’'s avatar
louiz’ committed
257
void Camera::handle_middle_release(const sf::Event&)
258
{
259 260
}

261
void Camera::update(const utils::Duration& dt)
262
{
263 264 265
  if (this->get_game_client()->get_selection().is_empty())
    {
      sf::Vector2i pos = this->screen->get_mouse_position();
266

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
      const sf::Vector2u win_size = this->get_win_size();
      if (this->focused)
        {
          if ((pos.x > 0) && (static_cast<uint>(pos.x) > (win_size.x - 2)))
            pos.x = (win_size.x - 2);
          if (pos.x < 1)
            pos.x = 1;
          if ((pos.y > 0) && (static_cast<uint>(pos.y) > (win_size.y - 2)))
            pos.y = (win_size.y - 2);
          if (pos.y < 1)
            pos.y = 1;
          // TODO
          // sf::Mouse::setPosition(pos, *this->win);
          if (pos.x < 20)
            this->x -= this->movement_speed * utils::sec(dt).count();
          if (pos.y < 20)
            this->y -= this->movement_speed * utils::sec(dt).count();
          if ((pos.y > 0) && static_cast<uint>(pos.y) > (win_size.y - 20))
            this->y += this->movement_speed * utils::sec(dt).count();
          if ((pos.x > 0) && static_cast<uint>(pos.x) > (win_size.x - 20))
            this->x += this->movement_speed * utils::sec(dt).count();
        }
      this->fixup_camera_position();
    }
291 292 293 294 295 296 297 298 299 300 301 302 303
    for (auto& effect: this->effects)
      effect->update(dt);
    for (auto& sprite: this->sprites)
      sprite->update(dt);
    for (auto& sprite: this->decoration_sprites)
      sprite->update(dt);

    this->effects.erase(std::remove_if(this->effects.begin(), this->effects.end(),
                                       [](const std::unique_ptr<Effect>& effect)
                                       {
                                         return effect->current_life() <= 0s;
                                       }),
                        this->effects.end());
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
}

void Camera::center(const sf::Vector2i& center)
{
  auto size = this->win().getSize();
  size.x /= 2;
  size.y /= 2;
  log_debug("width :"  << size.x);
  log_debug("height:"  << size.y);
  if (size.x < center.x)
    this->x = center.x - size.x;
  else
    this->x = 0;

  if (size.y < center.y)
    this->y = center.y - size.y;
  else
    this->y = 0;
322
}
louiz’'s avatar
louiz’ committed
323

324 325 326 327 328 329 330 331 332 333 334 335 336 337
bool Camera::tile_before_sprite(const CellIndex cell, const WorldSprite* sprite,
                                const Cell sprite_cell) const
{
  unsigned short x, y;
  std::tie(x, y) = this->map().index_to_cell(cell);
  unsigned short sprite_x, sprite_y;
  std::tie(sprite_x, sprite_y) = sprite_cell;
  CellIndex sprite_cell_index = this->map().cell_to_index(std::make_pair(sprite_x, sprite_y));
  // Same tile
  if (sprite_cell_index == cell)
    return true;
  if (sprite_y > y)
    return true;
  return this->map().is_cell_in_neighbour_lower_cells(sprite_cell_index, cell);
louiz’'s avatar
louiz’ committed
338
void Camera::draw()
louiz’'s avatar
louiz’ committed
339
{
340
  const sf::Vector2i mouse_pos = this->get_mouse_position();
341
  const Entity* entity_under_mouse = this->get_entity_under_mouse();
342

343 344 345 346
  std::vector<const WorldSprite*> sorted_sprites;
  sorted_sprites.reserve(this->sprites.size() +
                         this->effects.size() +
                         this->decoration_sprites.size());
louiz’'s avatar
louiz’ committed
347

348
  for (auto& sprite: this->sprites)
louiz’'s avatar
louiz’ committed
349
    {
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
      if (this->world().can_be_seen_by_team(sprite->get_world_pos(),
                                            this->game->get_self_team()))
        sorted_sprites.push_back(sprite.get());
    }
  for (auto& effect: this->effects)
    sorted_sprites.push_back(effect.get());
  for (auto& sprite: this->decoration_sprites)
    sorted_sprites.push_back(sprite.get());

  std::vector<std::unique_ptr<SimpleWorldSprite>> flag_sprites;

  for (const std::shared_ptr<Entity>& entity: this->world().entities)
    {
      const PathWork* path_work = entity->get_current_work<PathWork>();
      if (!path_work)
        continue;
      const PathTask* path_task = path_work->get_task<PathTask>();
      if (!path_task)
        continue;
      const Path& path = path_task->get_path();
      MobilitySprites::insert_flag_sprites(path, flag_sprites);
    }

  for (const std::unique_ptr<SimpleWorldSprite>& flag_sprite: flag_sprites)
    sorted_sprites.push_back(flag_sprite.get());

  std::sort(sorted_sprites.begin(),
            sorted_sprites.end(),
            [](const WorldSprite* a, const WorldSprite* b)
            {
              return a->get_world_pos().y < b->get_world_pos().y;
            });

  std::vector<Cell> sprite_cells;
  sprite_cells.reserve(this->sprites.size() + this->effects.size());
  for (const auto& sprite: sorted_sprites)
    sprite_cells.push_back(this->world().get_cell_at_position(sprite->get_world_pos()));

  std::vector<std::vector<CellIndex>> tiles_before_sprite;
  // We have one more vector, in which we put cells that are to be drawn
  // after all the tiles
  tiles_before_sprite.resize(sorted_sprites.size() + 1);

  unsigned short start_x = std::max(0, static_cast<int>((this->x / TILE_WIDTH)) - 1);
  unsigned short start_y = std::max(0, static_cast<int>(this->y / (TILE_HEIGHT / 2)) - 3);
  for (auto y = start_y; y < start_y + 30; y++)
    for (auto x = start_x; x < start_x + 25; x++)
      {
        CellIndex cell = this->map().cell_to_index(std::make_pair(x, y));
        for (std::size_t i = 0; i < sorted_sprites.size(); i++)
          {
            const WorldSprite* sprite = sorted_sprites[i];
            const Cell sprite_cell = sprite_cells[i];
            if (this->tile_before_sprite(cell, sprite, sprite_cell))
404
              {
405 406
                tiles_before_sprite[i].push_back(cell);
                goto break_outerloop;
407
              }
408 409 410 411 412 413
          }
        // We con only get here if the cell was added in no vector at all
        tiles_before_sprite[tiles_before_sprite.size()-1].push_back(cell);
      break_outerloop:
        continue;
      }
414

415 416 417
  for (std::size_t i = 0; i < tiles_before_sprite.size(); ++i)
    {
      for (const CellIndex index: tiles_before_sprite[i])
louiz’'s avatar
louiz’ committed
418
        {
419 420 421 422 423 424 425 426
          unsigned short col;
          unsigned short row;
          std::tie(col, row) = this->map().index_to_cell(index);
          auto x = col * TILE_WIDTH;
          if (row % 2 != 0)
            x += HALF_TILE_W;
          auto y = row * (TILE_HEIGHT / 2);
          for (Layer* layer: this->map().layers)
427
            {
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
              if (layer && layer->cells)
                {
                  std::size_t gid = layer->cells[index];
                  GraphTile* tile = this->tileset.tiles[gid].get();
                  if (tile)
                    {
                      if (std::find(this->world().current_path.begin(),
                                    this->world().current_path.end(),
                                    index) != this->world().current_path.end())
                        tile->sprite.setColor(sf::Color::Red);
                      else
                        tile->sprite.setColor(sf::Color::White);
                      tile->sprite.setPosition(x - this->x, y - this->y);
                      this->win().draw(tile->sprite);
                    }
                }
              y -= LEVEL_HEIGHT;
            }
        }
      // Draw the WorldSprite that is above all these tiles
      if (i < sorted_sprites.size())
        { // Unless we were at the last queue of tiles, which have no tile above them
          const WorldSprite* sprite = sorted_sprites[i];
          auto entity_sprite = dynamic_cast<const EntitySprite*>(sprite);
          const auto camera_pos = this->world_to_camera_position(sprite->get_world_pos());
          sf::Transform transform;

          if (entity_sprite &&
              entity_sprite->get_entity()->is_manipulable() &&
              (this->mouse_selection.contains(this->get_mouse_position(), camera_pos)))
            this->draw_hover_indicator(camera_pos, 80);

          if (entity_sprite &&
              this->get_game_client()->is_entity_selected(entity_sprite->get_entity()))
            this->draw_selected_indicator(camera_pos, 80);

          transform.translate(camera_pos.x - this->x,
                              camera_pos.y - this->y);
          sprite->draw(this->win(), transform);
          if (entity_sprite)
            {
              auto entity = entity_sprite->get_entity();
470 471 472 473 474 475 476 477 478 479 480
              auto health = entity->get<Health>();
              auto team = entity->get<Team>();

              if (health)
                {
                  auto bar = WorldSprite::standard_health_bar;
                  if (team && team->get() == 1)
                    bar.max_color = sf::Color::Blue;
                  this->draw_energy_bar(bar, health->get_max().to_int(),
                                        health->get().to_int(), transform);
                }
481
            }
louiz’'s avatar
louiz’ committed
482
        }
louiz’'s avatar
louiz’ committed
483
    }
484

485
  this->draw_mouse_selection();
486
  this->draw(this->fog.get_sprite());
487 488 489

  // Debug
  const std::string cam_pos = "Camera position: " + std::to_string(this->x) + ", " + std::to_string(this->y);
louiz’'s avatar
louiz’ committed
490 491
  this->game->get_debug_hud().add_debug_line(cam_pos);
  this->game->get_debug_hud().add_debug_line("Map width in pixel: " + std::to_string(this->map().get_width_in_pixels()) + ", " + std::to_string(this->map().get_height_in_pixels()));
492 493

  Position world_mouse_pos = this->camera_to_world_position(mouse_pos.x, mouse_pos.y);
louiz’'s avatar
louiz’ committed
494
  this->game->get_debug_hud().add_debug_line("Mouse world position: " +
495 496
                                             std::to_string(world_mouse_pos.x.to_double()) + ", " +
                                             std::to_string(world_mouse_pos.y.to_double()));
497

498 499 500 501 502
  if (entity_under_mouse)
    this->game->get_debug_hud().add_debug_line("Entity under mouse: " + std::to_string(entity_under_mouse->get_id()));
  else
    this->game->get_debug_hud().add_debug_line("No entity under mouse");

503 504
  this->game->get_debug_hud().add_debug_line("Current world time: "s + std::to_string(this->get_game_client()->current_world_time().count()));

505 506
  Cell cell_under_mouse = this->world().get_cell_at_position(world_mouse_pos);
  this->game->get_debug_hud().add_debug_line("Cell under mouse: "s + std::to_string(std::get<0>(cell_under_mouse)) + ":" + std::to_string(std::get<1>(cell_under_mouse)));
507 508 509 510 511 512
}

void Camera::draw_mouse_selection()
{
  if (this->mouse_selection.ongoing == false)
    return ;
513
  sf::Vector2i mouse_pos = this->get_mouse_position();
514 515 516
  sf::RectangleShape rect(sf::Vector2f(::abs(mouse_pos.x - this->mouse_selection.start_pos.x),
                                       ::abs(mouse_pos.y- this->mouse_selection.start_pos.y)));
  rect.setOutlineThickness(1);
517 518
  rect.setFillColor(sf::Color(13, 0, 152, 40));
  rect.setOutlineColor(sf::Color(13, 0, 152, 0x36));
519 520 521 522 523 524 525 526 527 528
  sf::Vector2f rect_pos;
  if (this->mouse_selection.start_pos.x < mouse_pos.x)
    rect_pos.x = this->mouse_selection.start_pos.x - this->x;
  else
    rect_pos.x = mouse_pos.x - this->x;
  if (this->mouse_selection.start_pos.y < mouse_pos.y)
    rect_pos.y = this->mouse_selection.start_pos.y - this->y;
  else
    rect_pos.y = mouse_pos.y - this->y;
  rect.setPosition(rect_pos);
louiz’'s avatar
louiz’ committed
529
  this->win().draw(rect);
530 531
}

532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
void Camera::draw_hover_indicator(const sf::Vector2i& center, const unsigned int width)
{
  const float radius = static_cast<float>(width) / 2.0;
  sf::CircleShape circle(radius, 6);
  circle.setOutlineColor(sf::Color::Red);
  circle.setFillColor({0, 0, 0, 0});
  circle.setOutlineThickness(2);
  circle.scale(1.0f, 0.666f);
  circle.setPosition(static_cast<float>(center.x) - radius - this->x,
                     static_cast<float>(center.y) - radius * 0.666f - this->y);
  this->draw(circle);
}

void Camera::draw_selected_indicator(const sf::Vector2i& center, const unsigned int width)
{
  const float radius = static_cast<float>(width) / 2.0;
  sf::CircleShape circle(radius);
  circle.setOutlineColor(sf::Color::Blue);
  circle.setFillColor({0, 0, 0, 0});
  circle.setOutlineThickness(2);
  circle.scale(1.0f, 0.666f);
  circle.setPosition(static_cast<float>(center.x) - radius - this->x,
                     static_cast<float>(center.y) - radius * 0.666f - this->y);
  this->draw(circle);
}

558 559
void Camera::fixup_camera_position()
{
louiz’'s avatar
louiz’ committed
560
  const sf::Vector2u win_size = this->win().getSize();
561 562
  if (this->x < 0)
    this->x = 0;
louiz’'s avatar
louiz’ committed
563 564
  else if (this->x > (this->map().get_width_in_pixels() - win_size.x))
    this->x = this->map().get_width_in_pixels() - win_size.x;
565 566
  if (this->y < 0)
    this->y = 0;
louiz’'s avatar
louiz’ committed
567 568
  else if (this->y > (this->map().get_height_in_pixels() - win_size.y))
    this->y = this->map().get_height_in_pixels() - win_size.y;
569 570
}

571 572 573 574 575 576 577 578
sf::Vector2i Camera::world_to_screen_position(const Position& pos) const
{
  auto res = this->world_to_camera_position(pos);
  res.x -= this->x;
  res.y -= this->y;
  return res;
}

579
sf::Vector2i Camera::world_to_camera_position(const Position& pos) const
580
{
581
  sf::Vector2i res;
582

louiz’'s avatar
louiz’ committed
583 584
  res.x = pos.x.to_int();
  res.y = pos.y.to_int();
585

louiz’'s avatar
louiz’ committed
586 587
  res.x = (res.x * TILE_WIDTH) / CELL_SIZE;
  res.y = (res.y * TILE_HEIGHT) / CELL_SIZE;
588 589

  // Then adjust y using the height of that position in the world
louiz’'s avatar
louiz’ committed
590
  Fix16 height = this->world().get_position_height(pos) * 24;
591

louiz’'s avatar
louiz’ committed
592 593
  res.y += TILE_TOP_OFFSET - height.to_int();

594 595 596
  return res;
}

597
CellIndex Camera::get_cell_at_coord(const unsigned int x, const unsigned int y) const
598
{
599 600 601
  const Position pos(x * CELL_SIZE / TILE_WIDTH,
                     y * CELL_SIZE / TILE_HEIGHT);

louiz’'s avatar
louiz’ committed
602 603
  const Cell cell = this->world().get_cell_at_position(pos);
  return this->map().cell_to_index(cell);
604 605 606 607 608 609 610 611 612 613
}

float get_edge_height(const float x, const float left_height, const float right_height)
{
  if (left_height == right_height)
    return left_height;

  const float ratio = x / HALF_TILE_W;
  if (left_height > right_height)
    return left_height - (ratio * (left_height - right_height));
614
  else
615 616 617
    return left_height + (ratio * (right_height - left_height));
}

618 619 620 621 622 623 624 625
sf::Vector2i Camera::get_mouse_position() const
{
  auto res = this->screen->get_mouse_position();
  res.x += this->x;
  res.y += this->y;
  return res;
}

626
Position Camera::camera_to_world_position(const int x, const int y) const
627 628 629 630 631
{
  return this->screen_to_world_position(x - this->x, y - this->y);
}

Position Camera::screen_to_world_position(const int x, const int y) const
632 633
{
  // The empty space at the top of the world, due to tile size. In pixels
louiz’'s avatar
louiz’ committed
634
  static const unsigned int top_offset = TILE_TOP_OFFSET;
635 636 637 638 639 640 641 642 643 644 645 646 647 648

  if (x + this->x <= 0 ||
      y + this->y - top_offset <= 0)
    return Position::zero;

  static const float cell_size = static_cast<const float>(CELL_SIZE);

  // Get the cell (at the floor level) at the position
  const CellIndex cell_index = this->get_cell_at_coord(x + this->x,
                                                       y + this->y - top_offset);

  // DEBUG only
  selected_cell = cell_index;

louiz’'s avatar
louiz’ committed
649 650
  if (cell_index == InvalidCellIndex)
    return Position::invalid;
651 652 653

  unsigned int col;
  unsigned int row;
louiz’'s avatar
louiz’ committed
654
  std::tie(col, row) = this->map().index_to_cell(cell_index);
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672

  // If the world was completely flat, this would be the result position
  Position res;
  res.x = (x + this->x) * (cell_size / TILE_WIDTH);
  res.y = (y + this->y - top_offset) * (cell_size / TILE_HEIGHT);

  // Now we need to check if, due to the levels of the world, this position
  // is hidden or not by a surrounding cell. If yes, the position is
  // actually on this other cell.

  // If we are on the left side of the cell, we may be hidden by the bottom
  // or the left cells. If we are on the right side, the bottom or the right
  // cells.
  unsigned int xx = x + this->x;
  if (row % 2)
    xx += HALF_TILE_W;

  // TODO this in a (World::?) function
louiz’'s avatar
louiz’ committed
673
  TileHeights heights = this->map().get_cell_heights(col, row);
674

louiz’'s avatar
louiz’ committed
675
  this->game->get_debug_hud().add_debug_line("Current cell corner heights: " +
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
                                               std::to_string(heights.corners.left) + ", " +
                                               std::to_string(heights.corners.top) + ", " +
                                               std::to_string(heights.corners.right) + ", " +
                                               std::to_string(heights.corners.bottom));

  // Relative x and y position on the base square of the grid-aligned tile
  unsigned int rel_x = (x + this->x) - (TILE_WIDTH * col);
  unsigned int rel_y = (y + this->y - top_offset) - ((TILE_HEIGHT / 2) * row);
  if (row % 2)
    rel_x -= HALF_TILE_W;

  float adj_rel_x;
  float edge_height;
  float bot_edge_height;
  // TODO fix the height. It should not be (bot + top)/2
  float height = 0;
  CellIndex adj_cell;

  if (xx % TILE_WIDTH >= HALF_TILE_W)
695
    {
696 697 698 699 700 701 702 703 704 705 706
      // RIGHT
      adj_rel_x = rel_x - HALF_TILE_W;

      edge_height = ::get_edge_height(adj_rel_x,
                                      heights.corners.top, heights.corners.right);
      bot_edge_height = ::get_edge_height(adj_rel_x,
                                          heights.corners.bottom, heights.corners.right);
      height = (edge_height + bot_edge_height) / 2;

      // Get the bottom-right cell (adj_cell) and its heights
      if (row % 2 == 0)
louiz’'s avatar
louiz’ committed
707
        adj_cell = col + (row + 1) * this->map().get_width_in_tiles();
708
      else
louiz’'s avatar
louiz’ committed
709 710
        adj_cell = col + 1 + (row + 1) * this->map().get_width_in_tiles();
      heights = this->map().get_cell_heights(adj_cell);
711 712 713 714 715 716 717 718 719 720 721 722 723

      edge_height = ::get_edge_height(adj_rel_x,
                                      heights.corners.left, heights.corners.top);
      bot_edge_height = ::get_edge_height(adj_rel_x,
                                          heights.corners.left, heights.corners.bottom);

      if ((edge_height * LAYER_HEIGHT) + adj_rel_x * TILE_HW_RATIO > (TILE_HEIGHT - rel_y))
        {
          selected_cell = adj_cell;
          height = (edge_height + bot_edge_height) / 2;
        }

      // Now do the “same” thing with the cell at the bottom
louiz’'s avatar
louiz’ committed
724 725
      adj_cell = col + (row + 2) * this->map().get_width_in_tiles();
      heights = this->map().get_cell_heights(adj_cell);
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749

      edge_height = ::get_edge_height(adj_rel_x,
                                       heights.corners.top, heights.corners.right);
      bot_edge_height = ::get_edge_height(adj_rel_x,
                                           heights.corners.bottom, heights.corners.right);

      if ((edge_height * LAYER_HEIGHT) - adj_rel_x * TILE_HW_RATIO > (TILE_HEIGHT - rel_y))
        {
          selected_cell = adj_cell;
          height = (edge_height + bot_edge_height) / 2;
        }
    }
  else
    {
      // LEFT
      adj_rel_x = static_cast<float>(rel_x);

      edge_height = ::get_edge_height(adj_rel_x,
                                      heights.corners.left, heights.corners.top);
      bot_edge_height = ::get_edge_height(adj_rel_x,
                                          heights.corners.left, heights.corners.bottom);
      height = (edge_height + bot_edge_height) / 2;

      if (row % 2 == 0)
louiz’'s avatar
louiz’ committed
750
          adj_cell = col - 1 + (row + 1) * this->map().get_width_in_tiles();
751
        else
louiz’'s avatar
louiz’ committed
752 753
          adj_cell = col + (row + 1) * this->map().get_width_in_tiles();
      heights = this->map().get_cell_heights(adj_cell);
754 755 756 757 758 759 760 761 762 763 764 765 766

      edge_height = ::get_edge_height(adj_rel_x,
                                      heights.corners.top, heights.corners.right);
      bot_edge_height = ::get_edge_height(adj_rel_x,
                                          heights.corners.bottom, heights.corners.right);

      if (edge_height * LAYER_HEIGHT + (HALF_TILE_W - adj_rel_x) * TILE_HW_RATIO > TILE_HEIGHT - rel_y)
        {
          selected_cell = adj_cell;
          height = (edge_height + bot_edge_height) / 2;
        }

      // Now do the “same” thing with the cell at the bottom
louiz’'s avatar
louiz’ committed
767 768
      adj_cell = col + (row + 2) * this->map().get_width_in_tiles();
      heights = this->map().get_cell_heights(adj_cell);
769 770 771 772 773 774 775

      edge_height = ::get_edge_height(adj_rel_x,
                                     heights.corners.left, heights.corners.top);
      bot_edge_height = ::get_edge_height(adj_rel_x,
                                     heights.corners.left, heights.corners.bottom);

      if ((edge_height * LAYER_HEIGHT) - (HALF_TILE_W - adj_rel_x) * TILE_HW_RATIO > (TILE_HEIGHT - rel_y))
776
        {
777 778
          selected_cell = adj_cell;
          height = (edge_height + bot_edge_height) / 2;
779 780
        }
    }
781 782

  res.y += height / TILE_HW_RATIO * static_cast<float>(LAYER_HEIGHT);
louiz’'s avatar
louiz’ committed
783
  this->game->get_debug_hud().add_debug_line("World position: " + std::to_string(res.x.to_double()) + ":" + std::to_string(res.y.to_double()));
784

785 786 787 788 789 790
  return res;
}

bool Camera::is_mouse_selection_ongoing() const
{
  return this->mouse_selection.ongoing;
louiz’'s avatar
louiz’ committed
791
}
792

793 794 795 796 797 798
const Entity* Camera::get_entity_under_mouse() const
{
  auto mouse_pos = this->get_mouse_position();
  for (auto it = this->sprites.crbegin(); it != this->sprites.crend(); ++it)
    {
      EntitySprite* sprite = it->get();
799
      if (this->is_mouse_over(sprite) == true)
800 801 802 803 804
        return sprite->get_entity();
    }
  return nullptr;
}

805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
bool Camera::is_mouse_over(const EntitySprite* sprite) const
{
  auto location = sprite->get_entity()->get<Location>();
  if (!location)
    return false;

  const auto pos = this->get_mouse_position();
  Position mouse_pos = this->camera_to_world_position(pos.x,
                                                        pos.y);
  Position ent_pos = location->position();

  // TODO, use different values depending on the sprite's size
  return (mouse_pos.x > ent_pos.x - 50 &&
          mouse_pos.x < ent_pos.x + 50 &&
          mouse_pos.y > ent_pos.y - 80 &&
          mouse_pos.y < ent_pos.y + 20);
}

823
void Camera::draw(const sf::Drawable& drawable, const sf::RenderStates& states)
824
{
825
  this->win().draw(drawable, states);
826 827
}

828 829
void Camera::draw_energy_bar(const EnergyBar& bar_specs, const std::size_t max_val,
                             int current_val, const sf::RenderStates& states)
830 831 832
{
  sf::RectangleShape rect;
  rect.setSize(bar_specs.size);
833
  rect.setOrigin(bar_specs.size.x/2, bar_specs.size.y/2);
834 835 836
  rect.setOutlineColor(sf::Color::Black);
  rect.setOutlineThickness(1);
  rect.setFillColor({25, 25, 25, 200});
837
  rect.setPosition(0, -70);
838

839
  this->draw(rect, states);
840

louiz’'s avatar
louiz’ committed
841
  rect.setOutlineThickness(1);
842 843 844
  float grad_width = bar_specs.size.x / (max_val / bar_specs.little_graduation);

  sf::Color color = mix(bar_specs.min_color, bar_specs.max_color,
845
                        0.3 + (static_cast<float>(current_val) / max_val) * 0.7);
846 847 848 849 850 851 852 853

  rect.setSize({grad_width, bar_specs.size.y});
  while (current_val > 0)
    {
      if (current_val >= bar_specs.little_graduation)
        rect.setFillColor(color);
      else
        rect.setFillColor(color * sf::Color(255, 255, 255, 100));
854 855
      this->draw(rect, states);
      rect.move(grad_width, 0);
856 857 858 859 860

      current_val -= bar_specs.little_graduation;
    }
}

louiz’'s avatar
louiz’ committed
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
void Camera::draw_vertical_bar(sf::Vector2f screen_position, const EnergyBar& bar_specs,
                               const std::size_t max_val, int current_val)
{
  sf::RectangleShape rect;
  rect.setSize(bar_specs.size);
  rect.setOutlineColor(sf::Color::Black);
  rect.setOutlineThickness(1);
  rect.setFillColor({25, 25, 25, 200});
  screen_position.x -= bar_specs.size.x/2;
  screen_position.y -= bar_specs.size.y/2;
  rect.setPosition(screen_position);

  float grad_width = bar_specs.size.x / (max_val / bar_specs.little_graduation);

  this->draw(rect);

  rect.setOutlineThickness(1);
  float grad_height = bar_specs.size.y / (max_val / bar_specs.little_graduation);

  sf::Color color = mix(bar_specs.min_color, bar_specs.max_color,
                        static_cast<float>(current_val) / max_val);

  rect.setSize({bar_specs.size.x, grad_height});
  while (current_val > 0)
    {
      if (current_val >= bar_specs.little_graduation)
        rect.setFillColor(color);
      else
        rect.setFillColor(color * sf::Color(255, 255, 255, 100));
      rect.setPosition(screen_position);
      this->draw(rect);

      current_val -= bar_specs.little_graduation;
      screen_position.y += grad_height;
    }
}

louiz’'s avatar
louiz’ committed
898
void Camera::on_new_entity(const Entity* entity)
899
{
louiz’'s avatar
louiz’ committed
900 901 902 903
  if (entity->get_type() == 0)
    this->sprites.push_back(std::make_unique<PicpicSprite>(entity));
  else if (entity->get_type() == 1)
    this->sprites.push_back(std::make_unique<BulletSprite>(entity));
louiz’'s avatar
louiz’ committed
904 905
  else if (entity->get_type() == 2)
    this->sprites.push_back(std::make_unique<EmpSprite>(entity));
louiz’'s avatar
louiz’ committed
906
  else if (entity->get_type() == 4)
907
    this->sprites.push_back(std::make_unique<OrangeBlob>(entity));
louiz’'s avatar
louiz’ committed
908

909 910
}

911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
void Camera::on_entity_deleted(const Entity* entity)
{
  // Look for an EntitySprite using this entity pointer, and remove it
  auto it = std::find_if(this->sprites.begin(),
                         this->sprites.end(),
                         [entity](const auto& s)
                         {
                           return s->get_entity() == entity;
                         });
  if (it != this->sprites.end())
    {
      log_debug("removing sprite.");
      this->sprites.erase(it);
    }
}

louiz’'s avatar
louiz’ committed
927 928 929 930 931 932 933 934 935 936 937 938 939
void Camera::on_entity_task_changed(const Entity* entity, const Task* task)
{
  // Look for an EntitySprite using this entity pointer
  auto it = std::find_if(this->sprites.begin(),
                         this->sprites.end(),
                         [entity](const auto& s)
                         {
                           return s->get_entity() == entity;
                         });
  assert(it != this->sprites.end());
  (*it)->set_task(task);
}

940 941
const sf::Vector2u Camera::get_win_size() const
{
louiz’'s avatar
louiz’ committed
942
  return this->win().getSize();
943
}
944 945 946

void Camera::graphical_tick()
{
947
  for (auto& sprite: this->sprites)
948
    sprite->tick();
949
  this->fog.invalidate();
950
}
951

952 953 954 955
const GameClient* Camera::get_game_client() const
{
  return this->game;
}
956 957 958 959 960

void Camera::add_effect(std::unique_ptr<Effect>&& effect)
{
  this->effects.push_back(std::move(effect));
}