// Makes the saved games the Machine ships with: each one drops the player close to one of the
// game's big fights, facing it, armed for it. Added to the engine by tools/doom/build.py, so the
// saves come out of the very engine that loads them (saved games are tied to the engine's build).
//
// Used once, by tools/doom/saves.py, never by visitors. With none of its options given it does
// nothing. The options:
//
//   -warp NN -skill S                  the map and skill, as usual
//   -bosssave SLOT TYPE DIST "NAME"    find the thing whose editor number is TYPE (16 the
//                                      Cyberdemon, 7 the Spider Mastermind, 88 the boss brain),
//                                      stand the player about DIST units from it where it can be
//                                      seen, face it, arm the player (every weapon, a backpack
//                                      and full ammunition, all keys, 200 health, 200 armour),
//                                      save into SLOT as NAME, quit
//   -bossnth N                         use the Nth such thing on the map (from 0), not the first
//   -bossat X Y                        stand here instead of searching for a place
//   -bossto X Y                        first move the boss here: for a boss that waits in a sealed
//                                      closet until it teleports into its arena, this is where it
//                                      would arrive (the teleport destination its closet leads to)
//   -bossopen X Y                      open the door (or lift) whose sector holds this point, for
//                                      good, so the player sees into a closed arena
//   -bossgrace T                       no monster fires a missile until it has taken T steps
//                                      after loading (default 35; a step is 2 to 4 tics, so about
//                                      three seconds), so the player can get their bearings. It is
//                                      the monsters' own reactiontime, which is saved with them
//   -bossface X Y                      face this point rather than the boss (for two bosses)
//   -bossloose                         skip the first round of placing (a straight walk to the
//                                      boss): for arenas of terraces and lifts
//   -bossweapon W                      the weapon in hand (4 rockets, 5 plasma, 6 BFG; default 4)
//   -bosscheck TYPE                    after -loadgame: report how many such things are on the
//                                      map, how far the nearest is, and whether the player can
//                                      see it, then quit
//   -bosswait T                        with -bosscheck: first let the game run T tics (35 a
//                                      second) with the player standing still, to see whether a
//                                      save throws the player into a fight that cannot be survived
//
// Placing: it tries points on rings round the boss, nearest the way the boss faces first. A point
// passes the first round when the player fits there, the floor does it no harm, and a straight
// walk to the boss crosses no wall or ledge; failing that, the second round asks only that the
// boss can be seen from there.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include "doomdef.h"
#include "doomstat.h"
#include "d_player.h"
#include "g_game.h"
#include "i_system.h"
#include "info.h"
#include "m_argv.h"
#include "p_local.h"
#include "p_spec.h"
#include "r_main.h"
#include "r_state.h"
#include "tables.h"

static int stage = 0;
static int tics = 0;
static int from = -1, wait = 0; // -bosswait: when the check began, and how long it waits

void P_SetPsprite(player_t *player, int position, statenum_t stnum); // p_pspr.c
#define WEAPONTOP (32 * FRACUNIT) // as in p_pspr.c

/** The Nth thing on the map with this editor number, or NULL. */
static mobj_t *FindThing(int type, int nth)
{
    thinker_t *th;
    for (th = thinkercap.next; th != &thinkercap; th = th->next)
    {
        mobj_t *mo;
        if (th->function.acp1 != (actionf_p1) P_MobjThinker)
            continue;
        mo = (mobj_t *) th;
        if (mo->info->doomednum == type && mo->health > 0 && nth-- == 0)
            return mo;
    }
    return NULL;
}

static int CountThings(int type)
{
    thinker_t *th;
    int n = 0;
    for (th = thinkercap.next; th != &thinkercap; th = th->next)
        if (th->function.acp1 == (actionf_p1) P_MobjThinker && ((mobj_t *) th)->info->doomednum == type && ((mobj_t *) th)->health > 0)
            n++;
    return n;
}

/** Counts the living monsters within RANGE units of the boss, the boss included. */
static int Crowd(mobj_t *boss, int range)
{
    thinker_t *th;
    int n = 0;
    for (th = thinkercap.next; th != &thinkercap; th = th->next)
    {
        mobj_t *mo;
        if (th->function.acp1 != (actionf_p1) P_MobjThinker)
            continue;
        mo = (mobj_t *) th;
        if ((mo->flags & MF_COUNTKILL) && mo->health > 0 && P_AproxDistance(mo->x - boss->x, mo->y - boss->y) < range * FRACUNIT)
            n++;
    }
    return n;
}

static boolean Harmful(sector_t *s)
{
    int k = s->special & 31;
    return k == 4 || k == 5 || k == 7 || k == 11 || k == 16;
}

// A straight walk: no one-sided wall, no impassable line, no step taller than the player can
// climb, no gap too low to pass.
static boolean walkable;

