Skip to content

Instantly share code, notes, and snippets.

@x1nixmzeng
Last active July 31, 2021 20:43
Show Gist options
  • Save x1nixmzeng/167d33ef0b24fe18d973 to your computer and use it in GitHub Desktop.
Save x1nixmzeng/167d33ef0b24fe18d973 to your computer and use it in GitHub Desktop.
Unity packed font binary template
//--------------------------------------
//--- 010 Editor v5.0 Binary Template
//--------------------------------------
// Unity binary font atlas format
// Documented by WRS
//--------------------------------------
struct UnityFontAtlas
{
uint unknown_0[2];
uint unknown_1[2];
uint version; // ?
uint unknown_02;
uint len <bgcolor=0x00ff80>;
char name[len] <bgcolor=0x80ff00>;
if(len&3)ubyte name_pad[4-(len&3)]; // Aligned to 4 bytes
};
struct UnityGlyph
{
wchar_t character[2] <bgcolor=0x8080ff>;
float x,w,y,h; // mult by image dim (512,2048)
float pool[7]; // other glyph info (kerning, etc)
};
//--------------------------------------
UnityFontAtlas hdr <bgcolor=0xc0c0c0>;
if(hdr.version>1728) { Printf("Warning: May fail to parse\n"); }
uint ascii_count <bgcolor=0xffff00>;
UnityGlyph ascii_glyphs[ascii_count];
uint unicode_count <bgcolor=0xffff00>;
UnityGlyph unicode_glyphs[unicode_count];
local uint rem_count = (FileSize()-FTell()) / sizeof(float);
float tail[rem_count];
//--------------------------------------
Printf("------ Info -------\n");
Printf("Font: %s\n", hdr.name);
Printf("Ascii: %d\n", ascii_count);
Printf("Unicode: %d\n", unicode_count);
Printf("Tail: %d\n", rem_count);
//--------------------------------------
local int used_space = 0;
void Process(UnityGlyph& g, uint d)
{
local uint x1 = g.x*d;
local uint x2 = g.w*d;
local uint y1 = g.y*d;
local uint y2 = g.h*d;
local uint space = (y2-y1)*(x2-x1);
used_space += space;
}
local uint dim = 2048;
local uint i;
i=0;while(i<ascii_count)
{
Process(ascii_glyphs[i],dim);
++i;
}
i=0;while(i<unicode_count)
{
Process(unicode_glyphs[i],dim);
++i;
}
Printf("------ Metrics -------\n");
Printf("Pixels: %d\n", (dim*dim));
Printf("In-use: %d\n", used_space);
local float p=(float)used_space/(float)(dim*dim);
Printf("Used: %.03f%%\n", p);
//--------------------------------------
@x1nixmzeng
Copy link
Author

Included a metrics calculator which shows how well packed the image is.

Also (thinking about it) the bounding boxes are guaranteed to overlap...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment