mandag den 31. oktober 2011

Rasterizing

Tonight I reviewed the FreeType rasterizer and a couple of other sources. What I found was that the FreeType rasterizer does not handle self-intersecting glyphs (glyphs or outlines, not just contours), but this is not a real problem since glyphs are not supposed to be self-intersecting anyway, and even so, the error that is introduced may not even be noticeable. FreeType supports the Non-Zero Winding Rule as well as the Even-Odd rule.

I shall use an algorithm similar to FreeType, but I am aiming for simplicity, and I shall take a lot of shortcuts compared to the FreeType rasterizer. I believe I shall store cells in arrays rather than linked lists, and include a qsort in the final sweep. A mailing list post seems to indicate that this is what FreeType used to do.

Thinking about it, I might make the buffer large enough for every pixel - this would be a sacrifice of memory for ultimate speed. I will be limiting the band to around 6 lines anyway. Still... 320 times 6 times 8 - 16kbytes... too much yea. Sorry if I am thinking aloud here.

Perhaps a hash table? I think I prefer that to linked lists. To avoid linked lists I would then use open addressing with linear probing. I would have to make sure that the load factor was sufficiently low. No, wait, a hash table is not nice to iterate. Oh dear I am committing a cardinal sin now: premature optimization. I shall have to compare different buffering schemes at various glyph complexities and sizes. A mammoth task.

Ah, all the beautiful code and information that is available by the click on a link.

lørdag den 29. oktober 2011

The Font Files

One of my primary goals for the LCD library is to be able to render outline fonts. There is already a great open-source library out there for doing that. It's called Freetype. This is the library used on Android. It is a simple task to get Freetype running on the MCB1700, Freetype is a beautiful piece of work and well documented too. However, in my opinion, using Freetype to render Truetype fonts files stored in flash still uses too many resources, notably flash and ram. The main reason is the Truetype font file format. It has no place on an restricted embedded system. The MCB1700 is definately restricted when it comes to Truetype font files.

What I want is to store outlines, glyphs, and character maps in a readily accessible manner in flash so that they require the least amount of processing to render. In order to use Truetype font files I must preprocess them. To that end I have begun writing a Python script to parse Truetype fonts. The output from the script will be C source code. I wish to use only two bytes for each coordinate set, so I have to somehow normalize the input. Last night I finished the parsing part of the task. Weather or not that was the simplest part, you determine. What did it take to get thus far? Let's see.

First, import some stuff. I use OptionParser even though the script has no options at this point:
from sys import stdout, stdin, argv
from struct import unpack
from optparse import OptionParser
The Table class is used as a placeholder. There is probably an even simpler python way to do this:
class Table:
  "blah"
Font files have checksums in various places. If you want to check those, you must calculate the checsum:
def chk(tab):
  return 0xFFFFFFFF & sum([unpack(">I", tab[i:i+4])[0] for i in range(0, len(tab), 4)])
Then, read the file:
parser = OptionParser()
(options, args) = parser.parse_args()
f = open(args[0], "rb")
font = f.read()
This is where you would check the entire file:
assert 0xB1B0AFBA == chk(font)
Make a dictionary of tables in the file. This is the place where you would check the checksum for each table, but I found that for some reason the head table does not check out, and anyway I don't feel the need to perform the check, I just want the outlines and be done with it:
for n in range(numTables):
  table = Table()
  tag = font[16 * n + 12 : 16 * n + 16]
  table.checkSum, table.offset, table.length = unpack(">III", font[16*n+16:16*n+28])
  c = chk(font[table.offset:table.offset + ((table.length + 3) / 4) * 4])
  tables[tag] = table