static boolean PTR_Walk(intercept_t *in)
{
    line_t *li;
    if (!in->isaline)
        return true;
    li = in->d.line;
    if (!li->backsector || (li->flags & ML_BLOCKING))
    {
        walkable = false;
        return false;
    }
    P_LineOpening(li);
    if (openrange < 56 * FRACUNIT || abs(li->frontsector->floorheight - li->backsector->floorheight) > 24 * FRACUNIT)
    {
        walkable = false;
        return false;
    }
    return true;
}

static boolean Walkable(fixed_t x1, fixed_t y1, fixed_t x2, fixed_t y2)
{
    walkable = true;
    P_PathTraverse(x1, y1, x2, y2, PT_ADDLINES, PTR_Walk);
    return walkable;
}

// Why points were turned down, for the log: harmful or low, not level with the boss or no straight
// walk, the player does not fit, cannot be moved there, cannot see the boss.
static int refused[5];

/** Tries to stand the player at (x, y); true if the player fits there and can see the boss. */
static boolean TryAt(player_t *p, mobj_t *boss, fixed_t x, fixed_t y, boolean strict)
{
    mobj_t *mo = p->mo;
    sector_t *s = R_PointInSubsector(x, y)->sector;
    if (Harmful(s) || s->ceilingheight - s->floorheight < 64 * FRACUNIT)
        return refused[0]++, false;
    if (strict && (abs(s->floorheight - boss->subsector->sector->floorheight) > 48 * FRACUNIT || !Walkable(x, y, boss->x, boss->y)))
        return refused[1]++, false;
    if (!P_CheckPosition(mo, x, y))
        return refused[2]++, false;
    if (!P_TeleportMove(mo, x, y))
        return refused[3]++, false;
    mo->z = mo->floorz;
    if (!P_CheckSight(mo, boss))
        return refused[4]++, false;
    return true;
}

static boolean Place(player_t *p, mobj_t *boss, int dist)
{
    static const double scale[] = {1.0, 0.8, 1.25, 1.5, 0.6, 2.0};
    int pass, r, k;
    double face = boss->angle * (M_PI * 2 / 4294967296.0);
    for (pass = M_CheckParm("-bossloose") ? 1 : 0; pass < 2; pass++)
        for (r = 0; r < (int) (sizeof scale / sizeof *scale); r++)
            for (k = 0; k < 64; k++)
            {
                // 0, +1, -1, +2, -2, ... steps of a 64th of a turn away from the boss's facing.
                int step = (k + 1) / 2 * (k % 2 ? 1 : -1);
                double a = face + step * (M_PI * 2 / 64);
                fixed_t x = boss->x + (fixed_t) (cos(a) * dist * scale[r] * FRACUNIT);
                fixed_t y = boss->y + (fixed_t) (sin(a) * dist * scale[r] * FRACUNIT);
                if (TryAt(p, boss, x, y, pass == 0))
                {
                    printf("bosssave: placed on pass %d at %d %d, %d units from the boss\n", pass,
                           x >> FRACBITS, y >> FRACBITS, P_AproxDistance(x - boss->x, y - boss->y) >> FRACBITS);
                    return true;
                }
            }
    printf("bosssave: refused %d harmful or low, %d not level or walled, %d no fit, %d no move, %d no sight\n",
           refused[0], refused[1], refused[2], refused[3], refused[4]);
    return false;
}

static void Arm(player_t *p, int weapon)
{
    int i;
    p->health = p->mo->health = 200; // as a soulsphere gives
    p->armorpoints = 200;
    p->armortype = 2;
    if (!p->backpack)
    {
        for (i = 0; i < NUMAMMO; i++)
            p->maxammo[i] *= 2;
        p->backpack = true;
    }
    for (i = 0; i < NUMAMMO; i++)
        p->ammo[i] = p->maxammo[i];
    for (i = 0; i < NUMWEAPONS; i++)
        p->weaponowned[i] = true;
    for (i = 0; i < NUMCARDS; i++)
        p->cards[i] = true;
    p->readyweapon = weapon;
    p->pendingweapon = wp_nochange;
    P_SetPsprite(p, ps_weapon, weaponinfo[weapon].readystate);
    p->psprites[ps_weapon].sy = WEAPONTOP;
}

/** Holds every monster's fire for a while: they still wake and move. */
static void Grace(int tics)
{
    thinker_t *th;
    for (th = thinkercap.next; th != &thinkercap; th = th->next)
        if (th->function.acp1 == (actionf_p1) P_MobjThinker && (((mobj_t *) th)->flags & MF_COUNTKILL))
            ((mobj_t *) th)->reactiontime = tics;
}

static void Arg(int at, int *out)
{
    if (at > 0 && at + 1 < myargc)
        *out = atoi(myargv[at + 1]);
}

