From 9709106aff52fe62b04f5a1faa1a2c259cd6cf89 Mon Sep 17 00:00:00 2001 From: Leonardo Zide Date: Tue, 20 Oct 2026 11:54:19 -0700 Subject: [PATCH] Bound grid generation for distant pieces A piece at an extreme coordinate expands the grid to millions of lines, causing excessive allocations or a truncated vertex buffer size followed by writes past its end. Larger coordinates can also exceed the integer range during conversion. Clamp finite grid bounds before converting to integers, limiting the vertex buffer to less than 1 MB, and use the default grid for non-finite bounds. Calculate texture extents in floating point to avoid integer overflow with large spacing values. --- common/lc_view.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/common/lc_view.cpp b/common/lc_view.cpp index e1c2ab98..8cba0c67 100644 --- a/common/lc_view.cpp +++ b/common/lc_view.cpp @@ -1640,12 +1640,16 @@ void lcView::DrawGrid() } } - if (GridSizeValid) + if (GridSizeValid && std::isfinite(Min[0]) && std::isfinite(Min[1]) && std::isfinite(Max[0]) && std::isfinite(Max[1])) { - MinX = (int)(floorf(Min[0] / (20.0f * Spacing))) - 1; - MinY = (int)(floorf(Min[1] / (20.0f * Spacing))) - 1; - MaxX = (int)(ceilf(Max[0] / (20.0f * Spacing))) + 1; - MaxY = (int)(ceilf(Max[1] / (20.0f * Spacing))) + 1; + // Bound grid coordinates before converting to integers, keeping the vertex buffer below 1 MB. + constexpr float MaxGridExtent = 10000.0f; + const float GridSpacing = 20.0f * Spacing; + + MinX = static_cast(floorf(lcClamp(Min[0] / GridSpacing, -MaxGridExtent + 1.0f, MaxGridExtent - 1.0f))) - 1; + MinY = static_cast(floorf(lcClamp(Min[1] / GridSpacing, -MaxGridExtent + 1.0f, MaxGridExtent - 1.0f))) - 1; + MaxX = static_cast(ceilf(lcClamp(Max[0] / GridSpacing, -MaxGridExtent + 1.0f, MaxGridExtent - 1.0f))) + 1; + MaxY = static_cast(ceilf(lcClamp(Max[1] / GridSpacing, -MaxGridExtent + 1.0f, MaxGridExtent - 1.0f))) + 1; MinX = lcMin(MinX, -2); MinY = lcMin(MinY, -2); @@ -1689,8 +1693,8 @@ void lcView::DrawGrid() float Top = MinY * 20.0f * Spacing; float Bottom = MaxY * 20.0f * Spacing; float Z = 0; - float U = (MaxX - MinX) * Spacing; - float V = (MaxY - MinY) * Spacing; + float U = (MaxX - MinX) * static_cast(Spacing); + float V = (MaxY - MinY) * static_cast(Spacing); *CurVert++ = Left; *CurVert++ = Top;