Example #1
0
void Font::drawText(vec2 pen, vec4 color, const char* text)
{
  uint vertexCount = 0;

  // Realize vertices for glyphs
  {
    const size_t length = std::strlen(text);
    m_vertices.resize(length * 6);

    for (const char* c = text;  *c != '\0'; )
    {
      const uint32 codepoint = utf8::next<const char*>(c, text + length);
      const Glyph* glyph = findGlyph(codepoint);
      if (!glyph)
      {
        glyph = findGlyph(0xfffd);
        if (!glyph)
          continue;
      }

      pen = round(pen);

      if (all(greaterThan(glyph->size, vec2(0.f))))
      {
        const Rect pa(pen + glyph->bearing - vec2(0.5f), glyph->size);
        const Rect ta(glyph->offset + vec2(0.5f), glyph->size);

        m_vertices[vertexCount + 0].texcoord = ta.position;
        m_vertices[vertexCount + 0].position = pa.position;
        m_vertices[vertexCount + 1].texcoord = ta.position + vec2(ta.size.x, 0.f);
        m_vertices[vertexCount + 1].position = pa.position + vec2(pa.size.x, 0.f);
        m_vertices[vertexCount + 2].texcoord = ta.position + ta.size;
        m_vertices[vertexCount + 2].position = pa.position + pa.size;

        m_vertices[vertexCount + 3] = m_vertices[vertexCount + 2];
        m_vertices[vertexCount + 4].texcoord = ta.position + vec2(0.f, ta.size.y);
        m_vertices[vertexCount + 4].position = pa.position + vec2(0.f, pa.size.y);
        m_vertices[vertexCount + 5] = m_vertices[vertexCount + 0];

        vertexCount += 6;
      }

      pen += vec2(glyph->advance, 0.f);
    }
  }

  if (!vertexCount)
    return;

  VertexRange range = m_context.allocateVertices(vertexCount,
                                                 Vertex2ft2fv::format);
  if (range.isEmpty())
  {
    logError("Failed to allocate vertices for text drawing");
    return;
  }

  range.copyFrom(m_vertices.data());

  m_pass.setUniformState(m_colorIndex, color);
  m_pass.apply();

  m_context.render(PrimitiveRange(TRIANGLE_LIST, range));
}