From dcff8cd18e191eec4c4fbf68b7959fe7406aa957 Mon Sep 17 00:00:00 2001 From: ae Date: Sun, 1 Jun 2025 22:05:22 +0300 Subject: [PATCH] feat: track prev. pos. attempts to speed up bruteforcing --- banner.go | 39 +++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/banner.go b/banner.go index 9e81587..54eee8f 100644 --- a/banner.go +++ b/banner.go @@ -91,8 +91,7 @@ func getTextBounds(text []string, size float64) (width, height int) { } func rectsOverlap(r1, r2 struct{ x, y, w, h int }) bool { - return !(r1.x+r1.w <= r2.x || r2.x+r2.w <= r1.x || - r1.y+r1.h <= r2.y || r2.y+r2.h <= r1.y) + return !(r1.x+r1.w <= r2.x || r2.x+r2.w <= r1.x || r1.y+r1.h <= r2.y || r2.y+r2.h <= r1.y) } func drawTextWithOutline(canvas *image.RGBA, text []string, x, y int, textColor, outlineColor color.RGBA, size float64) { @@ -144,7 +143,18 @@ func drawTextWithOutline(canvas *image.RGBA, text []string, x, y int, textColor, } } +func abs(a int) int { + if a < 0 { + return -a + } + return a +} + func findTextPositions(textData []*TextData, filename string) { + type attemptedPos struct { + x, y int + } + padding := 10 for i, data := range textData { @@ -172,12 +182,33 @@ func findTextPositions(textData []*TextData, filename string) { continue } + // track attempted positions to avoid redundancy + attempts := make([]attemptedPos, 0, maxPositioningAttempts) + + // min. distance between attempts (1/5 of text height) + minAttemptDistance := max(h/5, 10) + + isTooCloseToAttempted := func(x, y int) bool { + for _, pos := range attempts { + if abs(x-pos.x) < minAttemptDistance && abs(y-pos.y) < minAttemptDistance { + return true + } + } + return false + } + // try random positions for attempt := 0; attempt < maxPositioningAttempts && !placed; attempt++ { // gen. random pos. x := rand.IntN(maxX-minX+1) + minX y := rand.IntN(maxY-minY+1) + minY + // skip if too close to a previously attempt pos. + if isTooCloseToAttempted(x, y) { + continue + } + attempts = append(attempts, attemptedPos{x: x, y: y}) + // bounding box for cur. text curRect := struct{ x, y, w, h int }{ x: x, @@ -188,7 +219,7 @@ func findTextPositions(textData []*TextData, filename string) { // checks of overlaps with already placed texts overlaps := false - for j := 0; j < i; j++ { + for j := range i { other := textData[j] if !other.Positioned { continue @@ -245,7 +276,7 @@ func findTextPositions(textData []*TextData, filename string) { totalOverlapArea := 0 // calculate total overlap area with existing texts - for j := 0; j < i; j++ { + for j := range i { other := textData[j] if !other.Positioned { continue