diff --git a/CMakeLists.txt b/CMakeLists.txt index f1b7a31..330aede 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -34,7 +34,7 @@ if(VITA) add_compile_options(-fno-use-cxa-atexit) endif() -if(NOT WIN32 AND NOT APPLE AND NOT VITA) +if(NOT WIN32 AND NOT APPLE AND NOT VITA AND NOT EMSCRIPTEN) add_link_options(-Wl,--no-undefined) endif() diff --git a/cl_dll/cdll_int.cpp b/cl_dll/cdll_int.cpp index 4f5a9e8..1cc73b5 100644 --- a/cl_dll/cdll_int.cpp +++ b/cl_dll/cdll_int.cpp @@ -245,9 +245,15 @@ so the HUD can reinitialize itself. bool isLoaded = false; +#ifdef __EMSCRIPTEN__ +void CL_ResetServerViewModels( void ); +#endif int DLLEXPORT HUD_VidInit( void ) { gHUD.VidInit(); +#ifdef __EMSCRIPTEN__ + CL_ResetServerViewModels(); // model indexes change with the map +#endif isLoaded = true; diff --git a/cl_dll/cs_wpn/cs_weapons.cpp b/cl_dll/cs_wpn/cs_weapons.cpp index 56a59de..bec71cd 100644 --- a/cl_dll/cs_wpn/cs_weapons.cpp +++ b/cl_dll/cs_wpn/cs_weapons.cpp @@ -48,6 +48,24 @@ #include "pm_shared.h" #include "GameStudioModelRenderer.h" #include "ammohistory.h" + +#ifdef __EMSCRIPTEN__ +// web build: the view model the server last used for each weapon, and the stock model it replaced (see DefaultDeploy) +static int g_iServerViewModel[MAX_WEAPONS]; +static int g_iStockViewModel[MAX_WEAPONS]; + +void CL_NoteServerViewModel( int id, int model ) +{ + if( id > 0 && id < MAX_WEAPONS && model ) + g_iServerViewModel[id] = model; +} + +void CL_ResetServerViewModels( void ) +{ + memset( g_iServerViewModel, 0, sizeof( g_iServerViewModel )); + memset( g_iStockViewModel, 0, sizeof( g_iStockViewModel )); +} +#endif #ifndef min #define min(a,b) (((a) < (b)) ? (a) : (b)) #endif @@ -431,7 +449,24 @@ BOOL CBasePlayerWeapon :: DefaultDeploy( const char *szViewModel, const char *sz if ( !CanDeploy() ) return FALSE; +#ifdef __EMSCRIPTEN__ + // web build: deploy with the server's view model for this weapon when it has one (skin plugins), so the + // predicted draw does not start on the stock model and jump to the server's + int stock = 0; + gEngfuncs.CL_LoadModel( szViewModel, &stock ); + if( m_iId > 0 && m_iId < MAX_WEAPONS ) + { + if( g_iStockViewModel[m_iId] != stock ) + { + g_iStockViewModel[m_iId] = stock; + g_iServerViewModel[m_iId] = 0; + } + m_pPlayer->pev->viewmodel = g_iServerViewModel[m_iId] ? g_iServerViewModel[m_iId] : stock; + } + else m_pPlayer->pev->viewmodel = stock; +#else gEngfuncs.CL_LoadModel( szViewModel, &m_pPlayer->pev->viewmodel ); +#endif SendWeaponAnim( iAnim, skiplocal ); diff --git a/cl_dll/entity.cpp b/cl_dll/entity.cpp index 582ef53..1f00940 100644 --- a/cl_dll/entity.cpp +++ b/cl_dll/entity.cpp @@ -82,9 +82,16 @@ playerstate update in entity_state_t. In order for these overrides to eventuall structure, we need to copy them into the state structure at this point. ========================= */ +#ifdef __EMSCRIPTEN__ +void CL_NoteServerViewModel( int id, int model ); +#endif void DLLEXPORT HUD_TxferLocalOverrides( struct entity_state_s *state, const struct clientdata_s *client ) { VectorCopy( client->origin, state->origin ); +#ifdef __EMSCRIPTEN__ + // the server's view model for the weapon in hand (cs_weapons.cpp, DefaultDeploy) + CL_NoteServerViewModel( client->m_iId, client->viewmodel ); +#endif // Spectator state->iuser1 = client->iuser1; diff --git a/cl_dll/events/event_createsmoke.cpp b/cl_dll/events/event_createsmoke.cpp index 0d267fb..7521dee 100644 --- a/cl_dll/events/event_createsmoke.cpp +++ b/cl_dll/events/event_createsmoke.cpp @@ -29,7 +29,11 @@ #include "com_model.h" +#ifdef __EMSCRIPTEN__ +#define SMOKE_CLOUDS 44 // web build: denser cloud (see below) +#else #define SMOKE_CLOUDS 20 +#endif void EV_CreateSmoke(event_args_s *args) { @@ -48,7 +52,12 @@ void EV_CreateSmoke(event_args_s *args) org.x += Com_RandomFloat(-100.0f, 100.0f); org.y += Com_RandomFloat(-100.0f, 100.0f); } - org.z += 30; + org.z += 30; +#ifdef __EMSCRIPTEN__ + // web build: the second half of the puffs make a higher layer, so the cloud covers head height too + if( i >= SMOKE_CLOUDS / 2 ) + org.z += Com_RandomFloat( 40.0f, 70.0f ); +#endif pTemp = gEngfuncs.pEfxAPI->CL_TempEntAllocNoModel( org ); if( pTemp ) diff --git a/cl_dll/hud.h b/cl_dll/hud.h index bcfdf6e..7f1a0fc 100644 --- a/cl_dll/hud.h +++ b/cl_dll/hud.h @@ -1003,7 +1003,11 @@ public: return i; } +#ifdef __EMSCRIPTEN__ + gEngfuncs.Con_DPrintf( "GetSpriteIndex: %s sprite not found\n", SpriteName ); +#else gEngfuncs.Con_Printf( "GetSpriteIndex: %s sprite not found\n", SpriteName ); +#endif return -1; // invalid sprite } diff --git a/cl_dll/hud/MOTD.cpp b/cl_dll/hud/MOTD.cpp index 83208f5..a11d170 100644 --- a/cl_dll/hud/MOTD.cpp +++ b/cl_dll/hud/MOTD.cpp @@ -32,6 +32,10 @@ #define strcasestr strstr #endif +#ifdef __EMSCRIPTEN__ +#include +#endif + int CHudMOTD :: Init( void ) { gHUD.AddHudElem( this ); @@ -145,6 +149,19 @@ int CHudMOTD :: MsgFunc_MOTD( const char *pszName, int iSize, void *pbuf ) int is_finished = reader.ReadByte(); m_szMOTD.Append( reader.ReadString() ); +#ifdef __EMSCRIPTEN__ + // web build: the page shows it (HTML included) + if( EM_ASM_INT({ return Module['onMotd'] ? 1 : 0; })) + { + if( is_finished ) + { + EM_ASM({ Module['onMotd'](UTF8ToString($0)); }, m_szMOTD.String() ); + Reset(); + } + return 1; + } +#endif + // we still don't support html tags in motd :( if( strcasestr( m_szMOTD.String(), "" ) ) { diff --git a/cl_dll/hud/scoreboard.cpp b/cl_dll/hud/scoreboard.cpp index e1feea4..b78614d 100644 --- a/cl_dll/hud/scoreboard.cpp +++ b/cl_dll/hud/scoreboard.cpp @@ -39,6 +39,120 @@ int g_iUser2; int g_iUser3; int g_iTeamNumber; +#ifdef __EMSCRIPTEN__ +#include +#include + +static int g_iWebTeamScore[3]; // rounds won, by team number (TeamScore message) +static bool g_bWebScoreShown; +static double g_flWebScoreNext; +static char g_szWebScore[24576], g_szWebScoreLast[24576]; +static size_t g_iWebScoreLen; + +static void WS_Put( const char *fmt, ... ) +{ + if( g_iWebScoreLen >= sizeof( g_szWebScore ) - 1 ) + return; + va_list va; + va_start( va, fmt ); + int n = vsnprintf( g_szWebScore + g_iWebScoreLen, sizeof( g_szWebScore ) - g_iWebScoreLen, fmt, va ); + va_end( va ); + if( n > 0 ) + g_iWebScoreLen = min( g_iWebScoreLen + n, sizeof( g_szWebScore ) - 1 ); +} + +// a JSON string; control characters become spaces, other bytes go through (the page decodes UTF-8) +static void WS_Str( const char *s ) +{ + char buf[256]; + size_t n = 0; + buf[n++] = '"'; + for( ; s && *s && n < sizeof( buf ) - 3; s++ ) + { + unsigned char c = *s; + if( c == '"' || c == '\\' ) { buf[n++] = '\\'; buf[n++] = c; } + else buf[n++] = c < 0x20 ? ' ' : c; + } + buf[n++] = '"'; + buf[n] = 0; + WS_Put( "%s", buf ); +} + +static void WebNoteTeamScore( const char *team, int score ) +{ + if( !stricmp( team, "TERRORIST" )) g_iWebTeamScore[TEAM_TERRORIST] = score; + else if( !stricmp( team, "CT" )) g_iWebTeamScore[TEAM_CT] = score; +} + +// true when the page draws the scoreboard (then the client draws nothing) +static bool WebScoreboard( bool show, int me ) +{ + if( !EM_ASM_INT({ return Module['onScoreboard'] ? 1 : 0; })) + return false; + + if( !show ) + { + if( g_bWebScoreShown ) + { + g_bWebScoreShown = false; + EM_ASM({ Module['onScoreboard'](0); }); + } + return true; + } + + double now = emscripten_get_now(); + if( g_bWebScoreShown && now < g_flWebScoreNext ) + return true; + g_flWebScoreNext = now + 250.0; + + g_iWebScoreLen = 0; + g_szWebScore[0] = 0; + WS_Put( "{\"sv\":" ); + WS_Str( gHUD.m_szServerName ); + WS_Put( ",\"map\":" ); + WS_Str( gEngfuncs.pfnGetLevelName( )); + WS_Put( ",\"me\":%d,\"ts\":[%d,%d],\"p\":[", me, g_iWebTeamScore[TEAM_TERRORIST], g_iWebTeamScore[TEAM_CT] ); + + bool first = true; + for( int i = 1; i < MAX_PLAYERS; i++ ) + { + hud_player_info_t info; + memset( &info, 0, sizeof( info )); + GetPlayerInfo( i, &info ); + if( !info.name || !info.name[0] ) + continue; + + const extra_player_info_t &ex = g_PlayerExtraInfo[i]; + int flags = 0; + if( ex.dead ) flags |= 1; + if( ex.has_c4 ) flags |= 2; + if( ex.vip ) flags |= 4; + if( ex.has_defuse_kit ) flags |= 8; + const char *bot = gEngfuncs.PlayerInfo_ValueForKey( i, "*bot" ); + if( info.ping <= 5 && bot && atoi( bot ) > 0 ) flags |= 16; + if( info.thisplayer ) flags |= 32; + + int hp = ( ex.sb_health >= 0 && !ex.dead && gHUD.m_pShowHealth->value ) ? ex.sb_health : -1; + int money = ( ex.sb_account >= 0 && gHUD.m_pShowMoney->value ) ? ex.sb_account : -1; + int team = ex.teamname[0] ? ex.teamnumber : 0; + + WS_Put( first ? "[%d," : ",[%d,", i ); + WS_Str( info.name ); + WS_Put( ",%d,%d,%d,%d,%d,%d,%d]", team, ex.frags, ex.deaths, info.ping, flags, hp, money ); + first = false; + } + WS_Put( "]}" ); + + if( !g_bWebScoreShown || strcmp( g_szWebScore, g_szWebScoreLast )) + { + strcpy( g_szWebScoreLast, g_szWebScore ); + EM_ASM({ Module['onScoreboard'](UTF8ToString($0)); }, g_szWebScore ); + } + g_bWebScoreShown = true; + return true; +} +#endif + // X positions @@ -185,6 +299,11 @@ void CHudScoreboard :: InitHUDData( void ) g_PlayerExtraInfo[i].sb_account = -1; } +#ifdef __EMSCRIPTEN__ + memset( g_iWebTeamScore, 0, sizeof( g_iWebTeamScore )); + WebScoreboard( false, 0 ); +#endif + m_iFlags &= ~HUD_DRAW; // starts out inactive m_iFlags |= HUD_INTERMISSION; // is always drawn during an intermission @@ -209,6 +328,11 @@ bool CHudScoreboard :: ShouldDrawScoreboard() const int CHudScoreboard :: Draw( float flTime ) { +#ifdef __EMSCRIPTEN__ + // web build: the page draws it (the forced scoreboard of showscoreboard2 stays native) + if( !m_bForceDraw && WebScoreboard( ShouldDrawScoreboard(), m_iPlayerNum )) + return 1; +#endif if( !ShouldDrawScoreboard( )) return 1; @@ -765,6 +889,9 @@ int CHudScoreboard :: MsgFunc_TeamScore( const char *pszName, int iSize, void *p // use this new score data instead of combined player scores g_TeamInfo[i].scores_overriden = TRUE; g_TeamInfo[i].frags = reader.ReadShort(); +#ifdef __EMSCRIPTEN__ + WebNoteTeamScore( TeamName, g_TeamInfo[i].frags ); +#endif // g_TeamInfo[i].deaths = reader.ReadShort(); return 1; @@ -794,6 +921,10 @@ void CHudScoreboard :: UserCmd_ShowScores( void ) void CHudScoreboard :: UserCmd_HideScores( void ) { m_bForceDraw = m_bShowscoresHeld = false; +#ifdef __EMSCRIPTEN__ + if( !gHUD.m_iIntermission ) + WebScoreboard( false, 0 ); +#endif } diff --git a/cl_dll/menu.cpp b/cl_dll/menu.cpp index 6775e27..602f63b 100644 --- a/cl_dll/menu.cpp +++ b/cl_dll/menu.cpp @@ -36,6 +36,19 @@ char g_szPrelocalisedMenuString[MAX_MENU_STRING]; int KB_ConvertString( char *in, char **ppout ); +#ifdef __EMSCRIPTEN__ +#include +static bool g_bWebMenuDirty, g_bWebMenuShown; + +static void WebMenuHide( void ) +{ + if( !g_bWebMenuShown ) + return; + g_bWebMenuShown = false; + EM_ASM({ if( Module['onHudMenu'] ) Module['onHudMenu'](0); }); +} +#endif + void Touch_CloseMenu() { gMobileAPI.pfnTouchRemoveButton( "_menu_*" ); @@ -68,6 +81,9 @@ void CHudMenu :: InitHUDData( void ) m_fMenuDisplayed = 0; m_bitsValidSlots = 0; Reset(); +#ifdef __EMSCRIPTEN__ + WebMenuHide(); +#endif } void CHudMenu :: Reset( void ) @@ -97,6 +113,21 @@ int CHudMenu :: Draw( float flTime ) //if ( gViewPort && gViewPort->IsScoreBoardVisible() ) //return 1; +#ifdef __EMSCRIPTEN__ + // web build: the page draws it + if( EM_ASM_INT({ return Module['onHudMenu'] ? 1 : 0; })) + { + if( g_bWebMenuDirty || !g_bWebMenuShown ) + { + g_bWebMenuDirty = false; + g_bWebMenuShown = true; + int left = m_flShutoffTime > 0 ? (int)( m_flShutoffTime - gHUD.m_flTime + 0.5f ) : -1; + EM_ASM({ Module['onHudMenu'](UTF8ToString($0), $1, $2); }, g_szMenuString, m_bitsValidSlots, left ); + } + return 1; + } +#endif + // draw the menu, along the left-hand side of the screen // count the number of newlines @@ -208,6 +239,9 @@ int CHudMenu :: MsgFunc_ShowMenu( const char *pszName, int iSize, void *pbuf ) if ( !NeedMore ) { // we have the whole string, so we can localise it now +#ifdef __EMSCRIPTEN__ + g_bWebMenuDirty = true; +#endif strlcpy( g_szMenuString, gHUD.m_TextMessage.BufferedLocaliseTextString( g_szPrelocalisedMenuString ), sizeof( g_szMenuString ) ); // Swap in characters if ( KB_ConvertString( g_szMenuString, &temp ) ) @@ -259,6 +293,9 @@ void CHudMenu::UserCmd_OldStyleMenuOpen() { m_flShutoffTime = -1; // stay open until user will not close it strlcpy( g_szMenuString, gHUD.m_TextMessage.BufferedLocaliseTextString("Buy"), sizeof( g_szMenuString ) ); +#ifdef __EMSCRIPTEN__ + g_bWebMenuDirty = true; +#endif } void CHudMenu::UserCmd_OldStyleMenuClose() @@ -267,6 +304,9 @@ void CHudMenu::UserCmd_OldStyleMenuClose() m_iFlags &= ~HUD_DRAW; Touch_CloseMenu(); +#ifdef __EMSCRIPTEN__ + WebMenuHide(); +#endif } // lol, no real VGUI here diff --git a/common/interface.cpp b/common/interface.cpp index a13a9fd..462524a 100644 --- a/common/interface.cpp +++ b/common/interface.cpp @@ -17,6 +17,9 @@ #elif XASH_APPLE == 1 #include #include +#elif !defined( _WIN32 ) +#include +#include #endif #if !defined( _WIN32 ) diff --git a/3rdparty/mainui_cpp/BaseMenu.cpp b/3rdparty/mainui_cpp/BaseMenu.cpp index 41dd3e3..bcf8162 100755 --- a/3rdparty/mainui_cpp/BaseMenu.cpp +++ b/3rdparty/mainui_cpp/BaseMenu.cpp @@ -1,1258 +1,1262 @@ -/* -ui_menu.c -- main menu interface -Copyright (C) 1997-2001 Id Software, Inc. -Copyright (C) 2017 a1batross - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -See the GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - -*/ -#include "extdll_menu.h" -#include "BaseMenu.h" -#include "PicButton.h" -#include "keydefs.h" -#include "Utils.h" -#include "Btns.h" -#include "YesNoMessageBox.h" -#include "BackgroundBitmap.h" -#include "FontManager.h" -#include "cursor_type.h" -#include "utflib.h" - -cvar_t *ui_showmodels; -cvar_t *ui_showclassmodels; -cvar_t *ui_show_window_stack; -cvar_t *ui_borderclip; -cvar_t *ui_prefer_won_background; -cvar_t *ui_background_stretch; -cvar_t *ui_logohorizontal; - -uiStatic_t uiStatic; -static CMenuEntry *s_pEntries = NULL; - -const char *uiSoundOldPrefix = "media/"; -const char *uiSoundNewPrefix = "sound/common/"; -const char *uiSounds[] = { - "media/launch_upmenu1.wav", - "media/launch_dnmenu1.wav", - "media/launch_select2.wav", - "", - "media/launch_glow1.wav", - "media/launch_deny2.wav", - "media/launch_select1.wav", - "media/launch_deny1.wav", - "", - "" -}; - -// they match default WON colors.lst now, except alpha -// a1ba: made uiColorHelp brighter so it's easier to read -unsigned int uiColorHelp = 0xFFA0A0A0; // 160, 160, 160, 255 // hint letters color -unsigned int uiPromptBgColor = 0xFF383838; // 56, 56, 56, 255 // dialog background color -unsigned int uiPromptTextColor = 0xFFF0B418; // 240, 180, 24, 255 // dialog or button letters color -unsigned int uiPromptFocusColor = 0xFFFFFF00; // 255, 255, 0, 255 // dialog or button focus letters color -unsigned int uiInputTextColor = 0xFFF0B418; // 240, 180, 24, 255 -unsigned int uiInputBgColor = 0x80383838; // 56, 56, 56, 128 // field, scrollist, checkbox background color -unsigned int uiInputFgColor = 0xFF555555; // 85, 85, 85, 255 // field, scrollist, checkbox foreground color -unsigned int uiColorWhite = 0xFFFFFFFF; // 255, 255, 255, 255 // useful for bitmaps -unsigned int uiColorDkGrey = 0x80404040; // 64, 64, 64, 128 // shadow and grayed items -unsigned int uiColorBlack = 0x80000000; // 0, 0, 0, 128 // some controls background -unsigned int uiColorConsole = 0xFFF0B418; // just for reference - -// color presets (this is nasty hack to allow color presets to part of text) -const unsigned int g_iColorTable[8] = -{ -0xFF000000, // black -0xFFFF0000, // red -0xFF00FF00, // green -0xFFFFFF00, // yellow -0xFF0000FF, // blue -0xFF00FFFF, // cyan -0xFFF0B418, // dialog or button letters color -0xFFFFFFFF, // white -}; - -CMenuEntry::CMenuEntry(const char *cmd, void (*pfnPrecache)(), void (*pfnShow)(), void (*pfnShutdown)() ) : - m_szCommand( cmd ), - m_pfnPrecache( pfnPrecache ), - m_pfnShow( pfnShow ), - m_pfnShutdown( pfnShutdown ), - m_pNext( s_pEntries ) -{ - s_pEntries = this; -} - -/* -================= -UI_ScaleCoords - -Any parameter can be NULL if you don't want it -================= -*/ -void UI_ScaleCoords( int *x, int *y, int *w, int *h ) -{ - if( x ) *x *= uiStatic.scaleX; - if( y ) *y *= uiStatic.scaleY; - if( w ) *w *= uiStatic.scaleX; - if( h ) *h *= uiStatic.scaleY; -} - -void UI_ScaleCoords( int &x, int &y ) -{ - x *= uiStatic.scaleX; - y *= uiStatic.scaleY; -} - -void UI_ScaleCoords( int &x, int &y, int &w, int &h ) -{ - UI_ScaleCoords( x, y ); - UI_ScaleCoords( w, h ); -} - -Point Point::Scale() -{ - return Point( x * uiStatic.scaleX, y * uiStatic.scaleY ); -} - -Size Size::Scale() -{ - return Size( w * uiStatic.scaleX, h * uiStatic.scaleY ); -} - -/* -================= -UI_CursorInRect -================= -*/ -bool UI_CursorInRect( int x, int y, int w, int h ) -{ - if( uiStatic.cursorX < x || uiStatic.cursorX > x + w ) - return false; - if( uiStatic.cursorY < y || uiStatic.cursorY > y + h ) - return false; - return true; -} - -/* -================= -UI_EnableAlphaFactor -================= -*/ -void UI_EnableAlphaFactor( float a ) -{ - uiStatic.enableAlphaFactor = true; - uiStatic.alphaFactor = bound( 0.0f, a, 1.0f ); -} - -/* -================= -UI_DisableAlphaFactor -================= -*/ -void UI_DisableAlphaFactor() -{ - uiStatic.enableAlphaFactor = false; -} - -/* -================= -UI_DrawPic -================= -*/ -void UI_DrawPic( int x, int y, int width, int height, const unsigned int color, CImage &pic, const ERenderMode eRenderMode ) -{ - HIMAGE hPic = pic.Handle(); - - if( !hPic ) - return; - - int r, g, b, a; - UnpackRGBA( r, g, b, a, color ); - - EngFuncs::PIC_Set( hPic, r, g, b, a ); - switch( eRenderMode ) - { - case QM_DRAWNORMAL: - if( !uiStatic.enableAlphaFactor ) - { - EngFuncs::PIC_Draw( x, y, width, height ); - break; - } - // intentional fallthrough - case QM_DRAWTRANS: - EngFuncs::PIC_DrawTrans( x, y, width, height ); - break; - case QM_DRAWADDITIVE: - EngFuncs::PIC_DrawAdditive( x, y, width, height ); - break; - case QM_DRAWHOLES: - EngFuncs::PIC_DrawHoles( x, y, width, height ); - break; - } -} - -/* -================= -UI_FillRect -================= -*/ -void UI_FillRect( int x, int y, int width, int height, const unsigned int color ) -{ - int r, g, b, a; - UnpackRGBA( r, g, b, a, color ); - - EngFuncs::FillRGBA( x, y, width, height, r, g, b, a ); -} - -/* -================= -UI_DrawRectangleExt -================= -*/ -void UI_DrawRectangleExt( int in_x, int in_y, int in_w, int in_h, const unsigned int color, int outlineWidth, int flag ) -{ - int x, y, w, h; - - if( outlineWidth == 0 ) outlineWidth = uiStatic.outlineWidth; - - if( flag & QM_LEFT ) - { - x = in_x - outlineWidth; - y = in_y - outlineWidth; - w = outlineWidth; - h = in_h + outlineWidth + outlineWidth; - - // draw left - UI_FillRect( x, y, w, h, color ); - } - - if( flag & QM_RIGHT ) - { - x = in_x + in_w; - y = in_y - outlineWidth; - w = outlineWidth; - h = in_h + outlineWidth + outlineWidth; - - // draw right - UI_FillRect( x, y, w, h, color ); - } - - if( flag & QM_TOP ) - { - x = in_x; - y = in_y - outlineWidth; - w = in_w; - h = outlineWidth; - - // draw top - UI_FillRect( x, y, w, h, color ); - } - - if( flag & QM_BOTTOM ) - { - // draw bottom - x = in_x; - y = in_y + in_h; - w = in_w; - h = outlineWidth; - - UI_FillRect( x, y, w, h, color ); - } -} - -/* -================= -UI_DrawString -================= -*/ -int UI_DrawString( HFont font, int x, int y, int w, int h, - const char *string, const unsigned int color, - int charH, uint justify, uint flags ) -{ - uint modulate, shadowModulate = 0; - int xx = 0, yy, shadowOffset = 0, ch; - int maxX = x; - - if( !string || !string[0] ) - return x; - - if( flags & ETF_SHADOW ) - { - shadowModulate = PackAlpha( uiColorBlack, UnpackAlpha( color )); - shadowOffset = Q_max( 1, uiStatic.scaleX * 3 ); - } - - modulate = color; - - if( justify & QM_TOP ) - { - yy = y; - h -= h % charH; - } - else if( justify & QM_BOTTOM ) - { - yy = y + h - charH; - h -= h % charH; - } - else - { - yy = y + (h - charH)/2; - h -= charH; - } - - if( flags & ETF_NO_WRAP ) - h = charH; - - int i = 0; - int ellipsisWide = g_FontMgr->GetEllipsisWide( font ); - bool giveup = false; - - while( string[i] && !giveup ) - { - char line[1024], *l; - int j = i, len = 0; - int pixelWide = 0; - int save_pixelWide = 0; - int save_j = 0; - utfstate_t state; - - while( string[j] ) - { - if( string[j] == '\n' ) - { - j++; - break; - } - - if( len == sizeof( line ) - 1 ) - break; - - line[len] = string[j]; - - uint32_t uch = state.Decode((uint8_t)string[j] ); - - if( IsColorString( string + j )) // don't calc wides for colorstrings - { - line[len+1] = string[j+1]; - len += 2; - j += 2; - } - else if( !uch ) // don't calc wides for invalid codepoints - { - len++; - j++; - } - else - { - int charWide; - - // does we have free space for new line? - if( yy < (y + h) - charH ) - { - if( uch == ' ' && pixelWide < w ) // remember last whitespace - { - save_pixelWide = pixelWide; - save_j = j; - } - } - else - { - // remember last position, when we still fit - if( pixelWide + ellipsisWide < w && j > 0 ) - { - save_pixelWide = pixelWide; - save_j = j; - } - } - - charWide = g_FontMgr->GetCharacterWidthScaled( font, uch, charH ); - - if( !(flags & ETF_NOSIZELIMIT) && pixelWide + charWide > w ) - { - // do we have free space for new line? - if( yy < (y + h) - charH ) - { - // try to word wrap - if( save_j != 0 && save_pixelWide != 0 ) - { - pixelWide = save_pixelWide; - len -= j - save_j; // skip whitespace - j = save_j + 1; // skip whitespace - } - - break; - } - else - { - - if( save_j != 0 && save_pixelWide != 0 ) - { - pixelWide = save_pixelWide; - len -= j - save_j; - j = save_j; - - - if( len > 0 ) - { - line[len] = '.'; - line[len+1] = '.'; - line[len+2] = '.'; - len += 3; - } - } - - // we don't have free space anymore, so just stop drawing - giveup = true; - - break; - } - } - else - { - pixelWide += charWide; - j++; - len++; - } - } - } - line[len] = 0; - - // align the text as appropriate - if( justify & QM_LEFT ) - { - xx = x; - } - else if( justify & QM_RIGHT ) - { - xx = x + (w - pixelWide); - } - else // QM_LEFT - { - xx = x + (w - pixelWide) / 2.0f; - } - - // draw it - l = line; - state.Reset(); - while( *l ) - { - if( IsColorString( l )) - { - int colorNum = ColorIndex( *(l+1) ); - - if( colorNum == 7 && color != 0 ) - { - modulate = color; - } - else if( !(flags & ETF_FORCECOL) ) - { - modulate = PackAlpha( g_iColorTable[colorNum], UnpackAlpha( color )); - } - - l += 2; - continue; - } - - ch = *l++; - ch &= 255; - -// when using custom font render, we use utf-8 - ch = state.Decode((uint8_t)ch ); - if( !ch ) - continue; - - if( flags & ETF_SHADOW ) - g_FontMgr->DrawCharacter( font, ch, Point( xx + shadowOffset, yy + shadowOffset ), charH, shadowModulate, flags & ETF_ADDITIVE ); - -#ifdef DEBUG_WHITESPACE - if( ch == ' ' ) - { - g_FontMgr->DrawCharacter( font, '_', Point( xx, yy ), charH, modulate, flags & ETF_ADDITIVE ); - xx += g_FontMgr->GetCharacterWidthScaled( font, ch, charH ); - continue; - } -#endif - - xx += g_FontMgr->DrawCharacter( font, ch, Point( xx, yy ), charH, modulate, flags & ETF_ADDITIVE ); - - maxX = Q_max( xx, maxX ); - } - yy += charH; - - i = j; - } - - return maxX; -} - -/* -================= -UI_DrawMouseCursor -================= -*/ -void UI_DrawMouseCursor( void ) -{ - CMenuBaseItem *item; - void *hCursor = (void *)dc_arrow; - int cursor = uiStatic.menu.Current()->GetCursor(); - item = uiStatic.menu.Current()->GetItemByIndex( cursor ); - - if( item && FBitSet( item->iFlags, QMF_HASMOUSEFOCUS )) // fast approach - { - if( FBitSet( item->iFlags, QMF_GRAYED )) - hCursor = (void *)dc_no; - else hCursor = (void *)item->CursorAction(); - } - else - { - FOR_EACH_VEC( uiStatic.menu.Current()->m_pItems, i ) - { - item = (CMenuBaseItem *)uiStatic.menu.Current()->GetItemByIndex(cursor); - - if( !item->IsVisible( )) - continue; - - if( !FBitSet( item->iFlags, QMF_HASMOUSEFOCUS )) - continue; - - if( FBitSet( item->iFlags, QMF_GRAYED )) - hCursor = (void *)dc_no; - else hCursor = (void *)item->CursorAction(); - - break; - } - } - - EngFuncs::SetCursor( hCursor ); -} - -// ===================================================================== - -/* -================= -UI_StartBackGroundMap -================= -*/ -bool UI_StartBackGroundMap( void ) -{ - static int check_dll; - - // the list is empty - if( uiStatic.bgmaps.IsEmpty()) - return false; - - // check if server dll available only once, as it might be implemented - // very inefficiently - if( !check_dll ) - { - if( EngFuncs::CheckGameDll( )) - check_dll = 1; - else - check_dll = -1; - } - - if( check_dll < 0 ) - return false; - - // some map is already running - if( CL_IsActive() || EngFuncs::GetCvarFloat( "cl_background" ) != 0.0f || gpGlobals->demoplayback ) - return false; - - int bgmapid = EngFuncs::RandomLong( 0, uiStatic.bgmaps.Count() - 1 ); - - char cmd[128]; - snprintf( cmd, sizeof( cmd ), "maps/%s.bsp", uiStatic.bgmaps[bgmapid].Get( )); - if( !EngFuncs::FileExists( cmd, true )) - return false; - - snprintf( cmd, sizeof( cmd ), "map_background %s\n", uiStatic.bgmaps[bgmapid].Get( )); - EngFuncs::ClientCmd( false, cmd ); - - return true; -} - -// ===================================================================== - -/* -================= -UI_CloseMenu -================= -*/ -void UI_CloseMenu( void ) -{ - uiStatic.menu.Clean(); - -// EngFuncs::KEY_ClearStates (); - if( !uiStatic.client.IsActive() ) - EngFuncs::KEY_SetDest( KEY_GAME ); -} - -void UI_CloseClientMenu( void ) -{ - if( !uiStatic.client.IsActive() ) - return; - - uiStatic.client.Clean(); - EngFuncs::KEY_ClearStates(); - EngFuncs::KEY_SetDest( KEY_GAME ); - EngFuncs::ClientCmd( false, "touch_setclientonly 0" ); -} - -// ===================================================================== - - -static bool UI_UpdateWindowInsets( void ) -{ - const float *insets = NULL; - int left = 0, top = 0, right = 0, bottom = 0; - - if( EngFuncs::textfuncs.pfnGetNativeObject ) - insets = (const float *)EngFuncs::textfuncs.pfnGetNativeObject( "WindowInsets" ); - if( insets ) - { - left = ceilf( ScreenWidth * insets[0] ); - top = ceilf( ScreenHeight * insets[1] ); - right = ceilf( ScreenWidth * insets[2] ); - bottom = ceilf( ScreenHeight * insets[3] ); - } - bool changed = left != uiStatic.safeLeft || top != uiStatic.safeTop || - right != uiStatic.safeRight || bottom != uiStatic.safeBottom; - uiStatic.safeLeft = left; - uiStatic.safeTop = top; - uiStatic.safeRight = right; - uiStatic.safeBottom = bottom; - return changed; -} - -/* -================= -UI_UpdateMenu -================= -*/ -void UI_UpdateMenu( float flTime ) -{ - if( !uiStatic.initialized ) - return; - - if( UI_UpdateWindowInsets() ) - UI_VidInit(); - - static bool loadStuff = true; - - // can't do this in Init, since these are dependent on cvar values - // set from user configs - if( loadStuff ) - { - // load background bitmaps - CMenuBackgroundBitmap::LoadBackground( ); - - // load localized strings - UI_LoadCustomStrings(); - - // load scr - UI_LoadScriptConfig(); - - loadStuff = false; - } - - UI_DrawFinalCredits (); - - // also moved opening main menu here from SetActiveMenu, so - // translation strings could will be loaded at this moment - if( uiStatic.nextFrameActive ) - { - if( !uiStatic.menu.IsActive() ) - UI_Main_Menu(); - - uiStatic.nextFrameActive = false; - } - - // advance global time - uiStatic.realTime = flTime * 1000; - - // let's use engine credits "feature" for drawing client windows - if( uiStatic.client.IsActive( )) - uiStatic.client.Update(); - - if( !uiStatic.menu.IsActive( )) - return; - - if( !EngFuncs::ClientInGame() && EngFuncs::GetCvarFloat( "cl_background" ) != 0.0f ) - return; // don't draw menu while level is loading - - if( uiStatic.firstDraw ) - { - static bool first = true; - - if( first ) - { - first = false; - - // we loading background so skip SCR_Update - if( UI_StartBackGroundMap( )) - return; - - // load background track - if( !CL_IsActive( )) - EngFuncs::PlayBackgroundTrack( "media/gamestartup", "media/gamestartup" ); - } - - uiStatic.firstDraw = false; - } - - // draw cursor - UI_DrawMouseCursor(); - - // background doesn't need to be drawn with transparency - bool enableAlphaFactor = uiStatic.enableAlphaFactor; - uiStatic.enableAlphaFactor = false; - uiStatic.background->Draw(); - uiStatic.enableAlphaFactor = enableAlphaFactor; - - uiStatic.menu.Update(); -} - -/* -================= -UI_KeyEvent -================= -*/ -void UI_KeyEvent( int key, int down ) -{ - bool clientActive, menuActive; - - if( !uiStatic.initialized ) - return; - - if( key == K_MOUSE1 ) - { - g_bCursorDown = !!down; - } - - clientActive = uiStatic.client.IsActive(); - menuActive = uiStatic.menu.IsActive(); - - if( clientActive && !menuActive ) - down ? uiStatic.client.KeyDownEvent( key ) : - uiStatic.client.KeyUpEvent( key ); - - if( menuActive ) - down ? uiStatic.menu.KeyDownEvent( key ) : - uiStatic.menu.KeyUpEvent( key ); -} - -/* -================= -UI_CharEvent -================= -*/ -void UI_CharEvent( int key ) -{ - if( !uiStatic.initialized ) - return; - - bool clientActive = uiStatic.client.IsActive(); - bool menuActive = uiStatic.menu.IsActive(); - - if( clientActive && !menuActive ) - uiStatic.client.CharEvent( key ); - - if( menuActive ) - uiStatic.menu.CharEvent( key ); -} - -bool g_bCursorDown; -float cursorDY; - -/* -================= -UI_MouseMove -================= -*/ -void UI_MouseMove( int x, int y ) -{ - bool clientActive, menuActive; - - if( !uiStatic.initialized ) - return; - - clientActive = uiStatic.client.IsActive(); - menuActive = uiStatic.menu.IsActive(); - - if( !clientActive && !menuActive ) - return; - - if( uiStatic.cursorX == x && uiStatic.cursorY == y ) - return; - - if( g_bCursorDown ) - { - static bool prevDown = false; - - if( !prevDown ) - { - prevDown = true; - cursorDY = 0; - } - else if( y - uiStatic.cursorY ) - { - cursorDY += y - uiStatic.cursorY; - } - } - else - cursorDY = 0; - //Con_Printf("%d %d %f\n",x, y, cursorDY); - - // now menu uses absolute coordinates - uiStatic.cursorX = x; - uiStatic.cursorY = y; - - if( UI_CursorInRect( 1, 1, ScreenWidth - 1, ScreenHeight - 1 )) - uiStatic.mouseInRect = true; - else uiStatic.mouseInRect = false; - - uiStatic.cursorX = bound( 0, uiStatic.cursorX, ScreenWidth ); - uiStatic.cursorY = bound( 0, uiStatic.cursorY, ScreenHeight ); - - if( clientActive && !menuActive ) - uiStatic.client.MouseEvent( x, y ); - - if( menuActive ) - uiStatic.menu.MouseEvent( x, y ); -} - - -/* -================= -UI_SetActiveMenu -================= -*/ -void UI_SetActiveMenu( int fActive ) -{ - if( !uiStatic.initialized ) - return; - - // don't continue firing if we leave game - EngFuncs::KEY_ClearStates(); - - if( fActive ) - { - EngFuncs::KEY_SetDest( KEY_MENU ); - uiStatic.nextFrameActive = true; // main menu open moved to UI_UpdateMenu - } - else - { - UI_CloseMenu(); - uiStatic.nextFrameActive = false; // don't call main menu next frame - } -} - -/* -================= -UI_IsVisible - -Some systems may need to know if it is visible or not -================= -*/ -int UI_IsVisible( void ) -{ - if( !uiStatic.initialized ) - return false; - return uiStatic.menu.IsActive(); -} - -void UI_GetCursorPos( int *pos_x, int *pos_y ) -{ - if( pos_x ) *pos_x = uiStatic.cursorX; - if( pos_y ) *pos_y = uiStatic.cursorY; -} - -// dead callback -void UI_SetCursorPos( int pos_x, int pos_y ) -{ - (void)(pos_x); - (void)(pos_y); - uiStatic.mouseInRect = true; -} - -void UI_ShowCursor( int show ) -{ - uiStatic.hideCursor = (show) ? false : true; -} - -int UI_MouseInRect( void ) -{ - return uiStatic.mouseInRect; -} - -/* -================= -UI_Precache -================= -*/ -void UI_Precache( void ) -{ - if( !uiStatic.initialized ) - return; - - EngFuncs::PIC_Load( UI_LEFTARROW ); - EngFuncs::PIC_Load( UI_LEFTARROWFOCUS ); - EngFuncs::PIC_Load( UI_RIGHTARROW ); - EngFuncs::PIC_Load( UI_RIGHTARROWFOCUS ); - EngFuncs::PIC_Load( UI_UPARROW ); - EngFuncs::PIC_Load( UI_UPARROWFOCUS ); - EngFuncs::PIC_Load( UI_DOWNARROW ); - EngFuncs::PIC_Load( UI_DOWNARROWFOCUS ); - EngFuncs::PIC_Load( "gfx/shell/splash" ); - - // load all menu buttons - uiStatic.btns.LoadBmpButtons(); - - // all menu buttons have the same view sizes - if( uiStatic.btns.GetWidth() == 0 || uiStatic.btns.GetHeight() == 0 ) - uiStatic.buttons_draw_size = Size( UI_BUTTONS_WIDTH, UI_BUTTONS_HEIGHT ); - else - uiStatic.buttons_draw_size = Size( uiStatic.btns.GetWidth() * 1024 / 640, uiStatic.btns.GetHeight() * 768 / 480 ); - - for( CMenuEntry *entry = s_pEntries; entry; entry = entry->m_pNext ) - { - if( entry->m_pfnPrecache ) - entry->m_pfnPrecache(); - } -} - -void UI_ParseColor( char *&pfile, unsigned int *outColor ) -{ - int color[3] = { 0xFF, 0xFF, 0xFF }; - char token[1024]; - - for( int i = 0; i < 3; i++ ) - { - pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token )); - if( !pfile ) break; - color[i] = atoi( token ); - } - - *outColor = PackRGB( color[0], color[1], color[2] ); -} - -void UI_ApplyCustomColors( void ) -{ - char *afile = (char *)EngFuncs::COM_LoadFile( "gfx/shell/colors.lst" ); - char *pfile = afile; - char token[1024]; - - if( !afile ) - { - // not error, not warning, just notify - Con_Printf( "UI_ApplyCustomColors: colors.lst not found\n" ); - return; - } - - while(( pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ))) != NULL ) - { - if( !stricmp( token, "HELP_COLOR" )) - { - UI_ParseColor( pfile, &uiColorHelp ); - } - else if( !stricmp( token, "PROMPT_BG_COLOR" )) - { - UI_ParseColor( pfile, &uiPromptBgColor ); - } - else if( !stricmp( token, "PROMPT_TEXT_COLOR" )) - { - UI_ParseColor( pfile, &uiPromptTextColor ); - } - else if( !stricmp( token, "PROMPT_FOCUS_COLOR" )) - { - UI_ParseColor( pfile, &uiPromptFocusColor ); - } - else if( !stricmp( token, "INPUT_TEXT_COLOR" )) - { - UI_ParseColor( pfile, &uiInputTextColor ); - } - else if( !stricmp( token, "INPUT_BG_COLOR" )) - { - UI_ParseColor( pfile, &uiInputBgColor ); - } - else if( !stricmp( token, "INPUT_FG_COLOR" )) - { - UI_ParseColor( pfile, &uiInputFgColor ); - } - else if( !stricmp( token, "CON_TEXT_COLOR" )) - { - UI_ParseColor( pfile, &uiColorConsole ); - } - } - - int r, g, b; - - UnpackRGB( r, g, b, uiColorConsole ); - EngFuncs::SetConsoleDefaultColor( r, g, b ); - - EngFuncs::COM_FreeFile( afile ); -} - -static void UI_LoadBackgroundMapList( void ) -{ - if( !EngFuncs::FileExists( "scripts/chapterbackgrounds.txt", true )) - return; - - char *afile = (char *)EngFuncs::COM_LoadFile( "scripts/chapterbackgrounds.txt", NULL ); - char *pfile = afile; - char token[1024]; - - if( !afile ) - { - Con_Printf( "UI_LoadBackgroundMapList: chapterbackgrounds.txt not found\n" ); - return; - } - - while(( pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ))) != NULL ) - { - // skip the numbers (old format list) - if( isdigit( token[0] )) continue; - - uiStatic.bgmaps.AddToTail( token ); - } - - EngFuncs::COM_FreeFile( afile ); -} - -static void UI_LoadSounds( void ) -{ - memset( uiStatic.sounds, 0, sizeof( uiStatic.sounds ) ); - - if ( uiStatic.lowmemory ) - return; - - for ( int i = 0; i < SND_COUNT; i++ ) - { - if ( !uiSounds[i] || *uiSounds[i] == '\0' ) - continue; - - if ( !EngFuncs::FileExists( uiSounds[i] ) ) - { - size_t len = strlen( uiSoundOldPrefix ); - - if ( !strncmp( uiSounds[i], uiSoundOldPrefix, len ) ) - snprintf( uiStatic.sounds[i], sizeof( uiStatic.sounds[i] ), "%s%s", uiSoundNewPrefix, uiSounds[i] + len ); - } - else - Q_strncpy( uiStatic.sounds[i], uiSounds[i], sizeof( uiStatic.sounds[i] ) ); - } -} - -/* -================= -UI_VidInit -================= -*/ - - -int UI_VidInit( void ) -{ - static bool calledOnce = false; - if( uiStatic.textInput ) - { - uiStatic.menu.InputMethodResized(); - - return 0; - } - - if( !calledOnce ) - { - UI_Precache(); - } - - UI_UpdateWindowInsets(); - float width = ScreenWidth - uiStatic.safeLeft - uiStatic.safeRight; - float height = ScreenHeight - uiStatic.safeTop - uiStatic.safeBottom; - - if( width * 3 < height * 4 ) - { - uiStatic.scaleX = uiStatic.scaleY = width / 1024.0f; - uiStatic.yOffset = height / ( 2.0f * uiStatic.scaleY ) - 768.0f / 2.0f; - } - else - { - uiStatic.scaleX = uiStatic.scaleY = height / 768.0f; - uiStatic.yOffset = 0; - } - - uiStatic.xOffset = uiStatic.safeLeft / uiStatic.scaleX; - uiStatic.yOffset += uiStatic.safeTop / uiStatic.scaleY; - uiStatic.width = width / uiStatic.scaleX; - // move cursor to screen center - uiStatic.cursorX = ScreenWidth / 2; - uiStatic.cursorY = ScreenHeight / 2; - uiStatic.outlineWidth = 4; - - UI_ScaleCoords( NULL, NULL, &uiStatic.outlineWidth, NULL ); - - // trying to load chapterbackgrounds.txt - UI_LoadBackgroundMapList (); - - // VidInit FontManager - g_FontMgr->VidInit(); - - // load button sounds - UI_LoadSounds(); - - // init global background, root windows don't have background anymore - if( !uiStatic.background ) - uiStatic.background = new CMenuBackgroundBitmap(); - uiStatic.background->VidInit(); - - uiStatic.menu.VidInit( calledOnce ); - - if( !calledOnce ) calledOnce = true; - - return 1; -} - -void UI_OpenUpdatePage( bool engine, bool preferstore ) -{ - const char *updateUrl = NULL; - - if( engine || !gMenu.m_gameinfo.update_url[0] ) - { - if( preferstore ) - updateUrl = PLATFORM_UPDATE_PAGE; - else - updateUrl = GENERIC_UPDATE_PAGE; - } - else - { - updateUrl = gMenu.m_gameinfo.update_url; - } - - if( updateUrl ) - EngFuncs::ShellExecute( updateUrl, NULL, true ); -} - -void UI_UpdateDialog( int preferStore ) -{ - static CMenuYesNoMessageBox msgBox; - static bool ignore = false; - static bool staticPreferStore; - - if( ignore ) - return; - - staticPreferStore = preferStore != 0; - - msgBox.SetMessage( "A new update is available.\nPress Update to open download page." ); - msgBox.SetPositiveButton( "Update", PC_UPDATE ); - msgBox.SetNegativeButton( "Later", PC_CANCEL ); - - SET_EVENT( msgBox.onPositive, UI_OpenUpdatePage( true, *(bool*)pExtra ) ); - msgBox.onPositive.pExtra = &staticPreferStore; - - SET_EVENT( msgBox.onNegative, *(bool*)pExtra = true ); // set ignore - msgBox.onNegative.pExtra = &ignore; - - msgBox.Show(); - -} - -static void UI_UpdateDialog_f( void ) -{ - if( !strcmp( EngFuncs::CmdArgv( 1 ), "nostore" )) - UI_UpdateDialog( false ); - else - UI_UpdateDialog( true ); -} - -ADD_COMMAND( menu_updatedialog, UI_UpdateDialog_f ); - -/* -================= -UI_Init -================= -*/ -void UI_Init( void ) -{ - // register our cvars and commands - ui_showmodels = EngFuncs::CvarRegister( "ui_showmodels", "0", FCVAR_ARCHIVE ); - ui_showclassmodels = EngFuncs::CvarRegister( "ui_showclassmodels", "1", FCVAR_ARCHIVE ); - ui_show_window_stack = EngFuncs::CvarRegister( "ui_show_window_stack", "0", FCVAR_ARCHIVE ); - ui_borderclip = EngFuncs::CvarRegister( "ui_borderclip", "0", FCVAR_ARCHIVE ); - ui_prefer_won_background = EngFuncs::CvarRegister( "ui_prefer_won_background", "0", FCVAR_ARCHIVE ); - ui_background_stretch = EngFuncs::CvarRegister( "ui_background_stretch", "0", FCVAR_ARCHIVE ); - ui_logohorizontal = EngFuncs::CvarRegister( "ui_logohorizontal", "0", FCVAR_ARCHIVE ); - - // show cl_predict dialog - EngFuncs::CvarRegister( "menu_mp_firsttime2", "1", FCVAR_ARCHIVE ); - - // autofill ammo after bought weapon - EngFuncs::CvarRegister( "ui_cs_autofill", "0", FCVAR_ARCHIVE ); - - for( CMenuEntry *entry = s_pEntries; entry; entry = entry->m_pNext ) - { - if( entry->m_szCommand && entry->m_pfnShow ) - { - EngFuncs::Cmd_AddCommand( entry->m_szCommand, entry->m_pfnShow ); - } - } - - g_FontMgr = new CFontManager(); - - uiStatic.initialized = true; - uiStatic.lowmemory = (int)EngFuncs::GetCvarFloat( "host_lowmemorymode" ); - - // setup game info - gameinfo2_t *gi = EngFuncs::GetGameInfo(); - if( !gi ) - Host_Error( "pfnGetGameInfo returned NULL!\n" ); - - gMenu.m_gameinfo = *gi; - - uiStatic.renderPicbuttonText = gMenu.m_gameinfo.flags & GFL_RENDER_PICBUTTON_TEXT; - - // trying to load colors.lst - UI_ApplyCustomColors (); -} - -/* -================= -UI_Shutdown -================= -*/ -void UI_Shutdown( void ) -{ - if( !uiStatic.initialized ) - return; - - for( CMenuEntry *entry = s_pEntries; entry; entry = entry->m_pNext ) - { - if( entry->m_szCommand && entry->m_pfnShow ) - { - EngFuncs::Cmd_RemoveCommand( entry->m_szCommand ); - } - - if( entry->m_pfnShutdown ) - { - entry->m_pfnShutdown(); - } - } - - UI_FreeCustomStrings(); - - delete uiStatic.background; - delete g_FontMgr; - - memset( &uiStatic, 0, sizeof( uiStatic_t )); -} +/* +ui_menu.c -- main menu interface +Copyright (C) 1997-2001 Id Software, Inc. +Copyright (C) 2017 a1batross + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +*/ +#include "extdll_menu.h" +#include "BaseMenu.h" +#include "PicButton.h" +#include "keydefs.h" +#include "Utils.h" +#include "Btns.h" +#include "YesNoMessageBox.h" +#include "BackgroundBitmap.h" +#include "FontManager.h" +#include "cursor_type.h" +#include "utflib.h" + +cvar_t *ui_showmodels; +cvar_t *ui_showclassmodels; +cvar_t *ui_show_window_stack; +cvar_t *ui_borderclip; +cvar_t *ui_prefer_won_background; +cvar_t *ui_background_stretch; +cvar_t *ui_logohorizontal; + +uiStatic_t uiStatic; +static CMenuEntry *s_pEntries = NULL; + +const char *uiSoundOldPrefix = "media/"; +const char *uiSoundNewPrefix = "sound/common/"; +const char *uiSounds[] = { + "media/launch_upmenu1.wav", + "media/launch_dnmenu1.wav", + "media/launch_select2.wav", + "", + "media/launch_glow1.wav", + "media/launch_deny2.wav", + "media/launch_select1.wav", + "media/launch_deny1.wav", + "", + "" +}; + +// they match default WON colors.lst now, except alpha +// a1ba: made uiColorHelp brighter so it's easier to read +unsigned int uiColorHelp = 0xFFA0A0A0; // 160, 160, 160, 255 // hint letters color +unsigned int uiPromptBgColor = 0xFF383838; // 56, 56, 56, 255 // dialog background color +unsigned int uiPromptTextColor = 0xFFF0B418; // 240, 180, 24, 255 // dialog or button letters color +unsigned int uiPromptFocusColor = 0xFFFFFF00; // 255, 255, 0, 255 // dialog or button focus letters color +unsigned int uiInputTextColor = 0xFFF0B418; // 240, 180, 24, 255 +unsigned int uiInputBgColor = 0x80383838; // 56, 56, 56, 128 // field, scrollist, checkbox background color +unsigned int uiInputFgColor = 0xFF555555; // 85, 85, 85, 255 // field, scrollist, checkbox foreground color +unsigned int uiColorWhite = 0xFFFFFFFF; // 255, 255, 255, 255 // useful for bitmaps +unsigned int uiColorDkGrey = 0x80404040; // 64, 64, 64, 128 // shadow and grayed items +unsigned int uiColorBlack = 0x80000000; // 0, 0, 0, 128 // some controls background +unsigned int uiColorConsole = 0xFFF0B418; // just for reference + +// color presets (this is nasty hack to allow color presets to part of text) +const unsigned int g_iColorTable[8] = +{ +0xFF000000, // black +0xFFFF0000, // red +0xFF00FF00, // green +0xFFFFFF00, // yellow +0xFF0000FF, // blue +0xFF00FFFF, // cyan +0xFFF0B418, // dialog or button letters color +0xFFFFFFFF, // white +}; + +CMenuEntry::CMenuEntry(const char *cmd, void (*pfnPrecache)(), void (*pfnShow)(), void (*pfnShutdown)() ) : + m_szCommand( cmd ), + m_pfnPrecache( pfnPrecache ), + m_pfnShow( pfnShow ), + m_pfnShutdown( pfnShutdown ), + m_pNext( s_pEntries ) +{ + s_pEntries = this; +} + +/* +================= +UI_ScaleCoords + +Any parameter can be NULL if you don't want it +================= +*/ +void UI_ScaleCoords( int *x, int *y, int *w, int *h ) +{ + if( x ) *x *= uiStatic.scaleX; + if( y ) *y *= uiStatic.scaleY; + if( w ) *w *= uiStatic.scaleX; + if( h ) *h *= uiStatic.scaleY; +} + +void UI_ScaleCoords( int &x, int &y ) +{ + x *= uiStatic.scaleX; + y *= uiStatic.scaleY; +} + +void UI_ScaleCoords( int &x, int &y, int &w, int &h ) +{ + UI_ScaleCoords( x, y ); + UI_ScaleCoords( w, h ); +} + +Point Point::Scale() +{ + return Point( x * uiStatic.scaleX, y * uiStatic.scaleY ); +} + +Size Size::Scale() +{ + return Size( w * uiStatic.scaleX, h * uiStatic.scaleY ); +} + +/* +================= +UI_CursorInRect +================= +*/ +bool UI_CursorInRect( int x, int y, int w, int h ) +{ + if( uiStatic.cursorX < x || uiStatic.cursorX > x + w ) + return false; + if( uiStatic.cursorY < y || uiStatic.cursorY > y + h ) + return false; + return true; +} + +/* +================= +UI_EnableAlphaFactor +================= +*/ +void UI_EnableAlphaFactor( float a ) +{ + uiStatic.enableAlphaFactor = true; + uiStatic.alphaFactor = bound( 0.0f, a, 1.0f ); +} + +/* +================= +UI_DisableAlphaFactor +================= +*/ +void UI_DisableAlphaFactor() +{ + uiStatic.enableAlphaFactor = false; +} + +/* +================= +UI_DrawPic +================= +*/ +void UI_DrawPic( int x, int y, int width, int height, const unsigned int color, CImage &pic, const ERenderMode eRenderMode ) +{ + HIMAGE hPic = pic.Handle(); + + if( !hPic ) + return; + + int r, g, b, a; + UnpackRGBA( r, g, b, a, color ); + + EngFuncs::PIC_Set( hPic, r, g, b, a ); + switch( eRenderMode ) + { + case QM_DRAWNORMAL: + if( !uiStatic.enableAlphaFactor ) + { + EngFuncs::PIC_Draw( x, y, width, height ); + break; + } + // intentional fallthrough + case QM_DRAWTRANS: + EngFuncs::PIC_DrawTrans( x, y, width, height ); + break; + case QM_DRAWADDITIVE: + EngFuncs::PIC_DrawAdditive( x, y, width, height ); + break; + case QM_DRAWHOLES: + EngFuncs::PIC_DrawHoles( x, y, width, height ); + break; + } +} + +/* +================= +UI_FillRect +================= +*/ +void UI_FillRect( int x, int y, int width, int height, const unsigned int color ) +{ + int r, g, b, a; + UnpackRGBA( r, g, b, a, color ); + + EngFuncs::FillRGBA( x, y, width, height, r, g, b, a ); +} + +/* +================= +UI_DrawRectangleExt +================= +*/ +void UI_DrawRectangleExt( int in_x, int in_y, int in_w, int in_h, const unsigned int color, int outlineWidth, int flag ) +{ + int x, y, w, h; + + if( outlineWidth == 0 ) outlineWidth = uiStatic.outlineWidth; + + if( flag & QM_LEFT ) + { + x = in_x - outlineWidth; + y = in_y - outlineWidth; + w = outlineWidth; + h = in_h + outlineWidth + outlineWidth; + + // draw left + UI_FillRect( x, y, w, h, color ); + } + + if( flag & QM_RIGHT ) + { + x = in_x + in_w; + y = in_y - outlineWidth; + w = outlineWidth; + h = in_h + outlineWidth + outlineWidth; + + // draw right + UI_FillRect( x, y, w, h, color ); + } + + if( flag & QM_TOP ) + { + x = in_x; + y = in_y - outlineWidth; + w = in_w; + h = outlineWidth; + + // draw top + UI_FillRect( x, y, w, h, color ); + } + + if( flag & QM_BOTTOM ) + { + // draw bottom + x = in_x; + y = in_y + in_h; + w = in_w; + h = outlineWidth; + + UI_FillRect( x, y, w, h, color ); + } +} + +/* +================= +UI_DrawString +================= +*/ +int UI_DrawString( HFont font, int x, int y, int w, int h, + const char *string, const unsigned int color, + int charH, uint justify, uint flags ) +{ + uint modulate, shadowModulate = 0; + int xx = 0, yy, shadowOffset = 0, ch; + int maxX = x; + + if( !string || !string[0] ) + return x; + + if( flags & ETF_SHADOW ) + { + shadowModulate = PackAlpha( uiColorBlack, UnpackAlpha( color )); + shadowOffset = Q_max( 1, uiStatic.scaleX * 3 ); + } + + modulate = color; + + if( justify & QM_TOP ) + { + yy = y; + h -= h % charH; + } + else if( justify & QM_BOTTOM ) + { + yy = y + h - charH; + h -= h % charH; + } + else + { + yy = y + (h - charH)/2; + h -= charH; + } + + if( flags & ETF_NO_WRAP ) + h = charH; + + int i = 0; + int ellipsisWide = g_FontMgr->GetEllipsisWide( font ); + bool giveup = false; + + while( string[i] && !giveup ) + { + char line[1024], *l; + int j = i, len = 0; + int pixelWide = 0; + int save_pixelWide = 0; + int save_j = 0; + utfstate_t state; + + while( string[j] ) + { + if( string[j] == '\n' ) + { + j++; + break; + } + + if( len == sizeof( line ) - 1 ) + break; + + line[len] = string[j]; + + uint32_t uch = state.Decode((uint8_t)string[j] ); + + if( IsColorString( string + j )) // don't calc wides for colorstrings + { + line[len+1] = string[j+1]; + len += 2; + j += 2; + } + else if( !uch ) // don't calc wides for invalid codepoints + { + len++; + j++; + } + else + { + int charWide; + + // does we have free space for new line? + if( yy < (y + h) - charH ) + { + if( uch == ' ' && pixelWide < w ) // remember last whitespace + { + save_pixelWide = pixelWide; + save_j = j; + } + } + else + { + // remember last position, when we still fit + if( pixelWide + ellipsisWide < w && j > 0 ) + { + save_pixelWide = pixelWide; + save_j = j; + } + } + + charWide = g_FontMgr->GetCharacterWidthScaled( font, uch, charH ); + + if( !(flags & ETF_NOSIZELIMIT) && pixelWide + charWide > w ) + { + // do we have free space for new line? + if( yy < (y + h) - charH ) + { + // try to word wrap + if( save_j != 0 && save_pixelWide != 0 ) + { + pixelWide = save_pixelWide; + len -= j - save_j; // skip whitespace + j = save_j + 1; // skip whitespace + } + + break; + } + else + { + + if( save_j != 0 && save_pixelWide != 0 ) + { + pixelWide = save_pixelWide; + len -= j - save_j; + j = save_j; + + + if( len > 0 ) + { + line[len] = '.'; + line[len+1] = '.'; + line[len+2] = '.'; + len += 3; + } + } + + // we don't have free space anymore, so just stop drawing + giveup = true; + + break; + } + } + else + { + pixelWide += charWide; + j++; + len++; + } + } + } + line[len] = 0; + + // align the text as appropriate + if( justify & QM_LEFT ) + { + xx = x; + } + else if( justify & QM_RIGHT ) + { + xx = x + (w - pixelWide); + } + else // QM_LEFT + { + xx = x + (w - pixelWide) / 2.0f; + } + + // draw it + l = line; + state.Reset(); + while( *l ) + { + if( IsColorString( l )) + { + int colorNum = ColorIndex( *(l+1) ); + + if( colorNum == 7 && color != 0 ) + { + modulate = color; + } + else if( !(flags & ETF_FORCECOL) ) + { + modulate = PackAlpha( g_iColorTable[colorNum], UnpackAlpha( color )); + } + + l += 2; + continue; + } + + ch = *l++; + ch &= 255; + +// when using custom font render, we use utf-8 + ch = state.Decode((uint8_t)ch ); + if( !ch ) + continue; + + if( flags & ETF_SHADOW ) + g_FontMgr->DrawCharacter( font, ch, Point( xx + shadowOffset, yy + shadowOffset ), charH, shadowModulate, flags & ETF_ADDITIVE ); + +#ifdef DEBUG_WHITESPACE + if( ch == ' ' ) + { + g_FontMgr->DrawCharacter( font, '_', Point( xx, yy ), charH, modulate, flags & ETF_ADDITIVE ); + xx += g_FontMgr->GetCharacterWidthScaled( font, ch, charH ); + continue; + } +#endif + + xx += g_FontMgr->DrawCharacter( font, ch, Point( xx, yy ), charH, modulate, flags & ETF_ADDITIVE ); + + maxX = Q_max( xx, maxX ); + } + yy += charH; + + i = j; + } + + return maxX; +} + +/* +================= +UI_DrawMouseCursor +================= +*/ +void UI_DrawMouseCursor( void ) +{ + CMenuBaseItem *item; + void *hCursor = (void *)dc_arrow; + int cursor = uiStatic.menu.Current()->GetCursor(); + item = uiStatic.menu.Current()->GetItemByIndex( cursor ); + + if( item && FBitSet( item->iFlags, QMF_HASMOUSEFOCUS )) // fast approach + { + if( FBitSet( item->iFlags, QMF_GRAYED )) + hCursor = (void *)dc_no; + else hCursor = (void *)item->CursorAction(); + } + else + { + FOR_EACH_VEC( uiStatic.menu.Current()->m_pItems, i ) + { + item = (CMenuBaseItem *)uiStatic.menu.Current()->GetItemByIndex(cursor); + + if( !item->IsVisible( )) + continue; + + if( !FBitSet( item->iFlags, QMF_HASMOUSEFOCUS )) + continue; + + if( FBitSet( item->iFlags, QMF_GRAYED )) + hCursor = (void *)dc_no; + else hCursor = (void *)item->CursorAction(); + + break; + } + } + + EngFuncs::SetCursor( hCursor ); +} + +// ===================================================================== + +/* +================= +UI_StartBackGroundMap +================= +*/ +bool UI_StartBackGroundMap( void ) +{ + static int check_dll; + + // the list is empty + if( uiStatic.bgmaps.IsEmpty()) + return false; + + // check if server dll available only once, as it might be implemented + // very inefficiently + if( !check_dll ) + { + if( EngFuncs::CheckGameDll( )) + check_dll = 1; + else + check_dll = -1; + } + + if( check_dll < 0 ) + return false; + + // some map is already running + if( CL_IsActive() || EngFuncs::GetCvarFloat( "cl_background" ) != 0.0f || gpGlobals->demoplayback ) + return false; + + int bgmapid = EngFuncs::RandomLong( 0, uiStatic.bgmaps.Count() - 1 ); + + char cmd[128]; + snprintf( cmd, sizeof( cmd ), "maps/%s.bsp", uiStatic.bgmaps[bgmapid].Get( )); + if( !EngFuncs::FileExists( cmd, true )) + return false; + + snprintf( cmd, sizeof( cmd ), "map_background %s\n", uiStatic.bgmaps[bgmapid].Get( )); + EngFuncs::ClientCmd( false, cmd ); + + return true; +} + +// ===================================================================== + +/* +================= +UI_CloseMenu +================= +*/ +void UI_CloseMenu( void ) +{ + uiStatic.menu.Clean(); + +// EngFuncs::KEY_ClearStates (); + if( !uiStatic.client.IsActive() ) + EngFuncs::KEY_SetDest( KEY_GAME ); +} + +void UI_CloseClientMenu( void ) +{ + if( !uiStatic.client.IsActive() ) + return; + + uiStatic.client.Clean(); + EngFuncs::KEY_ClearStates(); + EngFuncs::KEY_SetDest( KEY_GAME ); + EngFuncs::ClientCmd( false, "touch_setclientonly 0" ); +} + +// ===================================================================== + + +static bool UI_UpdateWindowInsets( void ) +{ + const float *insets = NULL; + int left = 0, top = 0, right = 0, bottom = 0; + + if( EngFuncs::textfuncs.pfnGetNativeObject ) + insets = (const float *)EngFuncs::textfuncs.pfnGetNativeObject( "WindowInsets" ); + if( insets ) + { + left = ceilf( ScreenWidth * insets[0] ); + top = ceilf( ScreenHeight * insets[1] ); + right = ceilf( ScreenWidth * insets[2] ); + bottom = ceilf( ScreenHeight * insets[3] ); + } + bool changed = left != uiStatic.safeLeft || top != uiStatic.safeTop || + right != uiStatic.safeRight || bottom != uiStatic.safeBottom; + uiStatic.safeLeft = left; + uiStatic.safeTop = top; + uiStatic.safeRight = right; + uiStatic.safeBottom = bottom; + return changed; +} + +/* +================= +UI_UpdateMenu +================= +*/ +void UI_UpdateMenu( float flTime ) +{ + if( !uiStatic.initialized ) + return; + + if( UI_UpdateWindowInsets() ) + UI_VidInit(); + + static bool loadStuff = true; + + // can't do this in Init, since these are dependent on cvar values + // set from user configs + if( loadStuff ) + { + // load background bitmaps + CMenuBackgroundBitmap::LoadBackground( ); + + // load localized strings + UI_LoadCustomStrings(); + + // load scr + UI_LoadScriptConfig(); + + loadStuff = false; + } + + UI_DrawFinalCredits (); + + // also moved opening main menu here from SetActiveMenu, so + // translation strings could will be loaded at this moment + if( uiStatic.nextFrameActive ) + { + if( !uiStatic.menu.IsActive() ) + UI_Main_Menu(); + + uiStatic.nextFrameActive = false; + } + + // advance global time + uiStatic.realTime = flTime * 1000; + + // let's use engine credits "feature" for drawing client windows + if( uiStatic.client.IsActive( )) + uiStatic.client.Update(); + + if( !uiStatic.menu.IsActive( )) + return; + + if( !EngFuncs::ClientInGame() && EngFuncs::GetCvarFloat( "cl_background" ) != 0.0f ) + return; // don't draw menu while level is loading + + if( uiStatic.firstDraw ) + { + static bool first = true; + + if( first ) + { + first = false; + + // we loading background so skip SCR_Update + if( UI_StartBackGroundMap( )) + return; + + // load background track + if( !CL_IsActive( )) + EngFuncs::PlayBackgroundTrack( "media/gamestartup", "media/gamestartup" ); + } + + uiStatic.firstDraw = false; + } + + // draw cursor + UI_DrawMouseCursor(); + + // background doesn't need to be drawn with transparency + bool enableAlphaFactor = uiStatic.enableAlphaFactor; + uiStatic.enableAlphaFactor = false; + uiStatic.background->Draw(); + uiStatic.enableAlphaFactor = enableAlphaFactor; + + uiStatic.menu.Update(); +} + +/* +================= +UI_KeyEvent +================= +*/ +void UI_KeyEvent( int key, int down ) +{ + bool clientActive, menuActive; + + if( !uiStatic.initialized ) + return; + + if( key == K_MOUSE1 ) + { + g_bCursorDown = !!down; + } + + clientActive = uiStatic.client.IsActive(); + menuActive = uiStatic.menu.IsActive(); + + if( clientActive && !menuActive ) + down ? uiStatic.client.KeyDownEvent( key ) : + uiStatic.client.KeyUpEvent( key ); + + if( menuActive ) + down ? uiStatic.menu.KeyDownEvent( key ) : + uiStatic.menu.KeyUpEvent( key ); +} + +/* +================= +UI_CharEvent +================= +*/ +void UI_CharEvent( int key ) +{ + if( !uiStatic.initialized ) + return; + + bool clientActive = uiStatic.client.IsActive(); + bool menuActive = uiStatic.menu.IsActive(); + + if( clientActive && !menuActive ) + uiStatic.client.CharEvent( key ); + + if( menuActive ) + uiStatic.menu.CharEvent( key ); +} + +bool g_bCursorDown; +float cursorDY; + +/* +================= +UI_MouseMove +================= +*/ +void UI_MouseMove( int x, int y ) +{ + bool clientActive, menuActive; + + if( !uiStatic.initialized ) + return; + + clientActive = uiStatic.client.IsActive(); + menuActive = uiStatic.menu.IsActive(); + + if( !clientActive && !menuActive ) + return; + + if( uiStatic.cursorX == x && uiStatic.cursorY == y ) + return; + + if( g_bCursorDown ) + { + static bool prevDown = false; + + if( !prevDown ) + { + prevDown = true; + cursorDY = 0; + } + else if( y - uiStatic.cursorY ) + { + cursorDY += y - uiStatic.cursorY; + } + } + else + cursorDY = 0; + //Con_Printf("%d %d %f\n",x, y, cursorDY); + + // now menu uses absolute coordinates + uiStatic.cursorX = x; + uiStatic.cursorY = y; + + if( UI_CursorInRect( 1, 1, ScreenWidth - 1, ScreenHeight - 1 )) + uiStatic.mouseInRect = true; + else uiStatic.mouseInRect = false; + + uiStatic.cursorX = bound( 0, uiStatic.cursorX, ScreenWidth ); + uiStatic.cursorY = bound( 0, uiStatic.cursorY, ScreenHeight ); + + if( clientActive && !menuActive ) + uiStatic.client.MouseEvent( x, y ); + + if( menuActive ) + uiStatic.menu.MouseEvent( x, y ); +} + + +/* +================= +UI_SetActiveMenu +================= +*/ +void UI_SetActiveMenu( int fActive ) +{ + if( !uiStatic.initialized ) + return; + + // don't continue firing if we leave game + EngFuncs::KEY_ClearStates(); + + if( fActive ) + { + EngFuncs::KEY_SetDest( KEY_MENU ); + uiStatic.nextFrameActive = true; // main menu open moved to UI_UpdateMenu + } + else + { + UI_CloseMenu(); + uiStatic.nextFrameActive = false; // don't call main menu next frame + } +} + +/* +================= +UI_IsVisible + +Some systems may need to know if it is visible or not +================= +*/ +int UI_IsVisible( void ) +{ + if( !uiStatic.initialized ) + return false; + return uiStatic.menu.IsActive(); +} + +void UI_GetCursorPos( int *pos_x, int *pos_y ) +{ + if( pos_x ) *pos_x = uiStatic.cursorX; + if( pos_y ) *pos_y = uiStatic.cursorY; +} + +// dead callback +void UI_SetCursorPos( int pos_x, int pos_y ) +{ + (void)(pos_x); + (void)(pos_y); + uiStatic.mouseInRect = true; +} + +void UI_ShowCursor( int show ) +{ + uiStatic.hideCursor = (show) ? false : true; +} + +int UI_MouseInRect( void ) +{ + return uiStatic.mouseInRect; +} + +/* +================= +UI_Precache +================= +*/ +void UI_Precache( void ) +{ + if( !uiStatic.initialized ) + return; + + EngFuncs::PIC_Load( UI_LEFTARROW ); + EngFuncs::PIC_Load( UI_LEFTARROWFOCUS ); + EngFuncs::PIC_Load( UI_RIGHTARROW ); + EngFuncs::PIC_Load( UI_RIGHTARROWFOCUS ); + EngFuncs::PIC_Load( UI_UPARROW ); + EngFuncs::PIC_Load( UI_UPARROWFOCUS ); + EngFuncs::PIC_Load( UI_DOWNARROW ); + EngFuncs::PIC_Load( UI_DOWNARROWFOCUS ); + EngFuncs::PIC_Load( "gfx/shell/splash" ); + + // load all menu buttons + uiStatic.btns.LoadBmpButtons(); + + // all menu buttons have the same view sizes + if( uiStatic.btns.GetWidth() == 0 || uiStatic.btns.GetHeight() == 0 ) + uiStatic.buttons_draw_size = Size( UI_BUTTONS_WIDTH, UI_BUTTONS_HEIGHT ); + else + uiStatic.buttons_draw_size = Size( uiStatic.btns.GetWidth() * 1024 / 640, uiStatic.btns.GetHeight() * 768 / 480 ); + + for( CMenuEntry *entry = s_pEntries; entry; entry = entry->m_pNext ) + { + if( entry->m_pfnPrecache ) + entry->m_pfnPrecache(); + } +} + +void UI_ParseColor( char *&pfile, unsigned int *outColor ) +{ + int color[3] = { 0xFF, 0xFF, 0xFF }; + char token[1024]; + + for( int i = 0; i < 3; i++ ) + { + pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token )); + if( !pfile ) break; + color[i] = atoi( token ); + } + + *outColor = PackRGB( color[0], color[1], color[2] ); +} + +void UI_ApplyCustomColors( void ) +{ + char *afile = (char *)EngFuncs::COM_LoadFile( "gfx/shell/colors.lst" ); + char *pfile = afile; + char token[1024]; + + if( !afile ) + { + // not error, not warning, just notify + Con_Printf( "UI_ApplyCustomColors: colors.lst not found\n" ); + return; + } + + while(( pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ))) != NULL ) + { + if( !stricmp( token, "HELP_COLOR" )) + { + UI_ParseColor( pfile, &uiColorHelp ); + } + else if( !stricmp( token, "PROMPT_BG_COLOR" )) + { + UI_ParseColor( pfile, &uiPromptBgColor ); + } + else if( !stricmp( token, "PROMPT_TEXT_COLOR" )) + { + UI_ParseColor( pfile, &uiPromptTextColor ); + } + else if( !stricmp( token, "PROMPT_FOCUS_COLOR" )) + { + UI_ParseColor( pfile, &uiPromptFocusColor ); + } + else if( !stricmp( token, "INPUT_TEXT_COLOR" )) + { + UI_ParseColor( pfile, &uiInputTextColor ); + } + else if( !stricmp( token, "INPUT_BG_COLOR" )) + { + UI_ParseColor( pfile, &uiInputBgColor ); + } + else if( !stricmp( token, "INPUT_FG_COLOR" )) + { + UI_ParseColor( pfile, &uiInputFgColor ); + } + else if( !stricmp( token, "CON_TEXT_COLOR" )) + { + UI_ParseColor( pfile, &uiColorConsole ); + } + } + + int r, g, b; + + UnpackRGB( r, g, b, uiColorConsole ); + EngFuncs::SetConsoleDefaultColor( r, g, b ); + + EngFuncs::COM_FreeFile( afile ); +} + +static void UI_LoadBackgroundMapList( void ) +{ + if( !EngFuncs::FileExists( "scripts/chapterbackgrounds.txt", true )) + return; + + char *afile = (char *)EngFuncs::COM_LoadFile( "scripts/chapterbackgrounds.txt", NULL ); + char *pfile = afile; + char token[1024]; + + if( !afile ) + { + Con_Printf( "UI_LoadBackgroundMapList: chapterbackgrounds.txt not found\n" ); + return; + } + + while(( pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ))) != NULL ) + { + // skip the numbers (old format list) + if( isdigit( token[0] )) continue; + + uiStatic.bgmaps.AddToTail( token ); + } + + EngFuncs::COM_FreeFile( afile ); +} + +static void UI_LoadSounds( void ) +{ + memset( uiStatic.sounds, 0, sizeof( uiStatic.sounds ) ); + + if ( uiStatic.lowmemory ) + return; + + for ( int i = 0; i < SND_COUNT; i++ ) + { + if ( !uiSounds[i] || *uiSounds[i] == '\0' ) + continue; + + if ( !EngFuncs::FileExists( uiSounds[i] ) ) + { + size_t len = strlen( uiSoundOldPrefix ); + + if ( !strncmp( uiSounds[i], uiSoundOldPrefix, len ) ) + snprintf( uiStatic.sounds[i], sizeof( uiStatic.sounds[i] ), "%s%s", uiSoundNewPrefix, uiSounds[i] + len ); + } + else + Q_strncpy( uiStatic.sounds[i], uiSounds[i], sizeof( uiStatic.sounds[i] ) ); + } +} + +/* +================= +UI_VidInit +================= +*/ + + +int UI_VidInit( void ) +{ + static bool calledOnce = false; + if( uiStatic.textInput ) + { + uiStatic.menu.InputMethodResized(); + + return 0; + } + + if( !calledOnce ) + { + UI_Precache(); + } + + UI_UpdateWindowInsets(); + float width = ScreenWidth - uiStatic.safeLeft - uiStatic.safeRight; + float height = ScreenHeight - uiStatic.safeTop - uiStatic.safeBottom; + + if( width * 3 < height * 4 ) + { + uiStatic.scaleX = uiStatic.scaleY = width / 1024.0f; + uiStatic.yOffset = height / ( 2.0f * uiStatic.scaleY ) - 768.0f / 2.0f; + } + else + { + uiStatic.scaleX = uiStatic.scaleY = height / 768.0f; + uiStatic.yOffset = 0; + } + + uiStatic.xOffset = uiStatic.safeLeft / uiStatic.scaleX; + uiStatic.yOffset += uiStatic.safeTop / uiStatic.scaleY; + uiStatic.width = width / uiStatic.scaleX; + // move cursor to screen center + uiStatic.cursorX = ScreenWidth / 2; + uiStatic.cursorY = ScreenHeight / 2; + uiStatic.outlineWidth = 4; + + UI_ScaleCoords( NULL, NULL, &uiStatic.outlineWidth, NULL ); + + // trying to load chapterbackgrounds.txt + UI_LoadBackgroundMapList (); + + // VidInit FontManager + g_FontMgr->VidInit(); + + // load button sounds + UI_LoadSounds(); + + // init global background, root windows don't have background anymore + if( !uiStatic.background ) + uiStatic.background = new CMenuBackgroundBitmap(); + uiStatic.background->VidInit(); + + uiStatic.menu.VidInit( calledOnce ); + + if( !calledOnce ) calledOnce = true; + + return 1; +} + +void UI_OpenUpdatePage( bool engine, bool preferstore ) +{ + const char *updateUrl = NULL; + + if( engine || !gMenu.m_gameinfo.update_url[0] ) + { + if( preferstore ) + updateUrl = PLATFORM_UPDATE_PAGE; + else + updateUrl = GENERIC_UPDATE_PAGE; + } + else + { + updateUrl = gMenu.m_gameinfo.update_url; + } + + if( updateUrl ) + EngFuncs::ShellExecute( updateUrl, NULL, true ); +} + +void UI_UpdateDialog( int preferStore ) +{ + static CMenuYesNoMessageBox msgBox; + static bool ignore = false; + static bool staticPreferStore; + + if( ignore ) + return; + + staticPreferStore = preferStore != 0; + + msgBox.SetMessage( "A new update is available.\nPress Update to open download page." ); + msgBox.SetPositiveButton( "Update", PC_UPDATE ); + msgBox.SetNegativeButton( "Later", PC_CANCEL ); + + SET_EVENT( msgBox.onPositive, UI_OpenUpdatePage( true, *(bool*)pExtra ) ); + msgBox.onPositive.pExtra = &staticPreferStore; + + SET_EVENT( msgBox.onNegative, *(bool*)pExtra = true ); // set ignore + msgBox.onNegative.pExtra = &ignore; + + msgBox.Show(); + +} + +static void UI_UpdateDialog_f( void ) +{ + if( !strcmp( EngFuncs::CmdArgv( 1 ), "nostore" )) + UI_UpdateDialog( false ); + else + UI_UpdateDialog( true ); +} + +ADD_COMMAND( menu_updatedialog, UI_UpdateDialog_f ); + +/* +================= +UI_Init +================= +*/ +void UI_Init( void ) +{ + // register our cvars and commands + ui_showmodels = EngFuncs::CvarRegister( "ui_showmodels", "0", FCVAR_ARCHIVE ); + ui_showclassmodels = EngFuncs::CvarRegister( "ui_showclassmodels", "1", FCVAR_ARCHIVE ); + ui_show_window_stack = EngFuncs::CvarRegister( "ui_show_window_stack", "0", FCVAR_ARCHIVE ); + ui_borderclip = EngFuncs::CvarRegister( "ui_borderclip", "0", FCVAR_ARCHIVE ); + ui_prefer_won_background = EngFuncs::CvarRegister( "ui_prefer_won_background", "0", FCVAR_ARCHIVE ); + ui_background_stretch = EngFuncs::CvarRegister( "ui_background_stretch", "0", FCVAR_ARCHIVE ); + ui_logohorizontal = EngFuncs::CvarRegister( "ui_logohorizontal", "0", FCVAR_ARCHIVE ); + + // show cl_predict dialog + EngFuncs::CvarRegister( "menu_mp_firsttime2", "1", FCVAR_ARCHIVE ); + + // autofill ammo after bought weapon + EngFuncs::CvarRegister( "ui_cs_autofill", "0", FCVAR_ARCHIVE ); + + for( CMenuEntry *entry = s_pEntries; entry; entry = entry->m_pNext ) + { + if( entry->m_szCommand && entry->m_pfnShow ) + { + EngFuncs::Cmd_AddCommand( entry->m_szCommand, entry->m_pfnShow ); + } + } + + g_FontMgr = new CFontManager(); + + uiStatic.initialized = true; + uiStatic.lowmemory = (int)EngFuncs::GetCvarFloat( "host_lowmemorymode" ); + + // setup game info + gameinfo2_t *gi = EngFuncs::GetGameInfo(); + if( !gi ) + Host_Error( "pfnGetGameInfo returned NULL!\n" ); + + gMenu.m_gameinfo = *gi; + + uiStatic.renderPicbuttonText = gMenu.m_gameinfo.flags & GFL_RENDER_PICBUTTON_TEXT; +#ifdef __EMSCRIPTEN__ + // SwedenCode web build: Steam CS 1.6 style text buttons in the menu font, not the WON-era orange picture buttons + uiStatic.renderPicbuttonText = true; +#endif + + // trying to load colors.lst + UI_ApplyCustomColors (); +} + +/* +================= +UI_Shutdown +================= +*/ +void UI_Shutdown( void ) +{ + if( !uiStatic.initialized ) + return; + + for( CMenuEntry *entry = s_pEntries; entry; entry = entry->m_pNext ) + { + if( entry->m_szCommand && entry->m_pfnShow ) + { + EngFuncs::Cmd_RemoveCommand( entry->m_szCommand ); + } + + if( entry->m_pfnShutdown ) + { + entry->m_pfnShutdown(); + } + } + + UI_FreeCustomStrings(); + + delete uiStatic.background; + delete g_FontMgr; + + memset( &uiStatic, 0, sizeof( uiStatic_t )); +} diff --git a/3rdparty/mainui_cpp/CMakeLists.txt b/3rdparty/mainui_cpp/CMakeLists.txt index 10c8c11..654e676 100644 --- a/3rdparty/mainui_cpp/CMakeLists.txt +++ b/3rdparty/mainui_cpp/CMakeLists.txt @@ -1,101 +1,106 @@ -# -# Copyright (c) 2015 Pavlo Lavrenenko -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -# - -cmake_minimum_required(VERSION 3.5) -project(MAINUI) - -set(CMAKE_CXX_STANDARD 11) - -option(MAINUI_USE_CUSTOM_FONT_RENDER "Use custom font rendering" ON) -option(MAINUI_USE_STB "Use stb_truetype.h for rendering(*nix-only)" OFF) -option(MAINUI_FONT_SCALE "Scale fonts by height" OFF) - -if(NOT XASH_SDK) - set(XASH_SDK "sdk_includes/") -endif() - -file(GLOB MAINUI_CONTROLS_SOURCES "controls/*.cpp") -file(GLOB MAINUI_MENUS_SOURCES "menus/*.cpp" "menus/dynamic/*.cpp" "menus/client/*.cpp") -file(GLOB MAINUI_FONT_RENDER_SOURCES "font/*.cpp") -file(GLOB MAINUI_SOURCES "miniutl/*.cpp" "*.cpp") - -add_library(menu SHARED ${MAINUI_CONTROLS_SOURCES} ${MAINUI_MENUS_SOURCES} ${MAINUI_FONT_RENDER_SOURCES} ${MAINUI_SOURCES} ${CMAKE_SOURCE_DIR}/common/interface.cpp) - -if(NOT WIN32 AND NOT MINGW) - add_compile_options(-Wall -Wextra -Wno-unused-parameter -Wno-unused-variable) -endif() - -if(MAINUI_FONT_SCALE) - add_definitions(-DMAINUI_FONT_SCALE) -endif() - -add_definitions(-DSTDINT_H=) - -# Android uses stb_truetype by default for rendering fonts -if(ANDROID) - set(MAINUI_USE_STB TRUE) -endif() - -include_directories(${XASH_SDK}/common ${XASH_SDK}/engine ${XASH_SDK}/pm_shared ${XASH_SDK}/public . controls/ menus/ miniutl/ font/ model/ ${CMAKE_SOURCE_DIR}/common ${CMAKE_SOURCE_DIR}/public) - -if(MSVC) - add_definitions(-D_CRT_SECURE_NO_WARNINGS) -endif() - -# Font Rendering(FreeType or WinAPI) -if(MAINUI_USE_CUSTOM_FONT_RENDER) - # Win32 will always use GDI font renderer - if(NOT WIN32) - if(MAINUI_USE_STB) - # Use stbtt - add_definitions(-DMAINUI_USE_STB) - else() - # Use freetype2 - find_package(PkgConfig) - find_package(Freetype REQUIRED) - include_directories(${FREETYPE_INCLUDE_DIRS}) - target_link_libraries(menu ${FREETYPE_LIBRARIES}) - add_definitions(-DMAINUI_USE_FREETYPE) - endif() - endif() - - add_definitions(-DMAINUI_USE_CUSTOM_FONT_RENDER) -endif() - -if(NOT BUILD_AS_PART_OF_ENGINE) - # grab platform library suffix - set_target_postfix(menu) - if(NOT DEFINED GAMEDIR AND DEFINED GAME_DIR) - # parent project provides GAME_DIR, use it as GAMEDIR for compatibility - set(GAMEDIR "${GAME_DIR}") - endif() -else() - # install to the same directory as engine - set(GAMEDIR ".") - set(CLIENT_INSTALL_DIR ".") -endif() - -install(TARGETS menu DESTINATION "${GAMEDIR}/${CLIENT_INSTALL_DIR}") - -if(MSVC) - install(FILES $ DESTINATION "${GAMEDIR}/${CLIENT_INSTALL_DIR}" OPTIONAL) -endif() +# +# Copyright (c) 2015 Pavlo Lavrenenko +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# + +cmake_minimum_required(VERSION 3.5) +project(MAINUI) + +set(CMAKE_CXX_STANDARD 11) + +option(MAINUI_USE_CUSTOM_FONT_RENDER "Use custom font rendering" ON) +option(MAINUI_USE_STB "Use stb_truetype.h for rendering(*nix-only)" OFF) +option(MAINUI_FONT_SCALE "Scale fonts by height" OFF) + +if(NOT XASH_SDK) + set(XASH_SDK "sdk_includes/") +endif() + +file(GLOB MAINUI_CONTROLS_SOURCES "controls/*.cpp") +file(GLOB MAINUI_MENUS_SOURCES "menus/*.cpp" "menus/dynamic/*.cpp" "menus/client/*.cpp") +file(GLOB MAINUI_FONT_RENDER_SOURCES "font/*.cpp") +file(GLOB MAINUI_SOURCES "miniutl/*.cpp" "*.cpp") + +add_library(menu SHARED ${MAINUI_CONTROLS_SOURCES} ${MAINUI_MENUS_SOURCES} ${MAINUI_FONT_RENDER_SOURCES} ${MAINUI_SOURCES} ${CMAKE_SOURCE_DIR}/common/interface.cpp) + +if(NOT WIN32 AND NOT MINGW) + add_compile_options(-Wall -Wextra -Wno-unused-parameter -Wno-unused-variable) +endif() + +if(EMSCRIPTEN) + # web build: every module shares one symbol table and the game client has its own gpGlobals (cs_weapons.cpp) + target_compile_definitions(menu PRIVATE gpGlobals=g_pMenuGlobals) +endif() + +if(MAINUI_FONT_SCALE) + add_definitions(-DMAINUI_FONT_SCALE) +endif() + +add_definitions(-DSTDINT_H=) + +# Android uses stb_truetype by default for rendering fonts +if(ANDROID) + set(MAINUI_USE_STB TRUE) +endif() + +include_directories(${XASH_SDK}/common ${XASH_SDK}/engine ${XASH_SDK}/pm_shared ${XASH_SDK}/public . controls/ menus/ miniutl/ font/ model/ ${CMAKE_SOURCE_DIR}/common ${CMAKE_SOURCE_DIR}/public) + +if(MSVC) + add_definitions(-D_CRT_SECURE_NO_WARNINGS) +endif() + +# Font Rendering(FreeType or WinAPI) +if(MAINUI_USE_CUSTOM_FONT_RENDER) + # Win32 will always use GDI font renderer + if(NOT WIN32) + if(MAINUI_USE_STB) + # Use stbtt + add_definitions(-DMAINUI_USE_STB) + else() + # Use freetype2 + find_package(PkgConfig) + find_package(Freetype REQUIRED) + include_directories(${FREETYPE_INCLUDE_DIRS}) + target_link_libraries(menu ${FREETYPE_LIBRARIES}) + add_definitions(-DMAINUI_USE_FREETYPE) + endif() + endif() + + add_definitions(-DMAINUI_USE_CUSTOM_FONT_RENDER) +endif() + +if(NOT BUILD_AS_PART_OF_ENGINE) + # grab platform library suffix + set_target_postfix(menu) + if(NOT DEFINED GAMEDIR AND DEFINED GAME_DIR) + # parent project provides GAME_DIR, use it as GAMEDIR for compatibility + set(GAMEDIR "${GAME_DIR}") + endif() +else() + # install to the same directory as engine + set(GAMEDIR ".") + set(CLIENT_INSTALL_DIR ".") +endif() + +install(TARGETS menu DESTINATION "${GAMEDIR}/${CLIENT_INSTALL_DIR}") + +if(MSVC) + install(FILES $ DESTINATION "${GAMEDIR}/${CLIENT_INSTALL_DIR}" OPTIONAL) +endif() diff --git a/3rdparty/mainui_cpp/controls/BackgroundBitmap.cpp b/3rdparty/mainui_cpp/controls/BackgroundBitmap.cpp index aa18fea..6f52b9d 100644 --- a/3rdparty/mainui_cpp/controls/BackgroundBitmap.cpp +++ b/3rdparty/mainui_cpp/controls/BackgroundBitmap.cpp @@ -1,381 +1,382 @@ -/* -BackgroundBitmap.cpp -- background menu item -Copyright (C) 2010 Uncle Mike -Copyright (C) 2017 a1batross - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. -*/ - -#include "extdll_menu.h" -#include "BaseMenu.h" -#include "BackgroundBitmap.h" -#include "Utils.h" -#include "BaseWindow.h" - -bool CMenuBackgroundBitmap::s_bEnableLogoMovie = false; -bool CMenuBackgroundBitmap::s_bGameHasSteamBackground = false; -bool CMenuBackgroundBitmap::s_bGameHasWONBackground = false; -CMenuBackgroundBitmap::bstate_e CMenuBackgroundBitmap::s_state; - -CMenuBackgroundBitmap::bimage_t CMenuBackgroundBitmap::s_WONBackground; - -Size CMenuBackgroundBitmap::s_SteamBackgroundImageSize; -CUtlVector CMenuBackgroundBitmap::s_SteamBackground; - -CMenuBackgroundBitmap::CMenuBackgroundBitmap() : CMenuBitmap() -{ - szPic = 0; - iFlags = QMF_INACTIVE|QMF_DISABLESCAILING; - bForceColor = false; -} - -void CMenuBackgroundBitmap::VidInit() -{ - pos.x = pos.y = 0; - - if( m_pParent ) - { - // fill parent - if( m_pParent->iFlags & QMF_DISABLESCAILING ) - { - size = m_pParent->size; - } - else - { - size = m_pParent->size.Scale(); - } - } - else - { - size = Size( ScreenWidth, ScreenHeight ); - } - - colorBase.SetDefault( 0xFF505050 ); - - CMenuBaseItem::VidInit(); -} - -void CMenuBackgroundBitmap::DrawInGameBackground() -{ - UI_FillRect( m_scPos, m_scSize, uiColorBlack ); -} - -void CMenuBackgroundBitmap::DrawColor() -{ - if( bDrawStroke ) - { - UI_DrawRectangleExt( m_scPos, m_scSize, colorStroke, 1 ); - } - - UI_FillRect( m_scPos, m_scSize, colorBase ); -} - -void CMenuBackgroundBitmap::DrawBackgroundPiece( const bimage_t &image, Point p, int xOffset, int yOffset, float xScale, float yScale ) -{ - EngFuncs::PIC_Set( image.hImage, 255, 255, 255, 255 ); - - int dx = (int)ceil( image.coord.x * xScale ); - int dy = (int)ceil( image.coord.y * yScale ); - int dw = (int)ceil( image.size.w * xScale ); - int dt = (int)ceil( image.size.h * yScale ); - - EngFuncs::PIC_Draw( p.x + dx + xOffset, p.y + dy + yOffset, dw, dt ); -} - -void CMenuBackgroundBitmap::DrawSteamBackgroundLayout( Point p, int xOffset, int yOffset, float xScale, float yScale ) -{ - // iterate and draw all the background pieces - for( int i = 0; i < s_SteamBackground.Count(); i++ ) - DrawBackgroundPiece( s_SteamBackground[i], p, xOffset, yOffset, xScale, yScale ); -} - -/* -================= -CMenuBackgroundBitmap::Draw -================= -*/ -void CMenuBackgroundBitmap::Draw() -{ - if( bForceColor ) - { - DrawColor(); - return; - } - - if( EngFuncs::ClientInGame() ) - { - if( EngFuncs::GetCvarFloat( "cl_background" ) ) - { - return; - } - - if( EngFuncs::GetCvarFloat( "ui_renderworld" ) ) - { - DrawInGameBackground(); - return; - } - } - - if( szPic ) - { - UI_DrawPic( m_scPos, m_scSize, uiColorWhite, szPic ); - return; - } - - if( FBitSet( ui_prefer_won_background->flags, FCVAR_CHANGED )) - { - UpdatePreference(); - - // because the cvar is set by user, tell them if chosen background is not available - if( ui_prefer_won_background->value && s_state != DRAW_WON ) - UI_ShowMessageBox( L( "WON background is not available" )); - } - - Point p; - float xScale, yScale; - Size s; - - if( s_state == DRAW_COLOR ) - { - DrawColor(); - return; - } - else if( s_state == DRAW_WON ) - s = s_WONBackground.size; - else - s = s_SteamBackgroundImageSize; - - // Disable parallax effect. It's just funny, but not really needed -#if 0 - float flParallaxScale = 0.02; - p.x = (uiStatic.cursorX - ScreenWidth) * flParallaxScale; - p.y = (uiStatic.cursorY - ScreenHeight) * flParallaxScale; - - // work out scaling factors - // work out scaling factors - if( ScreenWidth * s.h > ScreenHeight * s.w ) - { - xScale = ScreenWidth / s.w * (1 + flParallaxScale); - yScale = xScale; - } - else - { - yScale = ScreenHeight / s.h * (1 + flParallaxScale); - xScale = yScale; - } -#else - p.x = p.y = 0; - - // Stretch the background image if the user chose to do so - if( ui_background_stretch->value ) - { - xScale = ScreenWidth / s.w; - yScale = ScreenHeight / s.h; - } - else - { - // work out scaling factors - if( ScreenWidth * s.h > ScreenHeight * s.w ) - { - xScale = ScreenWidth / s.w; - yScale = xScale; - } - else - { - yScale = ScreenHeight / s.h; - xScale = yScale; - } - } -#endif - - int xOffset = 0, yOffset = 0; - if( !ui_background_stretch->value ) - { - // center wide background (for example if background is wider than our window) - if( s.w * xScale > ScreenWidth ) - xOffset = ( ScreenWidth - s.w * xScale ) / 2; - else if( s.h * yScale > ScreenHeight ) - yOffset = ( ScreenHeight - s.h * yScale ) / 2; - } - - if( s_state == DRAW_WON ) - DrawBackgroundPiece( s_WONBackground, p, xOffset, yOffset, xScale, yScale ); - else - DrawSteamBackgroundLayout( p, xOffset, yOffset, xScale, yScale ); - - // print CS16Client version - char version[32]; - int stringLen, charH; - - snprintf( version, 32, "cs16-client build %s", EngFuncs::GetCvarString( "cscl_ver" ) ); - - EngFuncs::engfuncs.pfnDrawConsoleStringLen( version, &stringLen, &charH ); - EngFuncs::engfuncs.pfnDrawConsoleString( stringLen * 0.05f, ScreenHeight - charH * 1.05f, version ); - -} - -bool CMenuBackgroundBitmap::LoadSteamBackground( bool gamedirOnly ) -{ - char *afile = NULL, *pfile; - char token[4096]; - - bool loaded = false; - - // try 25'th anniversary update background first - if( FBitSet( gMenu.m_gameinfo.flags, GFL_HD_BACKGROUND )) - afile = (char *)EngFuncs::COM_LoadFile( "resource/HD_BackgroundLayout.txt" ); - - if( !afile ) - afile = (char *)EngFuncs::COM_LoadFile( "resource/BackgroundLayout.txt" ); - - if( !afile ) - return false; - - pfile = afile; - - pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ) ); - if( !pfile || strcmp( token, "resolution" )) // resolution at first! - goto freefile; - - pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ) ); - if( !pfile ) goto freefile; - - s_SteamBackgroundImageSize.w = atoi( token ); - - pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ) ); - if( !pfile ) goto freefile; - - s_SteamBackgroundImageSize.h = atoi( token ); - - // Now read all tiled background list - while(( pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ) ))) - { - bimage_t img; - - if( !EngFuncs::FileExists( token, gamedirOnly )) - goto freefile; - - img.hImage = EngFuncs::PIC_Load( token, PIC_NOFLIP_TGA ); - - if( !img.hImage ) goto freefile; - - // ignore "scaled" attribute. What does it mean? - pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ) ); - if( !pfile ) goto freefile; - - pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ) ); - if( !pfile ) goto freefile; - img.coord.x = atoi( token ); - - pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ) ); - if( !pfile ) goto freefile; - img.coord.y = atoi( token ); - - img.size.w = EngFuncs::PIC_Width( img.hImage ); - img.size.h = EngFuncs::PIC_Height( img.hImage ); - - s_SteamBackground.AddToTail( img ); - } - - loaded = true; - -freefile: - EngFuncs::COM_FreeFile( afile ); - return loaded; -} - -bool CMenuBackgroundBitmap::LoadWONBackground( bool gamedirOnly ) -{ - if( EngFuncs::FileExists( ART_BACKGROUND, gamedirOnly )) - { - bimage_t img; - - img.hImage = EngFuncs::PIC_Load( ART_BACKGROUND ); - - if( !img.hImage ) - return false; - - img.coord.x = img.coord.y = 0; - img.size.w = EngFuncs::PIC_Width( img.hImage ); - img.size.h = EngFuncs::PIC_Height( img.hImage ); - s_WONBackground = img; - - return true; - } - - return false; -} - -void CMenuBackgroundBitmap::UpdatePreference() -{ - if( ui_prefer_won_background->value ) - { - if( s_bGameHasWONBackground ) - s_state = DRAW_WON; - else if( s_bGameHasSteamBackground ) - s_state = DRAW_STEAM; - else if( s_WONBackground.hImage ) - s_state = DRAW_WON; - else if( s_SteamBackground.Count() > 0 ) - s_state = DRAW_STEAM; - else - s_state = DRAW_COLOR; - } - else - { - if( s_bGameHasSteamBackground ) - s_state = DRAW_STEAM; - else if( s_bGameHasWONBackground ) - s_state = DRAW_WON; - else if( s_SteamBackground.Count() > 0 ) - s_state = DRAW_STEAM; - else if( s_WONBackground.hImage ) - s_state = DRAW_WON; - else - s_state = DRAW_COLOR; - } - - // Enable logo.avi only for WON background, disable otherwise - if( s_state == DRAW_WON ) - s_bEnableLogoMovie = EngFuncs::FileExists( "media/logo.avi", true ); - else - s_bEnableLogoMovie = false; - - ClearBits( ui_prefer_won_background->flags, FCVAR_CHANGED ); -} - -void CMenuBackgroundBitmap::LoadBackground() -{ - s_bEnableLogoMovie = false; - s_bGameHasSteamBackground = false; - s_bGameHasWONBackground = false; - - if( uiStatic.lowmemory ) - return; - - if( LoadSteamBackground( true )) - { - Con_DPrintf( "%s: found %s background in %s directory\n", __func__, "steam", "game" ); - s_bGameHasSteamBackground = true; - } - else if( LoadSteamBackground( false )) - Con_DPrintf( "%s: found %s background in %s directory\n", __func__, "steam", "base" ); - - if( LoadWONBackground( true )) - { - Con_DPrintf( "%s: found %s background in %s directory\n", __func__, "won", "game" ); - s_bGameHasWONBackground = true; - } - else if( LoadWONBackground( false )) - Con_DPrintf( "%s: found %s background in %s directory\n", __func__, "won", "base" ); - - UpdatePreference(); -} +/* +BackgroundBitmap.cpp -- background menu item +Copyright (C) 2010 Uncle Mike +Copyright (C) 2017 a1batross + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. +*/ + +#include "extdll_menu.h" +#include "BaseMenu.h" +#include "BackgroundBitmap.h" +#include "Utils.h" +#include "BaseWindow.h" + +bool CMenuBackgroundBitmap::s_bEnableLogoMovie = false; +bool CMenuBackgroundBitmap::s_bGameHasSteamBackground = false; +bool CMenuBackgroundBitmap::s_bGameHasWONBackground = false; +CMenuBackgroundBitmap::bstate_e CMenuBackgroundBitmap::s_state; + +CMenuBackgroundBitmap::bimage_t CMenuBackgroundBitmap::s_WONBackground; + +Size CMenuBackgroundBitmap::s_SteamBackgroundImageSize; +CUtlVector CMenuBackgroundBitmap::s_SteamBackground; + +CMenuBackgroundBitmap::CMenuBackgroundBitmap() : CMenuBitmap() +{ + szPic = 0; + iFlags = QMF_INACTIVE|QMF_DISABLESCAILING; + bForceColor = false; +} + +void CMenuBackgroundBitmap::VidInit() +{ + pos.x = pos.y = 0; + + if( m_pParent ) + { + // fill parent + if( m_pParent->iFlags & QMF_DISABLESCAILING ) + { + size = m_pParent->size; + } + else + { + size = m_pParent->size.Scale(); + } + } + else + { + size = Size( ScreenWidth, ScreenHeight ); + } + + colorBase.SetDefault( 0xFF505050 ); + + CMenuBaseItem::VidInit(); +} + +void CMenuBackgroundBitmap::DrawInGameBackground() +{ + UI_FillRect( m_scPos, m_scSize, uiColorBlack ); +} + +void CMenuBackgroundBitmap::DrawColor() +{ + if( bDrawStroke ) + { + UI_DrawRectangleExt( m_scPos, m_scSize, colorStroke, 1 ); + } + + UI_FillRect( m_scPos, m_scSize, colorBase ); +} + +void CMenuBackgroundBitmap::DrawBackgroundPiece( const bimage_t &image, Point p, int xOffset, int yOffset, float xScale, float yScale ) +{ + EngFuncs::PIC_Set( image.hImage, 255, 255, 255, 255 ); + + int dx = (int)ceil( image.coord.x * xScale ); + int dy = (int)ceil( image.coord.y * yScale ); + int dw = (int)ceil( image.size.w * xScale ); + int dt = (int)ceil( image.size.h * yScale ); + + EngFuncs::PIC_Draw( p.x + dx + xOffset, p.y + dy + yOffset, dw, dt ); +} + +void CMenuBackgroundBitmap::DrawSteamBackgroundLayout( Point p, int xOffset, int yOffset, float xScale, float yScale ) +{ + // iterate and draw all the background pieces + for( int i = 0; i < s_SteamBackground.Count(); i++ ) + DrawBackgroundPiece( s_SteamBackground[i], p, xOffset, yOffset, xScale, yScale ); +} + +/* +================= +CMenuBackgroundBitmap::Draw +================= +*/ +void CMenuBackgroundBitmap::Draw() +{ + if( bForceColor ) + { + DrawColor(); + return; + } + + if( EngFuncs::ClientInGame() ) + { + if( EngFuncs::GetCvarFloat( "cl_background" ) ) + { + return; + } + + if( EngFuncs::GetCvarFloat( "ui_renderworld" ) ) + { + DrawInGameBackground(); + return; + } + } + + if( szPic ) + { + UI_DrawPic( m_scPos, m_scSize, uiColorWhite, szPic ); + return; + } + + if( FBitSet( ui_prefer_won_background->flags, FCVAR_CHANGED )) + { + UpdatePreference(); + + // because the cvar is set by user, tell them if chosen background is not available + if( ui_prefer_won_background->value && s_state != DRAW_WON ) + UI_ShowMessageBox( L( "WON background is not available" )); + } + + Point p; + float xScale, yScale; + Size s; + + if( s_state == DRAW_COLOR ) + { + DrawColor(); + return; + } + else if( s_state == DRAW_WON ) + s = s_WONBackground.size; + else + s = s_SteamBackgroundImageSize; + + // Disable parallax effect. It's just funny, but not really needed +#if 0 + float flParallaxScale = 0.02; + p.x = (uiStatic.cursorX - ScreenWidth) * flParallaxScale; + p.y = (uiStatic.cursorY - ScreenHeight) * flParallaxScale; + + // work out scaling factors + // work out scaling factors + if( ScreenWidth * s.h > ScreenHeight * s.w ) + { + xScale = ScreenWidth / s.w * (1 + flParallaxScale); + yScale = xScale; + } + else + { + yScale = ScreenHeight / s.h * (1 + flParallaxScale); + xScale = yScale; + } +#else + p.x = p.y = 0; + + // Stretch the background image if the user chose to do so + if( ui_background_stretch->value ) + { + xScale = ScreenWidth / s.w; + yScale = ScreenHeight / s.h; + } + else + { + // work out scaling factors + if( ScreenWidth * s.h > ScreenHeight * s.w ) + { + xScale = ScreenWidth / s.w; + yScale = xScale; + } + else + { + yScale = ScreenHeight / s.h; + xScale = yScale; + } + } +#endif + + int xOffset = 0, yOffset = 0; + if( !ui_background_stretch->value ) + { + // center wide background (for example if background is wider than our window) + if( s.w * xScale > ScreenWidth ) + xOffset = ( ScreenWidth - s.w * xScale ) / 2; + else if( s.h * yScale > ScreenHeight ) + yOffset = ( ScreenHeight - s.h * yScale ) / 2; + } + + if( s_state == DRAW_WON ) + DrawBackgroundPiece( s_WONBackground, p, xOffset, yOffset, xScale, yScale ); + else + DrawSteamBackgroundLayout( p, xOffset, yOffset, xScale, yScale ); + + // print CS16Client version + char version[32]; + int stringLen, charH; + + // SwedenCode web build: our client name in the corner + snprintf( version, 32, "SwedenCode CS client %s", EngFuncs::GetCvarString( "cscl_ver" ) ); + + EngFuncs::engfuncs.pfnDrawConsoleStringLen( version, &stringLen, &charH ); + EngFuncs::engfuncs.pfnDrawConsoleString( stringLen * 0.05f, ScreenHeight - charH * 1.05f, version ); + +} + +bool CMenuBackgroundBitmap::LoadSteamBackground( bool gamedirOnly ) +{ + char *afile = NULL, *pfile; + char token[4096]; + + bool loaded = false; + + // try 25'th anniversary update background first + if( FBitSet( gMenu.m_gameinfo.flags, GFL_HD_BACKGROUND )) + afile = (char *)EngFuncs::COM_LoadFile( "resource/HD_BackgroundLayout.txt" ); + + if( !afile ) + afile = (char *)EngFuncs::COM_LoadFile( "resource/BackgroundLayout.txt" ); + + if( !afile ) + return false; + + pfile = afile; + + pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ) ); + if( !pfile || strcmp( token, "resolution" )) // resolution at first! + goto freefile; + + pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ) ); + if( !pfile ) goto freefile; + + s_SteamBackgroundImageSize.w = atoi( token ); + + pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ) ); + if( !pfile ) goto freefile; + + s_SteamBackgroundImageSize.h = atoi( token ); + + // Now read all tiled background list + while(( pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ) ))) + { + bimage_t img; + + if( !EngFuncs::FileExists( token, gamedirOnly )) + goto freefile; + + img.hImage = EngFuncs::PIC_Load( token, PIC_NOFLIP_TGA ); + + if( !img.hImage ) goto freefile; + + // ignore "scaled" attribute. What does it mean? + pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ) ); + if( !pfile ) goto freefile; + + pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ) ); + if( !pfile ) goto freefile; + img.coord.x = atoi( token ); + + pfile = EngFuncs::COM_ParseFile( pfile, token, sizeof( token ) ); + if( !pfile ) goto freefile; + img.coord.y = atoi( token ); + + img.size.w = EngFuncs::PIC_Width( img.hImage ); + img.size.h = EngFuncs::PIC_Height( img.hImage ); + + s_SteamBackground.AddToTail( img ); + } + + loaded = true; + +freefile: + EngFuncs::COM_FreeFile( afile ); + return loaded; +} + +bool CMenuBackgroundBitmap::LoadWONBackground( bool gamedirOnly ) +{ + if( EngFuncs::FileExists( ART_BACKGROUND, gamedirOnly )) + { + bimage_t img; + + img.hImage = EngFuncs::PIC_Load( ART_BACKGROUND ); + + if( !img.hImage ) + return false; + + img.coord.x = img.coord.y = 0; + img.size.w = EngFuncs::PIC_Width( img.hImage ); + img.size.h = EngFuncs::PIC_Height( img.hImage ); + s_WONBackground = img; + + return true; + } + + return false; +} + +void CMenuBackgroundBitmap::UpdatePreference() +{ + if( ui_prefer_won_background->value ) + { + if( s_bGameHasWONBackground ) + s_state = DRAW_WON; + else if( s_bGameHasSteamBackground ) + s_state = DRAW_STEAM; + else if( s_WONBackground.hImage ) + s_state = DRAW_WON; + else if( s_SteamBackground.Count() > 0 ) + s_state = DRAW_STEAM; + else + s_state = DRAW_COLOR; + } + else + { + if( s_bGameHasSteamBackground ) + s_state = DRAW_STEAM; + else if( s_bGameHasWONBackground ) + s_state = DRAW_WON; + else if( s_SteamBackground.Count() > 0 ) + s_state = DRAW_STEAM; + else if( s_WONBackground.hImage ) + s_state = DRAW_WON; + else + s_state = DRAW_COLOR; + } + + // Enable logo.avi only for WON background, disable otherwise + if( s_state == DRAW_WON ) + s_bEnableLogoMovie = EngFuncs::FileExists( "media/logo.avi", true ); + else + s_bEnableLogoMovie = false; + + ClearBits( ui_prefer_won_background->flags, FCVAR_CHANGED ); +} + +void CMenuBackgroundBitmap::LoadBackground() +{ + s_bEnableLogoMovie = false; + s_bGameHasSteamBackground = false; + s_bGameHasWONBackground = false; + + if( uiStatic.lowmemory ) + return; + + if( LoadSteamBackground( true )) + { + Con_DPrintf( "%s: found %s background in %s directory\n", __func__, "steam", "game" ); + s_bGameHasSteamBackground = true; + } + else if( LoadSteamBackground( false )) + Con_DPrintf( "%s: found %s background in %s directory\n", __func__, "steam", "base" ); + + if( LoadWONBackground( true )) + { + Con_DPrintf( "%s: found %s background in %s directory\n", __func__, "won", "game" ); + s_bGameHasWONBackground = true; + } + else if( LoadWONBackground( false )) + Con_DPrintf( "%s: found %s background in %s directory\n", __func__, "won", "base" ); + + UpdatePreference(); +} diff --git a/3rdparty/mainui_cpp/controls/BaseClientWindow.cpp b/3rdparty/mainui_cpp/controls/BaseClientWindow.cpp index 49e1cd0..52ce4c1 100644 --- a/3rdparty/mainui_cpp/controls/BaseClientWindow.cpp +++ b/3rdparty/mainui_cpp/controls/BaseClientWindow.cpp @@ -1,40 +1,45 @@ -/* -BaseWindow.h -- base client menu window -Copyright (C) 2018 a1batross - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. -*/ -#include "BaseMenu.h" -#include "BaseClientWindow.h" - -CMenuBaseClientWindow::CMenuBaseClientWindow( const char *name ) : - BaseClass( name, &uiStatic.client ) -{ -} - -bool CMenuBaseClientWindow::KeyDown( int key ) -{ - // copy engine behaviour - if( UI::Key::IsEscape( key )) - { - EngFuncs::KEY_SetDest( KEY_GAME ); // set engine states before "escape" - EngFuncs::ClientCmd( false, "escape\n" ); - return true; - } - else if( UI::Key::IsConsole( key )) - { - EngFuncs::KEY_SetDest( KEY_CONSOLE ); - } - - return BaseClass::KeyDown( key ); -} - - +/* +BaseWindow.h -- base client menu window +Copyright (C) 2018 a1batross + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. +*/ +#include "BaseMenu.h" +#include "BaseClientWindow.h" + +CMenuBaseClientWindow::CMenuBaseClientWindow( const char *name ) : + BaseClass( name, &uiStatic.client ) +{ +} + +bool CMenuBaseClientWindow::KeyDown( int key ) +{ + // copy engine behaviour + if( UI::Key::IsEscape( key )) + { +#ifdef __EMSCRIPTEN__ + // web build: Esc just closes the window; "escape" would open the page's game menu over it + UI_CloseClientMenu(); +#else + EngFuncs::KEY_SetDest( KEY_GAME ); // set engine states before "escape" + EngFuncs::ClientCmd( false, "escape\n" ); +#endif + return true; + } + else if( UI::Key::IsConsole( key )) + { + EngFuncs::KEY_SetDest( KEY_CONSOLE ); + } + + return BaseClass::KeyDown( key ); +} + + diff --git a/3rdparty/mainui_cpp/font/FontManager.cpp b/3rdparty/mainui_cpp/font/FontManager.cpp index 971cab5..8d8b0cb 100644 --- a/3rdparty/mainui_cpp/font/FontManager.cpp +++ b/3rdparty/mainui_cpp/font/FontManager.cpp @@ -1,579 +1,583 @@ -/* -FontManager.cpp - font manager -Copyright (C) 2017 a1batross - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. -*/ -#include -#include "FontManager.h" -#include "BaseMenu.h" -#include "Utils.h" - -#include "BaseFontBackend.h" - -#if defined(MAINUI_USE_FREETYPE) -#include "FreeTypeFont.h" -#elif defined(MAINUI_USE_STB) -#include "StbFont.h" -#elif defined(_WIN32) -#include "WinAPIFont.h" -#endif - -#include "BitmapFont.h" -#include "utflib.h" - -#define DEFAULT_MENUFONT "Trebuchet MS" -#define DEFAULT_CONFONT "Tahoma" -#define DEFAULT_WEIGHT 500 - -CFontManager *g_FontMgr; - -CFontManager::CFontManager() -{ -#ifdef MAINUI_USE_FREETYPE - FT_Init_FreeType( &CFreeTypeFont::m_Library ); -#endif - m_Fonts.EnsureCapacity( 4 ); - m_FontFiles.EnsureCapacity( 2 ); -} - -CFontManager::~CFontManager() -{ - DeleteAllFonts(); -#ifdef MAINUI_USE_FREETYPE - FT_Done_FreeType( CFreeTypeFont::m_Library ); - CFreeTypeFont::m_Library = NULL; -#endif - - FOR_EACH_HASHMAP( m_FontFiles, i ) - { - byte *p = m_FontFiles.Element( i ).data; - EngFuncs::COM_FreeFile( p ); - } - - m_FontFiles.Purge(); -} - -void CFontManager::VidInit( void ) -{ - static float prevScale = 0; - - float scale = uiStatic.scaleY; - - if( !prevScale -#ifndef SCALE_FONTS // complete disables font re-rendering - || fabs( scale - prevScale ) > 0.1f -#endif - ) - { - DeleteAllFonts(); - uiStatic.hDefaultFont = CFontBuilder( DEFAULT_MENUFONT, UI_MED_CHAR_HEIGHT * scale, DEFAULT_WEIGHT ) - .SetHandleNum( QM_DEFAULTFONT ) - .Create(); - uiStatic.hSmallFont = CFontBuilder( DEFAULT_MENUFONT, UI_SMALL_CHAR_HEIGHT * scale, DEFAULT_WEIGHT ) - .SetHandleNum( QM_SMALLFONT ) - .Create(); - uiStatic.hSmallerFont = CFontBuilder( DEFAULT_MENUFONT, UI_SMALLER_CHAR_HEIGHT * scale, DEFAULT_WEIGHT ) - .SetHandleNum( QM_SMALLERFONT ) - .Create(); - uiStatic.hTinyFont = CFontBuilder( DEFAULT_MENUFONT, UI_TINY_CHAR_HEIGHT * scale, DEFAULT_WEIGHT ) - .SetHandleNum( QM_TINYFONT ) - .Create(); - uiStatic.hBigFont = CFontBuilder( DEFAULT_MENUFONT, UI_BIG_CHAR_HEIGHT * scale, DEFAULT_WEIGHT ) - .SetHandleNum( QM_BIGFONT ) - .Create(); - uiStatic.hBoldFont = CFontBuilder( DEFAULT_MENUFONT, UI_MED_CHAR_HEIGHT * scale, 1000 ) - .SetHandleNum( QM_BOLDFONT ) - .Create(); - - if( !uiStatic.lowmemory ) - { - uiStatic.hLightBlur = CFontBuilder( DEFAULT_MENUFONT, UI_MED_CHAR_HEIGHT * scale, DEFAULT_WEIGHT ) - .SetBlurParams( 2 * scale, 1.25f ) - .Create(); - - uiStatic.hHeavyBlur = CFontBuilder( DEFAULT_MENUFONT, UI_MED_CHAR_HEIGHT * scale, DEFAULT_WEIGHT ) - .SetBlurParams( 8 * scale, 2.0f ) - .Create(); - } - - uiStatic.hConsoleFont = CFontBuilder( DEFAULT_CONFONT, UI_CONSOLE_CHAR_HEIGHT * scale, 500 ) - .SetOutlineSize() - .Create(); - prevScale = scale; - } -} - -void CFontManager::DeleteAllFonts() -{ - for( int i = 0; i < m_Fonts.Count(); i++ ) - { - delete m_Fonts[i]; - } - m_Fonts.RemoveAll(); -} - -void CFontManager::DeleteFont(HFont hFont) -{ - CBaseFont *font = GetIFontFromHandle(hFont); - if( font ) - { - m_Fonts[hFont-1] = NULL; - - delete font; - } -} - -CBaseFont *CFontManager::GetIFontFromHandle(HFont font) -{ - if( m_Fonts.IsValidIndex( font - 1 ) ) - return m_Fonts[font-1]; - - return NULL; -} - -int CFontManager::GetEllipsisWide(HFont font) -{ - if( m_Fonts.IsValidIndex( font - 1 ) ) - return m_Fonts[font-1]->GetEllipsisWide(); - return 0; -} - -void CFontManager::GetCharABCWide(HFont font, int ch, int &a, int &b, int &c) -{ - CBaseFont *pFont = GetIFontFromHandle( font ); - if( pFont ) - pFont->GetCharABCWidths( ch, a, b, c ); - else - a = b = c = 0; -} - -int CFontManager::GetCharacterWidth(HFont font, int ch) -{ - int a, b, c; - GetCharABCWide( font, ch, a, b, c ); - return a + b + c; -} - -int CFontManager::GetCharacterWidthScaled(HFont font, int ch, int height) -{ - return GetCharacterWidth( font, ch ) -#ifdef SCALE_FONTS - * ((float)height / (float)GetFontTall( font )) -#endif - ; -} - -HFont CFontManager::GetFontByName(const char *name) -{ - for( int i = 0; i < m_Fonts.Count(); i++ ) - { - if( !stricmp( name, m_Fonts[i]->GetName() ) ) - return i; - } - return -1; -} - -int CFontManager::GetFontTall(HFont font) -{ - CBaseFont *pFont = GetIFontFromHandle( font ); - if( pFont ) - return pFont->GetTall(); - return 0; -} - -int CFontManager::GetFontAscent(HFont font) -{ - CBaseFont *pFont = GetIFontFromHandle( font ); - if( pFont ) - return pFont->GetAscent(); - return 0; -} - -bool CFontManager::GetFontUnderlined(HFont font) -{ - CBaseFont *pFont = GetIFontFromHandle( font ); - if( pFont ) - return pFont->GetFlags() & FONT_UNDERLINE; - return false; -} - -void CFontManager::GetTextSize(HFont fontHandle, const char *text, int *wide, int *tall, int size ) -{ - CBaseFont *font = GetIFontFromHandle( fontHandle ); - - if( !font || !text || !text[0] ) - { - if( wide ) *wide = 0; - if( tall ) *tall = 0; - return; - } - - int fontTall = font->GetHeight(), x = 0; - int _wide = 0, _tall; - const char *ch = text; - _tall = fontTall; - int i = 0; - utfstate_t state; - - while( *ch && ( size < 0 || i < size ) ) - { - // Skip colorcodes - if( IsColorString( ch ) ) - { - ch += 2; - continue; - } - - int uch = state.Decode((uint8_t)*ch ); - - if( uch ) - { - if( uch == '\n' && *( ch + 1 ) != '\0' ) - { - _tall += fontTall; - x = 0; - } - else - { - int a, b, c; - font->GetCharABCWidths( uch, a, b, c ); - x += a + b + c; - if( x > _wide ) - _wide = x; - } - } - i++; - ch++; - } - - if( tall ) *tall = _tall; - if( wide ) *wide = _wide; -} - -int CFontManager::CutText(HFont fontHandle, const char *text, int height, int visibleSize, bool reverse, bool stopAtWhitespace, int *wide, bool *remaining ) -{ - CBaseFont *font = GetIFontFromHandle( fontHandle ); - - if( remaining ) - *remaining = false; - - if( !font || !text || !text[0] || visibleSize <= 0 ) - return 0; - - int _wide = 0; - const char *ch = text; - utfstate_t state; - -#ifdef SCALE_FONTS - visibleSize = (float)visibleSize / (float)height * (float)font->GetTall(); -#endif - - int whiteSpacePos = 0; - - // calculate full text wide - while( *ch ) - { - // skip colorcodes - if( IsColorString( ch ) ) - { - ch += 2; - continue; - } - - int uch = state.Decode((uint8_t)*ch ); - int x = 0; - if( uch ) - { - if( uch == '\n' ) - { - ch++; - break; // - } - - int a, b, c; - font->GetCharABCWidths( uch, a, b, c ); - x = a + b + c; - - if( uch == ' ' ) - { - whiteSpacePos = ch - text; - } - } - - if( !reverse && _wide + x >= visibleSize ) - break; - - ch++; - _wide += x; - } - - if( !reverse ) - { - if( *ch && remaining ) *remaining = true; - if( wide ) *wide = _wide; - if( stopAtWhitespace && whiteSpacePos ) - return whiteSpacePos; - return ch - text; - } - - if( _wide < visibleSize ) - { - if( remaining ) *remaining = false; - if( wide ) *wide = _wide; - return 0; - } - - ch = text; - - whiteSpacePos = 0; - - // now remove character one by one to fit - state.Reset(); - while( *ch && _wide > visibleSize ) - { - // skip colorcodes - if( IsColorString( ch ) ) - { - ch += 2; - continue; - } - - int uch = state.Decode((uint8_t)*ch ); - if( uch ) - { - // we don't need check for newlines here, it's only done for oneline Field widget - int a, b, c; - font->GetCharABCWidths( uch, a, b, c ); - _wide -= a + b + c; - - if( uch == ' ' ) - { - whiteSpacePos = ch - text; - } - } - ch++; - } - - if( remaining ) *remaining = true; - if( wide ) *wide = _wide; - if( stopAtWhitespace && whiteSpacePos ) return whiteSpacePos; - return ch - text; - -} - -int CFontManager::GetTextWide(HFont font, const char *text, int size) -{ - int wide; - - GetTextSize( font, text, &wide, NULL, size ); - - return wide; -} - -int CFontManager::GetTextHeight(HFont fontHandle, const char *text, int size ) -{ - CBaseFont *font = GetIFontFromHandle( fontHandle ); - if( !font || !text || !text[0] ) - { - return 0; - } - - int height = font->GetHeight(); - - // lightweight variant only for getting text height - int i = 0; - while( *text&&( size < 0 || i < size ) ) - { - if( *text == '\n' ) - height += height; - - text++; - i++; - } - return height; -} - -int CFontManager::GetTextHeightExt( HFont fontHandle, const char *text, int height, int w, int size ) -{ - CBaseFont *font = GetIFontFromHandle( fontHandle ); - if( !font || !text || !text[0] || !w ) - { - return 0; - } - - const char *text2 = text; - int y = 0; - - while( *text2 && ( size < 0 || text2 - text < size ) ) - { - int pos = CutText( fontHandle, text2, height, w, false, true ); - if( pos == 0 ) - break; - - y += height; - text2 += pos; - } - - return y; - -} - -int CFontManager::GetTextWideScaled(HFont font, const char *text, const int height, int size) -{ - CBaseFont *pFont = GetIFontFromHandle( font ); - if( pFont ) - { - return GetTextWide( font, text, size ) -#ifdef SCALE_FONTS - * ((float)height / (float)pFont->GetTall()) -#endif - ; - } - - return 0; -} - -void CFontManager::UploadTextureForFont(CBaseFont *font) -{ - // upload only latin needed for english and cyrillic needed for russian - // maybe it would be extended someday... - - charRange_t range[] = - { - { 0x0021, 0x007E, NULL, 0 }, // ascii printable range - { 0x00C0, 0x00FF, NULL, 0 }, // latin-1 supplement (letters only) - { 0x0100, 0x017F, NULL, 0 }, // latin extended a - { 0x0400, 0x045F, NULL, 0 }, // cyrillic range - { 0, 0, table_cp1251, V_ARRAYSIZE( table_cp1251 ) }, // cp1251 - }; - - font->UploadGlyphsForRanges( range, V_ARRAYSIZE( range ) ); -} - -int CFontManager::DrawCharacter(HFont fontHandle, int ch, Point pt, int charH, const unsigned int color, bool forceAdditive ) -{ - CBaseFont *font = GetIFontFromHandle( fontHandle ); - - if( !font ) - return 0; - - return font->DrawCharacter( ch, pt, charH, color, forceAdditive ); -} - -void CFontManager::DebugDraw(HFont fontHandle) -{ - CBaseFont *font = GetIFontFromHandle(fontHandle); - - font->DebugDraw(); -} - - -HFont CFontBuilder::Create() -{ - CBaseFont *font; - - // check existing font at first - if( !m_hForceHandle ) - { - for( int i = 0; i < g_FontMgr->m_Fonts.Count(); i++ ) - { - font = g_FontMgr->m_Fonts[i]; - - if( font->IsEqualTo( m_szName, m_iTall, m_iWeight, m_iBlur, m_iFlags ) ) - return i + 1; - } - } - -#if defined(MAINUI_USE_FREETYPE) - font = new CFreeTypeFont(); -#elif defined(MAINUI_USE_STB) - font = new CStbFont(); -#elif defined(_WIN32) && defined(MAINUI_USE_CUSTOM_FONT_RENDER) - font = new CWinAPIFont(); -#else - font = new CBitmapFont(); -#endif - - double starttime = EngFuncs::DoubleTime(); - - if( !font->Create( m_szName, m_iTall, m_iWeight, m_iBlur, m_fBrighten, m_iOutlineSize, m_iScanlineOffset, m_fScanlineScale, m_iFlags ) ) - { - delete font; - - // fallback to bitmap font - font = new CBitmapFont(); - - // should never fail - if( !font->Create( "Bitmap Font", m_iTall, m_iWeight, m_iBlur, m_fBrighten, m_iOutlineSize, m_iScanlineOffset, m_fScanlineScale, m_iFlags ) ) - { - delete font; - return -1; - } - } - - g_FontMgr->UploadTextureForFont( font ); - - double endtime = EngFuncs::DoubleTime(); - - Con_DPrintf( "Rendering %s(%i, %i) took %f seconds\n", font->GetName(), m_iTall, m_iWeight, endtime - starttime ); - - if( m_hForceHandle != -1 && g_FontMgr->m_Fonts.Count() != m_hForceHandle ) - { - if( g_FontMgr->m_Fonts.IsValidIndex( m_hForceHandle ) ) - { - g_FontMgr->m_Fonts.FastRemove( m_hForceHandle ); - return g_FontMgr->m_Fonts.InsertBefore( m_hForceHandle, font ); - } - } - - return g_FontMgr->m_Fonts.AddToTail(font) + 1; -} - -bool CFontManager::FindFontDataFile( const char *name, int tall, int weight, int flags, char *dataFile, size_t dataFileChars ) -{ - if( !strcmp( name, "Trebuchet MS" )) - { - Q_strncpy( dataFile, "gfx/fonts/FiraSans-Regular.ttf", dataFileChars ); - return true; - } - else if( !strcmp( name, "Tahoma" )) - { - Q_strncpy( dataFile, "gfx/fonts/tahoma.ttf", dataFileChars ); - return true; - } - - return false; -} - -byte *CFontManager::LoadFontDataFile( const char *vfspath, int *plen ) -{ - int i = m_FontFiles.Find( vfspath ); - if( i != m_FontFiles.InvalidIndex( )) - { - if( plen ) - *plen = m_FontFiles[i].length; - - return m_FontFiles[i].data; - } - int len = 0; - byte *p = EngFuncs::COM_LoadFile( vfspath, &len ); - if( p != nullptr ) - { - if( plen ) - *plen = len; - - font_file file = { len, p }; - m_FontFiles.Insert( vfspath, file ); - } - - return p; -} +/* +FontManager.cpp - font manager +Copyright (C) 2017 a1batross + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. +*/ +#include +#include "FontManager.h" +#include "BaseMenu.h" +#include "Utils.h" + +#include "BaseFontBackend.h" + +#if defined(MAINUI_USE_FREETYPE) +#include "FreeTypeFont.h" +#elif defined(MAINUI_USE_STB) +#include "StbFont.h" +#elif defined(_WIN32) +#include "WinAPIFont.h" +#endif + +#include "BitmapFont.h" +#include "utflib.h" + +#define DEFAULT_MENUFONT "Trebuchet MS" +#define DEFAULT_CONFONT "Tahoma" +#define DEFAULT_WEIGHT 500 + +CFontManager *g_FontMgr; + +CFontManager::CFontManager() +{ +#ifdef MAINUI_USE_FREETYPE + FT_Init_FreeType( &CFreeTypeFont::m_Library ); +#endif + m_Fonts.EnsureCapacity( 4 ); + m_FontFiles.EnsureCapacity( 2 ); +} + +CFontManager::~CFontManager() +{ + DeleteAllFonts(); +#ifdef MAINUI_USE_FREETYPE + FT_Done_FreeType( CFreeTypeFont::m_Library ); + CFreeTypeFont::m_Library = NULL; +#endif + + FOR_EACH_HASHMAP( m_FontFiles, i ) + { + byte *p = m_FontFiles.Element( i ).data; + EngFuncs::COM_FreeFile( p ); + } + + m_FontFiles.Purge(); +} + +void CFontManager::VidInit( void ) +{ + static float prevScale = 0; + + float scale = uiStatic.scaleY; + + if( !prevScale +#ifndef SCALE_FONTS // complete disables font re-rendering + || fabs( scale - prevScale ) > 0.1f +#endif + ) + { + DeleteAllFonts(); + uiStatic.hDefaultFont = CFontBuilder( DEFAULT_MENUFONT, UI_MED_CHAR_HEIGHT * scale, DEFAULT_WEIGHT ) + .SetHandleNum( QM_DEFAULTFONT ) + .Create(); + uiStatic.hSmallFont = CFontBuilder( DEFAULT_MENUFONT, UI_SMALL_CHAR_HEIGHT * scale, DEFAULT_WEIGHT ) + .SetHandleNum( QM_SMALLFONT ) + .Create(); + uiStatic.hSmallerFont = CFontBuilder( DEFAULT_MENUFONT, UI_SMALLER_CHAR_HEIGHT * scale, DEFAULT_WEIGHT ) + .SetHandleNum( QM_SMALLERFONT ) + .Create(); + uiStatic.hTinyFont = CFontBuilder( DEFAULT_MENUFONT, UI_TINY_CHAR_HEIGHT * scale, DEFAULT_WEIGHT ) + .SetHandleNum( QM_TINYFONT ) + .Create(); + uiStatic.hBigFont = CFontBuilder( DEFAULT_MENUFONT, UI_BIG_CHAR_HEIGHT * scale, DEFAULT_WEIGHT ) + .SetHandleNum( QM_BIGFONT ) + .Create(); + uiStatic.hBoldFont = CFontBuilder( DEFAULT_MENUFONT, UI_MED_CHAR_HEIGHT * scale, 1000 ) + .SetHandleNum( QM_BOLDFONT ) + .Create(); + + if( !uiStatic.lowmemory ) + { + uiStatic.hLightBlur = CFontBuilder( DEFAULT_MENUFONT, UI_MED_CHAR_HEIGHT * scale, DEFAULT_WEIGHT ) + .SetBlurParams( 2 * scale, 1.25f ) + .Create(); + + uiStatic.hHeavyBlur = CFontBuilder( DEFAULT_MENUFONT, UI_MED_CHAR_HEIGHT * scale, DEFAULT_WEIGHT ) + .SetBlurParams( 8 * scale, 2.0f ) + .Create(); + } + + uiStatic.hConsoleFont = CFontBuilder( DEFAULT_CONFONT, UI_CONSOLE_CHAR_HEIGHT * scale, 500 ) + .SetOutlineSize() + .Create(); + prevScale = scale; + } +} + +void CFontManager::DeleteAllFonts() +{ + for( int i = 0; i < m_Fonts.Count(); i++ ) + { + delete m_Fonts[i]; + } + m_Fonts.RemoveAll(); +} + +void CFontManager::DeleteFont(HFont hFont) +{ + CBaseFont *font = GetIFontFromHandle(hFont); + if( font ) + { + m_Fonts[hFont-1] = NULL; + + delete font; + } +} + +CBaseFont *CFontManager::GetIFontFromHandle(HFont font) +{ + if( m_Fonts.IsValidIndex( font - 1 ) ) + return m_Fonts[font-1]; + + return NULL; +} + +int CFontManager::GetEllipsisWide(HFont font) +{ + if( m_Fonts.IsValidIndex( font - 1 ) ) + return m_Fonts[font-1]->GetEllipsisWide(); + return 0; +} + +void CFontManager::GetCharABCWide(HFont font, int ch, int &a, int &b, int &c) +{ + CBaseFont *pFont = GetIFontFromHandle( font ); + if( pFont ) + pFont->GetCharABCWidths( ch, a, b, c ); + else + a = b = c = 0; +} + +int CFontManager::GetCharacterWidth(HFont font, int ch) +{ + int a, b, c; + GetCharABCWide( font, ch, a, b, c ); + return a + b + c; +} + +int CFontManager::GetCharacterWidthScaled(HFont font, int ch, int height) +{ + return GetCharacterWidth( font, ch ) +#ifdef SCALE_FONTS + * ((float)height / (float)GetFontTall( font )) +#endif + ; +} + +HFont CFontManager::GetFontByName(const char *name) +{ + for( int i = 0; i < m_Fonts.Count(); i++ ) + { + if( !stricmp( name, m_Fonts[i]->GetName() ) ) + return i; + } + return -1; +} + +int CFontManager::GetFontTall(HFont font) +{ + CBaseFont *pFont = GetIFontFromHandle( font ); + if( pFont ) + return pFont->GetTall(); + return 0; +} + +int CFontManager::GetFontAscent(HFont font) +{ + CBaseFont *pFont = GetIFontFromHandle( font ); + if( pFont ) + return pFont->GetAscent(); + return 0; +} + +bool CFontManager::GetFontUnderlined(HFont font) +{ + CBaseFont *pFont = GetIFontFromHandle( font ); + if( pFont ) + return pFont->GetFlags() & FONT_UNDERLINE; + return false; +} + +void CFontManager::GetTextSize(HFont fontHandle, const char *text, int *wide, int *tall, int size ) +{ + CBaseFont *font = GetIFontFromHandle( fontHandle ); + + if( !font || !text || !text[0] ) + { + if( wide ) *wide = 0; + if( tall ) *tall = 0; + return; + } + + int fontTall = font->GetHeight(), x = 0; + int _wide = 0, _tall; + const char *ch = text; + _tall = fontTall; + int i = 0; + utfstate_t state; + + while( *ch && ( size < 0 || i < size ) ) + { + // Skip colorcodes + if( IsColorString( ch ) ) + { + ch += 2; + continue; + } + + int uch = state.Decode((uint8_t)*ch ); + + if( uch ) + { + if( uch == '\n' && *( ch + 1 ) != '\0' ) + { + _tall += fontTall; + x = 0; + } + else + { + int a, b, c; + font->GetCharABCWidths( uch, a, b, c ); + x += a + b + c; + if( x > _wide ) + _wide = x; + } + } + i++; + ch++; + } + + if( tall ) *tall = _tall; + if( wide ) *wide = _wide; +} + +int CFontManager::CutText(HFont fontHandle, const char *text, int height, int visibleSize, bool reverse, bool stopAtWhitespace, int *wide, bool *remaining ) +{ + CBaseFont *font = GetIFontFromHandle( fontHandle ); + + if( remaining ) + *remaining = false; + + if( !font || !text || !text[0] || visibleSize <= 0 ) + return 0; + + int _wide = 0; + const char *ch = text; + utfstate_t state; + +#ifdef SCALE_FONTS + visibleSize = (float)visibleSize / (float)height * (float)font->GetTall(); +#endif + + int whiteSpacePos = 0; + + // calculate full text wide + while( *ch ) + { + // skip colorcodes + if( IsColorString( ch ) ) + { + ch += 2; + continue; + } + + int uch = state.Decode((uint8_t)*ch ); + int x = 0; + if( uch ) + { + if( uch == '\n' ) + { + ch++; + break; // + } + + int a, b, c; + font->GetCharABCWidths( uch, a, b, c ); + x = a + b + c; + + if( uch == ' ' ) + { + whiteSpacePos = ch - text; + } + } + + if( !reverse && _wide + x >= visibleSize ) + break; + + ch++; + _wide += x; + } + + if( !reverse ) + { + if( *ch && remaining ) *remaining = true; + if( wide ) *wide = _wide; + if( stopAtWhitespace && whiteSpacePos ) + return whiteSpacePos; + return ch - text; + } + + if( _wide < visibleSize ) + { + if( remaining ) *remaining = false; + if( wide ) *wide = _wide; + return 0; + } + + ch = text; + + whiteSpacePos = 0; + + // now remove character one by one to fit + state.Reset(); + while( *ch && _wide > visibleSize ) + { + // skip colorcodes + if( IsColorString( ch ) ) + { + ch += 2; + continue; + } + + int uch = state.Decode((uint8_t)*ch ); + if( uch ) + { + // we don't need check for newlines here, it's only done for oneline Field widget + int a, b, c; + font->GetCharABCWidths( uch, a, b, c ); + _wide -= a + b + c; + + if( uch == ' ' ) + { + whiteSpacePos = ch - text; + } + } + ch++; + } + + if( remaining ) *remaining = true; + if( wide ) *wide = _wide; + if( stopAtWhitespace && whiteSpacePos ) return whiteSpacePos; + return ch - text; + +} + +int CFontManager::GetTextWide(HFont font, const char *text, int size) +{ + int wide; + + GetTextSize( font, text, &wide, NULL, size ); + + return wide; +} + +int CFontManager::GetTextHeight(HFont fontHandle, const char *text, int size ) +{ + CBaseFont *font = GetIFontFromHandle( fontHandle ); + if( !font || !text || !text[0] ) + { + return 0; + } + + int height = font->GetHeight(); + + // lightweight variant only for getting text height + int i = 0; + while( *text&&( size < 0 || i < size ) ) + { + if( *text == '\n' ) + height += height; + + text++; + i++; + } + return height; +} + +int CFontManager::GetTextHeightExt( HFont fontHandle, const char *text, int height, int w, int size ) +{ + CBaseFont *font = GetIFontFromHandle( fontHandle ); + if( !font || !text || !text[0] || !w ) + { + return 0; + } + + const char *text2 = text; + int y = 0; + + while( *text2 && ( size < 0 || text2 - text < size ) ) + { + int pos = CutText( fontHandle, text2, height, w, false, true ); + if( pos == 0 ) + break; + + y += height; + text2 += pos; + } + + return y; + +} + +int CFontManager::GetTextWideScaled(HFont font, const char *text, const int height, int size) +{ + CBaseFont *pFont = GetIFontFromHandle( font ); + if( pFont ) + { + return GetTextWide( font, text, size ) +#ifdef SCALE_FONTS + * ((float)height / (float)pFont->GetTall()) +#endif + ; + } + + return 0; +} + +void CFontManager::UploadTextureForFont(CBaseFont *font) +{ + // upload only latin needed for english and cyrillic needed for russian + // maybe it would be extended someday... + + charRange_t range[] = + { + { 0x0021, 0x007E, NULL, 0 }, // ascii printable range + { 0x00C0, 0x00FF, NULL, 0 }, // latin-1 supplement (letters only) + { 0x0100, 0x017F, NULL, 0 }, // latin extended a + { 0x0400, 0x045F, NULL, 0 }, // cyrillic range + { 0, 0, table_cp1251, V_ARRAYSIZE( table_cp1251 ) }, // cp1251 + }; + + font->UploadGlyphsForRanges( range, V_ARRAYSIZE( range ) ); +} + +int CFontManager::DrawCharacter(HFont fontHandle, int ch, Point pt, int charH, const unsigned int color, bool forceAdditive ) +{ + CBaseFont *font = GetIFontFromHandle( fontHandle ); + + if( !font ) + return 0; + + return font->DrawCharacter( ch, pt, charH, color, forceAdditive ); +} + +void CFontManager::DebugDraw(HFont fontHandle) +{ + CBaseFont *font = GetIFontFromHandle(fontHandle); + + font->DebugDraw(); +} + + +HFont CFontBuilder::Create() +{ + CBaseFont *font; + + // check existing font at first + if( !m_hForceHandle ) + { + for( int i = 0; i < g_FontMgr->m_Fonts.Count(); i++ ) + { + font = g_FontMgr->m_Fonts[i]; + + if( font->IsEqualTo( m_szName, m_iTall, m_iWeight, m_iBlur, m_iFlags ) ) + return i + 1; + } + } + +#if defined(MAINUI_USE_FREETYPE) + font = new CFreeTypeFont(); +#elif defined(MAINUI_USE_STB) + font = new CStbFont(); +#elif defined(_WIN32) && defined(MAINUI_USE_CUSTOM_FONT_RENDER) + font = new CWinAPIFont(); +#else + font = new CBitmapFont(); +#endif + + double starttime = EngFuncs::DoubleTime(); + + if( !font->Create( m_szName, m_iTall, m_iWeight, m_iBlur, m_fBrighten, m_iOutlineSize, m_iScanlineOffset, m_fScanlineScale, m_iFlags ) ) + { + delete font; + + // fallback to bitmap font + font = new CBitmapFont(); + + // should never fail + if( !font->Create( "Bitmap Font", m_iTall, m_iWeight, m_iBlur, m_fBrighten, m_iOutlineSize, m_iScanlineOffset, m_fScanlineScale, m_iFlags ) ) + { + delete font; + return -1; + } + } + + g_FontMgr->UploadTextureForFont( font ); + + double endtime = EngFuncs::DoubleTime(); + + Con_DPrintf( "Rendering %s(%i, %i) took %f seconds\n", font->GetName(), m_iTall, m_iWeight, endtime - starttime ); + + if( m_hForceHandle != -1 && g_FontMgr->m_Fonts.Count() != m_hForceHandle ) + { + if( g_FontMgr->m_Fonts.IsValidIndex( m_hForceHandle ) ) + { + g_FontMgr->m_Fonts.FastRemove( m_hForceHandle ); + return g_FontMgr->m_Fonts.InsertBefore( m_hForceHandle, font ); + } + } + + return g_FontMgr->m_Fonts.AddToTail(font) + 1; +} + +bool CFontManager::FindFontDataFile( const char *name, int tall, int weight, int flags, char *dataFile, size_t dataFileChars ) +{ + if( !strcmp( name, "Trebuchet MS" )) + { + // SwedenCode: the CS 1.6 menus use Verdana Bold; DejaVu Sans Bold (cs16/extras.pk3) is its free stand-in + if( LoadFontDataFile( "gfx/fonts/DejaVuSans-Bold.ttf", nullptr )) + Q_strncpy( dataFile, "gfx/fonts/DejaVuSans-Bold.ttf", dataFileChars ); + else + Q_strncpy( dataFile, "gfx/fonts/FiraSans-Regular.ttf", dataFileChars ); + return true; + } + else if( !strcmp( name, "Tahoma" )) + { + Q_strncpy( dataFile, "gfx/fonts/tahoma.ttf", dataFileChars ); + return true; + } + + return false; +} + +byte *CFontManager::LoadFontDataFile( const char *vfspath, int *plen ) +{ + int i = m_FontFiles.Find( vfspath ); + if( i != m_FontFiles.InvalidIndex( )) + { + if( plen ) + *plen = m_FontFiles[i].length; + + return m_FontFiles[i].data; + } + int len = 0; + byte *p = EngFuncs::COM_LoadFile( vfspath, &len ); + if( p != nullptr ) + { + if( plen ) + *plen = len; + + font_file file = { len, p }; + m_FontFiles.Insert( vfspath, file ); + } + + return p; +} diff --git a/3rdparty/mainui_cpp/sdk_includes/public/build.h b/3rdparty/mainui_cpp/sdk_includes/public/build.h index b92c51e..ad4ba14 100644 --- a/3rdparty/mainui_cpp/sdk_includes/public/build.h +++ b/3rdparty/mainui_cpp/sdk_includes/public/build.h @@ -76,6 +76,7 @@ Then you can use another oneliner to query all variables: #undef XASH_OPENBSD #undef XASH_OSX #undef XASH_POSIX +#undef XASH_EMSCRIPTEN #undef XASH_PPC #undef XASH_PS4 #undef XASH_PSP @@ -144,6 +145,8 @@ Then you can use another oneliner to query all variables: #define XASH_PSVITA 1 #elif defined __wasi__ #define XASH_WASI 1 + #elif defined __EMSCRIPTEN__ + #define XASH_EMSCRIPTEN 1 #elif defined __sun__ #define XASH_SUNOS 1 #elif defined __gnu_hurd__ diff --git a/3rdparty/mainui_cpp/sdk_includes/public/buildenums.h b/3rdparty/mainui_cpp/sdk_includes/public/buildenums.h index c91f5e6..fa58a35 100644 --- a/3rdparty/mainui_cpp/sdk_includes/public/buildenums.h +++ b/3rdparty/mainui_cpp/sdk_includes/public/buildenums.h @@ -61,6 +61,7 @@ For more information, please refer to #define PLATFORM_PSP 18 #define PLATFORM_IOS 19 #define PLATFORM_PS4 20 +#define PLATFORM_EMSCRIPTEN 21 #if XASH_WIN32 #define XASH_PLATFORM PLATFORM_WIN32 @@ -100,6 +101,8 @@ For more information, please refer to #define XASH_PLATFORM PLATFORM_PSP #elif XASH_PS4 #define XASH_PLATFORM PLATFORM_PS4 +#elif XASH_EMSCRIPTEN + #define XASH_PLATFORM PLATFORM_EMSCRIPTEN #else #error #endif diff --git a/3rdparty/mainui_cpp/udll_int.cpp b/3rdparty/mainui_cpp/udll_int.cpp index b0b01ec..31b45e7 100644 --- a/3rdparty/mainui_cpp/udll_int.cpp +++ b/3rdparty/mainui_cpp/udll_int.cpp @@ -1,246 +1,267 @@ -/* -dll_int.cpp - dll entry point -Copyright (C) 2010 Uncle Mike - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. -*/ - - -#include "extdll_menu.h" -#include "BaseMenu.h" -#include "Utils.h" -#include "cl_dll/IGameMenuExports.h" -#include "cl_dll/IGameClientExports.h" -#include "interface.h" -#include "font/FontManager.h" - -extern void UI_JoinGame_Show( int param1, int param2 ); -extern void UI_JoinClassT_Show( int param1, int param2 ); -extern void UI_JoinClassCT_Show( int param1, int param2 ); -extern void UI_BuyMenu_Show( int param1, int param2 ); -extern void UI_BuyMenu_Pistol_Show( int param1, int param2 ); -extern void UI_BuyMenu_Shotgun_Show( int param1, int param2 ); -extern void UI_BuyMenu_Submachine_Show( int param1, int param2 ); -extern void UI_BuyMenu_Rifle_Show( int param1, int param2 ); -extern void UI_BuyMenu_Machinegun_Show( int param1, int param2 ); -extern void UI_BuyMenu_Item_Show( int param1, int param2 ); - -ui_enginefuncs_t EngFuncs::engfuncs; -ui_extendedfuncs_t EngFuncs::textfuncs; -ui_globalvars_t *gpGlobals; -IGameClientExports *g_pClient; -CMenu gMenu; - -static UI_FUNCTIONS gFunctionTable = -{ - UI_VidInit, - UI_Init, - UI_Shutdown, - UI_UpdateMenu, - UI_KeyEvent, - UI_MouseMove, - UI_SetActiveMenu, - UI_AddServerToList, - UI_GetCursorPos, - UI_SetCursorPos, - UI_ShowCursor, - UI_CharEvent, - UI_MouseInRect, - UI_IsVisible, - UI_CreditsActive, - UI_FinalCredits -}; - -//======================================================================= -// GetApi -//======================================================================= -extern "C" EXPORT int GetMenuAPI(UI_FUNCTIONS *pFunctionTable, ui_enginefuncs_t* pEngfuncsFromEngine, ui_globalvars_t *pGlobals) -{ - if( !pFunctionTable || !pEngfuncsFromEngine ) - { - return false; - } - - // copy HUD_FUNCTIONS table to engine, copy engfuncs table from engine - memcpy( pFunctionTable, &gFunctionTable, sizeof( UI_FUNCTIONS )); - memcpy( &EngFuncs::engfuncs, pEngfuncsFromEngine, sizeof( ui_enginefuncs_t )); - memset( &EngFuncs::textfuncs, 0, sizeof( ui_extendedfuncs_t )); - - gpGlobals = pGlobals; - - return true; -} - -static UI_EXTENDED_FUNCTIONS gExtendedTable = -{ - AddTouchButtonToList, - UI_MenuResetPing_f, - UI_ConnectionWarning_f, - UI_UpdateDialog, - UI_ShowMessageBox, - UI_ConnectionProgress_Disconnect, - UI_ConnectionProgress_Download, - UI_ConnectionProgress_DownloadEnd, - UI_ConnectionProgress_Precache, - UI_ConnectionProgress_Connect, - UI_ConnectionProgress_ChangeLevel, - UI_ConnectionProgress_ParseServerInfo -}; - -extern "C" EXPORT int GetExtAPI( int version, UI_EXTENDED_FUNCTIONS *pFunctionTable, ui_extendedfuncs_t *pEngfuncsFromEngine ) -{ - if( !pFunctionTable || !pEngfuncsFromEngine ) - { - return false; - } - - if( version != MENU_EXTENDED_API_VERSION ) - { - Con_Printf( "Error: failed to initialize extended menu API. Expected by DLL: %d. Got from engine: %d\n", MENU_EXTENDED_API_VERSION, version ); - return false; - } - - memcpy( &EngFuncs::textfuncs, pEngfuncsFromEngine, sizeof( ui_extendedfuncs_t ) ); - memcpy( pFunctionTable, &gExtendedTable, sizeof( UI_EXTENDED_FUNCTIONS )); - - return true; -} - -static class CGameMenuExports : public IGameMenuExports -{ -public: - bool Initialize( CreateInterfaceFn appFactory ) override - { - // Menu is already initialized by the module, but we still need to - // resolve the client export interface for the menu system. - if( !appFactory ) - return false; - - g_pClient = static_cast( appFactory( GAMECLIENTEXPORTS_INTERFACE_VERSION, NULL ) ); - return g_pClient != nullptr; - } - - bool IsActive() override - { - // Return true only for client-side menu activity. - // Main menu should not be counted as client menu here. - if( !uiStatic.initialized ) - return false; - return uiStatic.client.IsActive() && !uiStatic.menu.IsActive(); - } - - bool IsMainMenuActive() override - { - // Return true when the main menu is active, regardless of client UI stack. - if( !uiStatic.initialized ) - return false; - return uiStatic.menu.IsActive(); - } - - void MouseMove( int x, int y ) override - { - // Pass mouse position to menu system - UI_MouseMove( x, y ); - } - - void Key( int keynum, int down ) override - { - // Pass keyboard events to the menu system - UI_KeyEvent( keynum, down ); - } - - void ShowVGUIMenu( int menuType, int param1, int param2 ) override - { - // Clear button states to prevent stuck input - // when opening the menu while a key is held down - EngFuncs::KEY_ClearStates(); - - switch( menuType ) - { - case MENU_TEAM: UI_JoinGame_Show( param1, param2 ); break; - case MENU_CLASS_T: UI_JoinClassT_Show( param1, param2 ); break; - case MENU_CLASS_CT: UI_JoinClassCT_Show( param1, param2 ); break; - case MENU_BUY: UI_BuyMenu_Show( param1, param2 ); break; - case MENU_BUY_PISTOL: UI_BuyMenu_Pistol_Show( param1, param2 ); break; - case MENU_BUY_SHOTGUN: UI_BuyMenu_Shotgun_Show( param1, param2 ); break; - case MENU_BUY_SUBMACHINEGUN: UI_BuyMenu_Submachine_Show( param1, param2 ); break; - case MENU_BUY_RIFLE: UI_BuyMenu_Rifle_Show( param1, param2 ); break; - case MENU_BUY_MACHINEGUN: UI_BuyMenu_Machinegun_Show( param1, param2 ); break; - case MENU_BUY_ITEM: UI_BuyMenu_Item_Show( param1, param2 ); break; - } - } - - void HideVGUIMenu( void ) override - { - UI_CloseClientMenu(); - } - - const char *L( const char *szStr ) override - { - // Localization function - route through the shared string lookup - return ::L( szStr ); - } - - HFont BuildFont( CFontBuilder &builder ) override - { - return builder.Create(); - } - - void GetCharABCWide( HFont font, int ch, int &a, int &b, int &c ) override - { - g_FontMgr->GetCharABCWide( font, ch, a, b, c ); - } - - int GetFontTall( HFont font ) override - { - return g_FontMgr->GetFontTall( font ); - } - - int GetCharacterWidth( HFont font, int ch, int charH ) override - { - return g_FontMgr->GetCharacterWidthScaled( font, ch, charH ); - } - - void GetTextSize( HFont font, const char *text, int *wide, int *height, int size ) override - { - g_FontMgr->GetTextSize( font, text, wide, height, size ); - } - - int GetTextHeight( HFont font, const char *text, int size ) override - { - return g_FontMgr->GetTextHeight( font, text, size ); - } - - int DrawCharacter( HFont font, int ch, int x, int y, int charH, const unsigned int color, bool forceAdditive ) override - { - return g_FontMgr->DrawCharacter( font, ch, Point(x, y), charH, color, forceAdditive ); - } - - void SetupScoreboard( int xstart, int xend, int ystart, int yend, unsigned int color, bool drawStroke ) override - { - // TODO: Implement scoreboard setup using mainui drawing functions - // This should configure scoreboard rendering parameters - } - - void DrawScoreboard( void ) override - { - // TODO: Implement scoreboard drawing using mainui font and drawing functions - // This should render the actual scoreboard with player names, scores, etc. - } - - void DrawSpectatorMenu( void ) override - { - // TODO: Implement spectator menu drawing using mainui font and drawing functions - // This should render spectator-specific UI elements - } -} s_Menu; - -EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CGameMenuExports, IGameMenuExports, GAMEMENUEXPORTS_INTERFACE_VERSION, s_Menu ); +/* +dll_int.cpp - dll entry point +Copyright (C) 2010 Uncle Mike + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. +*/ + + +#ifdef __EMSCRIPTEN__ +#include +#endif +#include "extdll_menu.h" +#include "BaseMenu.h" +#include "Utils.h" +#include "cl_dll/IGameMenuExports.h" +#include "cl_dll/IGameClientExports.h" +#include "interface.h" +#include "font/FontManager.h" + +extern void UI_JoinGame_Show( int param1, int param2 ); +extern void UI_JoinClassT_Show( int param1, int param2 ); +extern void UI_JoinClassCT_Show( int param1, int param2 ); +extern void UI_BuyMenu_Show( int param1, int param2 ); +extern void UI_BuyMenu_Pistol_Show( int param1, int param2 ); +extern void UI_BuyMenu_Shotgun_Show( int param1, int param2 ); +extern void UI_BuyMenu_Submachine_Show( int param1, int param2 ); +extern void UI_BuyMenu_Rifle_Show( int param1, int param2 ); +extern void UI_BuyMenu_Machinegun_Show( int param1, int param2 ); +extern void UI_BuyMenu_Item_Show( int param1, int param2 ); + +ui_enginefuncs_t EngFuncs::engfuncs; +ui_extendedfuncs_t EngFuncs::textfuncs; +ui_globalvars_t *gpGlobals; +IGameClientExports *g_pClient; +CMenu gMenu; + +static UI_FUNCTIONS gFunctionTable = +{ + UI_VidInit, + UI_Init, + UI_Shutdown, + UI_UpdateMenu, + UI_KeyEvent, + UI_MouseMove, + UI_SetActiveMenu, + UI_AddServerToList, + UI_GetCursorPos, + UI_SetCursorPos, + UI_ShowCursor, + UI_CharEvent, + UI_MouseInRect, + UI_IsVisible, + UI_CreditsActive, + UI_FinalCredits +}; + +//======================================================================= +// GetApi +//======================================================================= +extern "C" EXPORT int GetMenuAPI(UI_FUNCTIONS *pFunctionTable, ui_enginefuncs_t* pEngfuncsFromEngine, ui_globalvars_t *pGlobals) +{ + if( !pFunctionTable || !pEngfuncsFromEngine ) + { + return false; + } + + // copy HUD_FUNCTIONS table to engine, copy engfuncs table from engine + memcpy( pFunctionTable, &gFunctionTable, sizeof( UI_FUNCTIONS )); + memcpy( &EngFuncs::engfuncs, pEngfuncsFromEngine, sizeof( ui_enginefuncs_t )); + memset( &EngFuncs::textfuncs, 0, sizeof( ui_extendedfuncs_t )); + + gpGlobals = pGlobals; + + return true; +} + +static UI_EXTENDED_FUNCTIONS gExtendedTable = +{ + AddTouchButtonToList, + UI_MenuResetPing_f, + UI_ConnectionWarning_f, + UI_UpdateDialog, + UI_ShowMessageBox, + UI_ConnectionProgress_Disconnect, + UI_ConnectionProgress_Download, + UI_ConnectionProgress_DownloadEnd, + UI_ConnectionProgress_Precache, + UI_ConnectionProgress_Connect, + UI_ConnectionProgress_ChangeLevel, + UI_ConnectionProgress_ParseServerInfo +}; + +extern "C" EXPORT int GetExtAPI( int version, UI_EXTENDED_FUNCTIONS *pFunctionTable, ui_extendedfuncs_t *pEngfuncsFromEngine ) +{ + if( !pFunctionTable || !pEngfuncsFromEngine ) + { + return false; + } + + if( version != MENU_EXTENDED_API_VERSION ) + { + Con_Printf( "Error: failed to initialize extended menu API. Expected by DLL: %d. Got from engine: %d\n", MENU_EXTENDED_API_VERSION, version ); + return false; + } + + memcpy( &EngFuncs::textfuncs, pEngfuncsFromEngine, sizeof( ui_extendedfuncs_t ) ); + memcpy( pFunctionTable, &gExtendedTable, sizeof( UI_EXTENDED_FUNCTIONS )); + + return true; +} + +static class CGameMenuExports : public IGameMenuExports +{ +public: + bool Initialize( CreateInterfaceFn appFactory ) override + { + // Menu is already initialized by the module, but we still need to + // resolve the client export interface for the menu system. + if( !appFactory ) + return false; + + g_pClient = static_cast( appFactory( GAMECLIENTEXPORTS_INTERFACE_VERSION, NULL ) ); + return g_pClient != nullptr; + } + + bool IsActive() override + { + // Return true only for client-side menu activity. + // Main menu should not be counted as client menu here. + if( !uiStatic.initialized ) + return false; + return uiStatic.client.IsActive() && !uiStatic.menu.IsActive(); + } + + bool IsMainMenuActive() override + { + // Return true when the main menu is active, regardless of client UI stack. + if( !uiStatic.initialized ) + return false; + return uiStatic.menu.IsActive(); + } + + void MouseMove( int x, int y ) override + { + // Pass mouse position to menu system + UI_MouseMove( x, y ); + } + + void Key( int keynum, int down ) override + { + // Pass keyboard events to the menu system + UI_KeyEvent( keynum, down ); + } + + void ShowVGUIMenu( int menuType, int param1, int param2 ) override + { + // Clear button states to prevent stuck input + // when opening the menu while a key is held down + EngFuncs::KEY_ClearStates(); + +#ifdef __EMSCRIPTEN__ + // web build: the page shows its own team and class screens when it has them + if( menuType == MENU_TEAM || menuType == MENU_CLASS_T || menuType == MENU_CLASS_CT ) + { + const char *map = g_pClient ? g_pClient->GetLevelName() : ""; + if( EM_ASM_INT({ return Module['onTeamMenu'] && Module['onTeamMenu']($0, $1, $2, UTF8ToString($3)) ? 1 : 0; }, menuType, param1, param2, map ? map : "" )) + return; + } + if( menuType >= MENU_BUY && menuType <= MENU_BUY_ITEM ) + { + if( EM_ASM_INT({ return Module['onBuyMenu'] && Module['onBuyMenu']($0, $1, $2, $3) ? 1 : 0; }, menuType, param1, param2, (int)EngFuncs::GetCvarFloat( "cscl_currentmoney" ) )) + return; + } +#endif + + switch( menuType ) + { + case MENU_TEAM: UI_JoinGame_Show( param1, param2 ); break; + case MENU_CLASS_T: UI_JoinClassT_Show( param1, param2 ); break; + case MENU_CLASS_CT: UI_JoinClassCT_Show( param1, param2 ); break; + case MENU_BUY: UI_BuyMenu_Show( param1, param2 ); break; + case MENU_BUY_PISTOL: UI_BuyMenu_Pistol_Show( param1, param2 ); break; + case MENU_BUY_SHOTGUN: UI_BuyMenu_Shotgun_Show( param1, param2 ); break; + case MENU_BUY_SUBMACHINEGUN: UI_BuyMenu_Submachine_Show( param1, param2 ); break; + case MENU_BUY_RIFLE: UI_BuyMenu_Rifle_Show( param1, param2 ); break; + case MENU_BUY_MACHINEGUN: UI_BuyMenu_Machinegun_Show( param1, param2 ); break; + case MENU_BUY_ITEM: UI_BuyMenu_Item_Show( param1, param2 ); break; + } + } + + void HideVGUIMenu( void ) override + { +#ifdef __EMSCRIPTEN__ + EM_ASM({ if( Module['onTeamMenuHide'] ) Module['onTeamMenuHide'](); }); +#endif + UI_CloseClientMenu(); + } + + const char *L( const char *szStr ) override + { + // Localization function - route through the shared string lookup + return ::L( szStr ); + } + + HFont BuildFont( CFontBuilder &builder ) override + { + return builder.Create(); + } + + void GetCharABCWide( HFont font, int ch, int &a, int &b, int &c ) override + { + g_FontMgr->GetCharABCWide( font, ch, a, b, c ); + } + + int GetFontTall( HFont font ) override + { + return g_FontMgr->GetFontTall( font ); + } + + int GetCharacterWidth( HFont font, int ch, int charH ) override + { + return g_FontMgr->GetCharacterWidthScaled( font, ch, charH ); + } + + void GetTextSize( HFont font, const char *text, int *wide, int *height, int size ) override + { + g_FontMgr->GetTextSize( font, text, wide, height, size ); + } + + int GetTextHeight( HFont font, const char *text, int size ) override + { + return g_FontMgr->GetTextHeight( font, text, size ); + } + + int DrawCharacter( HFont font, int ch, int x, int y, int charH, const unsigned int color, bool forceAdditive ) override + { + return g_FontMgr->DrawCharacter( font, ch, Point(x, y), charH, color, forceAdditive ); + } + + void SetupScoreboard( int xstart, int xend, int ystart, int yend, unsigned int color, bool drawStroke ) override + { + // TODO: Implement scoreboard setup using mainui drawing functions + // This should configure scoreboard rendering parameters + } + + void DrawScoreboard( void ) override + { + // TODO: Implement scoreboard drawing using mainui font and drawing functions + // This should render the actual scoreboard with player names, scores, etc. + } + + void DrawSpectatorMenu( void ) override + { + // TODO: Implement spectator menu drawing using mainui font and drawing functions + // This should render spectator-specific UI elements + } +} s_Menu; + +EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CGameMenuExports, IGameMenuExports, GAMEMENUEXPORTS_INTERFACE_VERSION, s_Menu );