/*
  Copyright (C) 1997-2026 Sam Lantinga <slouken@libsdl.org>

  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the authors be held liable for any damages
  arising from the use of this software.

  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely.
*/

#define SDL_MAIN_USE_CALLBACKS 1
#include <SDL3/SDL.h>
#include <SDL3/SDL_test.h>
#include <SDL3/SDL_main.h>

// The value, in nits, of scRGB 1.0
#define SCRGB_NITS 80.0f

#define WINDOW_WIDTH  640
#define WINDOW_HEIGHT 480

#define TEXT_START_X 6.0f
#define TEXT_START_Y 6.0f
#define TEXT_LINE_ADVANCE FONT_CHARACTER_SIZE * 2

static SDL_Window *window;
static SDL_Renderer *renderer;
static const char *renderer_name;
static const char *colorspace_names[] = {
       "sRGB",
       "linear",
       "HDR10"
};
static SDL_Colorspace colorspaces[] = {
       SDL_COLORSPACE_SRGB,
       SDL_COLORSPACE_SRGB_LINEAR,
       SDL_COLORSPACE_HDR10
};
static int colorspace_count = SDL_arraysize(colorspaces);
static int colorspace_index = 0;
static SDL_Colorspace colorspace = SDL_COLORSPACE_SRGB;
static const char *colorspace_name = "sRGB";
static int renderer_count = 0;
static int renderer_index = 0;
static float SDR_white_level = 1.0f;
static float HDR_headroom = 1.0f;

enum
{
    StageClearBackground,
    StageDrawBackground,
    StageTextureBackground,
    StageTargetBackground,
    StageBlendDrawing,
    StageBlendTexture,
    StageGradientDrawing,
    StageGradientTexture,
    StageHDR10Texture,
    StageCount
};
static int stage_index = StageClearBackground;

static void FreeRenderer(void)
{
    SDLTest_CleanupTextDrawing();
    SDL_DestroyRenderer(renderer);
    renderer = NULL;
}

static void UpdateHDRState(void)
{
    SDL_PropertiesID props;
    bool HDR_enabled;

    props = SDL_GetWindowProperties(window);
    HDR_enabled = SDL_GetBooleanProperty(props, SDL_PROP_WINDOW_HDR_ENABLED_BOOLEAN, false);

    SDL_Log("HDR %s", HDR_enabled ? "enabled" : "disabled");

    if (HDR_enabled) {
        props = SDL_GetRendererProperties(renderer);
        colorspace = SDL_GetNumberProperty(props, SDL_PROP_RENDERER_OUTPUT_COLORSPACE_NUMBER, SDL_COLORSPACE_SRGB);
        if (colorspace != SDL_COLORSPACE_SRGB_LINEAR &&
            colorspace != SDL_COLORSPACE_HDR10) {
            SDL_Log("Run with --colorspace linear to display HDR colors");
        }
        SDR_white_level = SDL_GetFloatProperty(props, SDL_PROP_RENDERER_SDR_WHITE_POINT_FLOAT, 1.0f);
        HDR_headroom = SDL_GetFloatProperty(props, SDL_PROP_RENDERER_HDR_HEADROOM_FLOAT, 1.0f);
        if (((SDR_white_level * SCRGB_NITS) * HDR_headroom) == 10000.0f) {
			// The system is advertising the PQ luminance range (10000 nits)
			// and tone mapping into the actual display capabilities.
			// Let's use a more reasonable range for the gradient test.
			HDR_headroom = 5.0f;
		}
    } else {
        SDR_white_level = 1.0f;
        HDR_headroom = 1.0f;
    }
}

static void CreateRenderer(void)
{
    SDL_PropertiesID props;

    props = SDL_CreateProperties();
    SDL_SetPointerProperty(props, SDL_PROP_RENDERER_CREATE_WINDOW_POINTER, window);
    SDL_SetStringProperty(props, SDL_PROP_RENDERER_CREATE_NAME_STRING, SDL_GetRenderDriver(renderer_index));
    SDL_SetNumberProperty(props, SDL_PROP_RENDERER_CREATE_OUTPUT_COLORSPACE_NUMBER, colorspace);
    renderer = SDL_CreateRendererWithProperties(props);
    SDL_DestroyProperties(props);
    if (!renderer) {
        SDL_Log("Couldn't create renderer: %s", SDL_GetError());
        return;
    }

    renderer_name = SDL_GetRendererName(renderer);
    SDL_Log("Created renderer %s", renderer_name);

    UpdateHDRState();
}

static void NextRenderer( void )
{
    if (renderer_count <= 0) {
        return;
    }

#ifdef CYCLE_COLORSPACES
    ++colorspace_index;
    if (colorspace_index == colorspace_count) {
        colorspace_index = 0;
    }
    colorspace = colorspaces[colorspace_index];
    colorspace_name = colorspace_names[colorspace_index];
#else
    ++renderer_index;
    if (renderer_index == renderer_count) {
        renderer_index = 0;
    }
#endif
    FreeRenderer();
    CreateRenderer();
}

static void PrevRenderer(void)
{
    if (renderer_count <= 0) {
        return;
    }

#ifdef CYCLE_COLORSPACES
    --colorspace_index;
    if (colorspace_index == -1) {
        colorspace_index += colorspace_count;
    }
    colorspace = colorspaces[colorspace_index];
    colorspace_name = colorspace_names[colorspace_index];
#else
    --renderer_index;
    if (renderer_index == -1) {
        renderer_index += renderer_count;
    }
#endif
    FreeRenderer();
    CreateRenderer();
}

static void NextStage(void)
{
    ++stage_index;
    if (stage_index == StageCount) {
        stage_index = 0;
    }
}

static void PrevStage(void)
{
    --stage_index;
    if (stage_index == -1) {
        stage_index += StageCount;
    }
}

static bool ReadPixel(int x, int y, SDL_Color *c)
{
    SDL_Surface *surface;
    SDL_Rect r;
    bool result = false;

    r.x = x;
    r.y = y;
    r.w = 1;
    r.h = 1;

    surface = SDL_RenderReadPixels(renderer, &r);
    if (surface) {
        /* Don't tonemap back to SDR, our source content was SDR */
        SDL_SetStringProperty(SDL_GetSurfaceProperties(surface), SDL_PROP_SURFACE_TONEMAP_OPERATOR_STRING, "*=1");

        if (SDL_ReadSurfacePixel(surface, 0, 0, &c->r, &c->g, &c->b, &c->a)) {
            result = true;
        } else {
            SDL_Log("Couldn't read pixel: %s", SDL_GetError());
        }
        SDL_DestroySurface(surface);
    } else {
        SDL_Log("Couldn't read back pixels: %s", SDL_GetError());
    }
    return result;
}

typedef enum
{
    TextAlignLeft,
    TextAlignRight,
    TextAlignCenter
} TextAlignment;

static void DrawAlignedText(float x, float y, TextAlignment align, const char *fmt, ...)
{
    char *text;

    va_list ap;
    va_start(ap, fmt);
    SDL_vasprintf(&text, fmt, ap);
    va_end(ap);

    size_t text_width = SDL_strlen(text) * SDL_DEBUG_TEXT_FONT_CHARACTER_SIZE;
    switch (align) {
    case TextAlignLeft:
        break;
    case TextAlignRight:
        x -= text_width;
        break;
    case TextAlignCenter:
        x -= text_width / 2.0f;
        break;
    }

    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDLTest_DrawString(renderer, x + 1.0f, y + 1.0f, text);
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDLTest_DrawString(renderer, x, y, text);
    SDL_free(text);
}

static void DrawText(float x, float y, const char *fmt, ...)
{
    char *text;

    va_list ap;
    va_start(ap, fmt);
    SDL_vasprintf(&text, fmt, ap);
    va_end(ap);

    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDLTest_DrawString(renderer, x + 1.0f, y + 1.0f, text);
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDLTest_DrawString(renderer, x, y, text);
    SDL_free(text);
}

