#pragma once

#include <assert.h>
#include <stdint.h>

static const unsigned char FontGlyphStart     = 32;  // Space.
static const unsigned char FontGlyphEnd       = 127; // One past tilde.
static const unsigned int  FontAtlasNumGlyphs = FontGlyphEnd - FontGlyphStart;

/// Font atlas header.
typedef struct FontHeader {
  uint16_t glyph_width;
  uint16_t glyph_height;
  uint16_t num_glyphs;
} FontHeader;

/// Font atlas.
///
/// Pixels are stored in "glyph-major" order. First the rows of the first glyph,
/// followed by the rows of the second glyph, etc. Thus, pixels should be viewed
/// as a linear array, not a 2d array. This arrangement allows an application to
/// render glyphs by scanning atlas memory linearly.
typedef struct FontAtlas {
  FontHeader    header;
  unsigned char pixels[1];
} FontAtlas;

/// Load a font atlas from a file.
FontAtlas* LoadFontAtlas(const char* path);

/// Get the glyph into the atlas.
static inline const unsigned char* FontGetGlyph(
    const FontAtlas* atlas, unsigned char c) {
  assert(atlas);
  unsigned index = c - FontGlyphStart;
  if (index >= FontAtlasNumGlyphs) {
    index = '?' - FontGlyphStart;
  }
  assert(index < FontAtlasNumGlyphs);
  return atlas->pixels +
         index * (atlas->header.glyph_width * atlas->header.glyph_height);
}