Search code examples
gorgbpixelsurface

I am using sdl in golang and want to get pixel data from window, but that doesn't work


I want to get pixel data using surface.At()

package main

import (
    "fmt"
    "github.com/veandco/go-sdl2/sdl"
)

func main() {
    var (
        winTitle string = "Surface At"
        winWidth, winHeight int32 = 1200, 720
        window *sdl.Window
        renderer *sdl.Renderer
        surface *sdl.Surface
    )
    window, _ = sdl.CreateWindow(winTitle, sdl.WINDOWPOS_CENTERED, sdl.WINDOWPOS_CENTERED, winWidth, winHeight, sdl.WINDOW_SHOWN)
    renderer, _ = sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED)
    
    renderer.SetDrawColor(35, 80, 0, 180)
    renderer.Clear()
    renderer.Present()
    surface, _ = window.GetSurface()
    
    for x := 0; x < int(winWidth); x++ {
        for y := 0; y < int(winHeight); y++ {
            color := surface.At(x, y)
            fmt.Println(color, "color", x, "x", y, "y")
        }
    }
    sdl.Delay(1000)
    sdl.Quit()
}

But instead of returning actual color ({35, 80, 0, 180} color 0 x 0 y) of every pixel it returns {0 0 0 255} color 0 x 0 y all the way up to the end.

How to fix this? Or maybe there's something, that I can use instead of surface.At()?


Solution

  • I found out what was wrong, I actually had to make changes to the surface. Here's the code:

    package main
    
    import (
        "fmt"
        "github.com/veandco/go-sdl2/sdl"
    )
    
    func main() {
        var (
            winTitle string = "Surface At"
            winWidth, winHeight int32 = 1200, 720
            window *sdl.Window
            surface *sdl.Surface
        )
        
        window, _ = sdl.CreateWindow(winTitle, sdl.WINDOWPOS_CENTERED, sdl.WINDOWPOS_CENTERED, winWidth, winHeight, sdl.WINDOW_SHOWN)
        surface, _ = window.GetSurface()
        surface.FillRect(&sdl.Rect{50, 50, 600, 300}, 39700) //Change color from x - {50; 600}, y - {50; 300}
        
        color1 := surface.At(100, 100)
        color2 := surface.At(5, 5)
        fmt.Printf("%v color at %d x, %d y\n", color1, 100, 100)
        fmt.Printf("%v color at %d x, %d y\n", color2, 5, 5)
        
        sdl.Delay(4000)
        sdl.Quit()
    }
    

    Output is:

    {20 155 0 255} color at 100 x, 100 y

    {0 0 0 255} color at 5 x, 5 y