Log In  
Follow
pancelor

hi! here is some text for you to read.
some selected carts that I've uploaded here:

the tower
mine1k
linecook

for more, see my itch page or my website

:: Unfold ::

Bitplanes are powerful, but they can be difficult to understand. How do you use them in PICO-8?

The short version: bitplanes let you draw colors to the screen without completely overwriting the existing colors, making it possible to do effects like shadows, transparency, etc. But be warned: they come with a lot of unintuitive restrictions, like monopolizing half your screen palette or requiring it to be set up in a particular way.

Longer version: PICO-8 colors are 4-bit numbers (0-15). The screen is a 128x128 4-bit image, but you can imagine it as 4 separate 12x128 1-bit images overlaid on top of each other. By poking a particular location in memory, we can tell PICO-8 to draw to these "bit planes" separately. Normally, drawing overwrites any existing colors, but if we selectively disable some of the bitplanes, some bits of the old color will remain onscreen.

Technical version: see "Technical details" below.

This post lists some specific examples and tricks that you can do with bitplanes. I won't attempt to fully explain how bitplanes work, but I'll leave some resources at the end.

Examples

Shadows

  1. set up your screen palette:
    i. 0-7: shadow palette; 0 is the shadow color for 8, 1 is the shadow color for 9, etc
    ii. 8-15: any colors
  2. draw anything
  3. enable bitplane mode 0x08 (clear the 0/8 bitplane)
  4. draw anything -- any pixels "drawn" will instead overwrite colors 8-15 with their shadow colors
  5. disable bitplane mode

Cart #bitplane_shadows-2 | 2023-09-21 | Code ▽ | Embed ▽ | License: CC4-BY-NC-SA
6

I used this method in my freecell clone.

Spotlight

  1. set up your screen palette:
    i. 0-7: all identical; e.g. all 0 (black)
    ii. 8-15: any colors
  2. draw your scene using colors 0-7. they will all appear black
  3. enable bitplane mode 0xf8 (only draw the 0/8 bit)
  4. draw a circfill in color 8 -- instead of drawing red, it will add 8 to each color it hits, revealing the image "underneath" the darkness
  5. disable bitplane mode

This cart uses a very similar technique to create an "xray" effect. (They set up their palette differently and use a different bitplane mode, swapping adjacent colors instead of shifting the palette by 8)

1-bit sprite packing

If you have 1-bit sprites, you can store them merged in the 4 bitplanes in the spritesheet, and extract them at runtime using bitplanes. It's essentially another way to do this sprite-layering technique. Here's a tool that does something similar. Neither of these actually use pico8's bitplane feature, but they could be implemented that way to save some tokens and a tiny bit of cpu.

Chromatic aberration