void BossSave_Ticker(void)
{
    int save = M_CheckParmWithArgs("-bosssave", 4);
    int check = M_CheckParmWithArgs("-bosscheck", 1);
    player_t *p = &players[consoleplayer];

    if ((!save && !check) || gamestate != GS_LEVEL || !p->mo)
        return;

    if (stage == 1)
    {
        // The save is written a tic or two after it is asked for; then the job is done.
        if (++tics > 8)
            I_Quit();
        return;
    }
    if (stage != 0 || leveltime < 2)
        return;

    if (check)
    {
        if (from < 0)
        {
            from = leveltime;
            Arg(M_CheckParmWithArgs("-bosswait", 1), &wait);
        }
        if (leveltime - from < wait && p->playerstate == PST_LIVE)
            return;
    }
    stage = 1;

    if (check)
    {
        int type = atoi(myargv[check + 1]);
        mobj_t *boss = FindThing(type, 0), *best = NULL;
        int i, d, nearest = 1 << 30, n = CountThings(type);
        for (i = 0; i < n; i++)
        {
            mobj_t *b = FindThing(type, i);
            d = P_AproxDistance(b->x - p->mo->x, b->y - p->mo->y) >> FRACBITS;
            if (d < nearest)
                nearest = d, best = b;
        }
        printf("bosscheck: map %d skill %d after %d tics, %d of type %d, nearest %d units, %s, health %d armour %d\n",
               gamemap, gameskill + 1, leveltime - from, n, type, boss ? nearest : -1,
               best && P_CheckSight(p->mo, best) ? "in sight" : "not in sight", p->health, p->armorpoints);
        I_Quit();
    }

    {
        int slot = atoi(myargv[save + 1]);
        int type = atoi(myargv[save + 2]);
        int dist = atoi(myargv[save + 3]);
        char *name = myargv[save + 4];
        int nth = 0, weapon = wp_missile, at = M_CheckParmWithArgs("-bossat", 2);
        mobj_t *boss;

        Arg(M_CheckParmWithArgs("-bossnth", 1), &nth);
        Arg(M_CheckParmWithArgs("-bossweapon", 1), &weapon);
        boss = FindThing(type, nth);
        if (!boss)
            I_Error("bosssave: no thing of type %d (number %d) on this map", type, nth);
        {
            int to = M_CheckParmWithArgs("-bossto", 2);
            if (to)
            {
                fixed_t x = atoi(myargv[to + 1]) * FRACUNIT, y = atoi(myargv[to + 2]) * FRACUNIT;
                if (!P_TeleportMove(boss, x, y))
                    I_Error("bosssave: cannot move the boss to %d %d", x >> FRACBITS, y >> FRACBITS);
                boss->z = boss->floorz;
            }
        }
        {
            int open = M_CheckParmWithArgs("-bossopen", 2);
            if (open)
            {
                sector_t *door = R_PointInSubsector(atoi(myargv[open + 1]) * FRACUNIT, atoi(myargv[open + 2]) * FRACUNIT)->sector;
                door->ceilingheight = P_FindLowestCeilingSurrounding(door) - 4 * FRACUNIT;
                printf("bosssave: opened sector %d\n", (int) (door - sectors));
            }
        }
        if (at)
        {
            fixed_t x = atoi(myargv[at + 1]) * FRACUNIT, y = atoi(myargv[at + 2]) * FRACUNIT;
            if (!P_TeleportMove(p->mo, x, y))
                I_Error("bosssave: cannot stand at %d %d", x >> FRACBITS, y >> FRACBITS);
            p->mo->z = p->mo->floorz;
            printf("bosssave: placed by hand at %d %d, %s\n", x >> FRACBITS, y >> FRACBITS,
                   P_CheckSight(p->mo, boss) ? "boss in sight" : "boss NOT in sight");
        }
        else if (!Place(p, boss, dist))
            I_Error("bosssave: found nowhere to stand near the boss");

        {
            int face = M_CheckParmWithArgs("-bossface", 2);
            p->mo->angle = face ? R_PointToAngle2(p->mo->x, p->mo->y, atoi(myargv[face + 1]) * FRACUNIT, atoi(myargv[face + 2]) * FRACUNIT)
                                : R_PointToAngle2(p->mo->x, p->mo->y, boss->x, boss->y);
        }
        p->mo->momx = p->mo->momy = p->mo->momz = 0;
        p->viewz = p->mo->z + p->viewheight;
        p->lookdir = 0;
        Arm(p, weapon);
        {
            int grace = 35;
            Arg(M_CheckParmWithArgs("-bossgrace", 1), &grace);
            Grace(grace);
        }
        printf("bosssave: boss at %d %d facing %d, %d monsters within 1024 units\n",
               boss->x >> FRACBITS, boss->y >> FRACBITS, (int) (boss->angle / ANG1), Crowd(boss, 1024));
        G_SaveGame(slot, name);
    }
}
