#include <stdint.h>
#include <stdio.h>

#include "coduo_engine_structs.h"
#include "animation/xanim_private.h"
#include "core_memory/core_memory_private.h"
#include "core_runtime/core_runtime_private.h"
#include "filesystem/fs_private.h"
#include "physics_collision/cm_world_sector_private.h"
#include "scripting/script_compile_private.h"
#include "scripting/script_memory_private.h"
#include "scripting/script_source_positions_private.h"
#include "server/sv_client_commands_private.h"

_Static_assert(sizeof(script_string_hash_slot_t) == 4,
               "script string hash slot size mismatch");

cvar_t *_host_cvar_sv_serverid_pointer_slot;
cvar_t *_host_cvar_sv_showloss_pointer_slot;
coduo_cmd_text_t cbuf_cmd_text;
coduo_cbuf_text_buffer_t cbuf_textBuffer;
int32_t cbuf_wait;
cvar_t *cl_running;
int32_t cm_floodValid;
worldSector_t *cm_freeWorldSectors;
worldSector_t cm_nullWorldSector;
int32_t cm_staticModelCount;
worldSectorAreaLink_t *cm_staticModels;
vec3_t cm_worldMaxs;
vec3_t cm_worldMins;
coduo_world_sector_pool_t cm_worldSectorPool;
worldSector_t cm_worldSectorRoot;
int32_t cmd_argc;
char cmd_args[CODUO_MAX_STRING_CHARS];
const char *cmd_argv[CODUO_CMD_MAX_ARGS];
cmd_function_t *cmd_functions;
coduo_cmd_token_buffer_t cmd_tokenBuffer;
coduo_sv_client_command_handler_table_t sv_clientCommandHandlers = {
    {"userinfo", SV_ClientCommand_Userinfo},
    {"disconnect", SV_ClientCommand_Disconnect},
    {"cp", SV_ClientCommand_Cp},
    {"vdr", SV_ClientCommand_Vdr},
    {"download", SV_ClientCommand_Download},
    {"nextdl", SV_ClientCommand_Nextdl},
    {"stopdl", SV_ClientCommand_Stopdl},
    {"donedl", SV_ClientCommand_Donedl},
    {"retransdl", SV_ClientCommand_Retransdl},
    {"wwwdl", SV_ClientCommand_Wwwdl},
    {NULL, NULL},
};
int32_t com_frameNumber;
cvar_t *com_journal;
int32_t com_logFileHandle;
qboolean com_printMessageOpeningLog;
int32_t com_timeBackend;
int32_t com_timeFrontend;
int32_t com_timeGame;
qboolean com_vprintfOpeningLog;
coduo_vm_t *currentVM;
int32_t dobjLastSearchSlot;
coduo_dobj_occupancy_table_t dobjOccupancy;
coduo_dobj_pool_t dobjPool;
qboolean dobjPoolInitialized;
coduo_dobj_primary_lookup_table_t dobjPrimaryLookup;
coduo_dobj_secondary_lookup_table_t dobjSecondaryLookup;
int32_t dobj_skelCacheKey;
cvar_t *fs_basegame;
cvar_t *fs_basepath;
cvar_t *fs_cdpath;
int32_t fs_checksumFeed;
cvar_t *fs_copyfiles;
char fs_currentGameDir[CODUO_FS_PACK_NAME_SIZE];
cvar_t *fs_debug;
fs_dir_file_list_t *fs_dir_file_lists;
int32_t fs_fakeChkSum;
cvar_t *fs_game;
char fs_gameDirVar[CODUO_FS_PACK_NAME_SIZE];
coduo_fs_handle_table_t fs_handleFiles;
cvar_t *fs_homepath;
cvar_t *fs_ignoreLozalized;
int fs_languageNameBufferIndex;
char fs_languageNameBuffers[CODUO_FS_LANGUAGE_NAME_BUFFER_COUNT]
                           [CODUO_FS_LANGUAGE_NAME_BUFFER_SIZE];
int fs_loadCount;
int fs_loadStack;
fs_dir_file_list_t *fs_lookup_dir_file_lists;
searchpath_t *fs_lookup_searchpaths;
int32_t fs_numServerReferencedPaks;
int32_t fs_numServerPaks;
uint32_t fs_packFiles;
cvar_t *fs_restrict;
char fs_savedBasepath[CODUO_FS_PACK_NAME_SIZE];
char fs_savedGame[CODUO_FS_PACK_NAME_SIZE];
searchpath_t *fs_searchpaths;
char fs_startupScratch[CODUO_FS_PACK_NAME_SIZE];
coduo_authorize_guid_cache_table_t host_authorizeGuidCache;
netadr_t host_authorizeServerAddress;
cvar_t *host_cvar_fs_basegame_pointer_slot;
cvar_t *host_cvar_g_gametype_pointer_slot;
cvar_t *host_cvar_mapname_pointer_slot;
cvar_t *host_cvar_rconPassword_pointer_slot;
cvar_t *host_cvar_scr_allow_jeeps_pointer_slot;
cvar_t *host_cvar_scr_allow_tanks_pointer_slot;
cvar_t *host_cvar_sv_allowAnonymous_pointer_slot;
cvar_t *host_cvar_sv_allowDownload_pointer_slot;
cvar_t *host_cvar_sv_disableClientConsole_pointer_slot;
cvar_t *host_cvar_sv_floodProtect_pointer_slot;
cvar_t *host_cvar_sv_fps_pointer_slot;
cvar_t *host_cvar_sv_hostname_pointer_slot;
cvar_t *host_cvar_sv_kickBanTime_pointer_slot;
cvar_t *host_cvar_sv_killserver_pointer_slot;
cvar_t *host_cvar_sv_mapRotationCurrent_pointer_slot;
cvar_t *host_cvar_sv_mapRotation_pointer_slot;
cvar_t *host_cvar_sv_maxPing_pointer_slot;
cvar_t *host_cvar_sv_maxRate_pointer_slot;
cvar_t *host_cvar_sv_maxclients_pointer_slot;
cvar_t *host_cvar_sv_minPing_pointer_slot;
cvar_t *host_cvar_sv_onlyVisibleClients_pointer_slot;
cvar_t *host_cvar_sv_packet_info_pointer_slot;
cvar_t *host_cvar_sv_padPackets_pointer_slot;
cvar_t *host_cvar_sv_privateClients_pointer_slot;
cvar_t *host_cvar_sv_privatePassword_pointer_slot;
cvar_t *host_cvar_sv_punkbuster_pointer_slot;
cvar_t *host_cvar_sv_pure_pointer_slot;
cvar_t *host_cvar_sv_reconnectlimit_pointer_slot;
cvar_t *host_cvar_sv_showAverageBPS_pointer_slot;
cvar_t *host_cvar_sv_showCommands_pointer_slot;
cvar_t *host_cvar_sv_timeout_pointer_slot;
cvar_t *host_cvar_sv_wwwBaseURL_pointer_slot;
cvar_t *host_cvar_sv_wwwDlDisconnected_pointer_slot;
cvar_t *host_cvar_sv_wwwDownload_pointer_slot;
cvar_t *host_cvar_sv_zombietime_pointer_slot;
cvar_t *host_cvar_sv_cracked_pointer_slot;
char *host_sv_configstrings[CODUO_MAX_CONFIGSTRINGS];
int32_t host_sv_frame_running_flag;
int32_t host_sv_rconThrottleTime;
int32_t host_sv_timeResidual;
coduo_challenge_table_t host_svs_challenges;
coduo_hunk_state_t hunk;
uint8_t *hunk_allocBase;
uint8_t *hunk_base;
coduo_hunk_log_block_t *hunk_logBlocks;
int32_t hunk_logFile;
size_t hunk_totalZoneSize;
cvar_t *net_lanauthorize;
loopback_table_t net_loopbacks;
cvar_t *net_profile;
coduo_net_profile_mode_t net_profileActiveMode;
const char *net_profileSocketNames[CODUO_NET_PROFILE_SOCKET_NAME_COUNT] = {
    "client", "server"};
cvar_t *net_qport;
cvar_t *net_showprofile;
uint32_t script_activeAnimTreeHandle;
int32_t script_animCheckEnabled;
int32_t script_animCommentDepth;
uint16_t script_animCurrentTreeRoot;
uint16_t script_animCurrentUsingTree;
const char *script_animParseStart;
char *script_animParseState;
const char *script_animPropertyNames[CODUO_SCRIPT_ANIM_PROPERTY_NAME_COUNT] = {
    "loopsync", "nonloopsync", "complete"};