static void RenderClearBackground(void)
{
    /* Draw a 50% gray background.
     * This will be darker when using sRGB colors and lighter using linear colors
     */
    SDL_SetRenderDrawColor(renderer, 128, 128, 128, 255);
    SDL_RenderClear(renderer);

    /* Check the rendered pixels */
    SDL_Color c;
    if (!ReadPixel(0, 0, &c)) {
        return;
    }

    float x = TEXT_START_X;
    float y = TEXT_START_Y;
    DrawText(x, y, "%s %s", renderer_name, colorspace_name);
    y += TEXT_LINE_ADVANCE;
    DrawText(x, y, "Test: Clear 50%% Gray Background");
    y += TEXT_LINE_ADVANCE;
    DrawText(x, y, "Background color written: 0x808080, read: 0x%.2x%.2x%.2x", c.r, c.g, c.b);
    y += TEXT_LINE_ADVANCE;
    if (c.r != 128) {
        DrawText(x, y, "Incorrect background color, unknown reason");
        y += TEXT_LINE_ADVANCE;
    }
}

static void RenderDrawBackground(void)
{
    /* Draw a 50% gray background.
     * This will be darker when using sRGB colors and lighter using linear colors
     */
    SDL_SetRenderDrawColor(renderer, 128, 128, 128, 255);
    SDL_RenderFillRect(renderer, NULL);

    /* Check the rendered pixels */
    SDL_Color c;
    if (!ReadPixel(0, 0, &c)) {
        return;
    }

    float x = TEXT_START_X;
    float y = TEXT_START_Y;
    DrawText(x, y, "%s %s", renderer_name, colorspace_name);
    y += TEXT_LINE_ADVANCE;
    DrawText(x, y, "Test: Draw 50%% Gray Background");
    y += TEXT_LINE_ADVANCE;
    DrawText(x, y, "Background color written: 0x808080, read: 0x%.2x%.2x%.2x", c.r, c.g, c.b);
    y += TEXT_LINE_ADVANCE;
    if (c.r != 128) {
        DrawText(x, y, "Incorrect background color, unknown reason");
        y += TEXT_LINE_ADVANCE;
    }
}

static SDL_Texture *CreateGrayTexture(void)
{
    SDL_Texture *texture;
    Uint8 pixels[4];

    /* Floating point textures are in the linear colorspace by default */
    texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, 1, 1);
    if (!texture) {
        return NULL;
    }

    pixels[0] = 128;
    pixels[1] = 128;
    pixels[2] = 128;
    pixels[3] = 255;
    SDL_UpdateTexture(texture, NULL, pixels, sizeof(pixels));

    return texture;
}

static void RenderTextureBackground(void)
{
    /* Fill the background with a 50% gray texture.
     * This will be darker when using sRGB colors and lighter using linear colors
     */
    SDL_Texture *texture = CreateGrayTexture();
    SDL_RenderTexture(renderer, texture, NULL, NULL);
    SDL_DestroyTexture(texture);

    /* Check the rendered pixels */
    SDL_Color c;
    if (!ReadPixel(0, 0, &c)) {
        return;
    }

    float x = TEXT_START_X;
    float y = TEXT_START_Y;
    DrawText(x, y, "%s %s", renderer_name, colorspace_name);
    y += TEXT_LINE_ADVANCE;
    DrawText(x, y, "Test: Fill 50%% Gray Texture");
    y += TEXT_LINE_ADVANCE;
    DrawText(x, y, "Background color written: 0x808080, read: 0x%.2x%.2x%.2x", c.r, c.g, c.b);
    y += TEXT_LINE_ADVANCE;
    if (c.r != 128) {
        DrawText(x, y, "Incorrect background color, unknown reason");
        y += TEXT_LINE_ADVANCE;
    }
}

