function [pixels,palette,packed,restored] = mugEncodingDemo(showFigure)
% Draw, encode and reconstruct Tipping Point's pixel mug.
% Set showFigure to false to return the arrays without opening a figure.
% pixels and restored contain uint8 pixel values; palette contains RGB colors.
% packed stores the run-length tokens as Unicode characters.

arguments
    showFigure (1,1) logical = true
end

[pixels,palette] = makeMugSprite();

% Encode runs of up to 32 pixels
values = double(pixels(:)');
starts = find([true,diff(values) ~= 0]);
lengths = diff([starts,numel(values)+1]);
tokens = [];
for k = 1:numel(starts)
    remaining = lengths(k);
    while remaining > 0
        runLength = min(32,remaining);
        tokens(end+1) = values(starts(k))+32*(runLength-1); %#ok<AGROW>
        remaining = remaining-runLength;
    end
end
packed = char(19968+tokens);

% Decode the runs and verify the reconstructed pixels
tokens = double(packed)-19968;
colors = mod(tokens,32);
lengths = floor(tokens/32)+1;
decoded = repelem(colors,lengths);
restored = uint8(reshape(decoded,15,15));
assert(isequal(restored,pixels),'The decoded pixels differ from the source.');

if showFigure
    background = [.035 .045 .06];
    fig = figure(Name = 'Mug encoding',NumberTitle = 'off',Color = background, ...
        Position = [100 100 800 420],DefaultTextInterpreter = 'none');
    layout = tiledlayout(fig,1,2,TileSpacing = 'compact',Padding = 'compact');
    images = {pixels,restored};
    names = ["Original","Decoded"];
    for k = 1:2
        ax = nexttile(layout);
        ax.Color = background;
        image(ax,images{k},CDataMapping = 'direct',AlphaData = images{k} > 0);
        colormap(ax,double(palette)/255);
        axis(ax,'image','off');
        title(ax,names(k),Color = [.92 .94 .97],FontName = 'Segoe UI',FontWeight = 'normal');
    end
end
if nargout == 0
    fprintf('%d pixels, %d run tokens; reconstruction is exact.\n', ...
        numel(pixels),numel(tokens));
end
end

function [pixels,palette,stages] = makeMugSprite()
% Draw the mug using the game's palette and drawing coordinates

hex = ["000000" "211829" "352238" "563141" "784132" "A95B45" ...
    "D98A59" "F2B66D" "F8DDA1" "FFF2C7" "823A48" "AF4D50" ...
    "D97162" "1D424B" "2E6568" "58938B" "9CB392" "4C5942" ...
    "737747" "B5A56E" "AD6B4D" "E8A06A" "FFCA8C" "6E3D32" ...
    "9D5941" "CC8557" "44465E" "707384" "A5ADB3" "D7DBCB" ...
    "FDF7DD" "BF9A57"];
palette = uint8(reshape(sscanf(char(join(hex,"")), '%2x'), 3, [])');
pixels = zeros(15,15,'uint8');
[x,y] = meshgrid(0:14);

polygon([1 3;10 3;10 12;8 14;3 14;1 12],1);
polygon([2 4;9 4;9 11;8 13;3 13;2 11],6);
stages = {pixels};

rectangle(11,4,3,8,1);
rectangle(11,5,2,6,28);
rectangle(11,6,1,4,0);
stages{2} = pixels;

rectangle(3,5,4,7,7);
rectangle(3,5,1,6,9);
rectangle(8,5,1,7,31);
stages{3} = pixels;

polygon([0 3;1 1;4 1;5 0;8 0;9 2;11 2;11 5;8 5;7 4;5 5;3 4;1 5;0 4],8);
polygon([1 2;4 2;5 1;8 1;8 3;10 3;10 4;8 4;7 3;5 4;3 3;1 4],30);
rectangle(2,4,2,2,8);
stages{4} = pixels;

    function rectangle(left,top,width,height,color)
        pixels(top+(1:height),left+(1:width)) = color;
    end

    function polygon(vertices,color)
        pixels(inpolygon(x,y,vertices(:,1),vertices(:,2))) = color;
    end
end
