//
// Created by trotFunky on 03/11/2019.
//

#include "MovementManager.h"

Vec3i current_map_colour(const Vec3d& world_pos, const Texture& texture, const int& pixel_scale)
{
    Vec2i map_pos{static_cast<int>(world_pos.x/pixel_scale),
                  static_cast<int>(world_pos.z/pixel_scale)};

    unsigned int data_index = (map_pos.x * texture.height + map_pos.y)*(texture.color_bits/8);

    return Vec3i{texture.image_data[data_index],
                 texture.image_data[data_index+1],
                 texture.image_data[data_index+2]};
}

void constrained_translation(const Vec3d& translation, Camera& camera, const Texture& map, const int& pixel_scale)
{
    Vec3d original_position = camera.get_eyepos();

    Vec3d forward_direction = camera.get_gaze();
    forward_direction.y = 0;
    forward_direction.normalize();

    // Forward and up movements are global, disconnects with viewing pitch.
    if (translation.x != 0 || translation.y != 0)
    {
        forward_direction = forward_direction * translation.x;
        forward_direction.y = translation.y;
        camera.translate(forward_direction);
    }

    // Strafing movement is relative local.
    if (translation.z != 0)
    {
        camera.local_translate({0,0,translation.z});
    }

    if  (current_map_colour(camera.get_eyepos(), map, pixel_scale) == Tiles::wall)
    {
        // If we are going into a wall, revert
        camera.set_position(original_position);
    }
}