uint32_t script_animTreeChecksum;
coduo_script_anim_tree_count_table_t script_animTreeCounts;
coduo_script_anim_tree_handle_table_t script_animTreeHandles;
uint16_t script_animTreeRoot;
coduo_script_anim_tree_table_t script_animTrees;
uint8_t script_breakAllowed;
uint8_t script_breakAllowedInDeveloperBlock;
script_code_offset_patch_t *script_breakPatchList;
coduo_script_call_stack_codepos_t script_callStackCodepos;
uint32_t script_callStackDepth;
uint8_t script_caseAllowed;
uint8_t script_caseAllowedInDeveloperBlock;
script_switch_case_record_t *script_caseRecordList;
uint16_t script_classMapRoot;
uint8_t *script_codeBase;
uint32_t script_codeChecksum;
uint8_t *script_codeEmitCursor;
uint8_t *script_codeEnd;
uint8_t *script_codeLastOpcodePos;
int32_t script_codeMaxLocalDepth;
int32_t script_codeMaxStackDepth;
uint8_t script_codeNeedsDeferredCheck;
uint8_t script_codeOwnsStrings;
uint8_t *script_codeRelocationEnd;
uint8_t *script_codeRelocationStart;
size_t script_codeSize;
int32_t script_codeStackDepth;
script_code_string_fixup_t *script_codeStringFixups;
size_t script_codeTempSize;
int32_t script_codegenMode;
coduo_script_variable_type_t script_coerceLeftType;
coduo_script_variable_type_t script_coerceRightType;
uint8_t script_continueAllowed;
uint8_t script_continueAllowedInDeveloperBlock;
script_code_offset_patch_t *script_continuePatchList;
uint16_t script_currentFunctionRoot;
uint32_t script_currentTimeKey;
uint8_t *script_developerOpBuffer;
int32_t script_developerOpcodePatchCapacity;
uint8_t **script_developerOpcodePatchTable;
uint16_t script_entityTypeClassMapRoot;
uint32_t script_entityTypeUsageCount;
coduo_script_entity_type_usage_t *script_entityTypeUsageRecords;
int32_t script_errorParameterIndex;
const char *script_errorMessage;
const char *script_errorSource;
coduo_script_export_table_t script_exportCallbacks;
uint8_t script_forceErrorReport;
coduo_script_frame_backup_codepos_t script_frameBackupCodepos;
coduo_script_frame_backup_opcode_t script_frameBackupOpcode;
uint16_t script_animHandle;
coduo_script_import_table_t script_importCallbacks;
uint8_t *script_importFieldBuffer;
uint16_t script_levelHandle;
uint16_t script_loadAnimTreeRoot;
uint8_t script_loadAnimTreesActive;
uint16_t script_loadScriptCodeRoot;
uint16_t script_loadScriptHandleRoot;
uint8_t script_loadScriptsActive;
uint32_t script_loopWatchdogTick;
int32_t script_loopWatchdogWarningFlag;
int32_t script_memoryAllocatedBucketCount;
int32_t script_memoryAllocatedInstanceCount;
script_memory_allocator_header_t script_memoryAllocatorHeader;
uint8_t script_memoryBitWidthTable[SCRIPT_MEMORY_LOOKUP_COUNT];
script_memory_block_t script_memoryBlocks[SCRIPT_MEMORY_BLOCK_COUNT];
uint16_t script_memoryFreeRoots[SCRIPT_MEMORY_BUCKET_COUNT];
uint8_t script_memoryPopcountTable[SCRIPT_MEMORY_LOOKUP_COUNT];
uint8_t script_memoryTrailingZeroBits[SCRIPT_MEMORY_LOOKUP_COUNT];
uint16_t script_gameHandle;
uint16_t *script_objectIdToVariable;
uint32_t script_parameterCount;
int32_t script_parseErrorCount;
coduo_scr_ast_node_t *script_parseRoot;
char *script_parseSource;
int32_t script_parseSourceDone;
uint16_t script_pauseArrayHandle;
int32_t script_pendingScriptLoadCount;
coduo_scr_script_load_record_t *script_pendingScriptLoadCursor;
uint8_t script_runtimeActive;
int32_t script_runtimeDebugReportFlag;
int32_t script_runtimeDeveloperFlag;
int32_t script_runtimeDeveloperScriptFlag;
uint16_t script_savedObjectCount;
/*
 * Original .data RVA 0x000ad184 / VA 0x080f5184 stores ff ff ff ff.
 * ShutdownOpcodeLookup restores this sentinel after freeing saved sources;
 * Scr_LoadSource replaces it from the serialized count before allocation.
 */
int32_t script_savedSourceFileCount =
    SCRIPT_SAVED_SOURCE_FILE_COUNT_NONE;
script_saved_source_file_t *script_savedSourceFiles;
uint8_t *script_serializationCursor;
uint32_t script_sourceBufferOffset;
const uint8_t *script_sourceBufferEnd;
const uint8_t *script_sourceBufferStart;
uint32_t script_sourceChecksum;
const char *script_sourceFilename;
uint32_t script_sourceFileCapacity;
uint32_t script_sourceFileCount;
script_source_file_record_t *script_sourceFiles;
const char *script_sourcePos;
uint32_t script_sourcePosCountForLastCodePos;
uint8_t *script_sourcePosLastCodePos;
uint32_t *script_sourcePosPool;
uint32_t script_sourcePosPoolCapacity;
uint32_t script_sourcePosPoolCount;
uint32_t
    script_sourcePosTableCapacity[SCRIPT_SOURCE_POS_TABLE_COUNT];
uint32_t script_sourcePosTableCount[SCRIPT_SOURCE_POS_TABLE_COUNT];
script_source_pos_record_t *
    script_sourcePosTables[SCRIPT_SOURCE_POS_TABLE_COUNT];
uint16_t script_stringCanonicalCount;
uint16_t *script_stringCanonicalMap;
script_string_hash_slot_t *script_stringFreedHashSlot;
script_string_hash_slot_t script_stringHashSlots[SCRIPT_STRING_HASH_SLOT_COUNT];
uint16_t script_tempValueHandle;
uint16_t script_timeArrayHandle;
coduo_script_value_stack_t script_valueStack;
uint32_t script_valueStackDepth;
VariableValue *script_valueStackLimit;
VariableValue *script_valueStackTop;
coduo_script_variable_indirection_table_t script_variableIndirections;
coduo_script_variable_node_table_t script_variableNodes;
uint16_t *script_variableToObjectId;
const char *script_variableTypeNames[CODUO_SCRIPT_VARIABLE_TYPE_COUNT] = {
    "undefined",
    "string",
    "localized string",
    "vector",
    "float",
    "int",
    "codepos",
    "object",
    "key/value",
    "function",
    "stack",
    "animation",
    "thread",
    "entity",
    "struct",
    "array",
    "dead thread",
    "dead entity",
    "dead object",
};
cvar_t *showdrop;
cvar_t *showpackets;
coduo_sound_alias_checksum_table_t soundAlias_checksums;
coduo_sound_alias_count_table_t soundAlias_counts;
char *soundAlias_currentFile;
coduo_sound_alias_hash_table_t soundAlias_hashTable;
coduo_sound_alias_loaded_flags_t soundAlias_loadedFlags;
coduo_sound_alias_localized_source_name_t soundAlias_localizedSourceName;
coduo_sound_alias_parse_node_t *soundAlias_parseListHead;
coduo_sound_alias_subtitle_reference_buffer_t soundAlias_subtitleReferenceBuffer;
coduo_sound_alias_table_pointer_table_t soundAlias_tablePointers;
uint16_t sys_snapVectorSavedFpuControlWord;
uint16_t sys_snapVectorFpuControlWord = UINT16_C(0x037f);
coduo_host_sv_prefix_t sv;
int sv_averageBpsFrameCount;
int sv_averageCompressionRatioCount;
float sv_averageCompressionRatioSum;
int32_t sv_serverId;
int sv_compressedBpsMax;
int sv_compressedBpsWindow[20];
/*
 * Original .data VA 0x080f5110..0x080f5127.  SV_LinkEntity and
 * SV_SightTraceThroughEntity use these bounds for DObjs carrying svFlags 0x2.
 */
vec3_t sv_defaultEntityClipMaxs = {64.0f, 64.0f, 72.0f};
vec3_t sv_defaultEntityClipMins = {-64.0f, -64.0f, -32.0f};
coduo_host_entity_link_table_t sv_entityLinks;
char *sv_entityParsePoint;
cvar_t *sv_fps;
coduo_host_game_data_globals_t sv_gameData;
coduo_vm_t *sv_gameVM;
coduo_sv_gametype_normalize_buffer_t sv_gametypeNormalizeBuffer;
cvar_t *sv_maxRate;
cvar_t *sv_maxclients;
cvar_t *sv_padPackets;
int sv_reconnectSequence;
cvar_t *sv_running;
int32_t sv_serverId_source;
cvar_t *sv_showAverageBPS;
int sv_totalBytesSentThisFrame;
int sv_totalUncompressedBytesThisFrame;
int sv_uncompressedBpsMax;
int sv_uncompressedBpsWindow[20];
coduo_host_svs_header_t svs;
netProfileInfo_t *svs_oobNetProfile;
char sys_delayedProcessCommand[SYS_DELAYED_PROCESS_COMMAND_SIZE];
/*
 * Original .data RVA 0x000af340 / VA 0x080f7340 stores 01 00 00 00.
 * Sys_ConsoleInput reads it before the only runtime write, which disables
 * subsequent dedicated-console polling after stdin reaches EOF.
 */
int32_t sys_stdinActive = SYS_STDIN_ACTIVE;
int32_t sys_ttyConsoleActive;
coduo_sys_tty_line_t sys_ttyCurrentLine;
int32_t sys_ttyEofChar;
int32_t sys_ttyEraseChar;
coduo_sys_tty_history_t sys_ttyHistory;
int32_t sys_ttyHistoryCount;
/*
 * Original .data RVA 0x000af358 / VA 0x080f7358 stores ff ff ff ff.
 * The previous/next history readers consume this no-selection sentinel before
 * Sys_TTYStoreHistoryLine can restore it after the first submitted line.
 */
int32_t sys_ttyHistoryCursor =
    SYS_TTY_HISTORY_RESET_CURSOR;
coduo_sys_tty_input_return_buffer_t sys_ttyInputReturnBuffer;
coduo_terminal_state_t sys_ttyOriginalTermios;
int32_t sys_ttyOutputSuppressionDepth;
cvar_t *ttycon;
coduo_vm_table_t vmTable;
uint8_t *weaponInfo_memory;
int32_t weaponInfo_memoryState;
uint16_t xanimDefaultPartRemapHandle;
int32_t xanim_activePoolPayloadSlot;
DObj *xanim_currentEvalState;
XAnimTree *xanim_currentTree;
int32_t xanim_deferredNotifyCount;
uint16_t xanim_endNotifyHandle;
int32_t xanim_evalChildCount;
coduo_xanim_eval_child_ref_t *xanim_evalChildRefs;
uint16_t xanim_evalCurrentFrame;
float xanim_evalCurrentTime;
uint8_t xanim_evalLeafOutputMode;
coduo_xanim_part_bitset_t xanim_evalPartBits;
int32_t xanim_evalPartBytes;
int32_t xanim_evalPartCount;
int32_t xanim_evalPoolWeightSelector;
uint16_t xanim_evalRootHandle;
coduo_xanim_part_bitset_t xanim_evalSkipBits;
uint16_t xanim_evalStartFrame;
float xanim_evalStartTime;
float xanim_evalTime;
float xanim_evalTimeStep;
uint16_t xanim_evalWindowFrame;
float xanim_evalWindowTime;
coduo_xanim_pool_t xanim_pool;
int32_t xanim_poolHighWaterCount;
int32_t xanim_poolUsedCount;
uint16_t xanim_rootTreeHandle;
/*
 * Original .data RVA 0x000af330 / VA 0x080f7330 stores 01 00 00 00.
 * XModelSurfsPrecache, XModelPartsPrecache, and XModelPrecache test this value
 * to select the fatal missing-asset path; XModelEnforceExist writes it.
 */
qboolean xmodel_enforceExist = qtrue;
float xmodel_testLodDist;
coduo_xmodel_test_lod_distance_table_t xmodel_testLodDistances;
uint8_t xmodel_testLodsEnabled;
char *fs_serverReferencedPakNames[FS_MAX_SERVER_PAKS];
char *fs_serverPakNames[FS_MAX_SERVER_PAKS];
int32_t fs_serverReferencedPaks[FS_MAX_SERVER_PAKS];
int32_t fs_serverPaks[FS_MAX_SERVER_PAKS];
xanim_deferred_notify_t
    xanim_deferredNotifies[XANIM_NOTIFY_QUEUE_CAPACITY];
