Path: blob/master/SLICK_HOME/src/org/newdawn/slick/UnicodeFont.java
1456 views
1package org.newdawn.slick;23import java.awt.Font;4import java.awt.FontFormatException;5import java.awt.FontMetrics;6import java.awt.Rectangle;7import java.awt.font.GlyphVector;8import java.awt.font.TextAttribute;9import java.io.IOException;10import java.lang.reflect.Field;11import java.util.ArrayList;12import java.util.Collections;13import java.util.Comparator;14import java.util.Iterator;15import java.util.LinkedHashMap;16import java.util.List;17import java.util.Map;18import java.util.Map.Entry;1920import org.newdawn.slick.font.Glyph;21import org.newdawn.slick.font.GlyphPage;22import org.newdawn.slick.font.HieroSettings;23import org.newdawn.slick.opengl.Texture;24import org.newdawn.slick.opengl.TextureImpl;25import org.newdawn.slick.opengl.renderer.Renderer;26import org.newdawn.slick.opengl.renderer.SGL;27import org.newdawn.slick.util.ResourceLoader;2829/**30* A Slick bitmap font that can display unicode glyphs from a TrueTypeFont.31*32* For efficiency, glyphs are packed on to textures. Glyphs can be loaded to the textures on the fly, when they are first needed33* for display. However, it is best to load the glyphs that are known to be needed at startup.34* @author Nathan Sweet <[email protected]>35*/36public class UnicodeFont implements org.newdawn.slick.Font {37/** The number of display lists that will be cached for strings from this font */38private static final int DISPLAY_LIST_CACHE_SIZE = 200;39/** The highest glyph code allowed */40static private final int MAX_GLYPH_CODE = 0x10FFFF;41/** The number of glyphs on a page */42private static final int PAGE_SIZE = 512;43/** The number of pages */44private static final int PAGES = MAX_GLYPH_CODE / PAGE_SIZE;45/** Interface to OpenGL */46private static final SGL GL = Renderer.get();47/** A dummy display list used as a place holder */48private static final DisplayList EMPTY_DISPLAY_LIST = new DisplayList();4950/**51* Utility to create a Java font for a TTF file reference52*53* @param ttfFileRef The file system or classpath location of the TrueTypeFont file.54* @return The font created55* @throws SlickException Indicates a failure to locate or load the font into Java's font56* system.57*/58private static Font createFont (String ttfFileRef) throws SlickException {59try {60return Font.createFont(Font.TRUETYPE_FONT, ResourceLoader.getResourceAsStream(ttfFileRef));61} catch (FontFormatException ex) {62throw new SlickException("Invalid font: " + ttfFileRef, ex);63} catch (IOException ex) {64throw new SlickException("Error reading font: " + ttfFileRef, ex);65}66}6768/**69* Sorts glyphs by height, tallest first.70*/71private static final Comparator heightComparator = new Comparator() {72public int compare (Object o1, Object o2) {73return ((Glyph)o1).getHeight() - ((Glyph)o2).getHeight();74}75};7677/** The AWT font that is being rendered */78private Font font;79/** The reference to the True Type Font file that has kerning information */80private String ttfFileRef;81/** The ascent of the font */82private int ascent;83/** The decent of the font */84private int descent;85/** The leading edge of the font */86private int leading;87/** The width of a space for the font */88private int spaceWidth;89/** The glyphs that are available in this font */90private final Glyph[][] glyphs = new Glyph[PAGES][];91/** The pages that have been loaded for this font */92private final List glyphPages = new ArrayList();93/** The glyphs queued up to be rendered */94private final List queuedGlyphs = new ArrayList(256);95/** The effects that need to be applied to the font */96private final List effects = new ArrayList();9798/** The padding applied in pixels to the top of the glyph rendered area */99private int paddingTop;100/** The padding applied in pixels to the left of the glyph rendered area */101private int paddingLeft;102/** The padding applied in pixels to the bottom of the glyph rendered area */103private int paddingBottom;104/** The padding applied in pixels to the right of the glyph rendered area */105private int paddingRight;106/** The padding applied in pixels to horizontal advance for each glyph */107private int paddingAdvanceX;108/** The padding applied in pixels to vertical advance for each glyph */109private int paddingAdvanceY;110/** The glyph to display for missing glyphs in code points */111private Glyph missingGlyph;112113/** The width of the glyph page generated */114private int glyphPageWidth = 512;115/** The height of the glyph page generated */116private int glyphPageHeight = 512;117118/** True if display list caching is turned on */119private boolean displayListCaching = true;120/** The based display list ID */121private int baseDisplayListID = -1;122/** The ID of the display list that has been around the longest time */123private int eldestDisplayListID;124/** The eldest display list */125private DisplayList eldestDisplayList;126127/** The map fo the display list generated and cached - modified to allow removal of the oldest entry */128private final LinkedHashMap displayLists = new LinkedHashMap(DISPLAY_LIST_CACHE_SIZE, 1, true) {129protected boolean removeEldestEntry (Entry eldest) {130DisplayList displayList = (DisplayList)eldest.getValue();131if (displayList != null) eldestDisplayListID = displayList.id;132return size() > DISPLAY_LIST_CACHE_SIZE;133}134};135136/**137* Create a new unicode font based on a TTF file138*139* @param ttfFileRef The file system or classpath location of the TrueTypeFont file.140* @param hieroFileRef The file system or classpath location of the Hiero settings file.141* @throws SlickException if the UnicodeFont could not be initialized.142*/143public UnicodeFont (String ttfFileRef, String hieroFileRef) throws SlickException {144this(ttfFileRef, new HieroSettings(hieroFileRef));145}146147/**148* Create a new unicode font based on a TTF file and a set of heiro configuration149*150* @param ttfFileRef The file system or classpath location of the TrueTypeFont file.151* @param settings The settings configured via the Hiero tool152* @throws SlickException if the UnicodeFont could not be initialized.153*/154public UnicodeFont (String ttfFileRef, HieroSettings settings) throws SlickException {155this.ttfFileRef = ttfFileRef;156Font font = createFont(ttfFileRef);157initializeFont(font, settings.getFontSize(), settings.isBold(), settings.isItalic());158loadSettings(settings);159}160161/**162* Create a new unicode font based on a TTF file alone163*164* @param ttfFileRef The file system or classpath location of the TrueTypeFont file.165* @param size The point size of the font to generated166* @param bold True if the font should be rendered in bold typeface167* @param italic True if the font should be rendered in bold typeface168* @throws SlickException if the UnicodeFont could not be initialized.169*/170public UnicodeFont (String ttfFileRef, int size, boolean bold, boolean italic) throws SlickException {171this.ttfFileRef = ttfFileRef;172initializeFont(createFont(ttfFileRef), size, bold, italic);173}174175/**176* Creates a new UnicodeFont.177*178* @param font The AWT font to render179* @param hieroFileRef The file system or classpath location of the Hiero settings file.180* @throws SlickException if the UnicodeFont could not be initialized.181*/182public UnicodeFont (Font font, String hieroFileRef) throws SlickException {183this(font, new HieroSettings(hieroFileRef));184}185186/**187* Creates a new UnicodeFont.188*189* @param font The AWT font to render190* @param settings The settings configured via the Hiero tool191*/192public UnicodeFont (Font font, HieroSettings settings) {193initializeFont(font, settings.getFontSize(), settings.isBold(), settings.isItalic());194loadSettings(settings);195}196197/**198* Creates a new UnicodeFont.199*200* @param font The AWT font to render201*/202public UnicodeFont (Font font) {203initializeFont(font, font.getSize(), font.isBold(), font.isItalic());204}205206/**207* Creates a new UnicodeFont.208*209* @param font The AWT font to render210* @param size The point size of the font to generated211* @param bold True if the font should be rendered in bold typeface212* @param italic True if the font should be rendered in bold typeface213*/214public UnicodeFont (Font font, int size, boolean bold, boolean italic) {215initializeFont(font, size, bold, italic);216}217218/**219* Initialise the font to be used based on configuration220*221* @param baseFont The AWT font to render222* @param size The point size of the font to generated223* @param bold True if the font should be rendered in bold typeface224* @param italic True if the font should be rendered in bold typeface225*/226private void initializeFont(Font baseFont, int size, boolean bold, boolean italic) {227Map attributes = baseFont.getAttributes();228attributes.put(TextAttribute.SIZE, new Float(size));229attributes.put(TextAttribute.WEIGHT, bold ? TextAttribute.WEIGHT_BOLD : TextAttribute.WEIGHT_REGULAR);230attributes.put(TextAttribute.POSTURE, italic ? TextAttribute.POSTURE_OBLIQUE : TextAttribute.POSTURE_REGULAR);231try {232attributes.put(TextAttribute.class.getDeclaredField("KERNING").get(null), TextAttribute.class.getDeclaredField(233"KERNING_ON").get(null));234} catch (Exception ignored) {235}236font = baseFont.deriveFont(attributes);237238FontMetrics metrics = GlyphPage.getScratchGraphics().getFontMetrics(font);239ascent = metrics.getAscent();240descent = metrics.getDescent();241leading = metrics.getLeading();242243// Determine width of space glyph (getGlyphPixelBounds gives a width of zero).244char[] chars = " ".toCharArray();245GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);246spaceWidth = vector.getGlyphLogicalBounds(0).getBounds().width;247}248249/**250* Load the hiero setting and configure the unicode font's rendering251*252* @param settings The settings to be applied253*/254private void loadSettings(HieroSettings settings) {255paddingTop = settings.getPaddingTop();256paddingLeft = settings.getPaddingLeft();257paddingBottom = settings.getPaddingBottom();258paddingRight = settings.getPaddingRight();259paddingAdvanceX = settings.getPaddingAdvanceX();260paddingAdvanceY = settings.getPaddingAdvanceY();261glyphPageWidth = settings.getGlyphPageWidth();262glyphPageHeight = settings.getGlyphPageHeight();263effects.addAll(settings.getEffects());264}265266/**267* Queues the glyphs in the specified codepoint range (inclusive) to be loaded. Note that the glyphs are not actually loaded268* until {@link #loadGlyphs()} is called.269*270* Some characters like combining marks and non-spacing marks can only be rendered with the context of other glyphs. In this271* case, use {@link #addGlyphs(String)}.272*273* @param startCodePoint The code point of the first glyph to add274* @param endCodePoint The code point of the last glyph to add275*/276public void addGlyphs(int startCodePoint, int endCodePoint) {277for (int codePoint = startCodePoint; codePoint <= endCodePoint; codePoint++)278addGlyphs(new String(Character.toChars(codePoint)));279}280281/**282* Queues the glyphs in the specified text to be loaded. Note that the glyphs are not actually loaded until283* {@link #loadGlyphs()} is called.284*285* @param text The text containing the glyphs to be added286*/287public void addGlyphs(String text) {288if (text == null) throw new IllegalArgumentException("text cannot be null.");289290char[] chars = text.toCharArray();291GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);292for (int i = 0, n = vector.getNumGlyphs(); i < n; i++) {293int codePoint = text.codePointAt(vector.getGlyphCharIndex(i));294Rectangle bounds = getGlyphBounds(vector, i, codePoint);295getGlyph(vector.getGlyphCode(i), codePoint, bounds, vector, i);296}297}298299/**300* Queues the glyphs in the ASCII character set (codepoints 32 through 255) to be loaded. Note that the glyphs are not actually301* loaded until {@link #loadGlyphs()} is called.302*/303public void addAsciiGlyphs () {304addGlyphs(32, 255);305}306307/**308* Queues the glyphs in the NEHE character set (codepoints 32 through 128) to be loaded. Note that the glyphs are not actually309* loaded until {@link #loadGlyphs()} is called.310*/311public void addNeheGlyphs () {312addGlyphs(32, 32 + 96);313}314315/**316* Loads all queued glyphs to the backing textures. Glyphs that are typically displayed together should be added and loaded at317* the same time so that they are stored on the same backing texture. This reduces the number of backing texture binds required318* to draw glyphs.319*320* @return True if the glyphs were loaded entirely321* @throws SlickException if the glyphs could not be loaded.322*/323public boolean loadGlyphs () throws SlickException {324return loadGlyphs(-1);325}326327/**328* Loads up to the specified number of queued glyphs to the backing textures. This is typically called from the game loop to329* load glyphs on the fly that were requested for display but have not yet been loaded.330*331* @param maxGlyphsToLoad The maximum number of glyphs to be loaded this time332* @return True if the glyphs were loaded entirely333* @throws SlickException if the glyphs could not be loaded.334*/335public boolean loadGlyphs (int maxGlyphsToLoad) throws SlickException {336if (queuedGlyphs.isEmpty()) return false;337338if (effects.isEmpty())339throw new IllegalStateException("The UnicodeFont must have at least one effect before any glyphs can be loaded.");340341for (Iterator iter = queuedGlyphs.iterator(); iter.hasNext();) {342Glyph glyph = (Glyph)iter.next();343int codePoint = glyph.getCodePoint();344345// Don't load an image for a glyph with nothing to display.346if (glyph.getWidth() == 0 || codePoint == ' ') {347iter.remove();348continue;349}350351// Only load the first missing glyph.352if (glyph.isMissing()) {353if (missingGlyph != null) {354if (glyph != missingGlyph) iter.remove();355continue;356}357missingGlyph = glyph;358}359}360361Collections.sort(queuedGlyphs, heightComparator);362363// Add to existing pages.364for (Iterator iter = glyphPages.iterator(); iter.hasNext();) {365GlyphPage glyphPage = (GlyphPage)iter.next();366maxGlyphsToLoad -= glyphPage.loadGlyphs(queuedGlyphs, maxGlyphsToLoad);367if (maxGlyphsToLoad == 0 || queuedGlyphs.isEmpty())368return true;369}370371// Add to new pages.372while (!queuedGlyphs.isEmpty()) {373GlyphPage glyphPage = new GlyphPage(this, glyphPageWidth, glyphPageHeight);374glyphPages.add(glyphPage);375maxGlyphsToLoad -= glyphPage.loadGlyphs(queuedGlyphs, maxGlyphsToLoad);376if (maxGlyphsToLoad == 0) return true;377}378379return true;380}381382/**383* Clears all loaded and queued glyphs.384*/385public void clearGlyphs () {386for (int i = 0; i < PAGES; i++)387glyphs[i] = null;388389for (Iterator iter = glyphPages.iterator(); iter.hasNext();) {390GlyphPage page = (GlyphPage)iter.next();391try {392page.getImage().destroy();393} catch (SlickException ignored) {394}395}396glyphPages.clear();397398if (baseDisplayListID != -1) {399GL.glDeleteLists(baseDisplayListID, displayLists.size());400baseDisplayListID = -1;401}402403queuedGlyphs.clear();404missingGlyph = null;405}406407/**408* Releases all resources used by this UnicodeFont. This method should be called when this UnicodeFont instance is no longer409* needed.410*/411public void destroy () {412// The destroy() method is just to provide a consistent API for releasing resources.413clearGlyphs();414}415416/**417* Identical to {@link #drawString(float, float, String, Color, int, int)} but returns a418* DisplayList which provides access to the width and height of the text drawn.419*420* @param text The text to render421* @param x The horizontal location to render at422* @param y The vertical location to render at423* @param color The colour to apply as a filter on the text424* @param startIndex The start index into the string to start rendering at425* @param endIndex The end index into the string to render to426* @return The reference to the display list that was drawn and potentiall ygenerated427*/428public DisplayList drawDisplayList (float x, float y, String text, Color color, int startIndex, int endIndex) {429if (text == null) throw new IllegalArgumentException("text cannot be null.");430if (text.length() == 0) return EMPTY_DISPLAY_LIST;431if (color == null) throw new IllegalArgumentException("color cannot be null.");432433x -= paddingLeft;434y -= paddingTop;435436String displayListKey = text.substring(startIndex, endIndex);437438color.bind();439TextureImpl.bindNone();440441DisplayList displayList = null;442if (displayListCaching && queuedGlyphs.isEmpty()) {443if (baseDisplayListID == -1) {444baseDisplayListID = GL.glGenLists(DISPLAY_LIST_CACHE_SIZE);445if (baseDisplayListID == 0) {446baseDisplayListID = -1;447displayListCaching = false;448return new DisplayList();449}450}451// Try to use a display list compiled for this text.452displayList = (DisplayList)displayLists.get(displayListKey);453if (displayList != null) {454if (displayList.invalid)455displayList.invalid = false;456else {457GL.glTranslatef(x, y, 0);458GL.glCallList(displayList.id);459GL.glTranslatef(-x, -y, 0);460return displayList;461}462} else if (displayList == null) {463// Compile a new display list.464displayList = new DisplayList();465int displayListCount = displayLists.size();466displayLists.put(displayListKey, displayList);467if (displayListCount < DISPLAY_LIST_CACHE_SIZE)468displayList.id = baseDisplayListID + displayListCount;469else470displayList.id = eldestDisplayListID;471}472displayLists.put(displayListKey, displayList);473}474475GL.glTranslatef(x, y, 0);476477if (displayList != null) GL.glNewList(displayList.id, SGL.GL_COMPILE_AND_EXECUTE);478479char[] chars = text.substring(0, endIndex).toCharArray();480GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);481482int maxWidth = 0, totalHeight = 0, lines = 0;483int extraX = 0, extraY = ascent;484boolean startNewLine = false;485Texture lastBind = null;486for (int glyphIndex = 0, n = vector.getNumGlyphs(); glyphIndex < n; glyphIndex++) {487int charIndex = vector.getGlyphCharIndex(glyphIndex);488if (charIndex < startIndex) continue;489if (charIndex > endIndex) break;490491int codePoint = text.codePointAt(charIndex);492493Rectangle bounds = getGlyphBounds(vector, glyphIndex, codePoint);494Glyph glyph = getGlyph(vector.getGlyphCode(glyphIndex), codePoint, bounds, vector, glyphIndex);495496if (startNewLine && codePoint != '\n') {497extraX = -bounds.x;498startNewLine = false;499}500501Image image = glyph.getImage();502if (image == null && missingGlyph != null && glyph.isMissing()) image = missingGlyph.getImage();503if (image != null) {504// Draw glyph, only binding a new glyph page texture when necessary.505Texture texture = image.getTexture();506if (lastBind != null && lastBind != texture) {507GL.glEnd();508lastBind = null;509}510if (lastBind == null) {511texture.bind();512GL.glBegin(SGL.GL_QUADS);513lastBind = texture;514}515image.drawEmbedded(bounds.x + extraX, bounds.y + extraY, image.getWidth(), image.getHeight());516}517518if (glyphIndex > 0) extraX += paddingRight + paddingLeft + paddingAdvanceX;519maxWidth = Math.max(maxWidth, bounds.x + extraX + bounds.width);520totalHeight = Math.max(totalHeight, ascent + bounds.y + bounds.height);521522if (codePoint == '\n') {523startNewLine = true; // Mac gives -1 for bounds.x of '\n', so use the bounds.x of the next glyph.524extraY += getLineHeight();525lines++;526totalHeight = 0;527}528}529if (lastBind != null) GL.glEnd();530531if (displayList != null) {532GL.glEndList();533// Invalidate the display list if it had glyphs that need to be loaded.534if (!queuedGlyphs.isEmpty()) displayList.invalid = true;535}536537GL.glTranslatef(-x, -y, 0);538539if (displayList == null) displayList = new DisplayList();540displayList.width = (short)maxWidth;541displayList.height = (short)(lines * getLineHeight() + totalHeight);542return displayList;543}544545public void drawString (float x, float y, String text, Color color, int startIndex, int endIndex) {546drawDisplayList(x, y, text, color, startIndex, endIndex);547}548549public void drawString (float x, float y, String text) {550drawString(x, y, text, Color.white);551}552553public void drawString (float x, float y, String text, Color col) {554drawString(x, y, text, col, 0, text.length());555}556557/**558* Returns the glyph for the specified codePoint. If the glyph does not exist yet,559* it is created and queued to be loaded.560*561* @param glyphCode The code of the glyph to locate562* @param codePoint The code point associated with the glyph563* @param bounds The bounds of the glyph on the page564* @param vector The vector the glyph is part of565* @param index The index of the glyph within the vector566* @return The glyph requested567*/568private Glyph getGlyph (int glyphCode, int codePoint, Rectangle bounds, GlyphVector vector, int index) {569if (glyphCode < 0 || glyphCode >= MAX_GLYPH_CODE) {570// GlyphVector#getGlyphCode sometimes returns negative numbers on OS X.571return new Glyph(codePoint, bounds, vector, index, this) {572public boolean isMissing () {573return true;574}575};576}577int pageIndex = glyphCode / PAGE_SIZE;578int glyphIndex = glyphCode & (PAGE_SIZE - 1);579Glyph glyph = null;580Glyph[] page = glyphs[pageIndex];581if (page != null) {582glyph = page[glyphIndex];583if (glyph != null) return glyph;584} else585page = glyphs[pageIndex] = new Glyph[PAGE_SIZE];586// Add glyph so size information is available and queue it so its image can be loaded later.587glyph = page[glyphIndex] = new Glyph(codePoint, bounds, vector, index, this);588queuedGlyphs.add(glyph);589return glyph;590}591592/**593* Returns the bounds of the specified glyph.\594*595* @param vector The vector the glyph is part of596* @param index The index of the glyph within the vector597* @param codePoint The code point associated with the glyph598*/599private Rectangle getGlyphBounds (GlyphVector vector, int index, int codePoint) {600Rectangle bounds = vector.getGlyphPixelBounds(index, GlyphPage.renderContext, 0, 0);601if (codePoint == ' ') bounds.width = spaceWidth;602return bounds;603}604605/**606* Returns the width of the space character.607*/608public int getSpaceWidth () {609return spaceWidth;610}611612/**613* @see org.newdawn.slick.Font#getWidth(java.lang.String)614*/615public int getWidth (String text) {616if (text == null) throw new IllegalArgumentException("text cannot be null.");617if (text.length() == 0) return 0;618619if (displayListCaching) {620DisplayList displayList = (DisplayList)displayLists.get(text);621if (displayList != null) return displayList.width;622}623624char[] chars = text.toCharArray();625GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);626627int width = 0;628int extraX = 0;629boolean startNewLine = false;630for (int glyphIndex = 0, n = vector.getNumGlyphs(); glyphIndex < n; glyphIndex++) {631int charIndex = vector.getGlyphCharIndex(glyphIndex);632int codePoint = text.codePointAt(charIndex);633Rectangle bounds = getGlyphBounds(vector, glyphIndex, codePoint);634635if (startNewLine && codePoint != '\n') extraX = -bounds.x;636637if (glyphIndex > 0) extraX += paddingLeft + paddingRight + paddingAdvanceX;638width = Math.max(width, bounds.x + extraX + bounds.width);639640if (codePoint == '\n') startNewLine = true;641}642643return width;644}645646/**647* @see org.newdawn.slick.Font#getHeight(java.lang.String)648*/649public int getHeight (String text) {650if (text == null) throw new IllegalArgumentException("text cannot be null.");651if (text.length() == 0) return 0;652653if (displayListCaching) {654DisplayList displayList = (DisplayList)displayLists.get(text);655if (displayList != null) return displayList.height;656}657658char[] chars = text.toCharArray();659GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);660661int lines = 0, height = 0;662for (int i = 0, n = vector.getNumGlyphs(); i < n; i++) {663int charIndex = vector.getGlyphCharIndex(i);664int codePoint = text.codePointAt(charIndex);665if (codePoint == ' ') continue;666Rectangle bounds = getGlyphBounds(vector, i, codePoint);667668height = Math.max(height, ascent + bounds.y + bounds.height);669670if (codePoint == '\n') {671lines++;672height = 0;673}674}675return lines * getLineHeight() + height;676}677678/**679* Returns the distance from the y drawing location to the top most pixel of the680* specified text.681*682* @param text The text to analyse683* @return The distance fro the y drawing location ot the top most pixel of the specified text684*/685public int getYOffset (String text) {686if (text == null) throw new IllegalArgumentException("text cannot be null.");687688DisplayList displayList = null;689if (displayListCaching) {690displayList = (DisplayList)displayLists.get(text);691if (displayList != null && displayList.yOffset != null) return displayList.yOffset.intValue();692}693694int index = text.indexOf('\n');695if (index != -1) text = text.substring(0, index);696char[] chars = text.toCharArray();697GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);698int yOffset = ascent + vector.getPixelBounds(null, 0, 0).y;699700if (displayList != null) displayList.yOffset = new Short((short)yOffset);701702return yOffset;703}704705/**706* Returns the TrueTypeFont for this UnicodeFont.707*708* @return The AWT Font being rendered709*/710public Font getFont() {711return font;712}713714/**715* Returns the padding above a glyph on the GlyphPage to allow for effects to be drawn.716*717* @return The padding at the top of the glyphs when drawn718*/719public int getPaddingTop() {720return paddingTop;721}722723/**724* Sets the padding above a glyph on the GlyphPage to allow for effects to be drawn.725*726* @param paddingTop The padding at the top of the glyphs when drawn727*/728public void setPaddingTop(int paddingTop) {729this.paddingTop = paddingTop;730}731732/**733* Returns the padding to the left of a glyph on the GlyphPage to allow for effects to be drawn.734*735* @return The padding at the left of the glyphs when drawn736*/737public int getPaddingLeft() {738return paddingLeft;739}740741/**742* Sets the padding to the left of a glyph on the GlyphPage to allow for effects to be drawn.743*744* @param paddingLeft The padding at the left of the glyphs when drawn745*/746public void setPaddingLeft(int paddingLeft) {747this.paddingLeft = paddingLeft;748}749750/**751* Returns the padding below a glyph on the GlyphPage to allow for effects to be drawn.752*753* @return The padding at the bottom of the glyphs when drawn754*/755public int getPaddingBottom() {756return paddingBottom;757}758759/**760* Sets the padding below a glyph on the GlyphPage to allow for effects to be drawn.761*762* @param paddingBottom The padding at the bottom of the glyphs when drawn763*/764public void setPaddingBottom(int paddingBottom) {765this.paddingBottom = paddingBottom;766}767768/**769* Returns the padding to the right of a glyph on the GlyphPage to allow for effects to be drawn.770*771* @return The padding at the right of the glyphs when drawn772*/773public int getPaddingRight () {774return paddingRight;775}776777/**778* Sets the padding to the right of a glyph on the GlyphPage to allow for effects to be drawn.779*780* @param paddingRight The padding at the right of the glyphs when drawn781*/782public void setPaddingRight (int paddingRight) {783this.paddingRight = paddingRight;784}785786/**787* Gets the additional amount to offset glyphs on the x axis.788*789* @return The padding applied for each horizontal advance (i.e. when a glyph is rendered)790*/791public int getPaddingAdvanceX() {792return paddingAdvanceX;793}794795/**796* Sets the additional amount to offset glyphs on the x axis. This is typically set to a negative number when left or right797* padding is used so that glyphs are not spaced too far apart.798*799* @param paddingAdvanceX The padding applied for each horizontal advance (i.e. when a glyph is rendered)800*/801public void setPaddingAdvanceX (int paddingAdvanceX) {802this.paddingAdvanceX = paddingAdvanceX;803}804805/**806* Gets the additional amount to offset a line of text on the y axis.807*808* @return The padding applied for each vertical advance (i.e. when a glyph is rendered)809*/810public int getPaddingAdvanceY () {811return paddingAdvanceY;812}813814/**815* Sets the additional amount to offset a line of text on the y axis. This is typically set to a negative number when top or816* bottom padding is used so that lines of text are not spaced too far apart.817*818* @param paddingAdvanceY The padding applied for each vertical advance (i.e. when a glyph is rendered)819*/820public void setPaddingAdvanceY (int paddingAdvanceY) {821this.paddingAdvanceY = paddingAdvanceY;822}823824/**825* Returns the distance from one line of text to the next. This is the sum of the descent, ascent, leading, padding top,826* padding bottom, and padding advance y. To change the line height, use {@link #setPaddingAdvanceY(int)}.827*/828public int getLineHeight() {829return descent + ascent + leading + paddingTop + paddingBottom + paddingAdvanceY;830}831832/**833* Gets the distance from the baseline to the y drawing location.834*835* @return The ascent of this font836*/837public int getAscent() {838return ascent;839}840841/**842* Gets the distance from the baseline to the bottom of most alphanumeric characters843* with descenders.844*845* @return The distance from the baseline to the bottom of the font846*/847public int getDescent () {848return descent;849}850851/**852* Gets the extra distance between the descent of one line of text to the ascent of the next.853*854* @return The leading edge of the font855*/856public int getLeading () {857return leading;858}859860/**861* Returns the width of the backing textures.862*863* @return The width of the glyph pages in this font864*/865public int getGlyphPageWidth () {866return glyphPageWidth;867}868869/**870* Sets the width of the backing textures. Default is 512.871*872* @param glyphPageWidth The width of the glyph pages in this font873*/874public void setGlyphPageWidth(int glyphPageWidth) {875this.glyphPageWidth = glyphPageWidth;876}877878/**879* Returns the height of the backing textures.880*881* @return The height of the glyph pages in this font882*/883public int getGlyphPageHeight() {884return glyphPageHeight;885}886887/**888* Sets the height of the backing textures. Default is 512.889*890* @param glyphPageHeight The width of the glyph pages in this font891*/892public void setGlyphPageHeight(int glyphPageHeight) {893this.glyphPageHeight = glyphPageHeight;894}895896/**897* Returns the GlyphPages for this UnicodeFont.898*899* @return The glyph pages that have been loaded into this font900*/901public List getGlyphPages () {902return glyphPages;903}904905/**906* Returns a list of {@link org.newdawn.slick.font.effects.Effect}s that will be applied907* to the glyphs.908*909* @return The list of effects to be applied to the font910*/911public List getEffects () {912return effects;913}914915/**916* Returns true if this UnicodeFont caches the glyph drawing instructions to917* improve performance.918*919* @return True if caching is turned on920*/921public boolean isCaching () {922return displayListCaching;923}924925/**926* Sets if this UnicodeFont caches the glyph drawing instructions to improve performance.927* Default is true. Text rendering is very slow without display list caching.928*929* @param displayListCaching True if caching should be turned on930*/931public void setDisplayListCaching (boolean displayListCaching) {932this.displayListCaching = displayListCaching;933}934935/**936* Returns the path to the TTF file for this UnicodeFont, or null. If this UnicodeFont was created without specifying the TTF937* file, it will try to determine the path using Sun classes. If this fails, null is returned.938*939* @return The reference to the font file that the kerning was loaded from940*/941public String getFontFile () {942if (ttfFileRef == null) {943// Worst case if this UnicodeFont was loaded without a ttfFileRef, try to get the font file from Sun's classes.944try {945Object font2D = Class.forName("sun.font.FontManager").getDeclaredMethod("getFont2D", new Class[] {Font.class})946.invoke(null, new Object[] {font});947Field platNameField = Class.forName("sun.font.PhysicalFont").getDeclaredField("platName");948platNameField.setAccessible(true);949ttfFileRef = (String)platNameField.get(font2D);950} catch (Throwable ignored) {951}952if (ttfFileRef == null) ttfFileRef = "";953}954if (ttfFileRef.length() == 0) return null;955return ttfFileRef;956}957958/**959* A simple descriptor for display lists cached within this font960*/961public static class DisplayList {962/** True if this display list has been invalidated */963boolean invalid;964/** The ID of the display list this descriptor represents */965int id;966/** The vertical offset to the top of this display list */967Short yOffset;968969/** The width of rendered text in the list */970public short width;971/** The height of the rendered text in the list */972public short height;973/** Application data stored in the list */974public Object userData;975976DisplayList () {977}978}979}980981982