Skip to content

Instantly share code, notes, and snippets.

@JettMonstersGoBoom
Created September 18, 2020 20:38
Show Gist options
  • Save JettMonstersGoBoom/b72664b76d82af67c839bfebdbb8aebc to your computer and use it in GitHub Desktop.
Save JettMonstersGoBoom/b72664b76d82af67c839bfebdbb8aebc to your computer and use it in GitHub Desktop.
"""
NES CHR direct loading
( experiment in tiled + python )
based on https://github.com/samhocevar/tiled-pico8 by Sam Hocevar
"""
import tiled as T
import base64
PALETTE = [
(0x00, 0x00, 0x00), # black
(0x5f, 0x57, 0x4f), # dark_gray
(0xc2, 0xc3, 0xc7), # light_gray
(0xff, 0xf1, 0xe8), # white
]
class NES(T.Plugin):
@classmethod
def nameFilter(self):
return "NES CHR (*.chr)"
@classmethod
def shortName(self):
return "NES"
@classmethod
def supportsFile(self, f):
return open(f, 'rb').read(16) == b'NES CHR'
@classmethod
def read(self, filename):
with open(filename, 'rb') as f:
bits = list(f.read())
# Create a map
m = T.Tiled.Map(T.Tiled.Map.Orthogonal, 32, 30, 8, 8)
m.setBackgroundColor(T.qt.QColor(*PALETTE[0]))
# m.setProperty('data', base64.b64encode(cart))
# Create an image and a tileset for the palette
pal = [T.qt.QColor(*rgb).rgb() for rgb in PALETTE]
tsize = 12
img = T.qt.QImage(4 * tsize, 8 * tsize, T.qt.QImage.Format_Indexed8)
img.setColorTable(pal)
img.fill(0)
for n in range(4):
x, y = n % 4 * tsize, n // 4 * tsize
for j in range(tsize):
for i in range(tsize):
img.setPixel(x + i, y + j, n)
t = T.Tiled.Tileset.create('NES Palette', tsize, tsize, 0, 0)
t.data().loadFromImage(img, '')
m.addTileset(t)
pal = [T.qt.QColor(*rgb).rgb() for rgb in PALETTE]
img = T.qt.QImage(128, 128, T.qt.QImage.Format_Indexed8)
img.setColorTable(pal)
img.fill(0)
for n in range(256):
offset = n * 16
x, y = (n % 16) * 8, (n // 16) * 8
for j in range(8):
a = bits[offset+j]
b = bits[8+offset+j]
for i in range(8):
ix=7-i
c = (a>>ix)&1
d = ((b>>ix)&1)
d = d << 1
c = c | d
img.setPixel(x + i, y + j, c)
# Create fileset from the image
t = T.Tiled.Tileset.create('NES Sprites', 8,8, 0, 0)
t.data().loadFromImage(img, '')
m.addTileset(t)
# fake map data into a layer
l = T.Tiled.TileLayer('NES Map', 0, 0, 32, 30)
for i in range(32*30):
ti = t.data().tileAt(i&0xff)
l.setCell(i % 32, i // 32, T.Tiled.Cell(ti))
m.addLayer(l)
return m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment