# HG changeset patch # User Matthew Wild # Date 1257299676 0 # Node ID c75ae749adf5fcf3eaa54d92725afaf5cb902e75 Initial commit diff -r 000000000000 -r c75ae749adf5 xpm.lua --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/xpm.lua Wed Nov 04 01:54:36 2009 +0000 @@ -0,0 +1,73 @@ + +module("xpm", package.seeall); +_M.__index = _M; + +function new(width, height, name) + return setmetatable({ + name = name, + width = width, + height = height, + colours = { [false] = true }, ncolours = 1; + }, _M); +end + +function setpixel(xpm, x, y, colour) + if not xpm[y] then + xpm[y] = { [x] = colour }; + else + xpm[y][x] = colour; + end + if colour and not xpm.colours[colour] then + xpm.colours[colour] = true; + xpm.ncolours = xpm.ncolours + 1; + end +end + +function render(xpm, f) + local err; + if type(f) == "string" then + f = io.open(out, "w+"); + end + if io.type(f) ~= "file" then + error("No valid output file", 2); + end + + f:write("/* XPM */\n"); + f:write("static char * ", name or "xpm", "[] = {\n"); + f:write(string.format([["%d %d %d %d",]], xpm.width, xpm.height, xpm.ncolours, 1), "\n"); + + local colourmap = new_colourmap(xpm.colours); + + for colour in pairs(xpm.colours) do + f:write('"', colourmap[colour], " c ", colour or "None", '",\n'); + end + + for y=1,xpm.height do + if xpm[y] then + f:write('"'); + for x=1,xpm.width do + local pixel = xpm[y][x]; + if pixel then + f:write(colourmap[pixel]); + else + f:write(" "); + end + end + f:write('"', y == xpm.height and "" or ",",'\n'); + else + f:write('"', string.rep(" ", xpm.width), '"', y == xpm.height and "" or ",", '\n'); + end + end + f:write("};\n"); +end + +function new_colourmap(colours) + return setmetatable({ [false] = " ", curr = 35 }, { __index = + function (cm, colour) + cm.curr = cm.curr + 1; + cm[colour] = string.char(cm.curr); + return rawget(cm, colour); + end; }); +end + +return _M;