Parse required tables. I disclose the functions below:
head = parseHead(tables["head"].offset, tables["head"].offset)
maxp = parseMaxp(tables["maxp"].offset, tables["maxp"].length)
loca = parseLoca(tables["loca"].offset, tables["loca"].length, head.indexToLocFormat, maxp.numGlyphs)
glyf = parseGlyf(tables["glyf"].offset, tables["glyf"].length, loca)
cmap = parseCmap(tables["cmap"].offset, tables["cmap"].length)
The head table is simple, just a bunch of properties:
def parseHead(offset, length):
  head = Table()
  head.ver, head.fontRevision, head.checkSumAdjustment, head.magicNumber, \
  head.flags, head.unitsPerEm, head.created, head.modified, \
  head.xMin, head.yMin, head.xMax, head.yMax, head.macStyle, head.lowestRecPPEM, \
  head.fontDirectionHint, head.indexToLocFormat, head.glyphDataFormat = \
    unpack(">IIIIHHQQhhhhHHhhh", font[offset : offset + 54])
  return head
the maxp table is equally simple, also just a bunch of properties:
def parseMaxp(offset, length):
  maxp = Table()
  maxp.ver, maxp.numGlyphs, maxp.maxPoints, maxp.maxContours, maxCompositePoints, \
  maxp.maxCompositeContours, maxp.maxZones, maxp.maxTwilightPoints, maxp.maxStorage, \
  maxp.maxFunctionDefs, maxp.maxInstructionDefs, maxp.maxStackElements, \
  maxp.maxSizeOfInstructions, maxp.maxComponentElements, maxp.maxComponentDepth = \
    unpack(">iHHHHHHHHHHHHHH", font[offset : offset + 32])
  return maxp
The loca table requires some properties from head and maxp (which is why those were parsed first, see?) to interpret data correctly. The loca table contains information about where to find each glyph in the font file:
def parseLoca(offset, length, indexToLocFormat, numGlyphs):
  if 0 == indexToLocFormat: # short
    loca = [2 * unpack(">H", font[offset + 2*z: offset + 2*z + 2])[0] for z in range(numGlyphs + 1)]
  else: # long
    loca = [    unpack(">I", font[offset + 4*z: offset + 4*z + 4])[0] for z in range(numGlyphs + 1)]
  return loca
Now we can get at the glyph data. And this is where things start to get interesting. Currently the script only parses simple glyphs, not the composite ones. The script has only been tested on fonts without composite glyphs, and without instructions:
def parseGlyf(offset, length, loca):
  glyf = []
  for i, location in zip(range(len(loca[:-1])), loca[:-1]):
    o = offset + location
    num, xmin, ymin, xmax, ymax = unpack(">hhhhh", font[o : o + 10])
    o += 10
    assert num >= 0
    isComposite = num < 0
    if isComposite:
      print "  Composite glyph"
    else:
      endPoints    = [unpack(">H", font[o + z: o + z + 2])[0] for z in range(0, 2 * num, 2)]
      if endPoints:
        o += 2 * num
        instructionLength, = unpack(">H", font[o : o + 2])
        o += 2
        instructions = [unpack(">B", font[o + z])[0] for z in range(instructionLength)]
        o += instructionLength
        flags = []
        flagIndex = 0
        while flagIndex <= endPoints[-1]:
          flag = unpack(">B", font[o])[0]
          o += 1
          flags.append(flag)
          flagIndex += 1
          if 0 != (flag & (1 << 3)):
            repeat = unpack(">B", font[o])[0]
            o += 1
            flags.extend([flag] * repeat)
            flagIndex += repeat
        glyfx = []
        glyfy = []
        for firstPointIndex, lastPointIndex in zip([0] + [z + 1 for z in endPoints[:-1]], endPoints):
          xlist = []
          for pointIndex in range(firstPointIndex, lastPointIndex + 1):
            if 0 == ((1 << 1) & flags[pointIndex]):
              if 0 == ((1 << 4) & flags[pointIndex]):
                xlist.append(unpack(">h", font[o:o + 2])[0])
                o += 2
              else:
                xlist.append(0)
            else:
              xlist.append((((flags[pointIndex] >> 4) & 1)*2 - 1) * unpack(">B", font[o])[0])
              o += 1
          glyfx.append(xlist)
        for firstPointIndex, lastPointIndex in zip([0] + [z + 1 for z in endPoints[:-1]], endPoints):
          ylist = []
          for pointIndex in range(firstPointIndex, lastPointIndex + 1):
            if 0 == ((1 << 2) & flags[pointIndex]):
              if 0 == ((1 << 5) & flags[pointIndex]):
                ylist.append(unpack(">h", font[o:o + 2])[0])
                o += 2
              else:
                ylist.append(0)
            else:
              ylist.append((((flags[pointIndex] >> 5) & 1)*2 - 1) * unpack(">B", font[o])[0])
              o += 1
          glyfy.append(ylist)
        glyf.append([zip(gx, gy) for gx, gy in zip(glyfx, glyfy)])
  return glyf
As you can tell from the length of this function, the glyf table is one of the more interesting tables in the font file. It contains all the outlines, so why wouldn't it be? Among other things the glyf table contains a bunch of flags that are key to interpreting coordinate data. Using the flags you can indicate 8-bit or 16-bit coordinates, sign of 8-bit coordinates, repeat coordinates, on-curve or off-curve points, you can even repeat a set of flags a number of times. That makes it a little (but fortunately not a lot) tricky to read the outlines.

The last table that you need to map from a character code-point to an outline is CMAP. As hinted at in the previous sentence, this is "just" a table that maps from code-points to outlines. But how it does that, oh how it does that:
def parseCmap(offset, length):
  cmap = { }
  cmap_ver, cmap_num = unpack(">HH", font[offset:offset + 4])
  for t in range(cmap_num):
    cmap_plid, cmap_encid, cmap_suboffs = unpack(">HHI", font[offset + t*8 + 4 : offset + t * 8 + 12]);
    if (3, 1) == (cmap_plid, cmap_encid):
      o = offset + cmap_suboffs
      form = unpack(">H", font[o : o + 2])[0];
      o += 2
      if 4 == form:
        stuff = unpack(">HHHHHH", font[o: o + 12])
        o += 12
        cmlen, cmver, cmsegct2, cmsrang, cmesel, cmrangsh = stuff
        l = [(z,) + unpack(">HHHH", font[o+z:o+z+2] + font[o + 2 + cmsegct2+z:o + 2 + cmsegct2+z+2] + font[o + 2 + 2*cmsegct2+z:o + 2 + 2*cmsegct2+z+2] + font[o + 2 + 3*cmsegct2+z:o + 2 + 3*cmsegct2+z+2]) for z in range(0, cmsegct2, 2)]
        for i, iEnd, iStart, iDelta, iOffs in l: 
          if 0 != iOffs:
            for c in range(iStart, iEnd+1):
              glyph_index = unpack(">H", font[o + 2 + 3*cmsegct2 + i + 2 * (c - iStart) + iOffs - cmsegct2 : o + 2 + 3*cmsegct2 + i + 2 * (c - iStart) + iOffs - cmsegct2 + 2])[0]
              if 0 != glyph_index: cmap[c] = glyph_index
          else: 
            for c in range(iStart, iEnd+1):
              glyph_index = 0xFFFF & (iDelta + c)
              if 0 != glyph_index: cmap[c] = glyph_index
  return cmap
Actually the specification found at Microsoft contains these exact words:
"This obscure indexing trick works because glyphIdArray immediately follows idRangeOffset in the font file."
And obscure it is. Fortunately aforementioned specification explains it reasonably well and even contains  pieces of source code that are essential to at least my understanding of the explanation. There is probably also a perfectly reasonable explanation to why on earth a font files is constructed in this bizarre way. I personally believe that someone concocted it in a purple haze and marketing rushed it to market.

tirsdag den 25. oktober 2011

The Plasma Demo Effect.


The plasma effect drawing function uses a local buffer, lcd_getClip(), and lcd_drawBitmap() to keep the speed up:
static void drawPlasma(view_t * v) {
  int x, y, i;
  rect_t clip = lcd_getClip();
  color_t buf[clip->right - clip->left];
  (void)v;
  for (y = clip.top; y < clip.bottom; ++y) {
    for (i = 0, x = clip.left; x < clip.right; ++x, ++i) {
      buf[i] = pal[0xFF & (
          tab[0x1FF & ((pos1 >> 2) + 5 * x)]
        + tab[0x1FF & ((pos2 >> 2) + 3 * x)]
        + tab[0x1FF & ((pos3 >> 2) + 1 * y)]
        + tab[0x1FF & ((pos4 >> 2) + 3 * y)]
      )];
    }
    lcd_drawBitmap((rect_t){ clip.left, y, clip.right, y + 1 }, buf);
  }
}
tab is just a sine table, and pal is a color palette, both are placed in flash. I am using the palette from a demo effects collection i found.
The plasma is animated:
static void animatePlasma(void) {
  pos1 += 9; pos2 += 0; pos3 += 8; pos4 += 0;
}
The pos variables are just static integers starting at 0. Very simple stuff, but also very effective.

LCD Library

I thought I might add a few comments about the LCD library. The library is based around the idea that you want to update each pixel at most once each time the display changes. You might just draw everything you need to draw on top of each other, but let me tell you, that is quite slow, very visible and not so pretty. Been there, done that.

At the core of the library is a short routine that uses one DMA channel for moving pixel data from a memory buffer to SSP (the generalized peripheral used for SPI). The buffer only contains enough data for a fraction of the display. There is simply not enough RAM on the processor for the entire display. Think about it: 320 across times 240 down times two bytes of data, what's that? That's right, 150 kilobytes, and how much is on the processor? 64 kilobytes, not enough.

Actually there are two buffers, one buffer is updated with pixel data by the processor while the DMA peripheral moves data from the other buffer to the SSP peripheral and (as a SPI bit stream) to the LCD controller. This double-buffering scheme helps keep the SPI bit stream flowing, which is very necessary to make the graphics snappy. Of course, since the buffers are small, the buffer swapping must take place several times in order to refresh the entire display.

So, what does the core routine draw and how? Well, the core routine draws by calling functions supplied by any client of the library (that would be you, if you like) through an abstraction known as a view structure (much like in the Android platform). I intend to keep the view structure simple. It looks something like this now:
typedef struct View {
  scalar_t left, top, width, height;  
  struct View * parent;
  struct View * * children;
  size_t numChildren;
  void (*draw)(view_t * view);
  void (*click)(view_t * view);
} view_t;
I consider replacing draw and click with a single function which then will handle all notifications and requests. I probably will, since it saves view memory.

The view coordinates, left and right, are relative to any parent of the view, or to the screen in case the view has no parent. The coordinates are given in pixels. The dimensions, width and height are also given in pixels. The root view does not have a parent, for all other views the parent/children constitute a one-to-many relation that must be consistent. A view does not need to have children in which case children and numChildren are 0. Thinking about it, I might drop numChildren and zero-terminate the list instead, which makes sense, and conserves even more view memory. I was also considering replacing both with a call to the notification/request function, but I am reluctant to sacrifice simplicity for space savings in this case.

The member "draw" points to a function which is supposed to draw the view. This pointer may be NULL in which case the view is not drawn. Children of the view are still drawn (if they supply a draw function). The drawing primitives currently available to a view (and this is highly subject to change) are:
void lcd_drawPixel(point_t p, color_t c);
void lcd_fillRect(rect_t r, color_t color);
void lcd_drawBitmap(rect_t bounds, color_t * p);
Coordinates for these primitives are relative to the view origin.

The library keeps track of which rectangular part of a view is being redrawn. Any attempts to draw beyond the rectangle is futile, but in order to optimize drawing speed, a view may determine the clipping rectangle by calling:
rect_t lcd_getClip(void);
To have a view displayed, either set it as the root view or place in the root view hierarchy (or tree if you prefer):
void lcd_setRootView(view_t * v);
Then invalidate it:
void lcd_invalidateView(view_t * v);
Currently invalidation and redraw takes place immediately, I plan to decouple the redraw from the invalidation.


mandag den 24. oktober 2011

LCD demo

This is a first demo of a rudimentary LCD graphics library for the MCB1700. In case you can't make it out from the blurry video, it's a classic plasma background with a bunch of rectangles flying around on top. I think the SPI bit rate is a little beyond specification, but it seems to work. The SPI is a bottleneck here, so I try to keep it busy. Watch the Video below.


The KITT car style LEDs on the left just indicate that software is running, the one on the right toggle each time the entire LCD is redrawn. The wires connect the touch screen controller to the I2C peripheral on the ARM processor. Not much else to say.