static void RenderTargetBackground(void)
{
    /* Fill the background with a 50% gray texture.
     * This will be darker when using sRGB colors and lighter using linear colors
     */
    SDL_Texture *target = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_TARGET, 1, 1);
    SDL_Texture *texture = CreateGrayTexture();

    /* Fill the render target with the gray texture */
    SDL_SetRenderTarget(renderer, target);
    SDL_RenderTexture(renderer, texture, NULL, NULL);
    SDL_DestroyTexture(texture);

    /* Fill the output with the render target */
    SDL_SetRenderTarget(renderer, NULL);
    SDL_RenderTexture(renderer, target, NULL, NULL);
    SDL_DestroyTexture(target);

    /* Check the rendered pixels */
    SDL_Color c;
    if (!ReadPixel(0, 0, &c)) {
        return;
    }

    float x = TEXT_START_X;
    float y = TEXT_START_Y;
    DrawText(x, y, "%s %s", renderer_name, colorspace_name);
    y += TEXT_LINE_ADVANCE;
    DrawText(x, y, "Test: Fill 50%% Gray Render Target");
    y += TEXT_LINE_ADVANCE;
    DrawText(x, y, "Background color written: 0x808080, read: 0x%.2x%.2x%.2x", c.r, c.g, c.b);
    y += TEXT_LINE_ADVANCE;
    if (c.r != 128) {
        DrawText(x, y, "Incorrect background color, unknown reason");
        y += TEXT_LINE_ADVANCE;
    }
}

static void RenderBlendDrawing(void)
{
    SDL_Color a = { 238, 70, 166, 255 }; /* red square */
    SDL_Color b = { 147, 255, 0, 255 };  /* green square */
    SDL_FRect rect;

    /* Draw a green square blended over a red square
     * This will have different effects based on whether sRGB colorspaces and sRGB vs linear blending is used.
     */
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderClear(renderer);
    rect.x = WINDOW_WIDTH / 3;
    rect.y = 0;
    rect.w = WINDOW_WIDTH / 3;
    rect.h = WINDOW_HEIGHT;
    SDL_SetRenderDrawColor(renderer, a.r, a.g, a.b, a.a);
    SDL_RenderFillRect(renderer, &rect);

    rect.x = 0;
    rect.y = WINDOW_HEIGHT / 3;
    rect.w = WINDOW_WIDTH;
    rect.h = WINDOW_HEIGHT / 6;
    SDL_SetRenderDrawColor(renderer, b.r, b.g, b.b, b.a);
    SDL_RenderFillRect(renderer, &rect);
    SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
    SDL_SetRenderDrawColor(renderer, b.r, b.g, b.b, 128);
    rect.y += WINDOW_HEIGHT / 6;
    SDL_RenderFillRect(renderer, &rect);

    SDL_Color ar, br, cr;
    if (!ReadPixel(WINDOW_WIDTH / 2, 0, &ar) ||
        !ReadPixel(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 3, &br) ||
        !ReadPixel(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, &cr)) {
        return;
    }

    float x = TEXT_START_X;
    float y = TEXT_START_Y;
    DrawText(x, y, "%s %s", renderer_name, colorspace_name);
    y += TEXT_LINE_ADVANCE;
    DrawText(x, y, "Test: Draw Blending");
    y += TEXT_LINE_ADVANCE;
    if ((cr.r == 199 && cr.g == 193 && cr.b == 121) ||
        (cr.r == 199 && cr.g == 193 && cr.b == 120)) {
        DrawText(x, y, "Correct blend color, blending in linear space");
    } else if ((cr.r == 192 && cr.g == 163 && cr.b == 83) ||
               (cr.r == 191 && cr.g == 162 && cr.b == 82)) {
        DrawText(x, y, "Correct blend color, blending in sRGB space");
    } else if ((cr.r == 214 && cr.g == 156 && cr.b == 113) ||
               (cr.r == 214 && cr.g == 155 && cr.b == 113) ||
               (cr.r == 215 && cr.g == 155 && cr.b == 113) ||
               (cr.r == 215 && cr.g == 154 && cr.b == 112)) {
        DrawText(x, y, "Correct blend color, blending in PQ space");
    } else {
        DrawText(x, y, "Incorrect blend color (%d,%d,%d), unknown reason", cr.r, cr.g, cr.b);
    }
    y += TEXT_LINE_ADVANCE;
}

static void RenderBlendTexture(void)
{
    SDL_Color color_a = { 238, 70, 166, 255 }; /* red square */
    SDL_Color color_b = { 147, 255, 0, 255 };  /* green square */
    SDL_Texture *a;
    SDL_Texture *b;
    SDL_FRect rect;

    /* Draw a green square blended over a red square
     * This will have different effects based on whether sRGB colorspaces and sRGB vs linear blending is used.
     */
    a = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, 1, 1);
    SDL_UpdateTexture(a, NULL, &color_a, sizeof(color_a));
    b = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, 1, 1);
    SDL_UpdateTexture(b, NULL, &color_b, sizeof(color_b));

    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderClear(renderer);
    rect.x = WINDOW_WIDTH / 3;
    rect.y = 0;
    rect.w = WINDOW_WIDTH / 3;
    rect.h = WINDOW_HEIGHT;
    SDL_RenderTexture(renderer, a, NULL, &rect);

    rect.x = 0;
    rect.y = WINDOW_HEIGHT / 3;
    rect.w = WINDOW_WIDTH;
    rect.h = WINDOW_HEIGHT / 6;
    SDL_RenderTexture(renderer, b, NULL, &rect);
    rect.y += WINDOW_HEIGHT / 6;
    SDL_SetTextureBlendMode(b, SDL_BLENDMODE_BLEND);
    SDL_SetTextureAlphaModFloat(b, 128 / 255.0f);
    SDL_RenderTexture(renderer, b, NULL, &rect);

    SDL_Color ar, br, cr;
    if (!ReadPixel(WINDOW_WIDTH / 2, 0, &ar) ||
        !ReadPixel(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 3, &br) ||
        !ReadPixel(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, &cr)) {
        return;
    }

    float x = TEXT_START_X;
    float y = TEXT_START_Y;
    DrawText(x, y, "%s %s", renderer_name, colorspace_name);
    y += TEXT_LINE_ADVANCE;
    DrawText(x, y, "Test: Texture Blending");
    y += TEXT_LINE_ADVANCE;
    if ((cr.r == 199 && cr.g == 193 && cr.b == 121) ||
        (cr.r == 199 && cr.g == 193 && cr.b == 120)) {
        DrawText(x, y, "Correct blend color, blending in linear space");
    } else if ((cr.r == 192 && cr.g == 163 && cr.b == 83) ||
               (cr.r == 191 && cr.g == 162 && cr.b == 82)) {
        DrawText(x, y, "Correct blend color, blending in sRGB space");
    } else if ((cr.r == 214 && cr.g == 156 && cr.b == 113) ||
               (cr.r == 214 && cr.g == 155 && cr.b == 113) ||
               (cr.r == 215 && cr.g == 155 && cr.b == 113) ||
               (cr.r == 215 && cr.g == 154 && cr.b == 112)) {
        DrawText(x, y, "Correct blend color, blending in PQ space");
    } else {
        DrawText(x, y, "Incorrect blend color (%d,%d,%d), unknown reason", cr.r, cr.g, cr.b);
    }
    y += TEXT_LINE_ADVANCE;

    SDL_DestroyTexture(a);
    SDL_DestroyTexture(b);
}

static void DrawGradient(float x, float y, float width, float height, float start, float end)
{
    float xy[8];
    const int xy_stride = 2 * sizeof(float);
    SDL_FColor color[4];
    const int color_stride = sizeof(SDL_FColor);
    const int num_vertices = 4;
    const int indices[6] = { 0, 1, 2, 0, 2, 3 };
    const int num_indices = 6;
    const int size_indices = 4;
    float minx, miny, maxx, maxy;
    SDL_FColor min_color = { start, start, start, 1.0f };
    SDL_FColor max_color = { end, end, end, 1.0f };

    minx = x;
    miny = y;
    maxx = minx + width;
    maxy = miny + height;

    xy[0] = minx;
    xy[1] = miny;
    xy[2] = maxx;
    xy[3] = miny;
    xy[4] = maxx;
    xy[5] = maxy;
    xy[6] = minx;
    xy[7] = maxy;

    color[0] = min_color;
    color[1] = max_color;
    color[2] = max_color;
    color[3] = min_color;

    SDL_RenderGeometryRaw(renderer, NULL, xy, xy_stride, color, color_stride, NULL, 0, num_vertices, indices, num_indices, size_indices);
}

static void RenderGradientDrawing(void)
{
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderClear(renderer);

    float x = TEXT_START_X;
    float y = TEXT_START_Y;
    DrawText(x, y, "%s %s", renderer_name, colorspace_name);
    y += TEXT_LINE_ADVANCE;
    DrawText(x, y, "Test: Draw SDR and HDR gradients");
    y += TEXT_LINE_ADVANCE;

    y += TEXT_LINE_ADVANCE;

    DrawText(x, y, "SDR gradient");
    y += TEXT_LINE_ADVANCE;
    DrawGradient(x, y, WINDOW_WIDTH - 2 * x, 64.0f, 0.0f, 1.0f);
    y += 64.0f;

    y += TEXT_LINE_ADVANCE;
    y += TEXT_LINE_ADVANCE;

    if (HDR_headroom > 1.0f) {
        DrawText(x, y, "HDR gradient");
    } else {
        DrawText(x, y, "No HDR headroom, HDR and SDR gradient are the same");
    }
    y += TEXT_LINE_ADVANCE;
    /* Drawing is in the sRGB colorspace, so we need to use the color scale, which is applied in linear space, to get into high dynamic range */
    SDL_SetRenderColorScale(renderer, HDR_headroom);
    DrawGradient(x, y, WINDOW_WIDTH - 2 * x, 64.0f, 0.0f, 1.0f);
    SDL_SetRenderColorScale(renderer, 1.0f);
    y += 64.0f;
}

static SDL_Texture *CreateGradientTexture(int width, float start, float end)
{
    SDL_Texture *texture;
    float *pixels;

    /* Floating point textures are in the linear colorspace by default */
    texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA128_FLOAT, SDL_TEXTUREACCESS_STATIC, width, 1);
    if (!texture) {
        return NULL;
    }

    pixels = (float *)SDL_malloc(width * sizeof(float) * 4);
    if (pixels) {
        int i;
        float length = (end - start);

        for (i = 0; i < width; ++i) {
            float v = (start + (length * i) / width);
            pixels[i * 4 + 0] = v;
            pixels[i * 4 + 1] = v;
            pixels[i * 4 + 2] = v;
            pixels[i * 4 + 3] = 1.0f;
        }
        SDL_UpdateTexture(texture, NULL, pixels, width * sizeof(float) * 4);
        SDL_free(pixels);
    }
    return texture;
}

static void DrawGradientTexture(float x, float y, float width, float height, float start, float end)
{
    SDL_FRect rect = { x, y, width, height };
    SDL_Texture *texture = CreateGradientTexture((int)width, start, end);
    SDL_RenderTexture(renderer, texture, NULL, &rect);
    SDL_DestroyTexture(texture);
}

static void RenderGradientTexture(void)
{
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderClear(renderer);

    float x = TEXT_START_X;
    float y = TEXT_START_Y;
    DrawText(x, y, "%s %s", renderer_name, colorspace_name);
    y += TEXT_LINE_ADVANCE;
    DrawText(x, y, "Test: Texture SDR and HDR gradients");
    y += TEXT_LINE_ADVANCE;

    y += TEXT_LINE_ADVANCE;

    DrawText(x, y, "SDR gradient");
    y += TEXT_LINE_ADVANCE;
    DrawGradientTexture(x, y, WINDOW_WIDTH - 2 * x, 64.0f, 0.0f, 1.0f);
    y += 64.0f;

    y += TEXT_LINE_ADVANCE;
    y += TEXT_LINE_ADVANCE;

    if (HDR_headroom > 1.0f) {
        DrawText(x, y, "HDR gradient");
    } else {
        DrawText(x, y, "No HDR headroom, HDR and SDR gradient are the same");
    }
    y += TEXT_LINE_ADVANCE;
    /* The gradient texture is in the linear colorspace, so we can use the HDR_headroom value directly */
    DrawGradientTexture(x, y, WINDOW_WIDTH - 2 * x, 64.0f, 0.0f, HDR_headroom);
    y += 64.0f;
}

float PQfromNits(float v)
{
    const float c1 = 0.8359375f;
    const float c2 = 18.8515625f;
    const float c3 = 18.6875f;
    const float m1 = 0.1593017578125f;
    const float m2 = 78.84375f;

    float y = SDL_clamp(v / 10000.0f, 0.0f, 1.0f);
    float num = c1 + c2 * SDL_powf(y, m1);
    float den = 1.0f + c3 * SDL_powf(y, m1);
    return SDL_powf(num / den, m2);
}

static SDL_Texture *CreateHDR10Texture(int width, float max_nits)
{
    SDL_Texture *texture;
    Uint32 *pixels;

    /* ABGR2101010 textures are in the HDR10 colorspace by default */
    SDL_PropertiesID props = SDL_CreateProperties();
    SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, SDL_PIXELFORMAT_ABGR2101010);
    SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_ACCESS_NUMBER, SDL_TEXTUREACCESS_STATIC);
    SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER, width);
    SDL_SetNumberProperty(props, SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER, 1);
    // The white point for HDR10 textures is the SDR white level in nits
    if (SDR_white_level > 1.0f) {
        // We'll match the current display SDR white level so we don't get any scaling here
        SDL_SetFloatProperty(props, SDL_PROP_TEXTURE_CREATE_SDR_WHITE_POINT_FLOAT, SDR_white_level * SCRGB_NITS);
    } else {
        // ITU-R BT.2408-6 recommends using an SDR white point of 203 nits.
        SDL_SetFloatProperty(props, SDL_PROP_TEXTURE_CREATE_SDR_WHITE_POINT_FLOAT, 203.0f);
    }
    texture = SDL_CreateTextureWithProperties(renderer, props);
    SDL_DestroyProperties(props);
    if (!texture) {
        return NULL;
    }

    pixels = (Uint32 *)SDL_malloc(width * sizeof(Uint32));
    if (pixels) {
        int i;

        for (i = 0; i < width; ++i) {
            float nits = (max_nits * i) / width;
            Uint32 v = (Uint32)SDL_roundf(PQfromNits(nits) * 1023.0f);
            pixels[i] = 0xC0000000 | (v << 20) | (v << 10) | v;
        }
        SDL_UpdateTexture(texture, NULL, pixels, width * sizeof(Uint32));
        SDL_free(pixels);
    }
    return texture;
}

static void DrawHDR10Texture(float x, float y, float width, float height, float max_nits)
{
    SDL_FRect rect = { x, y, width, height };
    SDL_Texture *texture = CreateHDR10Texture((int)width, max_nits);
    SDL_RenderTexture(renderer, texture, NULL, &rect);
    SDL_DestroyTexture(texture);
}

static void RenderHDR10Texture(void)
{
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderClear(renderer);

    float x = TEXT_START_X;
    float y = TEXT_START_Y;
    DrawText(x, y, "%s %s", renderer_name, colorspace_name);
    y += TEXT_LINE_ADVANCE;
    DrawText(x, y, "Test: Texture HDR10 ramp");
    y += TEXT_LINE_ADVANCE;
    y += TEXT_LINE_ADVANCE;

    DrawText(x, y, "HDR10");
    y += TEXT_LINE_ADVANCE;

    /* The gradient texture is in the linear colorspace, so we can use the HDR_headroom value directly */
    const float max_nits = 1000.0f;
    float gradient_width = WINDOW_WIDTH - 2 * x;
    DrawHDR10Texture(x, y, gradient_width, 64.0f, max_nits);
    y += 64.0f;
    y += 4.0f;
    DrawAlignedText(x, y, TextAlignLeft, "Nits:");
    DrawAlignedText(x + gradient_width / 4, y, TextAlignCenter, "%g", max_nits / 4);
    DrawAlignedText(x + gradient_width / 2, y, TextAlignCenter, "%g", max_nits / 2);
    DrawAlignedText(x + gradient_width * 400 / max_nits, y, TextAlignCenter, "400");
    DrawAlignedText(x + gradient_width * 3 / 4, y, TextAlignCenter, "%g", max_nits * 3 / 4);
    DrawAlignedText(x + gradient_width, y, TextAlignRight, "%g", max_nits);
}

SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event)
{
    /* Check for events */
    if (event->type == SDL_EVENT_KEY_DOWN) {
        switch (event->key.key) {
        case SDLK_ESCAPE:
            return SDL_APP_SUCCESS;
        case SDLK_SPACE:
        case SDLK_RIGHT:
            NextStage();
            break;
        case SDLK_LEFT:
            PrevStage();
            break;
        case SDLK_DOWN:
            NextRenderer();
            break;
        case SDLK_UP:
            PrevRenderer();
            break;
        default:
            break;
        }
    } else if (event->type == SDL_EVENT_WINDOW_HDR_STATE_CHANGED) {
        UpdateHDRState();
    } else if (event->type == SDL_EVENT_QUIT) {
        return SDL_APP_SUCCESS;
    }
    return SDL_APP_CONTINUE;
}

SDL_AppResult SDL_AppIterate(void *appstate)
{
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderClear(renderer);

    switch (stage_index) {
    case StageClearBackground:
        RenderClearBackground();
        break;
    case StageDrawBackground:
        RenderDrawBackground();
        break;
    case StageTextureBackground:
        RenderTextureBackground();
        break;
    case StageTargetBackground:
        RenderTargetBackground();
        break;
    case StageBlendDrawing:
        RenderBlendDrawing();
        break;
    case StageBlendTexture:
        RenderBlendTexture();
        break;
    case StageGradientDrawing:
        RenderGradientDrawing();
        break;
    case StageGradientTexture:
        RenderGradientTexture();
        break;
    case StageHDR10Texture:
        RenderHDR10Texture();
        break;
    }

    SDL_RenderPresent(renderer);
    SDL_Delay(100);

    return SDL_APP_CONTINUE;
}

static void LogUsage(const char *argv0)
{
    SDL_Log("Usage: %s [--renderer renderer] [--colorspace colorspace]", argv0);
}

SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[])
{
    int i;

    for (i = 1; i < argc; ++i) {
        if (SDL_strcmp(argv[i], "--renderer") == 0) {
            if (argv[i + 1]) {
                renderer_name = argv[i + 1];
                ++i;
            } else {
                LogUsage(argv[0]);
                return SDL_APP_FAILURE;
            }
        } else if (SDL_strcmp(argv[i], "--colorspace") == 0) {
            if (argv[i + 1]) {
                colorspace_name = argv[i + 1];
                colorspace = SDL_COLORSPACE_UNKNOWN;
                for (int j = 0; j < colorspace_count; ++j) {
                    if (SDL_strcasecmp(colorspace_name, colorspace_names[j]) == 0) {
                        colorspace_index = j;
                        colorspace = colorspaces[j];
                        break;
                    }
                }
                if (colorspace == SDL_COLORSPACE_UNKNOWN) {
                    SDL_Log("Unknown colorspace %s", argv[i + 1]);
                    return SDL_APP_FAILURE;
                }
                ++i;
            } else {
                LogUsage(argv[0]);
                return SDL_APP_FAILURE;
            }
        } else {
            LogUsage(argv[0]);
            return SDL_APP_FAILURE;
        }
    }

    window = SDL_CreateWindow("SDL colorspace test", WINDOW_WIDTH, WINDOW_HEIGHT, 0);
    if (!window) {
        SDL_Log("Couldn't create window: %s", SDL_GetError());
        return SDL_APP_FAILURE;
    }

    renderer_count = SDL_GetNumRenderDrivers();
    SDL_Log("There are %d render drivers:", renderer_count);
    for (i = 0; i < renderer_count; ++i) {
        const char *name = SDL_GetRenderDriver(i);

        if (renderer_name && SDL_strcasecmp(renderer_name, name) == 0) {
            renderer_index = i;
        }
        SDL_Log("    %s", name);
    }
    CreateRenderer();

    return SDL_APP_CONTINUE;
}

void SDL_AppQuit(void *appstate, SDL_AppResult result)
{
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
}
