imagefont.monkey2 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. Namespace mojo.graphics
  2. Using std.resource
  3. #rem monkeydoc @hidden The ImageFont class.
  4. #end
  5. Class ImageFont Extends Font
  6. Method New( pixmap:Pixmap,charWidth:Int,charHeight:Int,firstChar:Int=32,numChars:Int=96,padding:Int=1,shader:Shader=Null,textureFlags:TextureFlags=TextureFlags.FilterMipmap )
  7. Local charsPerRow:=pixmap.Width/charWidth
  8. Local numRows:=(numChars-1)/charsPerRow+1
  9. Local ipixmap:Pixmap
  10. If padding
  11. ipixmap=New Pixmap( charsPerRow*(charWidth+padding),numRows*(charHeight+padding),pixmap.Format )
  12. ipixmap.Clear( Color.None )
  13. Endif
  14. _glyphs=New Glyph[numChars]
  15. Local spos:=New Vec2i,gpos:=New Vec2i,gsize:=New Vec2i( charWidth,charHeight )
  16. For Local i:=0 Until numChars
  17. Local char:=firstChar+i
  18. Local glyph:Glyph
  19. glyph.rect=New Recti( gpos,gpos+gsize )
  20. glyph.offset=Null
  21. glyph.advance=charWidth
  22. _glyphs[i]=glyph
  23. If ipixmap
  24. Local src:=pixmap.Window( spos.x,spos.y,charWidth,charHeight )
  25. ipixmap.Paste( src,gpos.x,gpos.y )
  26. Endif
  27. spos.x+=charWidth
  28. gpos.x+=charWidth+padding
  29. If spos.x+charWidth>pixmap.Width
  30. spos.y+=charHeight
  31. gpos.y+=charHeight+padding
  32. spos.x=0
  33. gpos.x=0
  34. Endif
  35. Next
  36. _page=New Image( ipixmap ?Else pixmap,textureFlags,shader )
  37. Init( charHeight,firstChar,numChars )
  38. End
  39. Method GetGlyph:Glyph( char:Int ) Override
  40. char-=FirstChar
  41. If char<0 Or char>=NumChars Return _glyphs[0]
  42. Return _glyphs[char]
  43. End
  44. Method GetGlyphPage:Image( char:Int ) Override
  45. Return _page
  46. End
  47. Function Load:ImageFont( path:String,charWidth:Int,charHeight:Int,firstChar:Int=32,numChars:Int=96,padding:Int=1,shader:Shader=Null,textureFlags:TextureFlags=TextureFlags.FilterMipmap )
  48. Local pixmap:=Pixmap.Load( path,Null,True )
  49. If Not pixmap
  50. If Not ExtractRootDir( path ) pixmap=Pixmap.Load( "font::"+path,Null,True )
  51. If Not pixmap Return Null
  52. Endif
  53. Local pshader:=shader ?Else (pixmap.Format=PixelFormat.I8 ? Shader.Open( "font" ) Else Shader.Open( "sprite" ))
  54. Local font:=New ImageFont( pixmap,charWidth,charHeight,firstChar,numChars,padding,pshader,textureFlags )
  55. Return font
  56. End
  57. Protected
  58. Method OnDiscard() Override
  59. _page.Discard()
  60. End
  61. Private
  62. field _glyphs:Glyph[]
  63. Field _page:Image
  64. End