( dev/audio )

%MOD { DUP2 DIV MUL SUB }

%%^! { .% DEI }  %%~! { .% DEO }
%%*! { .% DEI2 } %%=! { .% DEO2 }
%%^  { .% PEK }  %%~  { .% POK }
%%*  { .% PEK2 } %%=  { .% POK2 }

@timer    $1
@progress $1

( devices )

|00 @System     [ &vector $2 &pad    $6 &r      $2 &g     $2 &b      $2 ]
|20 @Screen     [ &vector $2 &width  $2 &height $2 &pad   $2 &x      $2 &y    $2 &addr  $2 &color $1 ]
|30 @Audio     	[ &wave $2   &env    $2 &pad    $4 &vol   $1 &pitch  $1 &play $1 &value $2 &delay $2 &finish $1 ]

|0100 ( -> )
	
	( set color pallete )
	#00ff System/r=! 
	#0f0f System/g=! 
	#0ff0 System/b=! 

	;on-frame Screen/vector=! ( run on-frame every 1/60th of a second )
	#ff Audio/vol~!            ( set volume to max )
	;saw Audio/wave=!         ( set waveform to saw for audio engine )
	;env Audio/env=!          ( set envelope for audio engine )

BRK

@on-frame ( -> )

	( incr ) timer^ #01 ADD timer~ 
	( skip ) timer^ #10 EQU ,&play-note JNZ BRK &play-note

	( get note )
	;melody #00 progress^ ADD2 GET 

	( play note )
	DUP #80 ORA Audio/pitch~!
	#01 Audio/play~!

	( erase last note )
	#20  Screen/color~!

	( draw note )
	#00 SWP #0004 MUL2 #0100 SUB2 Screen/y=!
	#00 progress^ #0008 MUL2 Screen/x=!
	;dot Screen/addr=!
	#21 Screen/color~!

	( incr ) progress^ #01 ADD #20 MOD progress~

	#00 timer~

BRK

@silence ( -> )

BRK

( defines a sawtooth wave. )

@saw ( -> )

	#6000 Audio/value=!
	#0000 Audio/delay=! ( move to volume #600 after 0 delay )
	#0000 Audio/value=!
	#ffff Audio/delay=! ( reach volume 0 after the whole note. Interpolated linearly )

BRK

( defines an envelope )

@env ( -> )

	#ffff Audio/value=!
	#1000 Audio/delay=! ( move pretty quickly to volume #ffff (maximum) ) 
	#0000 Audio/value=!
	#4000 Audio/delay=! ( interpolating linearly, move to #0000 after a delay of #4000 where #8000 is half a second )
	#00   Audio/finish~! ( end the envelope )

BRK

( song data, #ff is used for a rest )

@melody [ 
	54 52 54 4f 4b 4f 48 ff
	54 52 54 4f 4b 4f 48 ff
	54 56 57 56 57 54 56 54 
	56 52 54 52 54 50 54 ff
] 

( dot sprite )
	 
@dot [ 003c 7eff 7e3c 0000 ]