TIC-80 icon indicating copy to clipboard operation
TIC-80 copied to clipboard

memcpy glitches out in the web build

Open verysoftwares opened this issue 2 years ago • 4 comments

i'm using memcpy to move screen memory around. see the glitches here, choose 2-4 players and move around: http://tic80.com/play?cart=2740

image

a downloaded cartridge works just fine.

verysoftwares avatar Apr 09 '22 20:04 verysoftwares

Just reproduced it on the latest html build and I'm wondering what could be causing it, maybe compiler optimizations?

nesbox avatar Apr 10 '22 08:04 nesbox

No, I see the same thing in TIC-80 for desktop, are you sure your code is working correctly?

nesbox avatar Apr 10 '22 08:04 nesbox

i can't reproduce on desktop (0.90.1723 Pro)

verysoftwares avatar Apr 10 '22 17:04 verysoftwares

I see glitches on the latest dev build image

nesbox avatar Apr 11 '22 08:04 nesbox

AFAICT, there are two related issues here:

  1. The LUALA code uses memcpy to copy potentially overlapping buffers.
  2. The TIC-80 memcpy implementation uses the C memcpy function to do the copy.

It is undefined behaviour to use memcpy on overlapping buffers: https://en.cppreference.com/w/c/string/byte/memcpy. But, the documentation for the TIC-80 memcpy doesn't specify this as a constraint, so users have no way to know of this pitfall.

The immediate workaround for @verysoftwares is to copy memory manually. Something like:

function memmove(dst, src, length)
    if dst <= src then
        for i=0,length-1 do
            poke(dst+i, peek(src+i))
        end
    else
        for i=length-1,0,-1 do
            poke(dst+i, peek(src+i))
        end
    end
end

It's slower, but in my testing the bug is no longer present (AFAICT).

@nesbox, I think the correct fix is to use memmove in tic_api_memcpy, since that's the behaviour of the TIC-80 memcpy users expect.

mbikovitsky avatar Dec 24 '23 08:12 mbikovitsky