From a7611c481eb43165bbc8a95411429b8e6a568175 Mon Sep 17 00:00:00 2001
From: nillerusr <nillerusr@gmail.com>
Date: Sat, 17 Sep 2022 21:00:50 +0300
Subject: [PATCH] game(client): fix atlas generation for touch

---
 game/client/touch.cpp | 21 ++++++++++++++++-----
 game/client/touch.h   |  1 +
 lib                   |  2 +-
 3 files changed, 18 insertions(+), 6 deletions(-)

diff --git a/game/client/touch.cpp b/game/client/touch.cpp
index ddb38ed2ea..c80550bb88 100644
--- a/game/client/touch.cpp
+++ b/game/client/touch.cpp
@@ -420,13 +420,13 @@ void CTouchControls::Init()
 
 int nextPowerOfTwo(int x)
 {
-		if( (x & (x - 1)) == 0)
-				return x;
+	if( (x & (x - 1)) == 0)
+		return x;
 
-		int t = 1 << 30;
-		while (x < t) t >>= 1;
+	int t = 1 << 30;
+	while (x < t) t >>= 1;
 
-		return t << 1;
+	return t << 1;
 }
 
 void CTouchControls::CreateAtlasTexture()
@@ -438,6 +438,9 @@ void CTouchControls::CreateAtlasTexture()
 	stbrp_rect *rects = (stbrp_rect*)malloc(textureList.Count()*sizeof(stbrp_rect));
 	memset(rects, 0, sizeof(stbrp_node)*textureList.Count());
 
+	if( touchTextureID )
+		vgui::surface()->DeleteTextureByID( touchTextureID );
+
 	for( int i = 0; i < textureList.Count(); i++ )
 	{
 		CTouchTexture *t = textureList[i];
@@ -516,6 +519,7 @@ void CTouchControls::CreateAtlasTexture()
 		}
 
 		DestroyVTFTexture(t->vtf);
+		t->isInAtlas = true;
 	}
 
 	touchTextureID = vgui::surface()->CreateNewTextureID( true );
@@ -643,7 +647,12 @@ void CTouchControls::Paint( )
 		CTouchButton *btn = *it;
 
 		if( btn->texture != NULL && !(btn->flags & TOUCH_FL_HIDE) )
+		{
+			if( !btn->texture->isInAtlas )
+				CreateAtlasTexture();
+
 			meshCount++;
+		}
 	}
 
 	meshBuilder.Begin( m_pMesh, MATERIAL_QUADS, meshCount );
@@ -734,6 +743,8 @@ void CTouchControls::AddButton( const char *name, const char *texturefile, const
 
 	CTouchTexture *texture = new CTouchTexture;
 	btn->texture = texture;
+	texture->isInAtlas = false;
+	texture->X0 = 0; texture->X1 = 0; texture->Y0 = 0; texture->Y1 = 0;
 	Q_strncpy( texture->szName, btn->texturefile, sizeof(btn->texturefile) );
 	textureList.AddToTail(texture);
 
diff --git a/game/client/touch.h b/game/client/touch.h
index 4bfd43142d..ad55536835 100644
--- a/game/client/touch.h
+++ b/game/client/touch.h
@@ -83,6 +83,7 @@ struct CTouchTexture
 
 	float X0, Y0, X1, Y1; // position in atlas texture
 	int height, width;
+	bool isInAtlas;
 	char szName[1024];
 };
 
diff --git a/lib b/lib
index 9ffeba566e..86a66ee92d 160000
--- a/lib
+++ b/lib
@@ -1 +1 @@
-Subproject commit 9ffeba566ef076b829041f19f015155e21f325ed
+Subproject commit 86a66ee92d9fda0a09f54a435e850faa7ab5d0fa