You can create some cool effects (like https://mastodon.social/ @zep/109315783011955478) by drawing slightly different images on different bitplanes.

Motion blur

I remember a wild "cast.p8 + motion blur" post (implemented by cycling through the 4 bitplanes once per frame) on twitter or mastodon sometime in the last year -- does anyone have a link? I can't find it now... I thought zep posted it but maybe it was someone else. From memory, it was something like this, but it must have included some palette setup as well because this doesn't look great:

bpmode=0x1111.1111
function cls()
 bpmode=bpmode>><1
 poke(0x5f5e,bpmode)
end

Anti-aliasing

You can add anti-aliasing by drawing the same thing at slight subpixel offsets, like in this example. (Note that this restricts your palette to 5 colors)

Technical details

Wikipedia has some general info, and the PICO-8 wiki (search "bitplane") has specifics about how they work in PICO-8:

> 0x5f5e / 24414
> Allows PICO-8 to mask out certain bits of the input source color of drawing operations, and to write to specific bitplanes in the screen (there's 4 of them since PICO-8 uses a 4BPP display). Bits 0..3 indicate which bitplanes should be set to the new color value, while bits 4..7 indicate which input color bits to keep.
> For example, poke(0x5f5e, 0b00110111) will cause drawing operations to write to bitplanes 0, 1, and 2 only, with 0 and 1 receiving the color value bits, 2 being cleared, and 3 being unaltered.
> This formula is applied for every pixel written:
> dst_color = (dst_color & ~write_mask) | (src_color & write_mask & read_mask)

If you're not sure what to try, setting the write_mask and read_mask to the same value is often useful.

Other resources

-Bitwise math tutorial
-A simple bitplane example -- three circles rotating in 3D
-My bitplane explorer -- it helps visualize how colors will interact

-The original discovery
-Bitplanes confirmed by zep
-Circular Clipping Masks -- discusses other non-bitplane ways to get shadow and spotlight effects

P#134693 2023-09-21 11:11 ( Edited 2023-09-22 04:24)

:: Unfold ::

PICO-8 supports bitplane drawing; the wiki (search "bitplane") has a description of how they work:

> 0x5f5e / 24414
> Allows PICO-8 to mask out certain bits of the input source color of drawing operations, and to write to specific bitplanes in the screen (there's 4 of them since PICO-8 uses a 4BPP display). Bits 0..3 indicate which bitplanes should be set to the new color value, while bits 4..7 indicate which input color bits to keep.
> For example, poke(0x5f5e, 0b00110111) will cause drawing operations to write to bitplanes 0, 1, and 2 only, with 0 and 1 receiving the color value bits, 2 being cleared, and 3 being unaltered.
> This formula is applied for every pixel written:
> dst_color = (dst_color & ~write_mask) | (src_color & write_mask & read_mask)

This is precise and correct, but I find it a bit hard to understand. So I made this cart to give myself an interactive sandbox where I can play around with bitplanes, to see how they affect drawing.

Cart #bitplane_explorer-1 | 2023-09-21 | Code ▽ | Embed ▽ | License: CC4-BY-NC-SA
3

The code is straightforward:

  1. draw the full 16-color palette
  2. enable bitplanes, using the poke shown onscreen
  3. draw a circle, using the circfill shown onscreen

You can change the bitplane settings and the circle's "color" -- the controls are shown onscreen. This interactively shows how drawing any color will interact with any other color under the current bitplane settings.

You'll still need to study the description from the wiki to understand how to use bitplanes, but this cart is a helpful supplement for me when working with bitplanes. I hope you find it helpful too!

P#134692 2023-09-21 02:13 ( Edited 2023-09-21 10:01)

:: Unfold ::

PICO-8 has fancy menuitems but there are some gotchas and bugs to be aware of.

Here's an example of what I do by default; the rest of this post will explain how the code works and why I do things this way:

Cart #menuitems-1 | 2023-08-21 | Code ▽ | Embed ▽ | License: CC4-BY-NC-SA
3

L/R pitfall

Imagine you want to add a "mute" button to your game's menu. Can you spot the issue with this code?

function _init()
  menuitem(1,"mute",function()
    ismuted=not ismuted
    -- ... play/pause the music
  end)
  -- ... other game init
end

The issue: left/right can be used to change the menuitem, and left/right always leaves the menu open afterward (this may be a bug; it's unclear) so there's no indication to the player that they accidentally muted the game! It's a minor issue... but it's easy to accidentally hit left/right when navigating the menu on a gamepad, which makes this worse.

An easy fix: don't respond to L/R (menuitem(1,"mute",function(bb) if bb>=16 then ... end end). This is what I'd recommend for games that are short on tokens but willing to spare a few to fix this.

Responsive menu

If you'd like a more responsive menu, you can do this:

function _init()
  menuitem(1,ismuted and "music: off" or "music: on",function()
    ismuted=not ismuted
    -- ... play/pause the music
    -- update the label:
    menuitem(nil,ismuted and "music: off" or "music: on") -- feels like we could save some tokens...
    return true
  end)
  -- ... other game init
end

Now the option shows its status, and updates its label immediately when you change it!

Note the return true -- this keeps the menu open. Without this, if the player presses left (toggling the setting) and then presses enter (trying to close the menu but instead toggling the setting again), they'll wonder why their change isn't sticking. By leaving the menu open, we show them that they actually re-toggled the setting, and they need to choose "continue" instead to resume the game.

Code organization idiom

The repeated ismuted and "music: off" or "music: on" is suspicious -- can we save some tokens? Yes, by setting up each menuitem() again at the end of the callback, just to refresh the labels:

function _init()
  menuitems() -- setup all menuitem()s
  -- ... other game init
end
function menuitems()
  menuitem(1,ismuted and "music: off" or "music: on",function()
    ismuted=not ismuted
    -- ... play/pause the music
    menuitems() -- refresh the label
    return true
  end)
  -- menuitem(2,...
  -- menuitem(3,...
end

I do this for code-organizing reasons -- it's nice to have all the menuitem code in one place -- but it can also save a few tokens, depending on your setup.

Context-dependent menuitems

Some menuitems should only be show in certain situations -- e.g. don't show "back to title" if we're already on the title screen. You could break each menuitem into its own little setup function (like zep's original LOAD #CUSTOM_MENU cart does -- check it out, it's nice!) or do what I do: menuitem(1,condition and "label",...). This will only show the menuitem when condition is truthy. I call menuitems() anytime the menu needs changing (e.g. at the end of init_title_screen()) and it all works out.

Recommendations

I put all my menuitem() calls inside a custom menuitems() function. Every callback runs menuitems() at the end, to refresh the labels.

There are three types of menu options I commonly use: commands, toggles, and selectors.

  • For commands (run some code, e.g. return to the title screen), I wrap the callback code in a if bb>=16 then ... end block, to prevent L/R from triggering the command
  • For toggles (e.g. mute/unmute the game), my callback always has return true, leaving the menu open afterward and avoiding the UX issue described above
  • For selectors (choose a number from a range, e.g. change levels), my callback has return bb<16, leaving the menu open only if L/R were used to change the selection. (this is technically unnecessary due to a longstanding bug(?) in PICO-8's menu handling)

Read the code of the example cart at the top of this post for more info!

P#133332 2023-08-21 01:02 ( Edited 2023-08-22 00:22)

:: Unfold ::

I often use shell scripts to export and then upload my games to itch.io, and there's a small inconvenience that trips me up sometimes: If my game is too large, the export fails, but I have no way of detecting that from my shell script.

> pico8 game.p8 -export "-f froggypaint.html"
EXPORT: -f froggypaint.html
failed: code block too large

> echo $?
0

I would expect the status code (echo $?) to be 1 or some other failure code

(Hm, now that I've written this up I suppose I could work around this by reading stderr stdout and checking for the string "failed"...)

P#130092 2023-05-24 08:14

:: Unfold ::

A slow but token-efficient sort:

-- 35-token bubblesort, by pancelor
function sort(arr)
  for i=1,#arr do
    for j=i,#arr do
      if arr[j] < arr[i] then
        add(arr,deli(arr,j),i) --slow swap
      end
    end
  end
end

I did a brief speed analysis and this function seems reasonable to use for arrays up to around 50 or 100 elements, depending on how much CPU you have available to burn.

speed analysis:


I did some minimal testing, using this code:

cls()
function _draw()
arr={
--20,5,8,3,7,4,1,9,2,-30,
--20,5,8,3,7,4,1,9,2,-30,
--20,5,8,3,7,4,1,9,2,-30,
--20,5,8,3,7,4,1,9,2,-30,
20,5,8,3,7,4,1,9,2,-30,
}
sort(arr)
end

By commenting out lines of the array, I changed it's length. Here's how much CPU the function spent, as a percentage of a single 30fps frame (measured with the ctrl-p monitor, on pico8 0.2.5g)

The "best case cpu" was calculated by defining arr outside of _draw, so that the array was already sorted after the first frame

Array length Typical cpu (30fps) Best case cpu (30fps)
10 0% 0%
20 1% 1%
50 5% 4%
100 21% 15%
200 81% 58%
300 181% 130%
400 321% 231%

I believe this algorithm is O(n^3): O(n^2) for the two loops, and an additional O(n) b/c the swap step uses add and deli, which shift around the array elements. But the chart seems to indicate that doubling the length will quadruple the cpu cost (instead of octupling it) so maybe it's only O(n^2) somehow? It doesn't much matter, since you don't want to use this for large arrays anyway, but maybe add/deli are cheaper than I would expect.

P#128863 2023-04-21 23:04

:: Unfold ::

mildly interesting: when drawing a perfectly vertical line (line(1,1,1,h)) or perfectly horizontal line (line(1,1,w,1)), it used to be cheaper (in cpu cycles) to use rect or rectfill instead. but not anymore! I'm testing this on 0.2.5g; I'm not sure when this changed.

tl;dr: line and rectfill cost the same for orthogonal lines (rect is more expensive for vertical lines only)

simple test:


load #prof, then add these lines:

-- horizontal
prof(function()
 line(0,0,90,0,2)
end,function()
 rect(0,0,90,0,2)
end,function()
 rectfill(0,0,90,0,2)
end)
--  9+10=19 (lua+sys)
--  9+10=19 (lua+sys)
--  9+10=19 (lua+sys)

-- vertical
prof(function()
 line(0,0,0,90,2)
end,function()
 rect(0,0,0,90,2)
end,function()
 rectfill(0,0,0,90,2)
end)
--  9+10=19 (lua+sys)
--  9+22=31 (lua+sys)
--  9+10=19 (lua+sys)

full test:

function one(fn,opts)
  local fmt=function(n)
    -- leftpad a number to 2 columns
    return n<9.9 and " "..n or n
  end

  local dat=prof_one(fn,opts)
  printh(fmt(dat.lua)
    .."+"
    ..fmt(dat.sys)
    .."="
    ..fmt(dat.total)
    .." (lua+sys)")
end

function hline(x) line(0,0,x,0,2) end
function hrect(x) rect(0,0,x,0,2) end
function hrfil(x) rectfill(0,0,x,0,2) end
function vline(x) line(0,0,0,x,2) end
function vrect(x) rect(0,0,0,x,2) end
function vrfil(x) rectfill(0,0,0,x,2) end

printh"--"
for i=0,127 do
 printh(i..": ")
 one(hline,{locals={i}})
 one(hrect,{locals={i}})
 one(hrfil,{locals={i}})
 one(vline,{locals={i}})
 one(vrect,{locals={i}})
 one(vrfil,{locals={i}})
end

--[[
...
14: 
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
15: 
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
16: 
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
 9+ 4=13 (lua+sys)
 9+ 2=11 (lua+sys)
17: 
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
 9+ 2=11 (lua+sys)
 9+ 4=13 (lua+sys)
 9+ 2=11 (lua+sys)
...
]]

summary:

rect:
    when h is 1, sys cost is:
        max(1,w\16)*2 (agrees with CPU wiki page)
    when w is 1, sys cost is:
        max(1,(h-1)\8)*2 (disagrees? unsure)
line and rectfill
    a,b = max(w,h),min(w,h)
    when b is 1, sys cost is:
        max(1,a\16)*2 (agrees with CPU page for rectfill, but not line(?))

P#127584 2023-03-25 03:47

:: Unfold ::

Cart #thetower-2 | 2023-07-27 | Code ▽ | Embed ▽ | No License
23

welcome to the tower
welcome to the tower
welcome ‍ to the tower
welcome to the tower

controls

  • arrow keys: walk, interact
  • enter: pause menu (volume, toggle effects, etc)

the game will autosave your progress each floor

credits

made by tally (art, room design, dialog) and pancelor (code, game design, music, dialog)

pixel art created with tiles from teaceratops and yelta

built with pico-8, aseprite, PX9, and shrinko8

changelog

  • thetower-1: added title screen
  • thetower-0: initial release
P#125012 2023-02-18 13:09 ( Edited 2023-07-27 07:01)

:: Unfold ::

switching between custom and default fonts (?"\015") behaves a bit strangely; the first line of text is spaced differently from the rest, depending on whether:

  1. custom fonts are enabled by default (poke(0x5f58,0x81)), and
  2. the line height (peek(0x5602)) is more or less than 6 (the size of the default font)

run this cart to see what I mean:

Cart #kahedapibi-1 | 2023-01-30 | Code ▽ | Embed ▽ | No License
2

specifically:

  1. when the custom font is enabled by default and the custom font's height is more than 6, the default-font text in this cart has a large gap between the first and second lines:
  1. when the custom font is not enabled by default and the custom font's height is less than 6, the custom-font text in this cart has a large gap between the first and second lines:

I didn't test how ?"\^y" affects things.

my system info: 64-bit linux, pico8 0.2.5e

P#125013 2023-01-30 07:21

:: Unfold ::

how many tokens should this cart cost?

s="x".."="
a=1+2

in 0.2.1b, it costs 10 tokens (5 for each line). this seems correct to me. however, in 0.2.5e, the first line only costs 4 tokens for some reason.

edit: even weirder: s="x".."=" costs 4 tokens but s="x".."y" costs 5 tokens. it seems like concatenating any string that starts with the equals symbol is 1 token cheaper than it should be; how odd! maybe this is somehow due to the recent parser updates for += etc?

P#123586 2023-01-03 07:52

:: Unfold ::

When I'm making games or tweetcarts, I often adjust numbers just a tiny bit, then rerun the whole game. e.g. I change the player speed by 0.1, then change it back, then try 0.05...

This is a bit slow, so here's a library I made to help me do it faster. I also find it useful for analyzing other people's tweetcarts -- if I can easily adjust the values they use, I can quickly figure out what they mean

setup

  • load #twiddler
  • copy the knobs.lua + helpers tabs into your game
  • use kn[1], kn[2], ... kn[8] in place of any number
  • add twiddler() to the end of your _draw function

Now, run your code:

  • press tab and adjust the values (see "controls" below)
  • press tab again -- the values will be copied to your clipboard
  • paste the values into the start of your code to save them

example 1

Start with a tweetcart you want to study. For example, this one by 2DArray: https://twitter.com/2DArray/status/1492566780451205120

?"\^!5f10◆█🐱░4웃9♥"
::_::?"⁶1⁶c"
w=t()/8
c=cos(w)
s=sin(w)
n=1800
for i=0,n do
a=i*.618
j=1-i/n*i/n
y=1+j*j-2*j*j*j
r=1-(1-j)^3+sin(a*10)/9
p=(6+sin(a*10)*(.5+r/2))*(.7+y*y/3)
circfill(64+cos(a+w)*r*20,80-y*30+sin(a+w)*r*12,2,p)
end
goto _

Add the knobs, and replace some interesting-looking numbers with knobs:

kn={.5,.7,.618,2,0,0,0,0} --changed
?"\^!5f10◆█🐱░4웃9♥"
::_::?"⁶1⁶c"
w=t()/8
c=cos(w)
s=sin(w)
n=1200 --changed -- twiddler needs a little bit of cpu to run
for i=0,n do
a=i*kn[3] --changed
j=1-i/n*i/n
y=1+j*j-2*j*j*j
r=1-(1-j)^3+sin(a*10)/9
p=(6+sin(a*10)*(kn[1]+r/2))*(kn[2]+y*y/3) --changed
circfill(64+cos(a+w)*r*20,80-y*30+sin(a+w)*r*12,kn[4],p) --changed
end
twiddler() --changed
goto _

Now run the code and play around! looks like knobs 1 and 2 control the color gradient, knob 3 controls the spiralness of the circles. cool! Add new knobs, remove old knobs, keep going until satisfied.

example 2

This process works on your own code that you're in the middle of writing, too. Write kn[1] etc instead of a number, open the knobs panel, and edit the value until it looks right:

This is from the dev process of a recent tweetcart of mine (twitter, cohost)

controls:

Press Tab or W to open/close the knob panel

  • LMB - change slider value
  • MMB - pan slider range
  • RMB - cancel current interaction
  • wheel - zoom slider range

When you close the panel (Tab/W), knob values will be copied to your clipboard -- paste them into your code to save them.

Cart #twiddler-0 | 2022-10-28 | Code ▽ | Embed ▽ | License: CC4-BY-NC-SA
8

When you're done with the knobs, you can replace kn[1] etc with the literal value of the knobs, and delete the twiddler code. This is a tool meant for development, not meant to be used during a finished game. (although, a finished game that used something like this would be pretty nifty!)

P#119729 2022-10-28 22:11 ( Edited 2022-10-28 22:13)

:: Unfold ::

Cart #mine1k-0 | 2022-10-09 | Code ▽ | Embed ▽ | No License
16

A demake of the classic minesweeper.

The game cartridge is just 1024 bytes -- see https://gist.github.com/pancelor/a3aadc5e8cdf809cf0a4972ac9598433 for some lightly commented source code

RULES / CONTROLS:

  • left click to reveal a tile
    • if you hit a mine, you lose
    • revealed tiles will show a number, telling how many of their 8 neighbors are mines
  • right click to flag a tile
  • reveal all non-mine tiles to win!
  • click the smiley face to restart

TIPS

  • left click + right click (simultaneous) to auto-reveal neighbors, if the number of nearby flags matches the number on the tile you clicked
  • mines left and a timer are displayed in the top corners
P#118854 2022-10-09 21:57

:: Unfold ::

When exporting a game to a binary format (.exe, etc), the manual says:

> To include an extra file in the output folders and archives, use the -E switch:

> > EXPORT -E README.TXT MYGAME.BIN

I tried this (pico8 game.p8 -export "-f game.bin -e examples/ -e samples/") but it doesn't include those subfolders. If I -e examples/kick.pcm, then that file is included, but it's included at the top level, and not in an "examples" subfolder

Am I doing this wrong somehow? I assume this just isn't supported (yet? fingers crossed)

P#111906 2022-05-16 22:38 ( Edited 2022-06-04 19:26)

:: Unfold ::

Cart #imhungry-0 | 2022-04-26 | Code ▽ | Embed ▽ | License: CC4-BY-NC-SA
2

> Vous contrôlez un petit rennes qui doit attraper le plus de nourriture possible, il s'agit de pain et de mûres. Plus vous attrapez de, plus la nourriture va vite et plus il est compliqué de l'attraper. En haut à droite, vous verrez qu'il y a votre tableau de bord, chaque aliment pêché vaut un point. Et en haut à gauche, il y a un panneau qui vous montre combien d'aliments vous n'avez pas attrapés. Attention ! au bout d'une dizaine d'aliments non attrapés vous perdez et le jeu affiche alors « GAME OVER ! », alors il faut appuyer sur enter pour recommencer.

> Les commandes sont : la flèche droite pour se déplacer vers la droite, la flèche gauche pour se déplacer vers la gauche et la flèche vers le haut pour sauter. C'est si simple !

(for more info, see https://itch.io/jam/im-hungry / https://pancelor.itch.io/im-hungry)

P#110904 2022-04-26 21:12 ( Edited 2022-06-01 14:24)

:: Unfold ::

I hit this bug while working on a tweetcart:

?"\*6a"  -- prints 6 'a's    (expected)
?"\*6\"" -- prints 6 quotes  (expected)
?"\*6\n" -- prints 1 newline (unexpected!)
?"\n"    -- prints 1 newline (expected)
P#109613 2022-04-03 02:06

:: Unfold ::

here's a demo cart showing off some different ways to handle input in grid-based games:

Cart #hojohiyomu-1 | 2022-02-24 | Code ▽ | Embed ▽ | License: CC4-BY-NC-SA
25

controls:

  • move around with the arrow keys
  • change "chapters" in the pause menu (enter + arrow keys)
  • slow down the game speed (in the later chapters) in the pause menu

I made this cart as a companion to a blog post about input buffering

P#107587 2022-02-24 09:19 ( Edited 2022-02-24 09:55)

:: Unfold ::

@zep o/

A weird bug has been messing with me recently: pico-8 keeps telling me I have "unsaved changes" when I'm pretty sure I don't. I caught the bug on camera this time:

I don't know how to reproduce it; I tried adding a new tab and messing with the text cursor position (since I wondered if this had something to do with the fix for https://www.lexaloffle.com/bbs/?tid=39379 ) and soon after I was able to trigger the bug. But I was able to trigger the bug without even opening up the code editor -- all I did was load cart1 load cart2 load cart1 over and over again until it said "unsaved changes". strange

Jump to 1:12 and 1:24 in the video to see me trigger the bug two separate times. (the video description has a few other timestamps too)


I'm worried I'll stop trusting that message and accidentally lose real changes!

I think this bug is new as of 0.2.4b; I don't remember it happening beforehand.

P#107008 2022-02-16 05:04 ( Edited 2022-02-16 05:09)

:: Unfold ::

Cart #lasal-1 | 2022-01-19 | Code ▽ | Embed ▽ | No License
11

A short celeste map mod. It's built as a bit of a puzzle, meant to teach you one specific thing about the game's mechanics.

This doesn't require any advanced speedrunning tech (spike clips, corner jumps, etc) -- executing the intended solutions should be possible for anyone who's beaten celeste classic once or twice.

If you're trying something that seems too hard or only barely possible, try looking for alternatives!

controls

  • arrow keys / Z / X: move / jump / dash
  • E: toggle screenshake

credits

celeste classic: maddy thorson + noel berry

smalleste: a token-optimized version of classic celeste that I used as a starting point

playtesting: cryss, sharkwithlasers, James, meep

berry follow code: meep's Terra Australis

map editor

I made this map to see how my custom map editor felt to use. I think it's pretty neat -- check it out! It lets you build much larger maps than the built-in pico-8 map editor.

P#105290 2022-01-19 00:23 ( Edited 2022-01-19 06:31)

:: Unfold ::

demo cart

Cart #bigmap_demo-1 | 2022-01-18 | Code ▽ | Embed ▽ | No License
35

motivation

The recent 0.2.4 release added support for larger maps:

> Similar to gfx memory mapping, the map can now be placed at address 0x8000 and above (in increments of 0x100). This gives 4 times as much runtime space as the default map, and an additional POKE is provided to allow customisable map sizes.

Larger maps are now possible, but it's difficult to get them into memory -- the built-in map editor only works with vanilla-sized maps.

This cart is a full map editor that makes it easy to make these larger maps!

features

  • tight iteration loop - play a level in your game, jump into the map editor to make a small tweak, and return to the game with minimal friction
  • change map size at any time
    • max width: 256 tiles
    • max height: none
    • max total size: 32K tiles (e.g. 128*256, or 32*1024)
  • easy copy-paste (right mouse + drag to copy, left mouse to paste)
  • zooming in/out
  • large brushes - place multiple tiles at a time
  • show 16x16 "room" outlines (useful for carts like celeste that are made of many 16x16 rooms)
  • "transparency" - optionally treat sprite 0 in large brushes as "transparent"
  • compressed maps using PX9
  • autosaving
  • the map editor uses 0 of your tokens -- it's a completely separate cart that you only use during development
    (well, it costs ~300 tokens to load the map string and run the decompressor)
  • your game will still be splore-compatible
  • your game can call map(), mget(), tline() etc without any extra work

undo/redo?

The editor currently has no undo/redo functionality. That's not ideal! I'm hoping to get it working soon.

To undo all changes since your last save (probably the end of your last session using bigmap), use the "discard changes" button in the top-right.

If you make a large mistake, replace map.p8l with your an autosaved version (inside mygame/autosave/) and reload bigmap.

setup

Setting the bigmap editor up takes a bit of work. This is mainly necessary to enable a tight map iteration loop, and also to work around the restrictions of pico-8 (for example, it's impossible to read a file from disk without user interaction, and asking the user to drag-and-drop their map file every time they wanted to edit is way too much friction for my tastes)

To start, make sure you have a folder (e.g. mygame/) with your game cart inside (e.g. mygame/mygame.p8)

  1. cd mygame (navigate into the folder containing your game)
  2. mkdir autosave (create a folder to store backups/autosaves)
  3. printh("","map.p8l") (this creates an empty map.p8l file)
  4. Save this file (https://gist.github.com/pancelor/f933286f244c6b85b7720dbe6f809143) as px9_decomp.lua (inside the mygame/ directory)
  5. load #bigmap (note: this is different from the bigmap_demo cart)
  6. Uncomment the two #include lines in the second tab (tab 1)
  7. save bigmap.p8
  8. Paste this snippet into mygame.p8: (inside _init(), or at top-level; either works)

    menuitem(1,"▒ edit map",function()
      -- pass spritesheet through upper memory,
      -- avoiding an extra second of load time
      local focusx,focusy=0,0
      memcpy(0x8000,0x0000,0x2000)
      poke(0x5500,1,focusx,focusy) --signal
    
      load("bigmap.p8","discard changes","mygame.p8")
    end)

    (make sure you change "mygame.p8" to the actual filename of your game)

    This snippet adds the menu option to enter bigmap while playing your game. If you set focusx and focusy, bigmap will start focused on that map coordinate.

  9. Paste this snippet into mygame.p8 at top-level:
    #include map.p8l
    #include px9_decomp.lua
    if map_import then map_import() end
  10. Save mygame.p8

You should now be good to go!

test+edit iteration loop

  1. Save mygame.p8. any unsaved changes will be lost every time you launch bigmap. (I wish this was avoidable but I couldn't find a way around it that preserved the quick test+edit loop I wanted)
  2. Run mygame.p8
  3. Pause the game (with P or Enter)
  4. Choose "edit map"
  5. Edit your map!
    If you accidentally press escape and exit the map editor, type r or resume into the console to resume the map editor.
  6. Return to your game with P, Enter, or the clickable "Play" button in the top-right

I advise setting up mygame.p8 to jump you to the room you were editing when it starts - this can be done by reading the focusx and focusy global variables that are set inside the map_import() function (inside map.p8l)

See my celeste mod or the getting started video for an example of how to do this.

technical details

When you press the save or play button, bigmap uses printh to write a text file called map.p8l into the current directory. This text file happens to be valid lua code that defines a function called map_import(), so when mygame.p8 executes #include map.p8l and map_import(), it runs the code generated by bigmap.

Here's an example of what map.p8l looks like:

-- this file was auto-generated by bigmap.p8
function map_import()
 focusx=11
 focusy=12
 mapw=128
 maph=64
 poke(0x5f56,0x80,mapw)
 local function vget(x,y) return @(0x8000+x+y*mapw) end
 local function vset(x,y,v) return poke(0x8000+x+y*mapw,v) end
 px9_sdecomp(0,0,vget,vset,"◝◝◝ユ◝7な◝◝✽,ゃf\0★)&るちP;](♥KねF ... many many more chars here ... X▤ミヘラ⬇️⬇️Bれん")
end

This has 3 main parts:

  1. Set up some helpful global vars - mapw and maph are the width and height of the map, in tiles. focusx and focusy are the tile coordinate of the tile that was in the center of the screen when map.p8l was saved -- you can use this info to jump directly to that room to let you make small tweaks and test them very quickly
  2. poke(0x5f56,0x80,mapw) -- this tells pico-8 to use mapdata stored at 0x8000, with map width mapw
  3. The rest of the function uses PX9 to decompress the binary data stored in that long string. The decompressed data gets stored starting at 0x8000 and takes up mapw*maph bytes.

That compressed data string is created using PX9 and this snippet for encoding binary data in strings.

links

stuff I used:

alternative map editors you might consider using instead:

other:

happy map editing!

I'd like to see what you make -- let me know if you use this in your projects! And if you want to credit me I'd appreciate it :)

Is bigmap helpful? Is it too confusing to set up? Find any bugs? Let me know what you think!

P#105301 2022-01-19 00:12 ( Edited 2022-03-10 00:04)

:: Unfold ::

tl;dr

In the pico8 console, do load #prof, then edit the third tab with some code:

prof(function(x)
  local _=sqrt(x)   -- code to measure
end,function(x)
  local _=x^0.5     -- some other code to measure
end,{ locals={9} }) -- "locals" (optional) are passed in as args

Run the cart: it will tell you exactly how many cycles it takes to run each code snippet.


what is this?

The wiki is helpful to look up CPU costs for various bits of code, but I often prefer to directly compare two larger snippets of code against each other. (plus, the wiki can get out of date sometimes)

For the curious, here's how I'm able to calculate exact cycle counts
(essentially, I run the code many times and compare it against running nothing many times, using stat(1) and stat(2) for timing)

-- slightly simplified from the version in the cart
function profile_one(func)
  local n = 0x1000

  -- we want to type
  --   local m = 0x80_0000/n
  -- but 8𝘮𝘩z is too large a number to handle in pico-8,
  -- so we do (0x80_0000>>16)/(n>>16) instead
  -- (n is always an integer, so n>>16 won't lose any bits)
  local m = 0x80/(n>>16)

  -- given three timestamps (pre-calibration, middle, post-measurement),
  --   calculate how many more 𝘤𝘱𝘶 cycles func() took compared to noop()
  -- derivation:
  --   𝘵 := ((t2-t1)-(t1-t0))/n (frames)
  --     this is the extra time for each func call, compared to noop
  --     this is measured in #-of-frames (at 30fps) -- it will be a small fraction for most ops
  --   𝘧 := 1/30 (seconds/frame)
  --     this is just the framerate that the tests run at, not the framerate of your game
  --     can get this programmatically with stat(8) if you really wanted to
  --   𝘮 := 256*256*128 = 8𝘮𝘩z (cycles/second)
  --     (𝘱𝘪𝘤𝘰-8 runs at 8𝘮𝘩z; see https://www.lexaloffle.com/bbs/?tid=37695)
  --   cycles := 𝘵 frames * 𝘧 seconds/frame * 𝘮 cycles/second
  -- optimization / working around pico-8's fixed point numbers:
  --   𝘵2 := 𝘵*n = (t2-t1)-(t1-t0)
  --   𝘮2 := 𝘮/n := m (e.g. when n is 0x1000, m is 0x800)
  --   cycles := 𝘵2*𝘮2*𝘧
  local function cycles(t0,t1,t2) return ((t2-t1)-(t1-t0))*m/30 end

  local noop=function() end -- this must be local, because func is local
  flip()
  local atot,asys=stat(1),stat(2)
  for i=1,n do noop() end -- calibrate
  local btot,bsys=stat(1),stat(2)
  for i=1,n do func() end -- measure
  local ctot,csys=stat(1),stat(2)

  -- gather results
  local tot=cycles(atot,btot,ctot)
  local sys=cycles(asys,bsys,csys)
  return {
    lua=tot-sys,
    sys=sys,
    total=tot,
  }
end

how do I use it?

Here's an older demo to wow you:

Cart #cyclecounter-2 | 2022-01-16 | Code ▽ | Embed ▽ | License: CC4-BY-NC-SA
12

This is neat but impractical; for everyday usage, you'll want to load #prof and edit the last tab.

The cart comes with detailed instructions, reproduced here for your convenience:

=================
 ★ usage guide ★ 
=================

웃: i have two code snippets;
    which one is faster?

🐱: edit tab 2 with your
    snippets, then run.
    it will tell you precisely
    how much cpu it takes to
    run each snippet.

    the results are also copied
    to your clipboard.
    (for ease of use, consider
    integrating this cart into
    your own cart during dev)

웃: what do the numbers mean?

🐱: the cpu cost is reported
    as lua and system cycle
    counts. look up stat(1)
    and stat(2) for more info.

    if you're not sure, just
    look at the sum -- lower
    is faster (better)

웃: why "{locals={3,5}}"
    do in the example?

🐱: accessing local variables
    is faster than global vars.

    /!\     /!\     /!\     /!\
    "local" values outside
    the current scope are also
    slower to access!
    /!\     /!\     /!\     /!\

    so if the scenario you're
    trying to test involves
    local variables, simulate
    this by passing them in:

      prof(function(a)
        local _=sqrt(a)
      end,{ locals={9} })

    note: you can profile many
    functions at once, or just
    one. also, passing options
    at the end isn't required:

      prof(function()
        memcpy(0,0x200,64)
      end,function()
        poke4(0,peek4(0x200,16))
      end)

웃: can i do "prof(myfunc)"?

🐱: no, this will give wrong
    results! always use inline
    functions:

      prof(function()
        -- code for myfunc here
      end)

    as an example, "prof(sin)"
    reports "-2" -- wrong! but
    "prof(function()sin()end)"
    correctly reports "4"

    (see the notes at the start
    of the next tab for a brief
    technical explanation)

======================
 ★ alternate method ★
======================

this cart is based on code by
samhocevar:
https://www.lexaloffle.com/bbs/?pid=60198#p

if you do this method, be very
careful with local/global vars.
it's very easy to accidentally
measure the wrong thing.

here's an example of how to
measure cycles (ignoring this
cart and using the old method)

  local a=11.2 -- locals

  local n=1024
  flip()
  local tot1,sys1=stat(1),stat(2)
  for i=1,n do  end -- calibrate
  local tot2,sys2=stat(1),stat(2)
  for i=1,n do local _=sqrt(a) end -- measure
  local tot3,sys3=stat(1),stat(2)

  function cyc(t0,t1,t2) return ((t2-t1)-(t1-t0))*128/n*256/stat(8)*256 end
  local lua = cyc(tot1-sys1,tot2-sys2,tot3-sys3)
  local sys = cyc(sys1,sys2,sys3)
  print(lua.."+"..sys.."="..(lua+sys).." (lua+sys)")

run this once, see the results,
then change the "measure" line
to some other code you want
to measure.

misc results

(these may be out of date now, but they were interesting)

poke4 v. memcopy

  profile("memcpy     ", function() memcpy(0,0x200,64)       end)
  profile("poke4/poke4", function() poke4(0,peek4(0x200,16)) end)

> memcpy : 7 +64 = 71 (lua+sys)
> poke4/poke4 : 7 +60 = 67 (lua+sys)

Copying 64 bytes of memory is very slightly faster if you use poke4 instead of memcpy -- interesting!
(iirc this is true for other data sizes... find out for yourself for sure by downloading and running the cart!)

edit: this has changed in 0.2.4b! the memcpy in this example now takes 7 +32 cycles

constant folding

I thought lua code was not optimized by the lua compiler/JIT at all, but it turns out there are some very specific optimizations it will do.

  profile("     +", function() return 2+2 end)
  profile("   +++", function() return 2+2+2+2+2+2+2+2 end)

These functions both take a single cycle! That long addition gets optimized by lua, apparently. @luchak found these explanations:

https://stackoverflow.com/questions/33991369/does-the-lua-compiler-optimize-local-vars/33995520
> Since Lua often compiles source code into byte code on the fly, it is designed to be a fast single-pass compiler. It does do some constant folding

A No Frills Introduction to Lua 5.1 VM Instructions (book)
> As of Lua 5.1, the parser and code generator can perform limited constant expression folding or evaluation. Constant folding only works for binary arithmetic operators and the unary minus operator (UNM, which will be covered next.) There is no equivalent optimization for relational, boolean or string operators.

constant folding...?

One further test case:

  profile("tail add x3", function() local a=2 return 2+2+2+2+2+2+2+a end)
  profile("head add x3", function() local a=2 return a+2+2+2+2+2+2+2 end)

> tail add x3 : 2 + 0 = 2 (lua+sys)
> head add x3 : 8 + 0 = 8 (lua+sys)

These cost different amounts! Constant-folding only seems to work at the start of expressions. (This is all highly impractical code anyway, but it's fun to dig in and figure out this sort of thing)

credits

Cart by pancelor.

Thanks to @samhocevar for the initial snippet that I used as a basis for this profiler!

Thanks to @freds72 and @luchak for discussing an earlier version of this with me!

Thanks to thisismypassword for updating the wiki's CPU page!

changelog

v1.3

  • simpler BBS post, friendlier cart instructions

v1.2

  • rewrite; recommend using load #prof instead now

v1.1

  • added: press X to copy to clipboard
  • added: can pass args; e.g. profile("lerp", lerp, {args={1,4,0.3}})

v1.0

  • intial release
P#104795 2022-01-11 03:31 ( Edited 2023-03-13 09:35)

:: Unfold ::

Cart #linecook-2 | 2022-06-01 | Code ▽ | Embed ▽ | No License
4

these busy birds will eat almost anything that falls into their gullet -- what will you feed them? they have their preferences, but people food beats bird food any day of the week!

a difficult, chaotic arcade game. now with local multiplayer support! also available on itch.

controls:

  • left / right: move
  • x / up: grab
  • ESDF: movement keys for player 2

features

  • 4 difficulty modes: "easy", medium, hard, and practice
  • 3 different control schemes:
    • solo
    • local multiplayer
    • two-handed singleplayer
  • 4 challenging maps for 4 different flavors of gameplay

#ChainLetterJam

this was made for the #ChainLetterJam! Patrick nominated me; I had fun playing Arithmetic Bounce (my high score on hard mode is 24), so I decided to try making a game that would feel similarly chaotic.

I took inspiration from the fact that none of the target numbers in Arithmetic Bounce were inherently good or bad; their value changed depending on the current goal. This became the ingredient/recipe idea in linecook: specific ingredients are sometimes good and sometimes bad, depending on the current recipe. I also liked the chaos and time pressure caused by gravity in Arithmetic Bounce; I've gone for a slightly different but still chaotic spin by giving the player two grabber-claws that are tricky to aim.

the continuation of this chain is: https://tallywinkle.itch.io/the-witchs-almanac

blog

I wrote about this game's design here. tl;dr: if you allow your game systems to play out as physical processes in the game world, there's a lot more opportunities for the player to interrupt and cause surprising interactions

hope you enjoy it!

P#103294 2021-12-22 02:03 ( Edited 2022-06-01 19:37)

View Older Posts
Follow Lexaloffle:          
Generated 2023-09-23 22:06:32 | 0.109s | Q:77