// Copyright (C) 2022 RozK
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#version 320 es
precision highp float;

#include "include/vertex_format.glsl"
#include "include/camera.glsl"
#include "include/common.glsl"

layout(location = 3) in vec3 i_translation; // per mesh, model space -> world space

void main(void) {
    vec4 world_position = vec4(i_translation + a_position, 1.0);
    vec2 terrain_coords = c_terrain_shift + world_position.xy * c_terrain_scale;
    world_position.z += texture(u_height_sampler, terrain_coords).r;
    vec4 view_position = u_view * world_position;
    vec3 terrain_normal = normalize(c_normal_shift + texture(u_normal_sampler, terrain_coords).rgb * c_normal_scale);
    vec3 world_normal = mat3(cross(c_world_forward, terrain_normal), c_world_forward, terrain_normal) * a_normal;
    v_position = view_position;
    v_normal = u_view * vec4(world_normal, 0.0);
    v_terrain_normal = vec4((u_view * vec4(terrain_normal, 0.0)).xyz, 1.0);
    v_texcoord = vec4(a_texcoord.st * c_st_scale, a_texcoord.p, a_texcoord.p + 1.0);
    gl_Position = u_projection * view_position;
}
