veandco / go-sdl2

SDL2 binding for Go
https://godoc.org/github.com/veandco/go-sdl2
BSD 3-Clause "New" or "Revised" License
2.21k stars 221 forks source link

Usage of Texture.Lock #412

Closed jaenek closed 5 years ago

jaenek commented 5 years ago

Hi, Basically I wanted to recreate this:

SDL_LockTexture(texture, NULL, &surface->pixels, &surface->pitch);

but this implemetation of LockTexture is different from the SDL one. I saw the discussion under #238 but unfortunately the link to a solution has expired. So I want to know how can I write the surface pixels to a texture using this Lock method. BTW I think there should be some kind of compilation of the things that are different from the SDL lib.

veeableful commented 5 years ago

Hi @jaenek, do you mean something like this?

streamingTexture, err := renderer.CreateTexture(sdl.PIXELFORMAT_RGBA8888, sdl.TEXTUREACCESS_STREAMING, 100, 100)
if err != nil {
        fmt.Fprintf(os.Stderr, "Failed to create texture: %s\n", err)
        return 1
}

pixels, _, err := streamingTexture.Lock(nil)
if err != nil {
        fmt.Fprintf(os.Stderr, "Failed to lock texture: %s\n", err)
        return 1
}
defer streamingTexture.Unlock()

renderer.Copy(streamingTexture, nil, &sdl.Rect{0, 0, 100, 100})

for i := range pixels {
        pixels[i] = 0
}
jaenek commented 5 years ago

Well never mind turns out I need to freshen up my go builtins I tried to do:

copy(surface.Pixels(), pixels)

instead of:

copy(pixels, surface.Pixels())

And here is the code example:


package main

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

const (
    W = int32(800)
    H = int32(600)
)

func update(surface *sdl.Surface) {
    surface.FillRect(&sdl.Rect{0, 0, 200, 200}, 0xFF0000)
}

func main() {
    if err := sdl.Init(sdl.INIT_VIDEO); err != nil {
        panic(err)
    }
    defer sdl.Quit()

    window, renderer, err := sdl.CreateWindowAndRenderer(W, H,
        sdl.WINDOW_MAXIMIZED)
    if err != nil {
        panic(err)
    }
    defer window.Destroy()

    texture, err := renderer.CreateTexture(sdl.PIXELFORMAT_ARGB8888,
        sdl.TEXTUREACCESS_STREAMING, W, H)
    if err != nil {
        panic(err)
    }
    defer texture.Destroy()

    surface, err := sdl.CreateRGBSurface(0, W, H, 32, 0, 0, 0, 0)
    if err != nil {
        panic(err)
    }
    surface.SetRLE(true)

    running := true
    for running {
        for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
            switch event.(type) {
            case *sdl.QuitEvent:
                println("Quit")
                running = false
                break
            }
        }

        renderer.SetDrawColor(0x00, 0x00 , 0x00, 0xFF)
        renderer.Clear()

        pixels, _, err := texture.Lock(nil)
        if err != nil {
            panic(err)
        }
        update(surface)
        copy(pixels, surface.Pixels())

        texture.Unlock()

        renderer.Copy(texture, nil, nil)

        renderer.Present()

    }
}