2
0

fontloader_stb.monkey2 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. Namespace mojo.graphics.fontloader
  2. #Import "<stb-truetype>"
  3. Using stb.truetype
  4. #rem monkeydoc @hidden
  5. #end
  6. Function LoadFont:Font( path:String,height:Float )
  7. Local firstChar:=32
  8. Local numChars:=96
  9. Local data:=DataBuffer.Load( path )
  10. If Not data Return Null
  11. 'Get font info
  12. Local f:stbtt_fontinfo,fp:=Varptr f
  13. If Not stbtt_InitFont( fp,data.Data,0 ) Return Null
  14. Local ascenti:Int,descenti:Int,linegapi:Int
  15. stbtt_GetFontVMetrics( fp,Varptr ascenti,Varptr descenti,Varptr linegapi )
  16. Local scale:=stbtt_ScaleForPixelHeight( fp,height )
  17. Local ascent:=ascenti*scale,descent:=descenti*scale,linegap:=linegapi*scale
  18. Local fheight:=(ascenti-descenti+linegapi)*scale
  19. 'Bake the chars
  20. Local bakedChars:=New stbtt_bakedchar[numChars]
  21. Local pixmap:=New Pixmap( 512,512,PixelFormat.A8 )
  22. stbtt_BakeFontBitmap( data.Data,0,height,pixmap.Data,512,512,firstChar,numChars,bakedChars.Data )
  23. Local image:=New Image( pixmap,Shader.GetShader( "font" ) )
  24. Local glyphs:=New Glyph[numChars]
  25. For Local i:=0 Until numChars
  26. Local x:=bakedChars[i].x0
  27. Local y:=bakedChars[i].y0
  28. Local w:=bakedChars[i].x1-x
  29. Local h:=bakedChars[i].y1-y
  30. Local xoffset:=bakedChars[i].xoff
  31. Local yoffset:=bakedChars[i].yoff+ascent
  32. Local advance:=bakedChars[i].xadvance
  33. glyphs[i]=New Glyph( New Recti( x,y,x+w,y+h ),New Vec2f( xoffset,yoffset ),advance )
  34. Next
  35. Local font:=New Font( image,fheight,firstChar,glyphs )
  36. Return font
  37. End