/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include rect,render_task,gpu_cache,transform

#ifdef WR_VERTEX_SHADER

PER_INSTANCE in vec4 aClipDeviceArea;
PER_INSTANCE in vec4 aClipOrigins;
PER_INSTANCE in float aDevicePixelScale;
PER_INSTANCE in ivec2 aTransformIds;

struct ClipMaskInstanceCommon {
    RectWithEndpoint sub_rect;
    vec2 task_origin;
    vec2 screen_origin;
    float device_pixel_scale;
    int clip_transform_id;
    int prim_transform_id;
};

ClipMaskInstanceCommon fetch_clip_item_common() {
    ClipMaskInstanceCommon cmi;

    cmi.sub_rect = RectWithEndpoint(aClipDeviceArea.xy, aClipDeviceArea.zw);
    cmi.task_origin = aClipOrigins.xy;
    cmi.screen_origin = aClipOrigins.zw;
    cmi.device_pixel_scale = aDevicePixelScale;
    cmi.clip_transform_id = aTransformIds.x;
    cmi.prim_transform_id = aTransformIds.y;

    return cmi;
}

struct ClipVertexInfo {
    vec4 local_pos;
    RectWithEndpoint clipped_local_rect;
};

// The transformed vertex function that always covers the whole clip area,
// which is the intersection of all clip instances of a given primitive
ClipVertexInfo write_clip_tile_vertex(RectWithEndpoint local_clip_rect,
                                      Transform prim_transform,
                                      Transform clip_transform,
                                      RectWithEndpoint sub_rect,
                                      vec2 task_origin,
                                      vec2 screen_origin,
                                      float device_pixel_scale) {
    vec2 device_pos = screen_origin + mix(sub_rect.p0, sub_rect.p1, aPosition.xy);
    vec2 world_pos = device_pos / device_pixel_scale;

    vec4 pos = prim_transform.m * vec4(world_pos, 0.0, 1.0);
    pos.xyz /= pos.w;

    vec4 p = get_node_pos(pos.xy, clip_transform);
    vec4 local_pos = p * pos.w;

    //TODO: Interpolate in clip space, where "local_pos.w" contains
    // the W of the homogeneous transform *from* clip space into the world.
    //    float interpolate_w = 1.0 / local_pos.w;
    // This is problematic today, because the W<=0 hemisphere is going to be
    // clipped, while we currently want this shader to fill out the whole rect.
    // We can therefore simplify this when the clip construction is rewritten
    // to only affect the areas touched by a clip.
    vec4 vertex_pos = vec4(
        task_origin + mix(sub_rect.p0, sub_rect.p1, aPosition.xy),
        0.0,
        1.0
    );

    gl_Position = uTransform * vertex_pos;

    rectangle_aa_vertex(vec4(local_clip_rect.p0, local_clip_rect.p1));

    ClipVertexInfo vi = ClipVertexInfo(local_pos, local_clip_rect);
    return vi;
}

#endif //WR_VERTEX_SHADER
