Friday, April 9, 2010

Distance Field Based Rendering of AngelCode Fonts

This morning, we added support for distance field based font rendering to the BitSquid engine (from Valve's paper http://www.valvesoftware.com/publications/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf). An example is shown below:


The top row shows the original font, below that is the original font rendered with alpha test. The third row is a distance field representation of the font and the final row shows the distance field representation rendered with alpha test. Note that the distance field version gives better quality in the diagonal lines.

(Note: The last row looks thicker than the second row, because it was generated from a large font size and scaled down, while the second row was generated from a small font size. Because of true type font hinting at small sizes, the result is different. The last row gives a truer representation of the "actual" thickness of the font.)

A quick Google search didn't show any good tools for generating distance field font maps, so I decided to write my own. We use the excellent AngelCode Bitmap Font Generator (http://www.angelcode.com/products/bmfont/) to generate our font maps, so I decided to make a tool that works with the files generated by AngelCode:


The tool takes a high resolution AngelCode .fnt file as input. It scales it down by the specified scale factor and converts it to a distance field. The spread specifies how many pixels the distance field should extend outside the character outline before it clamps to zero. (It is useful if you want to add things such as glow effects to the font rendering.) After the conversion, the tool outputs new scaled down .tga images of the fonts and a new .fnt file with all measurements converted to work with the scaled down textures.

So to use it, you first generate a font bitmap and .fnt file using AngelCode at 8 x the font size and 8 x the texture size you want in the final image. (Make sure to add 8 x spread pixels of padding around the characters or else the distance fields will bleed into each other.) Then you run the tool to convert it to a distance field texture.

The tool is a bit limited -- it only works with monochrome uncompressed .tga files. It only reads and writes the XML version of the AngelCode font format. The distance field generation isn't particularly clever or fast. But I thought I should share it anyway since I couldn't find any other tools for generating distance field based font maps. Modifying it to support more formats shouldn't be much work.

Grab a binary version here:


Or the C# project files here:


Feel free to do whatever you want with it!

34 comments:

  1. Here's some other source/papers/exe you might want to check on the font/AA images topic, it might interest you:
    http://contourtextures.wikidot.com/
    http://www.ogre3d.org/forums/viewtopic.php?f=1&t=50844

    ReplyDelete
  2. Thank you. The anti-aliased version is interesting. One drawback with the method I'm using here is that you loose true type font hinting when you scale up/scale down. As a result, some of the finer details in the font can get lost (like in the upper part of the r in the example above) because the sample points where we measure the distance do not get optimally placed to capture the features of the font. (At least I think that is what is happening.)

    Using the AA method on a correctly sized font texture (i.e. not an upscaled one) might give a better result since it respects hinting. Would be worth trying.

    ReplyDelete
  3. Hi Niklas, very nice !
    I was researching those techniques for some new effects and ended on your page, what a coincidence.
    We used a similar technique in God of War 3 for our font rendering. It's a nice way to avoid baking the texts in textures while maintaining a good quality.

    ReplyDelete
  4. Hi Cedric!

    What a coincidence indeed! The game engine world sometimes seems a lot smaller than you would think.

    ReplyDelete
  5. Hi Niklas,

    In you app you generate a fnt file that has width and height values with decimal values. Am I right to assume that you use the rounded values of these? Does the error inserted by this is noticeable?

    Thanks for this great tool :),
    Jorge

    ReplyDelete
  6. No, I actually use the decimal values.

    ReplyDelete
  7. Have you tried this with more complex signs like a hanzi/kanji? I can imagine you won’t be able to scale it down that much without losing important information.

    In a system supporting Chinese typing you would probably need about 2x 1024x32 textures to get a reasonable amount of details (and using any form of texture compression for the GPU is probably unthinkable). I fear that our alphabet is only a fraction of the required memory, and probably among the few signs that can greatly benefit from this technique? It would though be interesting to hear if you have done any experimentation with this.

    We are currently using 2x 1024x32 textures for supporting the full Unicode char set, and Chinese seam to by far be the biggest char set with in it. It works okay, but I am considering starting rasterizing whole paragraphs in software and save to temporary textures. Because just thinking about adding support for large fonts for HUD and headers hurts... would probably require at least double that memory even if the distance field method works reasonably for hanzi.

    Do you have any thoughts on the matter? I can guess software rasterizing and the extra memory associated with that would have a whole other impact on console than on PC. And I have yet to get any real experience with programming larger projects for a console.
    (You can always try to scale down this one; 簣)

    ReplyDelete
  8. No I haven't experimented that much with complex characters. But you need a certain minimum resolution for this to work. If your resolution is so low that the basic strokes of the characters "blur together", then the distance field approach can't "unblur" them. But as long as that doesn't happen you should be fine.

    A scaled up distance field font will never look as good as the "real font" rendered at a bigger font size though. (Just better than a scaled up bitmap font.) For maximum quality that is the way to go. Juggling all those temporary textures is annoying though.

    ReplyDelete
  9. Hi, I wanted to use this tool, but it isn't working for me. It is generating all-white tga files. Have you run into that problem before? I want a 36 pixel font ultimately, so I generated a 288-pixel angelcode font. I put 64 pixels of padding on all four sides because I want 8 pixels of spread. I used the xml fnt format, and get no errors. Any idea what I might be doing wrong?

    Also I am wondering why you need to generate so large a font initially? The original distance field article just used a bitmap the same size as the resulting distance field image, didn't it? It's no big deal since the BMFont output is temporary but I was just wondering.

    Thanks for any assistance!
    Bob

    ReplyDelete
  10. Hi Bob. No I haven't seen that error.

    I use big textures just to get better values for the distance field. (Since I estimate the distance to the glyph curve by counting pixels.)

    ReplyDelete
  11. Oh that is funny -- the files are fine, actually. They just show up as all white when you view them in Quicktime Picture Viewer. That's the only program on my Windows 7 machine apparently that can show .tif files. What do you use? I'm installing Gimp but that's a heavy program just to look at TIFs.

    Thanks
    Bob

    ReplyDelete
  12. BMFont doesn't seem to be able to generate 600px size fonts exported to 2048x2048 textures. I guess that's too large?

    I tried converting to distance field using the same scale -- I put '1' into the Scale Down By box, is that right or should it be 0?

    The fonts aren't rendering yet but displaying them with the old shader shows the new font to be smaller, and more closely packed together, than the original. Shouldn't it be exactly the same if the scale is the same? In fact shouldn't I be able to use the original .fnt file in that case? Or does the converter change things about the glyphs?

    Thanks
    Bob

    ReplyDelete
  13. Hello again,

    I made some modifications to your tool that might be of use to other people working with distance field fonts.

    The giant fonts exported from BMFont for use in your tool will usually consist of several pages of texture map images, especially if you are making the entire alphabet. But once they are shrunken down into DF fonts, there's no need for them to be spread across several images. It's more convenient if the smaller DF letterforms are placed on a single texture map.

    I modified your code to do this -- for example, a font exported at 480 x 480 pixels per character takes four 2048x2048 texture maps. Shrinking down by a factor of 8, the distance field font fits on a single 1024x256 map.

    I haven't tested it beyond what I needed for my single application, and I am not a C# programmer -- so there could be some bugs in there. But it worked for me. Here's the executable and source code for the modified version if anyone wants to try it:

    http://www.flatblackfilms.com/distance_field_exe.zip
    http://www.flatblackfilms.com/distance_field_source.zip


    Thanks,
    Bob

    ReplyDelete
  14. Replies
    1. The original links appear to be down, but you can try the links I posted in the comment just above yours -- I made a slight modification which you can read about.

      Delete
  15. Hi there! The smaller font under each word tells the actual name of the font. The "sparkling" one is called Sweet Pea font

    and the link is: http://www.dafont.com/sweet-pea.font
    The clickable links to all of them are right under the image!
    Thanks!

    ReplyDelete
  16. Dafont.com is a site where you can download a ton of free fonts. You can search for a specific typeface, or search by the type of lettering you want, whether it’s serif or sans serif, hand lettered or grunge style. You can also put in your own phrase to see how it looks in a particular font. A lot of these fonts are very decorative and many are handdrawn, so it’s not always the best place to search for body text fonts. Each selection also tells you whether your download is free for personal or commercial use. The download is easy – you get a zip file with the font file inside. Unzip, install, and you’re ready to go.

    ReplyDelete
  17. Office.com/Setup is a set of desktop applications, which is widely used products for the home as well as an office. Microsoft office gives the freedom of writing documents, blogs, letters and with the use of Microsoft office PowerPoint one can prepare a presentation also.
    howtominernewswatt
    Norton.com/Setup
    Office.com/Setup
    Office.com/Setup
    office Setup
    Daily Helps
    office.com/Setup

    ReplyDelete
  18. Office Setup is a software which is used by almost all company and business and even by individuals For all their office activities or for personal use. It has excels, word, and ppt as their constituent are most widely used apps. For any concern and help just visit website for office help and key activation. You can do it by yourself if you know how to install office setup on your PC or Mac or you can call third party companies as well who can do it on your behalf.
    office.com/Setup
    office.com/Setup
    Norton.com/Setup
    office.com/Setup
    office.com/Setup
    office.com/Setup
    Norton.com/Setup

    ReplyDelete
  19. Allassignmenthelp is your academic caretaker. Our online assignment assistance is one of the most sought after in the US and other countries and you should give us a chance to assist you. Write My Assignment

    ReplyDelete
  20. hello everyone. I like writing and posting something new can be a really enjoyable task. By the way, do you know where to buy resume paper? I decided to change my job and I need a well-written essay.

    ReplyDelete
  21. The designing and application of this decorative staff are discussed in terms of the high needs the people wants for decoration depending on whether their required design is graphical, architectural or a product.freelance writer for hire

    ReplyDelete
  22. The assignment help online given by our devoted authors are of premium and high caliber. If you need assignment help Australia, get in touch with ABC Assignment Help. The assignments prepared by our dedicated writers are of premium and high quality. Avail the assignment help and get the desired results even at the last moment.

    ReplyDelete
  23. Take Assignment help Ireland services to finish your work without any stress. If you have no one to ask your queries, use Assignment help services and get experts’ guidance for your concerns.
    Assignment help Saudi Arabia
    assignment help Hong Kong
    assignment help Kuwait
    assignment help United Arab Emirates

    ReplyDelete

  24. 'I'm highly impressed by the piece of thoughts you have shared on this portal. all the best
    connect us on Assignment Help can shed your burden of assignments with a return of qualitative assignments.
    Online Assignment Help
    Programming Assignment Help
    Management Assignment Help
    My Assignment Help

    ReplyDelete
  25. I totally agree with the opinion that response paper is challenging task for students. They have not enough skills for this. I want to buy a response paper online because I also need some bits of advice.

    ReplyDelete
  26. Use Assignment Help to connect with Australian academic writers in just a few minutes. Students can take online assignment writing services in Australia when they have no one to ask their queries and find it tough to write your academic papers.
    My Assignment Help
    Assignment Help Online
    Online Assignment Help

    ReplyDelete
  27. En este momento de la digitalización, la técnica habitual para hacer pagos a través del dinero ha envejecido. Sustituya sus viejas técnicas por otras más actuales utilizando las administraciones en línea para pagar directamente a través de sus saldos financieros. Lo valioso de la administración de cuotas versátil que utiliza un pequeño mensaje, que se ha desarrollado obviamente patria desde que surgieron los problemas de ingresos, es que no necesita obtener un teléfono celular, es suficiente tener lo que ellos llaman un "responsable". Los clientes deben seleccionar en la fase de estos bancos, de los cuales indicarán la cantidad y la cantidad de intercambios habilitados siguiendo los parámetros, para utilizar la instalación por SMS. Las personas que utilizan saldos en el Banco de Venezuela banco de venezuela En Linea obtienen y harán compromisos interbancarios. Como un enfoque para obtener ganancias por la función, es urgente estar asociado con el BDV En Linea, en el cual debe iniciar la entrega esencial. Para las personas que tienen un registro gratuito en el banco del tesoro En Linea, puede crear la instalación de SMS de hasta 1,000,000 de bolívares de manera consistente, para eso debe consolidar la función en la instalación telefónica de Tesoro en Tesoro en la web y enviar, retirar la separación bnc , un correo electrónico al 2383 con toda la palabra Pagar, y los principales ejemplos de las cuentas bancarias de objetivos, el número de teléfono del destinatario, el tipo de cliente (V, Correo electrónico o J), el número de tarjeta de personalidad del beneficiario, el número fue con una coma y además dos decimales y código por la tarjeta de clasificación que se elegirá. Banco Bicentenario Debe inscribirse a través de su aplicación banco bicentenario En Linea Payment para explotar el servicio. En ese momento, pagará enviando un SMS al número 7077 juntos utilizando todo el términoEl código QR del video modificado se puede utilizar para descargar videos en su teléfono inteligente. Este convertidor mp3 en línea gratuito permite cambiar sus grabaciones de YouTube a MP3, MP4, MP4 HD, AVI y AVI HD. La interfaz es básica donde simplemente necesita pegar la URL del video y elegir el diseño de rendimiento. El registro modificado se hará accesible en la interfaz para descargar. También está disponible un módulo de programa gratuito para descargar videos. Con este programa en línea, sus grabaciones de YouTube se De hecho, mis abuelos tenían correo electrónico ... durante los años 90.Inevitablemente, el custodio estaba harto de observar involuntariamente que mi correo electrónico llegara al registro de la escuela. Por fin me arrinconó y dijo: "¿Has intentado hotmail ?" Entonces lo miré. Además, en ese primer año, fui un individuo sancionador por el trastorno de correo electrónico gratuito basado en la web. whatsapp web needs no presentation. It is all around the most well known texting application and has the most number of clients., GIFs, recordings, reports, this element bodes well. It tends to be exceptionally dull to return and quest for recently shared media, consequently another propelled search include. whatsapp web beta

    ReplyDelete
  28. Today, more and more students are going after assignment writing services so as to get assignment writing help and to escape from their writing troubles. Obviously, assignment writing services can help the students to get away from the tensions, strain and worries of writing assignments. Most of the students will be worried and stressed when they get assignments to be written on varied topics and it is definitely a matter of concern because not every assignment service provider has qualified experts and a team that specialises in that particular subject.
    top assignment help australia
    top assignment writing website
    best assignment writing help australia
    best online assignment writing help
    best assignment writing help

    ReplyDelete
  29. Get best biology assignment help from ABC assignment help, which is a one-stop solution for all your academic worries or related problems. Our experts help students to achieve their desired result and triumph in career. Contact us now to hire best team for your work.

    ReplyDelete
  30. Kunjungi situs panduan CARA BERMAIN LIVE GAME IDN yang baik dan benar di situs ini,kalian akan mengetahui tata cara bermain yang dianjurkan agar meraih keuntungan yang banyak di live game IDN. kalian bisa melihat panduan cara bermain game
    - ROULETTE
    - 12D
    - 24D
    - 24Dspin
    - 3D Shio
    - 5D Ball
    - Baccarat
    - Billiards
    - Dice 6
    - Dragon Tiger
    - Fantan
    - Gong Ball
    - Head Tail
    - Monopoly
    - Race Ball
    - Sicbo[Dice]


    Semua bisa kalian pelajari di Cara Bermain Live Game IDN LIVE

    ReplyDelete