# 16 bit pallet screen to RBG565 with x2,x3,x4...pixels
from micropython import const
import gc, array
import framebuf
from uctypes import addressof

MAXSCREEN_X=const(480)
MAXSCREEN_Y=const(320)
CHUNKS=const(5)

screen_buf=bytearray(MAXSCREEN_X*MAXSCREEN_Y//2)
chunk=bytearray(MAXSCREEN_X*MAXSCREEN_Y*2//5)
screen=framebuf.FrameBuffer(screen_buf,MAXSCREEN_X,MAXSCREEN_Y,framebuf.GS4_HMSB)

pallet=array.array('H',(0,1,2,3,4,5,6,7,8,9,10,11,12,13,15,16))
print('screen=',len(screen_buf),'chunk=',len(chunk))
print('free',gc.mem_free())

@micropython.viper
def convert():
  scr=ptr8(screen) # 480x320 
  chk=ptr16(chunk) # 480x64
  pal=ptr16(pallet)
  size=1
  screen_y=0
  chunk_y=0
  while chunk_y<64:
    for s_y in range(size):
      screen_x=0
      chunk_x=0
      while screen_x<240:
        addr=screen_y*MAXSCREEN_X//2+screen_x
        color_low=scr[addr] & 0xf
        color_hi =scr[addr] >> 4
        for s_x in range(size):
          chk[chunk_y*MAXSCREEN_X+chunk_x]=pal[color_hi]
          chunk_x += 1
        for s_x in range(size):
          chk[chunk_y*MAXSCREEN_X+chunk_x]=pal[color_low]
          chunk_x += 1
        screen_x += 1
      chunk_y += 1
    screen_y += 1


convert_ctl=array.array('i',(addressof(screen),addressof(chunk),1,MAXSCREEN_X))
@micropython.asm_thumb
def convert_asm(r0):
  mov(r1,0)         # r1=chunk_y
  label(CHUNK_Y)
  mov(r2,0)         # r2=s_y
  label(S_Y)        
  mov(r3,0)         # r3=screen_x
  mov(r4,0)         # r4=chunk_x
  label(SCREEN_X)
  #addr=screen_y*MAXSCREEN_X//2+screen_x
  #color_low=scr[addr] & 0xf
  #color_hi =scr[addr] >> 4

  mov(r5,0)         # r5=s_x
  label(S_X_HI)
  #chk[chunk_y*MAXSCREEN_X+chunk_x]=pal[color_hi]
  ldr(r7,[r0,12])   # MAXSCREEN_X
  mul(r7,r1)        # chunk_y*MAXSCREEN_X
  add(r7,r7,r4)     # chunk_y*MAXSCREEN_X+chunk_x
  add(r7,r7,r7)     # double for strh
  ldr(r6,[r0,4])    # r6=chunk address
  add(r7,r7,r6)
  mov(r6,1)
  strh(r6,[r7,0])   # chk[chunk_y*MAXSCREEN_X+chunk_x]=1
  
  add(r4,1)
  add(r5,1)
  ldr(r7,[r0,8])    # r7=size
  cmp(r5,r7)
  blt(S_X_HI) 
  


  add(r3,1)
  mov(r7,240)
  cmp(r3,r7)
  blt(SCREEN_X)

  add(r2,1)
  ldr(r7,[r0,8])    # r7=size
  cmp(r2,r7)
  blt(S_Y)

  add(r1,1)
  mov(r7,64)
  cmp(r1,r7)
  blt(CHUNK_Y)
  label(EXIT)


@micropython.viper
def plot_screen():
  chk=ptr16(chunk)
  for y in range(10):
    for x in range(30):
      #if chk[(y*MAXSCREEN_X)+x]==1:
      #  print('1',end='')
      #else:
      #  print('0',end='')
      print(chk[(y*MAXSCREEN_X)+x],end='')
    print()

def draw():
  #screen.line(0,0,0,0,1)
  screen.pixel(0,0,4)
  screen.pixel(2,0,1)
  #screen.fill_rect(0,0,10,10,2)

draw()
#convert()
convert_asm(convert_ctl)
plot_screen()



BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT