#pragma once

#ifdef SVQC
float tracebox_inverted (vector v1, vector mi, vector ma, vector v2, float nomonsters, entity forent, float stopatentity, entity ignorestopatentity); // returns the number of traces done, for benchmarking

void traceline_inverted (vector v1, vector v2, float nomonsters, entity forent, float stopatentity, entity ignorestopatentity);
#endif

#ifdef GAMEQC
#define CENTER_OF_ENT(ent) ((ent).origin + '0 0 0.5' * ((ent).mins.z + (ent).maxs.z))

/*
==================
findbetterlocation

Returns a point at least 12 units away from walls
(useful for explosion animations, although the blast is performed where it really happened)
Ripped from DPMod
==================
*/
vector findbetterlocation (vector org, float mindist);

vector real_origin(entity ent);
#endif

#ifdef SVQC
// temporary array used to dump settings for each weapon / turret
const int MAX_CONFIG_SETTINGS = 70;
string config_queue[MAX_CONFIG_SETTINGS];
#endif

.string netname;
.string message;

IntrusiveList g_saved_cvars;
STATIC_INIT(g_saved_cvars) { g_saved_cvars = IL_NEW(); }

// this returns a tempstring containing a copy of s with additional \n newlines added, it also replaces \n in the text with a real newline
// NOTE: s IS allowed to be a tempstring
string wordwrap(string s, float l);
#ifdef SVQC
void wordwrap_sprint(entity to, string s, float l);
#endif
void wordwrap_cb(string s, float l, void(string) callback);

#ifndef SVQC
string draw_currentSkin;
string draw_UseSkinFor(string pic);

string icon_path_from_HUDskin(string theIcon);
#ifdef MENUQC
string icon_path_from_menuskin(string theIcon);
#endif

// NOTE they aren't all registered mutators, e.g. jetpack, low gravity
// TODO add missing "mutators"
const int MUT_DODGING = 0;
const int MUT_INSTAGIB = 1;
const int MUT_NEW_TOYS = 2;
const int MUT_NIX = 3;
const int MUT_ROCKET_FLYING = 4;
const int MUT_INVINCIBLE_PROJECTILES = 5;
const int MUT_GRAVITY = 6;
const int MUT_CLOAKED = 7;
const int MUT_GRAPPLING_HOOK = 8;
const int MUT_MIDAIR = 9;
const int MUT_MELEE_ONLY = 10;
const int MUT_VAMPIRE = 11;
const int MUT_PINATA = 12;
const int MUT_WEAPON_STAY = 13;
const int MUT_BLOODLOSS = 14;
const int MUT_JETPACK = 15;
const int MUT_BUFFS = 16;
const int MUT_OVERKILL = 17;
const int MUT_NO_POWERUPS = 18;
const int MUT_POWERUPS = 19;
const int MUT_TOUCHEXPLODE = 20;
const int MUT_WALLJUMP = 21;
const int MUT_NO_START_WEAPONS = 22;
const int MUT_NADES = 23;
const int MUT_OFFHAND_BLASTER = 24;

const int MUT_MAX = 47;

int active_mutators[2];
bool mut_is_active(int mut);
string build_mutator_list(string s);
#endif

// iterative depth-first search, with fields that go "up", "down left" and "right" in a tree
// for each element, funcPre is called first, then funcPre and funcPost for all its children, and funcPost last
void depthfirst(entity start, .entity up, .entity downleft, .entity right, void(entity, entity) funcPre, void(entity, entity) funcPost, entity pass);

#define TIME_TO_NTHS(t,n) floor((t) * (n) + 0.5)

const int TIME_DECIMALS = 2;
const float TIME_FACTOR = 100;
#define TIME_ENCODED_TOSTRING(n, compact) mmssth(n, compact)
#define RACE_RECORD "/race100record/"
#define CTS_RECORD "/cts100record/"
#define CTF_RECORD "/ctf100record/"
#define TIME_ENCODE(t) TIME_TO_NTHS(t, TIME_FACTOR)
#define TIME_DECODE(n) ((n) / TIME_FACTOR)

