#!/usr/bin/python3

import itertools

from mrcrowbar import models as mrc
from mrcrowbar.lib.images import base as img


# source: http://segaretro.org/Palette#Mega_Drive_Palette

class VDPColour( img.Colour ):
    _block_size =   2
    b_raw = mrc.Bits( 0x0000, 0b00001110 )
    g_raw = mrc.Bits( 0x0001, 0b11100000 )
    r_raw = mrc.Bits( 0x0001, 0b00001110 )

    @property
    def r_8( self ):
        return (self.r_raw << 5)

    @property
    def g_8( self ):
        return (self.g_raw << 5)

    @property
    def b_8( self ):
        return (self.b_raw << 5)

    @property
    def r( self ):
        return self.r_raw/7

    @property
    def g( self ):
        return self.g_raw/7

    @property
    def b( self ):
        return self.b_raw/7



# source: http://www.emulatronia.com/doctec/consolas/megadrive/genesis_rom.txt

class SuperMagicDriveInterleave( mrc.Transform ):
    def import_data( self, buffer ):
        
        def deinterleave_block( block ):
            output = bytearray( len( block ) )
            for i in range( len( output ) ):
                if (i % 2):
                    index = i//2
                else:
                    index = (len( output )//2) + (i//2)
                output[i] = block[index]
            return output

        output = bytearray( len( buffer )-512 )

        for i in range( 0, len( buffer )-512, 16384 ):
            block = buffer[512:][i:i+16384]
            output[i:i+16384] = deinterleave_block( block )

        return output




@@ -173,16 +173,494 @@
 alette%0A%0A
+class VDPBlockMapping8( mrc.Block ):%0A    _block_size = 2%0A    priority        = mrc.Bits( 0x0000, 0b10000000 )%0A    palette_line    = mrc.Bits( 0x0000, 0b01100000 )%0A    flip_horiz      = mrc.Bits( 0x0000, 0b00010000 )%0A    flip_vert       = mrc.Bits( 0x0000, 0b00001000 )%0A%0A    tile_index_high = mrc.Bits( 0x0000, 0b00000111 )%0A    tile_index_low  = mrc.UInt8( 0x0001 )%0A    %0A    @property%0A    def tile_index( self ):%0A        return ((tile_index_high %3C%3C 8) + tile_index_low) * 0x20%0A%0A%0A
 class VD
@@ -678,24 +678,24 @@
 g.Colour ):%0A
-
     _block_s
@@ -1096,25 +1096,25 @@
  self.r_raw/
-7
+8
 %0A%0A    @prope
@@ -1162,17 +1162,17 @@
 f.g_raw/
-7
+8
 %0A%0A    @p
@@ -1228,9 +1228,9 @@
 raw/
-7
+8
 %0A%0A%0A%0A

fix palette