#ifdef GAMEQC
string ScoreString(float vflags, float value, int rounds_played);
#endif

vector decompressShortVector(float data);
float compressShortVector(vector vec);

#ifdef GAMEQC
float CheckWireframeBox(entity forent, vector v0, vector dvx, vector dvy, vector dvz);
#endif

string fixPriorityList(string pl, float from, float to, float subtract, float complete);
string mapPriorityList(string order, string(string) mapfunc);
string swapInPriorityList(string order, float i, float j);

float cvar_settemp(string pKey, string pValue);
float cvar_settemp_restore();

#ifdef GAMEQC
// modes: 0 = trust q3map2 (_mini images)
//        1 = trust tracebox (_radar images)
// in both modes, mapinfo's "size" overrides

string mi_shortname;
vector mi_min;
vector mi_max;
void get_mi_min_max(float mode);

vector mi_picmin; // adjusted mins that map to the picture (square)
vector mi_picmax; // adjusted maxs that map to the picture (square)
vector mi_pictexcoord0; // texcoords of the image corners (after transforming, these are 2D coords too)
vector mi_pictexcoord1; // texcoords of the image corners (after transforming, these are 2D coords too)
vector mi_pictexcoord2; // texcoords of the image corners (after transforming, these are 2D coords too)
vector mi_pictexcoord3; // texcoords of the image corners (after transforming, these are 2D coords too)
void get_mi_min_max_texcoords(float mode);
#endif

USING(textLengthUpToWidth_widthFunction_t, float(string s, vector size));
USING(textLengthUpToLength_lenFunction_t, float(string s));
float textLengthUpToWidth(string theText, float maxWidth, vector size, textLengthUpToWidth_widthFunction_t tw);
string textShortenToWidth(string theText, float maxWidth, vector size, textLengthUpToWidth_widthFunction_t tw);
float textLengthUpToLength(string theText, int maxLength, textLengthUpToLength_lenFunction_t tw);
string textShortenToLength(string theText, int maxLength, textLengthUpToLength_lenFunction_t tw);

string getWrappedLine_remaining;
string getWrappedLine(float w, vector size, textLengthUpToWidth_widthFunction_t tw);
string getWrappedLineLen(float w, textLengthUpToLength_lenFunction_t tw);

// FIXME can't use Gametype gt because Gitlab compilation unit test fails
float isGametypeInFilter(entity gt, float tp, float ts, string pattern);

vector solve_shotdirection(vector myorg, vector myvel, vector eorg, vector evel, float spd, float newton_style);
vector get_shotvelocity(vector myvel, vector mydir, float spd, float newton_style, float mi, float ma);

float compressShotOrigin(vector v);
vector decompressShotOrigin(float f);

#ifdef SVQC
string rankings_reply, ladder_reply, lsmaps_reply, maplist_reply, monsterlist_reply; // cached replies
string records_reply[10];
#endif

#ifdef GAMEQC
vector healtharmor_maxdamage(float h, float a, float armorblock, int deathtype); // returns vector: maxdamage, armorideal, 1 if fully armored
vector healtharmor_applydamage(float h, float a, float armorblock, int deathtype, float damage); // returns vector: take, save, 0
#endif

string getcurrentmod();

float matchacl(string acl, string str); // matches str against ACL acl (with entries +foo*, +foo, +*foo, +*foo*, and same with - for forbidding)

void write_String_To_File(int fh, string str, bool alsoprint);

string get_model_datafilename(string mod, float skn, string fil); // skin -1 will return wildcard, mod string_null will also put wildcard there
string get_model_parameters_modelname;
float get_model_parameters_modelskin;
string get_model_parameters_name;
float get_model_parameters_species;
string get_model_parameters_sex;
float get_model_parameters_weight;
float get_model_parameters_age;
bool get_model_parameters_hidden;
string get_model_parameters_description;
string get_model_parameters_bone_upperbody;
string get_model_parameters_bone_weapon;
const int MAX_AIM_BONES = 4;
string get_model_parameters_bone_aim[MAX_AIM_BONES];
float get_model_parameters_bone_aimweight[MAX_AIM_BONES];
float get_model_parameters_fixbone;
string get_model_parameters_desc;
float get_model_parameters(string mod, float skn); // call with string_null to clear; skin -1 means mod is the filename of the txt file and is to be split

ERASEABLE
string translate_key(string key);

// x-encoding (encoding as zero length invisible string)
// encodes approx. 14 bits into 5 bytes of color code string
const float XENCODE_MAX = 21295; // 2*22*22*22-1
const float XENCODE_LEN = 5;
string xencode(float f);
float xdecode(string s);

#ifdef GAMEQC
string strtolower(string s);
#endif

// generic shutdown handler
void Shutdown();

#ifdef GAMEQC
.float skeleton_bones;
void Skeleton_SetBones(entity e);
// loops through the tags of model v using counter tagnum
#define FOR_EACH_TAG(v) float tagnum; Skeleton_SetBones(v); for(tagnum = 0; tagnum < v.skeleton_bones; tagnum++, gettaginfo(v, tagnum))
#endif

// execute-stuff-next-frame subsystem
void execute_next_frame();
void queue_to_execute_next_frame(string s);

USING(findNextEntityNearFunction_t, entity(entity cur, entity near, entity pass));
USING(isConnectedFunction_t, float(entity a, entity b, entity pass));
void FindConnectedComponent(entity e, .entity fld, findNextEntityNearFunction_t nxt, isConnectedFunction_t iscon, entity pass);

// expand multiple arguments into one argument by stripping parenthesis
#define XPD(...) __VA_ARGS__

// Some common varargs functions. Lowercase as they match C.
#define fprintf(file, ...) fputs(file, sprintf(__VA_ARGS__))
#define bprintf(...) bprint(sprintf(__VA_ARGS__))

#ifdef GAMEQC
	#ifdef CSQC
		bool autocvar_cl_gentle;
		int autocvar_cl_gentle_messages;
		#define GENTLE (autocvar_cl_gentle || autocvar_cl_gentle_messages)
	#else
		int autocvar_sv_gentle;
		#define GENTLE autocvar_sv_gentle
	#endif
	#define normal_or_gentle(normal, gentle) ((GENTLE && (gentle != "")) ? gentle : normal)
#endif

#ifdef GAMEQC
vector animfixfps(entity e, vector a, vector b);
#endif

#ifdef GAMEQC
const int CNT_NORMAL = 1;
const int CNT_GAMESTART = 2;
//const int CNT_IDLE = 3;
const int CNT_KILL = 4;
const int CNT_RESPAWN = 5;
const int CNT_ROUNDSTART = 6;
entity Announcer_PickNumber(int type, int num);
#endif

#ifdef GAMEQC
int Mod_Q1BSP_SuperContentsFromNativeContents(int nativecontents);
int Mod_Q1BSP_NativeContentsFromSuperContents(int supercontents);
#endif

#define APPEND_TO_STRING(list,sep,add) ((list) = (((list) != "") ? strcat(list, sep, add) : (add)))

// Returns the correct difference between two always increasing numbers
#define COMPARE_INCREASING(to,from) (to < from ? from + to + 2 : to - from)

#ifdef SVQC
void attach_sameorigin(entity e, entity to, string tag);
void detach_sameorigin(entity e);
void follow_sameorigin(entity e, entity to);

void SetMovetypeFollow(entity ent, entity e);
void UnsetMovetypeFollow(entity ent);
int LostMovetypeFollow(entity ent);
#endif

#ifdef GAMEQC
string playername(string thename, int teamid, bool team_colorize);

float trace_hits_box_1d(float end, float thmi, float thma);

float trace_hits_box(vector start, vector end, vector thmi, vector thma);

float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma);

float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma);
#endif

float cvar_or(string cv, float v);

float blink_synced(float base, float range, float freq, float start_time, int start_blink);

float blink(float base, float range, float freq);

string find_last_color_code(string s);
