idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
38,200
public void fill ( Space target , float sx , float sy , float cost ) { if ( cost >= this . cost ) { return ; } this . cost = cost ; if ( target == this ) { return ; } for ( int i = 0 ; i < getLinkCount ( ) ; i ++ ) { Link link = getLink ( i ) ; float extraCost = link . distance2 ( sx , sy ) ; float nextCost = cost + extraCost ; link . getTarget ( ) . fill ( target , link . getX ( ) , link . getY ( ) , nextCost ) ; } }
Fill the spaces based on the cost from a given starting point
38,201
public boolean pickLowestCost ( Space target , NavPath path ) { if ( target == this ) { return true ; } if ( links . size ( ) == 0 ) { return false ; } Link bestLink = null ; for ( int i = 0 ; i < getLinkCount ( ) ; i ++ ) { Link link = getLink ( i ) ; if ( ( bestLink == null ) || ( link . getTarget ( ) . getCost ( ) < bestLink . getTarget ( ) . getCost ( ) ) ) { bestLink = link ; } } path . push ( bestLink ) ; return bestLink . getTarget ( ) . pickLowestCost ( target , path ) ; }
Pick the lowest cost route from this space to another on the path
38,202
public void addFrame ( int duration , int x , int y ) { if ( duration == 0 ) { Log . error ( "Invalid duration: " + duration ) ; throw new RuntimeException ( "Invalid duration: " + duration ) ; } if ( frames . isEmpty ( ) ) { nextChange = ( int ) ( duration / speed ) ; } frames . add ( new Frame ( duration , x , y ) ) ; currentFrame = 0 ; }
Add animation frame to the animation .
38,203
public void restart ( ) { if ( frames . size ( ) == 0 ) { return ; } stopped = false ; currentFrame = 0 ; nextChange = ( int ) ( ( ( Frame ) frames . get ( 0 ) ) . duration / speed ) ; firstUpdate = true ; lastUpdate = 0 ; }
Restart the animation from the beginning
38,204
public void addFrame ( Image frame , int duration ) { if ( duration == 0 ) { Log . error ( "Invalid duration: " + duration ) ; throw new RuntimeException ( "Invalid duration: " + duration ) ; } if ( frames . isEmpty ( ) ) { nextChange = ( int ) ( duration / speed ) ; } frames . add ( new Frame ( frame , duration ) ) ; currentFrame = 0 ; }
Add animation frame to the animation
38,205
public void draw ( float x , float y , Color filter ) { draw ( x , y , getWidth ( ) , getHeight ( ) , filter ) ; }
Draw the animation at a specific location
38,206
public void renderInUse ( int x , int y ) { if ( frames . size ( ) == 0 ) { return ; } if ( autoUpdate ) { long now = getTime ( ) ; long delta = now - lastUpdate ; if ( firstUpdate ) { delta = 0 ; firstUpdate = false ; } lastUpdate = now ; nextFrame ( delta ) ; } Frame frame = ( Frame ) frames . get ( currentFrame ) ; spriteSheet . renderInUse ( x , y , frame . x , frame . y ) ; }
Render the appropriate frame when the spriteSheet backing this Animation is in use .
38,207
public void drawFlash ( float x , float y , float width , float height , Color col ) { if ( frames . size ( ) == 0 ) { return ; } if ( autoUpdate ) { long now = getTime ( ) ; long delta = now - lastUpdate ; if ( firstUpdate ) { delta = 0 ; firstUpdate = false ; } lastUpdate = now ; nextFrame ( delta ) ; } Frame frame = ( Frame ) frames . get ( currentFrame ) ; frame . image . drawFlash ( x , y , width , height , col ) ; }
Draw the animation
38,208
public void updateNoDraw ( ) { if ( autoUpdate ) { long now = getTime ( ) ; long delta = now - lastUpdate ; if ( firstUpdate ) { delta = 0 ; firstUpdate = false ; } lastUpdate = now ; nextFrame ( delta ) ; } }
Update the animation cycle without draw the image useful for keeping two animations in sync
38,209
public Image getImage ( int index ) { Frame frame = ( Frame ) frames . get ( index ) ; return frame . image ; }
Get the image assocaited with a given frame index
38,210
public Image getCurrentFrame ( ) { Frame frame = ( Frame ) frames . get ( currentFrame ) ; return frame . image ; }
Get the image associated with the current animation frame
38,211
private void nextFrame ( long delta ) { if ( stopped ) { return ; } if ( frames . size ( ) == 0 ) { return ; } nextChange -= delta ; while ( nextChange < 0 && ( ! stopped ) ) { if ( currentFrame == stopAt ) { stopped = true ; break ; } if ( ( currentFrame == frames . size ( ) - 1 ) && ( ! loop ) && ( ! pingPong ) ) { stopped = true ; break ; } currentFrame = ( currentFrame + direction ) % frames . size ( ) ; if ( pingPong ) { if ( currentFrame <= 0 ) { currentFrame = 0 ; direction = 1 ; if ( ! loop ) { stopped = true ; break ; } } else if ( currentFrame >= frames . size ( ) - 1 ) { currentFrame = frames . size ( ) - 1 ; direction = - 1 ; } } int realDuration = ( int ) ( ( ( Frame ) frames . get ( currentFrame ) ) . duration / speed ) ; nextChange = nextChange + realDuration ; } }
Check if we need to move to the next frame
38,212
public int [ ] getDurations ( ) { int [ ] durations = new int [ frames . size ( ) ] ; for ( int i = 0 ; i < frames . size ( ) ; i ++ ) { durations [ i ] = getDuration ( i ) ; } return durations ; }
Get the durations of all the frames in this animation
38,213
public Animation copy ( ) { Animation copy = new Animation ( ) ; copy . spriteSheet = spriteSheet ; copy . frames = frames ; copy . autoUpdate = autoUpdate ; copy . direction = direction ; copy . loop = loop ; copy . pingPong = pingPong ; copy . speed = speed ; return copy ; }
Create a copy of this animation . Note that the frames are not duplicated but shared with the original
38,214
public Format decideTextureFormat ( Format fmt ) { switch ( colorType ) { case COLOR_TRUECOLOR : if ( ( fmt == ABGR ) || ( fmt == RGBA ) || ( fmt == BGRA ) || ( fmt == RGB ) ) { return fmt ; } return RGB ; case COLOR_TRUEALPHA : if ( ( fmt == ABGR ) || ( fmt == RGBA ) || ( fmt == BGRA ) || ( fmt == RGB ) ) { return fmt ; } return RGBA ; case COLOR_GREYSCALE : if ( ( fmt == LUMINANCE ) || ( fmt == ALPHA ) ) { return fmt ; } return LUMINANCE ; case COLOR_GREYALPHA : return LUMINANCE_ALPHA ; case COLOR_INDEXED : if ( ( fmt == ABGR ) || ( fmt == RGBA ) || ( fmt == BGRA ) ) { return fmt ; } return RGBA ; default : throw new UnsupportedOperationException ( "Not yet implemented" ) ; } }
Computes the implemented format conversion for the desired format .
38,215
private void destroyLWJGL ( ) { container . stopApplet ( ) ; try { gameThread . join ( ) ; } catch ( InterruptedException e ) { Log . error ( e ) ; } }
Clean up the LWJGL resources
38,216
public void startLWJGL ( ) { if ( gameThread != null ) { return ; } gameThread = new Thread ( ) { public void run ( ) { try { canvas . start ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; if ( Display . isCreated ( ) ) { Display . destroy ( ) ; } displayParent . setVisible ( false ) ; add ( new ConsolePanel ( e ) ) ; validate ( ) ; } } } ; gameThread . start ( ) ; }
Start a thread to run LWJGL in
38,217
public Shape [ ] subtract ( Shape target , Shape missing ) { target = target . transform ( new Transform ( ) ) ; missing = missing . transform ( new Transform ( ) ) ; int count = 0 ; for ( int i = 0 ; i < target . getPointCount ( ) ; i ++ ) { if ( missing . contains ( target . getPoint ( i ) [ 0 ] , target . getPoint ( i ) [ 1 ] ) ) { count ++ ; } } if ( count == target . getPointCount ( ) ) { return new Shape [ 0 ] ; } if ( ! target . intersects ( missing ) ) { return new Shape [ ] { target } ; } int found = 0 ; for ( int i = 0 ; i < missing . getPointCount ( ) ; i ++ ) { if ( target . contains ( missing . getPoint ( i ) [ 0 ] , missing . getPoint ( i ) [ 1 ] ) ) { if ( ! onPath ( target , missing . getPoint ( i ) [ 0 ] , missing . getPoint ( i ) [ 1 ] ) ) { found ++ ; } } } for ( int i = 0 ; i < target . getPointCount ( ) ; i ++ ) { if ( missing . contains ( target . getPoint ( i ) [ 0 ] , target . getPoint ( i ) [ 1 ] ) ) { if ( ! onPath ( missing , target . getPoint ( i ) [ 0 ] , target . getPoint ( i ) [ 1 ] ) ) { found ++ ; } } } if ( found < 1 ) { return new Shape [ ] { target } ; } return combine ( target , missing , true ) ; }
Subtract one shape from another - note this is experimental and doesn t currently handle islands
38,218
private boolean onPath ( Shape path , float x , float y ) { for ( int i = 0 ; i < path . getPointCount ( ) + 1 ; i ++ ) { int n = rationalPoint ( path , i + 1 ) ; Line line = getLine ( path , rationalPoint ( path , i ) , n ) ; if ( line . distance ( new Vector2f ( x , y ) ) < EPSILON * 100 ) { return true ; } } return false ; }
Check if the given point is on the path
38,219
public Shape [ ] union ( Shape target , Shape other ) { target = target . transform ( new Transform ( ) ) ; other = other . transform ( new Transform ( ) ) ; if ( ! target . intersects ( other ) ) { return new Shape [ ] { target , other } ; } boolean touches = false ; int buttCount = 0 ; for ( int i = 0 ; i < target . getPointCount ( ) ; i ++ ) { if ( other . contains ( target . getPoint ( i ) [ 0 ] , target . getPoint ( i ) [ 1 ] ) ) { if ( ! other . hasVertex ( target . getPoint ( i ) [ 0 ] , target . getPoint ( i ) [ 1 ] ) ) { touches = true ; break ; } } if ( other . hasVertex ( target . getPoint ( i ) [ 0 ] , target . getPoint ( i ) [ 1 ] ) ) { buttCount ++ ; } } for ( int i = 0 ; i < other . getPointCount ( ) ; i ++ ) { if ( target . contains ( other . getPoint ( i ) [ 0 ] , other . getPoint ( i ) [ 1 ] ) ) { if ( ! target . hasVertex ( other . getPoint ( i ) [ 0 ] , other . getPoint ( i ) [ 1 ] ) ) { touches = true ; break ; } } } if ( ( ! touches ) && ( buttCount < 2 ) ) { return new Shape [ ] { target , other } ; } return combine ( target , other , false ) ; }
Join to shapes together . Note that the shapes must be touching for this method to work .
38,220
private Shape [ ] combine ( Shape target , Shape other , boolean subtract ) { if ( subtract ) { ArrayList shapes = new ArrayList ( ) ; ArrayList used = new ArrayList ( ) ; for ( int i = 0 ; i < target . getPointCount ( ) ; i ++ ) { float [ ] point = target . getPoint ( i ) ; if ( other . contains ( point [ 0 ] , point [ 1 ] ) ) { used . add ( new Vector2f ( point [ 0 ] , point [ 1 ] ) ) ; if ( listener != null ) { listener . pointExcluded ( point [ 0 ] , point [ 1 ] ) ; } } } for ( int i = 0 ; i < target . getPointCount ( ) ; i ++ ) { float [ ] point = target . getPoint ( i ) ; Vector2f pt = new Vector2f ( point [ 0 ] , point [ 1 ] ) ; if ( ! used . contains ( pt ) ) { Shape result = combineSingle ( target , other , true , i ) ; shapes . add ( result ) ; for ( int j = 0 ; j < result . getPointCount ( ) ; j ++ ) { float [ ] kpoint = result . getPoint ( j ) ; Vector2f kpt = new Vector2f ( kpoint [ 0 ] , kpoint [ 1 ] ) ; used . add ( kpt ) ; } } } return ( Shape [ ] ) shapes . toArray ( new Shape [ 0 ] ) ; } else { for ( int i = 0 ; i < target . getPointCount ( ) ; i ++ ) { if ( ! other . contains ( target . getPoint ( i ) [ 0 ] , target . getPoint ( i ) [ 1 ] ) ) { if ( ! other . hasVertex ( target . getPoint ( i ) [ 0 ] , target . getPoint ( i ) [ 1 ] ) ) { Shape shape = combineSingle ( target , other , false , i ) ; return new Shape [ ] { shape } ; } } } return new Shape [ ] { other } ; } }
Perform the combination
38,221
public HitResult intersect ( Shape shape , Line line ) { float distance = Float . MAX_VALUE ; HitResult hit = null ; for ( int i = 0 ; i < shape . getPointCount ( ) ; i ++ ) { int next = rationalPoint ( shape , i + 1 ) ; Line local = getLine ( shape , i , next ) ; Vector2f pt = line . intersect ( local , true ) ; if ( pt != null ) { float newDis = pt . distance ( line . getStart ( ) ) ; if ( ( newDis < distance ) && ( newDis > EPSILON ) ) { hit = new HitResult ( ) ; hit . pt = pt ; hit . line = local ; hit . p1 = i ; hit . p2 = next ; distance = newDis ; } } } return hit ; }
Intersect a line with a shape
38,222
public static int rationalPoint ( Shape shape , int p ) { while ( p < 0 ) { p += shape . getPointCount ( ) ; } while ( p >= shape . getPointCount ( ) ) { p -= shape . getPointCount ( ) ; } return p ; }
Rationalise a point in terms of a given shape
38,223
public static void poll ( int delta ) { if ( currentMusic != null ) { SoundStore . get ( ) . poll ( delta ) ; if ( ! SoundStore . get ( ) . isMusicPlaying ( ) ) { if ( ! currentMusic . positioning ) { Music oldMusic = currentMusic ; currentMusic = null ; oldMusic . fireMusicEnded ( ) ; } } else { currentMusic . update ( delta ) ; } } }
Poll the state of the current music . This causes streaming music to stream and checks listeners . Note that if you re using a game container this will be auto - magically called for you .
38,224
private void fireMusicEnded ( ) { playing = false ; for ( int i = 0 ; i < listeners . size ( ) ; i ++ ) { ( ( MusicListener ) listeners . get ( i ) ) . musicEnded ( this ) ; } }
Fire notifications that this music ended
38,225
private void fireMusicSwapped ( Music newMusic ) { playing = false ; for ( int i = 0 ; i < listeners . size ( ) ; i ++ ) { ( ( MusicListener ) listeners . get ( i ) ) . musicSwapped ( this , newMusic ) ; } }
Fire notifications that this music was swapped out
38,226
private void startMusic ( float pitch , float volume , boolean loop ) { if ( currentMusic != null ) { currentMusic . stop ( ) ; currentMusic . fireMusicSwapped ( this ) ; } currentMusic = this ; if ( volume < 0.0f ) volume = 0.0f ; if ( volume > 1.0f ) volume = 1.0f ; sound . playAsMusic ( pitch , volume , loop ) ; playing = true ; setVolume ( volume ) ; if ( requiredPosition != - 1 ) { setPosition ( requiredPosition ) ; } }
play or loop the music at a given pitch and volume
38,227
public void setVolume ( float volume ) { if ( volume > 1 ) { volume = 1 ; } else if ( volume < 0 ) { volume = 0 ; } this . volume = volume ; if ( currentMusic == this ) { SoundStore . get ( ) . setCurrentMusicVolume ( volume ) ; } }
Set the volume of the music as a factor of the global volume setting
38,228
public void fade ( int duration , float endVolume , boolean stopAfterFade ) { this . stopAfterFade = stopAfterFade ; fadeStartGain = volume ; fadeEndGain = endVolume ; fadeDuration = duration ; fadeTime = duration ; }
Fade this music to the volume specified
38,229
void update ( int delta ) { if ( ! playing ) { return ; } if ( fadeTime > 0 ) { fadeTime -= delta ; if ( fadeTime <= 0 ) { fadeTime = 0 ; if ( stopAfterFade ) { stop ( ) ; return ; } } float offset = ( fadeEndGain - fadeStartGain ) * ( 1 - ( fadeTime / ( float ) fadeDuration ) ) ; setVolume ( fadeStartGain + offset ) ; } }
Update the current music applying any effects that need to updated per tick .
38,230
public boolean setPosition ( float position ) { if ( playing ) { requiredPosition = - 1 ; positioning = true ; playing = false ; boolean result = sound . setPosition ( position ) ; playing = true ; positioning = false ; return result ; } else { requiredPosition = position ; return false ; } }
Seeks to a position in the music . For streaming music seeking before the current position causes the stream to be reloaded .
38,231
public static void main ( String [ ] argv ) throws IOException { File dir = new File ( "." ) ; dir = new File ( "C:\\eclipse\\grobot-workspace\\anon\\res\\tiles\\indoor1" ) ; ArrayList list = new ArrayList ( ) ; File [ ] files = dir . listFiles ( ) ; for ( int i = 0 ; i < files . length ; i ++ ) { if ( files [ i ] . getName ( ) . endsWith ( ".png" ) ) { if ( ! files [ i ] . getName ( ) . startsWith ( "output" ) ) { list . add ( files [ i ] ) ; } } } Pack packer = new Pack ( ) ; packer . pack ( list , 512 , 512 , 1 , new File ( dir , "output.png" ) ) ; System . out . println ( "Output Generated." ) ; }
Entry point to the tool just pack the current directory of images
38,232
public boolean contains ( int xp , int yp ) { if ( xp < x ) { return false ; } if ( yp < y ) { return false ; } if ( xp >= x + width ) { return false ; } if ( yp >= y + height ) { return false ; } return true ; }
Check if this sprite location contains the given x y position
38,233
public void addEmitter ( ConfigurableEmitter emitter ) { emitters . add ( emitter ) ; if ( system == null ) { waiting . add ( emitter ) ; } else { system . addEmitter ( emitter ) ; } }
Add an emitter to the particle system held here
38,234
public void clearSystem ( boolean additive ) { system = new ParticleSystem ( "org/newdawn/slick/data/particle.tga" , 2000 ) ; if ( additive ) { system . setBlendingMode ( ParticleSystem . BLEND_ADDITIVE ) ; } system . setRemoveCompletedEmitters ( false ) ; }
Clear the particle system held in this canvas
38,235
public void setSystem ( ParticleSystem system ) { this . system = system ; emitters . clear ( ) ; system . setRemoveCompletedEmitters ( false ) ; for ( int i = 0 ; i < system . getEmitterCount ( ) ; i ++ ) { emitters . add ( system . getEmitter ( i ) ) ; } }
Set the particle system to be displayed
38,236
public CharSet copy ( ) { CharSet copy = new CharSet ( ) ; copy . name = name ; copy . source = source ; copy . mutable = true ; copy . chars = new boolean [ 256 ] ; System . arraycopy ( chars , 0 , copy . chars , 0 , chars . length ) ; return copy ; }
Copy this character set
38,237
public void save ( File file ) throws IOException { DataOutputStream dout = new DataOutputStream ( new FileOutputStream ( file ) ) ; dout . writeUTF ( name ) ; for ( int i = 0 ; i < 256 ; i ++ ) { dout . writeBoolean ( chars [ i ] ) ; } dout . close ( ) ; }
Save the set to a file
38,238
public void lineTo ( float x , float y ) { if ( hole != null ) { hole . add ( new float [ ] { x , y } ) ; } else { localPoints . add ( new float [ ] { x , y } ) ; } cx = x ; cy = y ; pointsDirty = true ; }
Add a line to the contour or hole which ends at the specified location .
38,239
private ArrayList transform ( ArrayList pts , Transform t ) { float [ ] in = new float [ pts . size ( ) * 2 ] ; float [ ] out = new float [ pts . size ( ) * 2 ] ; for ( int i = 0 ; i < pts . size ( ) ; i ++ ) { in [ i * 2 ] = ( ( float [ ] ) pts . get ( i ) ) [ 0 ] ; in [ ( i * 2 ) + 1 ] = ( ( float [ ] ) pts . get ( i ) ) [ 1 ] ; } t . transform ( in , 0 , out , 0 , pts . size ( ) ) ; ArrayList outList = new ArrayList ( ) ; for ( int i = 0 ; i < pts . size ( ) ; i ++ ) { outList . add ( new float [ ] { out [ ( i * 2 ) ] , out [ ( i * 2 ) + 1 ] } ) ; } return outList ; }
Transform a list of points
38,240
private String morphColor ( String str ) { if ( str . equals ( "" ) ) { return "#000000" ; } if ( str . equals ( "white" ) ) { return "#ffffff" ; } if ( str . equals ( "black" ) ) { return "#000000" ; } return str ; }
Morph the color from a string
38,241
public void addAttribute ( String attribute , String value ) { if ( value == null ) { value = "" ; } if ( attribute . equals ( FILL ) ) { value = morphColor ( value ) ; } if ( attribute . equals ( STROKE_OPACITY ) ) { if ( value . equals ( "0" ) ) { props . setProperty ( STROKE , "none" ) ; } } if ( attribute . equals ( STROKE_WIDTH ) ) { if ( value . equals ( "" ) ) { value = "1" ; } if ( value . endsWith ( "px" ) ) { value = value . substring ( 0 , value . length ( ) - 2 ) ; } } if ( attribute . equals ( STROKE ) ) { if ( "none" . equals ( props . getProperty ( STROKE ) ) ) { return ; } if ( "" . equals ( props . getProperty ( STROKE ) ) ) { return ; } value = morphColor ( value ) ; } props . setProperty ( attribute , value ) ; }
Add a configured style attribute into the data set
38,242
public Color getAsColor ( String attribute ) { if ( ! isColor ( attribute ) ) { throw new RuntimeException ( "Attribute " + attribute + " is not specified as a color:" + getAttribute ( attribute ) ) ; } int col = Integer . parseInt ( getAttribute ( attribute ) . substring ( 1 ) , 16 ) ; return new Color ( col ) ; }
Get an attribute value converted to a color . isColor should first be checked
38,243
public float getAsFloat ( String attribute ) { String value = getAttribute ( attribute ) ; if ( value == null ) { return 0 ; } try { return Float . parseFloat ( value ) ; } catch ( NumberFormatException e ) { throw new RuntimeException ( "Attribute " + attribute + " is not specified as a float:" + getAttribute ( attribute ) ) ; } }
Get an attribute converted to a float value
38,244
public int loadGlyphs ( List glyphs , int maxGlyphsToLoad ) throws SlickException { if ( rowHeight != 0 && maxGlyphsToLoad == - 1 ) { int testX = pageX ; int testY = pageY ; int testRowHeight = rowHeight ; for ( Iterator iter = getIterator ( glyphs ) ; iter . hasNext ( ) ; ) { Glyph glyph = ( Glyph ) iter . next ( ) ; int width = glyph . getWidth ( ) ; int height = glyph . getHeight ( ) ; if ( testX + width >= pageWidth ) { testX = 0 ; testY += testRowHeight ; testRowHeight = height ; } else if ( height > testRowHeight ) { testRowHeight = height ; } if ( testY + testRowHeight >= pageWidth ) return 0 ; testX += width ; } } Color . white . bind ( ) ; pageImage . bind ( ) ; int i = 0 ; for ( Iterator iter = getIterator ( glyphs ) ; iter . hasNext ( ) ; ) { Glyph glyph = ( Glyph ) iter . next ( ) ; int width = Math . min ( MAX_GLYPH_SIZE , glyph . getWidth ( ) ) ; int height = Math . min ( MAX_GLYPH_SIZE , glyph . getHeight ( ) ) ; if ( rowHeight == 0 ) { rowHeight = height ; } else { if ( pageX + width >= pageWidth ) { if ( pageY + rowHeight + height >= pageHeight ) break ; pageX = 0 ; pageY += rowHeight ; rowHeight = height ; } else if ( height > rowHeight ) { if ( pageY + height >= pageHeight ) break ; rowHeight = height ; } } renderGlyph ( glyph , width , height ) ; pageGlyphs . add ( glyph ) ; pageX += width ; iter . remove ( ) ; i ++ ; if ( i == maxGlyphsToLoad ) { orderAscending = ! orderAscending ; break ; } } TextureImpl . bindNone ( ) ; orderAscending = ! orderAscending ; return i ; }
Loads glyphs to the backing texture and sets the image on each loaded glyph . Loaded glyphs are removed from the list .
38,245
private void renderGlyph ( Glyph glyph , int width , int height ) throws SlickException { scratchGraphics . setComposite ( AlphaComposite . Clear ) ; scratchGraphics . fillRect ( 0 , 0 , MAX_GLYPH_SIZE , MAX_GLYPH_SIZE ) ; scratchGraphics . setComposite ( AlphaComposite . SrcOver ) ; scratchGraphics . setColor ( java . awt . Color . white ) ; for ( Iterator iter = unicodeFont . getEffects ( ) . iterator ( ) ; iter . hasNext ( ) ; ) ( ( Effect ) iter . next ( ) ) . draw ( scratchImage , scratchGraphics , unicodeFont , glyph ) ; glyph . setShape ( null ) ; WritableRaster raster = scratchImage . getRaster ( ) ; int [ ] row = new int [ width ] ; for ( int y = 0 ; y < height ; y ++ ) { raster . getDataElements ( 0 , y , width , 1 , row ) ; scratchIntBuffer . put ( row ) ; } GL . glTexSubImage2D ( SGL . GL_TEXTURE_2D , 0 , pageX , pageY , width , height , SGL . GL_BGRA , SGL . GL_UNSIGNED_BYTE , scratchByteBuffer ) ; scratchIntBuffer . clear ( ) ; glyph . setImage ( pageImage . getSubImage ( pageX , pageY , width , height ) ) ; }
Loads a single glyph to the backing texture if it fits .
38,246
private Iterator getIterator ( List glyphs ) { if ( orderAscending ) return glyphs . iterator ( ) ; final ListIterator iter = glyphs . listIterator ( glyphs . size ( ) ) ; return new Iterator ( ) { public boolean hasNext ( ) { return iter . hasPrevious ( ) ; } public Object next ( ) { return iter . previous ( ) ; } public void remove ( ) { iter . remove ( ) ; } } ; }
Returns an iterator for the specified glyphs sorted either ascending or descending .
38,247
boolean seekTab ( FontFileReader in , String name , long offset ) throws IOException { TTFDirTabEntry dt = ( TTFDirTabEntry ) dirTabs . get ( name ) ; if ( dt == null ) { log . error ( "Dirtab " + name + " not found." ) ; return false ; } else { in . seekSet ( dt . getOffset ( ) + offset ) ; this . currentDirTab = dt ; } return true ; }
Position inputstream to position indicated in the dirtab offset + offset
38,248
private void createCMaps ( ) { cmaps = new java . util . ArrayList ( ) ; TTFCmapEntry tce = new TTFCmapEntry ( ) ; Iterator e = unicodeMapping . listIterator ( ) ; UnicodeMapping um = ( UnicodeMapping ) e . next ( ) ; UnicodeMapping lastMapping = um ; tce . setUnicodeStart ( um . getUnicodeIndex ( ) ) ; tce . setGlyphStartIndex ( um . getGlyphIndex ( ) ) ; while ( e . hasNext ( ) ) { um = ( UnicodeMapping ) e . next ( ) ; if ( ( ( lastMapping . getUnicodeIndex ( ) + 1 ) != um . getUnicodeIndex ( ) ) || ( ( lastMapping . getGlyphIndex ( ) + 1 ) != um . getGlyphIndex ( ) ) ) { tce . setUnicodeEnd ( lastMapping . getUnicodeIndex ( ) ) ; cmaps . add ( tce ) ; tce = new TTFCmapEntry ( ) ; tce . setUnicodeStart ( um . getUnicodeIndex ( ) ) ; tce . setGlyphStartIndex ( um . getGlyphIndex ( ) ) ; } lastMapping = um ; } tce . setUnicodeEnd ( um . getUnicodeIndex ( ) ) ; cmaps . add ( tce ) ; }
Create teh CMAPS table
38,249
public int getFlags ( ) { int flags = 32 ; if ( italicAngle != 0 ) { flags = flags | 64 ; } if ( isFixedPitch != 0 ) { flags = flags | 2 ; } if ( hasSerifs ) { flags = flags | 1 ; } return flags ; }
Returns the Flags attribute of the font .
38,250
public int [ ] getFontBBox ( ) { final int [ ] fbb = new int [ 4 ] ; fbb [ 0 ] = fontBBox1 ; fbb [ 1 ] = fontBBox2 ; fbb [ 2 ] = fontBBox3 ; fbb [ 3 ] = fontBBox4 ; return fbb ; }
Returns the font bounding box .
38,251
public int [ ] getWidths ( ) { int [ ] wx = new int [ mtxTab . length ] ; for ( int i = 0 ; i < wx . length ; i ++ ) { wx [ i ] = ( mtxTab [ i ] . getWx ( ) ) ; } return wx ; }
Returns an array of character widths .
38,252
protected void readHorizontalHeader ( FontFileReader in ) throws IOException { seekTab ( in , "hhea" , 4 ) ; hheaAscender = in . readTTFShort ( ) ; log . debug ( "hhea.Ascender: " + hheaAscender + " " + ( hheaAscender ) ) ; hheaDescender = in . readTTFShort ( ) ; log . debug ( "hhea.Descender: " + hheaDescender + " " + ( hheaDescender ) ) ; in . skip ( 2 + 2 + 3 * 2 + 8 * 2 ) ; nhmtx = in . readTTFUShort ( ) ; log . debug ( "Number of horizontal metrics: " + nhmtx ) ; }
Read the hhea table to find the ascender and descender and size of hmtx table as a fixed size font might have only one width .
38,253
private final void readPostScript ( FontFileReader in ) throws IOException { seekTab ( in , "post" , 0 ) ; postFormat = in . readTTFLong ( ) ; italicAngle = in . readTTFULong ( ) ; underlinePosition = in . readTTFShort ( ) ; underlineThickness = in . readTTFShort ( ) ; isFixedPitch = in . readTTFULong ( ) ; in . skip ( 4 * 4 ) ; log . debug ( "PostScript format: 0x" + Integer . toHexString ( postFormat ) ) ; switch ( postFormat ) { case 0x00010000 : log . debug ( "PostScript format 1" ) ; for ( int i = 0 ; i < Glyphs . MAC_GLYPH_NAMES . length ; i ++ ) { mtxTab [ i ] . setName ( Glyphs . MAC_GLYPH_NAMES [ i ] ) ; } break ; case 0x00020000 : log . debug ( "PostScript format 2" ) ; int numGlyphStrings = 0 ; int l = in . readTTFUShort ( ) ; for ( int i = 0 ; i < l ; i ++ ) { mtxTab [ i ] . setIndex ( in . readTTFUShort ( ) ) ; if ( mtxTab [ i ] . getIndex ( ) > 257 ) { numGlyphStrings ++ ; } if ( log . isTraceEnabled ( ) ) { log . trace ( "PostScript index: " + mtxTab [ i ] . getIndexAsString ( ) ) ; } } String [ ] psGlyphsBuffer = new String [ numGlyphStrings ] ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Reading " + numGlyphStrings + " glyphnames, that are not in the standard Macintosh" + " set. Total number of glyphs=" + l ) ; } for ( int i = 0 ; i < psGlyphsBuffer . length ; i ++ ) { psGlyphsBuffer [ i ] = in . readTTFString ( in . readTTFUByte ( ) ) ; } for ( int i = 0 ; i < l ; i ++ ) { if ( mtxTab [ i ] . getIndex ( ) < NMACGLYPHS ) { mtxTab [ i ] . setName ( Glyphs . MAC_GLYPH_NAMES [ mtxTab [ i ] . getIndex ( ) ] ) ; } else { if ( ! mtxTab [ i ] . isIndexReserved ( ) ) { int k = mtxTab [ i ] . getIndex ( ) - NMACGLYPHS ; if ( log . isTraceEnabled ( ) ) { log . trace ( k + " i=" + i + " mtx=" + mtxTab . length + " ps=" + psGlyphsBuffer . length ) ; } mtxTab [ i ] . setName ( psGlyphsBuffer [ k ] ) ; } } } break ; case 0x00030000 : log . debug ( "PostScript format 3" ) ; break ; default : log . error ( "Unknown PostScript format: " + postFormat ) ; } }
Read the post table containing the PostScript names of the glyphs .
38,254
protected final void readIndexToLocation ( FontFileReader in ) throws IOException { if ( ! seekTab ( in , "loca" , 0 ) ) { throw new IOException ( "'loca' table not found, happens when the font file doesn't" + " contain TrueType outlines (trying to read an OpenType CFF font maybe?)" ) ; } for ( int i = 0 ; i < numberOfGlyphs ; i ++ ) { mtxTab [ i ] . setOffset ( locaFormat == 1 ? in . readTTFULong ( ) : ( in . readTTFUShort ( ) << 1 ) ) ; } lastLoca = ( locaFormat == 1 ? in . readTTFULong ( ) : ( in . readTTFUShort ( ) << 1 ) ) ; }
Read the loca table .
38,255
private final void readGlyf ( FontFileReader in ) throws IOException { TTFDirTabEntry dirTab = ( TTFDirTabEntry ) dirTabs . get ( "glyf" ) ; if ( dirTab == null ) { throw new IOException ( "glyf table not found, cannot continue" ) ; } for ( int i = 0 ; i < ( numberOfGlyphs - 1 ) ; i ++ ) { if ( mtxTab [ i ] . getOffset ( ) != mtxTab [ i + 1 ] . getOffset ( ) ) { in . seekSet ( dirTab . getOffset ( ) + mtxTab [ i ] . getOffset ( ) ) ; in . skip ( 2 ) ; final int [ ] bbox = { in . readTTFShort ( ) , in . readTTFShort ( ) , in . readTTFShort ( ) , in . readTTFShort ( ) } ; mtxTab [ i ] . setBoundingBox ( bbox ) ; } else { mtxTab [ i ] . setBoundingBox ( mtxTab [ 0 ] . getBoundingBox ( ) ) ; } } long n = ( ( TTFDirTabEntry ) dirTabs . get ( "glyf" ) ) . getOffset ( ) ; for ( int i = 0 ; i < numberOfGlyphs ; i ++ ) { if ( ( i + 1 ) >= mtxTab . length || mtxTab [ i ] . getOffset ( ) != mtxTab [ i + 1 ] . getOffset ( ) ) { in . seekSet ( n + mtxTab [ i ] . getOffset ( ) ) ; in . skip ( 2 ) ; final int [ ] bbox = { in . readTTFShort ( ) , in . readTTFShort ( ) , in . readTTFShort ( ) , in . readTTFShort ( ) } ; mtxTab [ i ] . setBoundingBox ( bbox ) ; } else { final int bbox0 = mtxTab [ 0 ] . getBoundingBox ( ) [ 0 ] ; final int [ ] bbox = { bbox0 , bbox0 , bbox0 , bbox0 } ; mtxTab [ i ] . setBoundingBox ( bbox ) ; } if ( log . isTraceEnabled ( ) ) { log . trace ( mtxTab [ i ] . toString ( this ) ) ; } } }
Read the glyf table to find the bounding boxes .
38,256
private final void readName ( FontFileReader in ) throws IOException { seekTab ( in , "name" , 2 ) ; int i = in . getCurrentPos ( ) ; int n = in . readTTFUShort ( ) ; int j = in . readTTFUShort ( ) + i - 2 ; i += 2 * 2 ; while ( n -- > 0 ) { in . seekSet ( i ) ; final int platformID = in . readTTFUShort ( ) ; final int encodingID = in . readTTFUShort ( ) ; final int languageID = in . readTTFUShort ( ) ; int k = in . readTTFUShort ( ) ; int l = in . readTTFUShort ( ) ; if ( ( ( platformID == 1 || platformID == 3 ) && ( encodingID == 0 || encodingID == 1 ) ) && ( k == 1 || k == 2 || k == 0 || k == 4 || k == 6 ) ) { in . seekSet ( j + in . readTTFUShort ( ) ) ; String txt = in . readTTFString ( l ) ; log . debug ( platformID + " " + encodingID + " " + languageID + " " + k + " " + txt ) ; switch ( k ) { case 0 : notice = txt ; break ; case 1 : familyName = txt ; break ; case 2 : subFamilyName = txt ; break ; case 4 : fullName = txt ; break ; case 6 : fontName = txt ; break ; } if ( ! notice . equals ( "" ) && ! fullName . equals ( "" ) && ! fontName . equals ( "" ) && ! familyName . equals ( "" ) && ! subFamilyName . equals ( "" ) ) { break ; } } i += 6 * 2 ; } }
Read the name table .
38,257
private final boolean readPCLT ( FontFileReader in ) throws IOException { TTFDirTabEntry dirTab = ( TTFDirTabEntry ) dirTabs . get ( "PCLT" ) ; if ( dirTab != null ) { in . seekSet ( dirTab . getOffset ( ) + 4 + 4 + 2 ) ; xHeight = in . readTTFUShort ( ) ; log . debug ( "xHeight from PCLT: " + xHeight + " " + ( xHeight ) ) ; in . skip ( 2 * 2 ) ; capHeight = in . readTTFUShort ( ) ; log . debug ( "capHeight from PCLT: " + capHeight + " " + ( capHeight ) ) ; in . skip ( 2 + 16 + 8 + 6 + 1 + 1 ) ; int serifStyle = in . readTTFUByte ( ) ; serifStyle = serifStyle >> 6 ; serifStyle = serifStyle & 3 ; if ( serifStyle == 1 ) { hasSerifs = false ; } else { hasSerifs = true ; } return true ; } else { return false ; } }
Read the PCLT table to find xHeight and capHeight .
38,258
protected final boolean checkTTC ( FontFileReader in , String name ) throws IOException { String tag = in . readTTFString ( 4 ) ; if ( "ttcf" . equals ( tag ) ) { in . skip ( 4 ) ; int numDirectories = ( int ) in . readTTFULong ( ) ; long [ ] dirOffsets = new long [ numDirectories ] ; for ( int i = 0 ; i < numDirectories ; i ++ ) { dirOffsets [ i ] = in . readTTFULong ( ) ; } log . info ( "This is a TrueType collection file with " + numDirectories + " fonts" ) ; log . info ( "Containing the following fonts: " ) ; boolean found = false ; long dirTabOffset = 0 ; for ( int i = 0 ; ( i < numDirectories ) ; i ++ ) { in . seekSet ( dirOffsets [ i ] ) ; readDirTabs ( in ) ; readName ( in ) ; if ( fullName . equals ( name ) ) { found = true ; dirTabOffset = dirOffsets [ i ] ; log . info ( fullName + " <-- selected" ) ; } else { log . info ( fullName ) ; } notice = "" ; fullName = "" ; familyName = "" ; fontName = "" ; subFamilyName = "" ; } in . seekSet ( dirTabOffset ) ; return found ; } else { in . seekSet ( 0 ) ; return true ; } }
Check if this is a TrueType collection and that the given name exists in the collection . If it does set offset in fontfile to the beginning of the Table Directory for that font .
38,259
private Integer [ ] unicodeToWinAnsi ( int unicode ) { List ret = new java . util . ArrayList ( ) ; for ( int i = 32 ; i < Glyphs . WINANSI_ENCODING . length ; i ++ ) { if ( unicode == Glyphs . WINANSI_ENCODING [ i ] ) { ret . add ( new Integer ( i ) ) ; } } return ( Integer [ ] ) ret . toArray ( new Integer [ 0 ] ) ; }
Helper methods they are not very efficient but that really doesn t matter ...
38,260
public void printStuff ( ) { System . out . println ( "Font name: " + fontName ) ; System . out . println ( "Full name: " + fullName ) ; System . out . println ( "Family name: " + familyName ) ; System . out . println ( "Subfamily name: " + subFamilyName ) ; System . out . println ( "Notice: " + notice ) ; System . out . println ( "xHeight: " + ( xHeight ) ) ; System . out . println ( "capheight: " + ( capHeight ) ) ; int italic = ( int ) ( italicAngle >> 16 ) ; System . out . println ( "Italic: " + italic ) ; System . out . print ( "ItalicAngle: " + ( short ) ( italicAngle / 0x10000 ) ) ; if ( ( italicAngle % 0x10000 ) > 0 ) { System . out . print ( "." + ( short ) ( ( italicAngle % 0x10000 ) * 1000 ) / 0x10000 ) ; } System . out . println ( ) ; System . out . println ( "Ascender: " + ( ascender ) ) ; System . out . println ( "Descender: " + ( descender ) ) ; System . out . println ( "FontBBox: [" + ( fontBBox1 ) + " " + ( fontBBox2 ) + " " + ( fontBBox3 ) + " " + ( fontBBox4 ) + "]" ) ; }
Dumps a few informational values to System . out .
38,261
private Integer unicodeToGlyph ( int unicodeIndex ) throws IOException { final Integer result = ( Integer ) unicodeToGlyphMap . get ( new Integer ( unicodeIndex ) ) ; if ( result == null ) { throw new IOException ( "Glyph index not found for unicode value " + unicodeIndex ) ; } return result ; }
Map a unicode code point to the corresponding glyph index
38,262
public static void main ( String [ ] args ) { try { TTFFile ttfFile = new TTFFile ( ) ; FontFileReader reader = new FontFileReader ( args [ 0 ] ) ; String name = null ; if ( args . length >= 2 ) { name = args [ 1 ] ; } ttfFile . readFont ( reader , name ) ; ttfFile . printStuff ( ) ; } catch ( IOException ioe ) { System . err . println ( "Problem reading font: " + ioe . toString ( ) ) ; ioe . printStackTrace ( System . err ) ; } }
Static main method to get info about a TrueType font .
38,263
public OggData getData ( InputStream input ) throws IOException { if ( input == null ) { throw new IOException ( "Failed to read OGG, source does not exist?" ) ; } ByteArrayOutputStream dataout = new ByteArrayOutputStream ( ) ; OggInputStream oggInput = new OggInputStream ( input ) ; boolean done = false ; while ( ! oggInput . atEnd ( ) ) { dataout . write ( oggInput . read ( ) ) ; } OggData ogg = new OggData ( ) ; ogg . channels = oggInput . getChannels ( ) ; ogg . rate = oggInput . getRate ( ) ; byte [ ] data = dataout . toByteArray ( ) ; ogg . data = ByteBuffer . allocateDirect ( data . length ) ; ogg . data . put ( data ) ; ogg . data . rewind ( ) ; return ogg ; }
Get the data out of an OGG file
38,264
private void createDirectory ( ) { int numTables = 9 ; writeByte ( ( byte ) 0 ) ; writeByte ( ( byte ) 1 ) ; writeByte ( ( byte ) 0 ) ; writeByte ( ( byte ) 0 ) ; realSize += 4 ; writeUShort ( numTables ) ; realSize += 2 ; int maxPow = maxPow2 ( numTables ) ; int searchRange = maxPow * 16 ; writeUShort ( searchRange ) ; realSize += 2 ; writeUShort ( maxPow ) ; realSize += 2 ; writeUShort ( ( numTables * 16 ) - searchRange ) ; realSize += 2 ; writeString ( "cvt " ) ; cvtDirOffset = currentPos ; currentPos += 12 ; realSize += 16 ; if ( hasFpgm ( ) ) { writeString ( "fpgm" ) ; fpgmDirOffset = currentPos ; currentPos += 12 ; realSize += 16 ; } writeString ( "glyf" ) ; glyfDirOffset = currentPos ; currentPos += 12 ; realSize += 16 ; writeString ( "head" ) ; headDirOffset = currentPos ; currentPos += 12 ; realSize += 16 ; writeString ( "hhea" ) ; hheaDirOffset = currentPos ; currentPos += 12 ; realSize += 16 ; writeString ( "hmtx" ) ; hmtxDirOffset = currentPos ; currentPos += 12 ; realSize += 16 ; writeString ( "loca" ) ; locaDirOffset = currentPos ; currentPos += 12 ; realSize += 16 ; writeString ( "maxp" ) ; maxpDirOffset = currentPos ; currentPos += 12 ; realSize += 16 ; writeString ( "prep" ) ; prepDirOffset = currentPos ; currentPos += 12 ; realSize += 16 ; }
Create the directory table
38,265
private void createCvt ( FontFileReader in ) throws IOException { TTFDirTabEntry entry = ( TTFDirTabEntry ) dirTabs . get ( "cvt " ) ; if ( entry != null ) { pad4 ( ) ; seekTab ( in , "cvt " , 0 ) ; System . arraycopy ( in . getBytes ( ( int ) entry . getOffset ( ) , ( int ) entry . getLength ( ) ) , 0 , output , currentPos , ( int ) entry . getLength ( ) ) ; int checksum = getCheckSum ( currentPos , ( int ) entry . getLength ( ) ) ; writeULong ( cvtDirOffset , checksum ) ; writeULong ( cvtDirOffset + 4 , currentPos ) ; writeULong ( cvtDirOffset + 8 , ( int ) entry . getLength ( ) ) ; currentPos += ( int ) entry . getLength ( ) ; realSize += ( int ) entry . getLength ( ) ; } else { throw new IOException ( "Can't find cvt table" ) ; } }
Copy the cvt table as is from original font to subset font
38,266
private void createLoca ( int size ) throws IOException { pad4 ( ) ; locaOffset = currentPos ; writeULong ( locaDirOffset + 4 , currentPos ) ; writeULong ( locaDirOffset + 8 , size * 4 + 4 ) ; currentPos += size * 4 + 4 ; realSize += size * 4 + 4 ; }
Create an empty loca table without updating checksum
38,267
private void createMaxp ( FontFileReader in , int size ) throws IOException { TTFDirTabEntry entry = ( TTFDirTabEntry ) dirTabs . get ( "maxp" ) ; if ( entry != null ) { pad4 ( ) ; seekTab ( in , "maxp" , 0 ) ; System . arraycopy ( in . getBytes ( ( int ) entry . getOffset ( ) , ( int ) entry . getLength ( ) ) , 0 , output , currentPos , ( int ) entry . getLength ( ) ) ; writeUShort ( currentPos + 4 , size ) ; int checksum = getCheckSum ( currentPos , ( int ) entry . getLength ( ) ) ; writeULong ( maxpDirOffset , checksum ) ; writeULong ( maxpDirOffset + 4 , currentPos ) ; writeULong ( maxpDirOffset + 8 , ( int ) entry . getLength ( ) ) ; currentPos += ( int ) entry . getLength ( ) ; realSize += ( int ) entry . getLength ( ) ; } else { throw new IOException ( "Can't find maxp table" ) ; } }
Copy the maxp table as is from original font to subset font and set num glyphs to size
38,268
private void createHead ( FontFileReader in ) throws IOException { TTFDirTabEntry entry = ( TTFDirTabEntry ) dirTabs . get ( "head" ) ; if ( entry != null ) { pad4 ( ) ; seekTab ( in , "head" , 0 ) ; System . arraycopy ( in . getBytes ( ( int ) entry . getOffset ( ) , ( int ) entry . getLength ( ) ) , 0 , output , currentPos , ( int ) entry . getLength ( ) ) ; checkSumAdjustmentOffset = currentPos + 8 ; output [ currentPos + 8 ] = 0 ; output [ currentPos + 9 ] = 0 ; output [ currentPos + 10 ] = 0 ; output [ currentPos + 11 ] = 0 ; output [ currentPos + 50 ] = 0 ; output [ currentPos + 51 ] = 1 ; int checksum = getCheckSum ( currentPos , ( int ) entry . getLength ( ) ) ; writeULong ( headDirOffset , checksum ) ; writeULong ( headDirOffset + 4 , currentPos ) ; writeULong ( headDirOffset + 8 , ( int ) entry . getLength ( ) ) ; currentPos += ( int ) entry . getLength ( ) ; realSize += ( int ) entry . getLength ( ) ; } else { throw new IOException ( "Can't find head table" ) ; } }
Copy the head table as is from original font to subset font and set indexToLocaFormat to long and set checkSumAdjustment to 0 store offset to checkSumAdjustment in checkSumAdjustmentOffset
38,269
private void createGlyf ( FontFileReader in , Map glyphs ) throws IOException { TTFDirTabEntry entry = ( TTFDirTabEntry ) dirTabs . get ( "glyf" ) ; int size = 0 ; int start = 0 ; int endOffset = 0 ; if ( entry != null ) { pad4 ( ) ; start = currentPos ; int [ ] origIndexes = new int [ glyphs . size ( ) ] ; Iterator e = glyphs . keySet ( ) . iterator ( ) ; while ( e . hasNext ( ) ) { Integer origIndex = ( Integer ) e . next ( ) ; Integer subsetIndex = ( Integer ) glyphs . get ( origIndex ) ; origIndexes [ subsetIndex . intValue ( ) ] = origIndex . intValue ( ) ; } for ( int i = 0 ; i < origIndexes . length ; i ++ ) { int glyphLength = 0 ; int nextOffset = 0 ; int origGlyphIndex = origIndexes [ i ] ; if ( origGlyphIndex >= ( mtxTab . length - 1 ) ) { nextOffset = ( int ) lastLoca ; } else { nextOffset = ( int ) mtxTab [ origGlyphIndex + 1 ] . getOffset ( ) ; } glyphLength = nextOffset - ( int ) mtxTab [ origGlyphIndex ] . getOffset ( ) ; System . arraycopy ( in . getBytes ( ( int ) entry . getOffset ( ) + ( int ) mtxTab [ origGlyphIndex ] . getOffset ( ) , glyphLength ) , 0 , output , currentPos , glyphLength ) ; writeULong ( locaOffset + i * 4 , currentPos - start ) ; if ( ( currentPos - start + glyphLength ) > endOffset ) { endOffset = ( currentPos - start + glyphLength ) ; } currentPos += glyphLength ; realSize += glyphLength ; } size = currentPos - start ; int checksum = getCheckSum ( start , size ) ; writeULong ( glyfDirOffset , checksum ) ; writeULong ( glyfDirOffset + 4 , start ) ; writeULong ( glyfDirOffset + 8 , size ) ; currentPos += 12 ; realSize += 12 ; writeULong ( locaOffset + glyphs . size ( ) * 4 , endOffset ) ; checksum = getCheckSum ( locaOffset , glyphs . size ( ) * 4 + 4 ) ; writeULong ( locaDirOffset , checksum ) ; } else { throw new IOException ( "Can't find glyf table" ) ; } }
Create the glyf table and fill in loca table
38,270
private List getIncludedGlyphs ( FontFileReader in , int glyphOffset , Integer glyphIdx ) throws IOException { List ret = new ArrayList ( ) ; ret . add ( glyphIdx ) ; int offset = glyphOffset + ( int ) mtxTab [ glyphIdx . intValue ( ) ] . getOffset ( ) + 10 ; Integer compositeIdx = null ; int flags = 0 ; boolean moreComposites = true ; while ( moreComposites ) { flags = in . readTTFUShort ( offset ) ; compositeIdx = new Integer ( in . readTTFUShort ( offset + 2 ) ) ; ret . add ( compositeIdx ) ; offset += 4 ; if ( ( flags & 1 ) > 0 ) { offset += 4 ; } else { offset += 2 ; } if ( ( flags & 8 ) > 0 ) { offset += 2 ; } else if ( ( flags & 64 ) > 0 ) { offset += 4 ; } else if ( ( flags & 128 ) > 0 ) { offset += 8 ; } if ( ( flags & 32 ) > 0 ) { moreComposites = true ; } else { moreComposites = false ; } } return ret ; }
Returns a List containing the glyph itself plus all glyphs that this composite glyph uses
38,271
private void remapComposite ( FontFileReader in , Map glyphs , int glyphOffset , Integer glyphIdx ) throws IOException { int offset = glyphOffset + ( int ) mtxTab [ glyphIdx . intValue ( ) ] . getOffset ( ) + 10 ; Integer compositeIdx = null ; int flags = 0 ; boolean moreComposites = true ; while ( moreComposites ) { flags = in . readTTFUShort ( offset ) ; compositeIdx = new Integer ( in . readTTFUShort ( offset + 2 ) ) ; Integer newIdx = ( Integer ) glyphs . get ( compositeIdx ) ; if ( newIdx == null ) { moreComposites = false ; continue ; } in . writeTTFUShort ( offset + 2 , newIdx . intValue ( ) ) ; offset += 4 ; if ( ( flags & 1 ) > 0 ) { offset += 4 ; } else { offset += 2 ; } if ( ( flags & 8 ) > 0 ) { offset += 2 ; } else if ( ( flags & 64 ) > 0 ) { offset += 4 ; } else if ( ( flags & 128 ) > 0 ) { offset += 8 ; } if ( ( flags & 32 ) > 0 ) { moreComposites = true ; } else { moreComposites = false ; } } }
Rewrite all compositepointers in glyphindex glyphIdx
38,272
private void scanGlyphs ( FontFileReader in , Map glyphs ) throws IOException { TTFDirTabEntry entry = ( TTFDirTabEntry ) dirTabs . get ( "glyf" ) ; Map newComposites = null ; Map allComposites = new java . util . HashMap ( ) ; int newIndex = glyphs . size ( ) ; if ( entry != null ) { while ( newComposites == null || newComposites . size ( ) > 0 ) { newComposites = new java . util . HashMap ( ) ; Iterator e = glyphs . keySet ( ) . iterator ( ) ; while ( e . hasNext ( ) ) { Integer origIndex = ( Integer ) e . next ( ) ; if ( in . readTTFShort ( entry . getOffset ( ) + mtxTab [ origIndex . intValue ( ) ] . getOffset ( ) ) < 0 ) { allComposites . put ( origIndex , glyphs . get ( origIndex ) ) ; List composites = getIncludedGlyphs ( in , ( int ) entry . getOffset ( ) , origIndex ) ; Iterator cps = composites . iterator ( ) ; while ( cps . hasNext ( ) ) { Integer cIdx = ( Integer ) cps . next ( ) ; if ( glyphs . get ( cIdx ) == null && newComposites . get ( cIdx ) == null ) { newComposites . put ( cIdx , new Integer ( newIndex ) ) ; newIndex ++ ; } } } } Iterator m = newComposites . keySet ( ) . iterator ( ) ; while ( m . hasNext ( ) ) { Integer im = ( Integer ) m . next ( ) ; glyphs . put ( im , newComposites . get ( im ) ) ; } } Iterator ce = allComposites . keySet ( ) . iterator ( ) ; while ( ce . hasNext ( ) ) { remapComposite ( in , glyphs , ( int ) entry . getOffset ( ) , ( Integer ) ce . next ( ) ) ; } } else { throw new IOException ( "Can't find glyf table" ) ; } }
Scan all the original glyphs for composite glyphs and add those glyphs to the glyphmapping also rewrite the composite glyph pointers to the new mapping
38,273
public byte [ ] readFont ( FontFileReader in , String name , Map glyphs ) throws IOException { if ( ! checkTTC ( in , name ) ) { throw new IOException ( "Failed to read font" ) ; } output = new byte [ in . getFileSize ( ) ] ; readDirTabs ( in ) ; readFontHeader ( in ) ; getNumGlyphs ( in ) ; readHorizontalHeader ( in ) ; readHorizontalMetrics ( in ) ; readIndexToLocation ( in ) ; scanGlyphs ( in , glyphs ) ; createDirectory ( ) ; createHead ( in ) ; createHhea ( in , glyphs . size ( ) ) ; createHmtx ( in , glyphs ) ; createMaxp ( in , glyphs . size ( ) ) ; try { createCvt ( in ) ; } catch ( IOException ex ) { } try { createFpgm ( in ) ; } catch ( IOException ex ) { } try { createPrep ( in ) ; } catch ( IOException ex ) { } try { createLoca ( glyphs . size ( ) ) ; } catch ( IOException ex ) { } try { createGlyf ( in , glyphs ) ; } catch ( IOException ex ) { } pad4 ( ) ; createCheckSumAdjustment ( ) ; byte [ ] ret = new byte [ realSize ] ; System . arraycopy ( output , 0 , ret , 0 , realSize ) ; return ret ; }
Returns a subset of the original font .
38,274
private void writeUShort ( int s ) { byte b1 = ( byte ) ( ( s >> 8 ) & 0xff ) ; byte b2 = ( byte ) ( s & 0xff ) ; writeByte ( b1 ) ; writeByte ( b2 ) ; }
Appends a USHORT to the output array updates currentPost but not realSize
38,275
private void writeUShort ( int pos , int s ) { byte b1 = ( byte ) ( ( s >> 8 ) & 0xff ) ; byte b2 = ( byte ) ( s & 0xff ) ; output [ pos ] = b1 ; output [ pos + 1 ] = b2 ; }
Appends a USHORT to the output array at the given position without changing currentPos
38,276
private void writeULong ( int s ) { byte b1 = ( byte ) ( ( s >> 24 ) & 0xff ) ; byte b2 = ( byte ) ( ( s >> 16 ) & 0xff ) ; byte b3 = ( byte ) ( ( s >> 8 ) & 0xff ) ; byte b4 = ( byte ) ( s & 0xff ) ; writeByte ( b1 ) ; writeByte ( b2 ) ; writeByte ( b3 ) ; writeByte ( b4 ) ; }
Appends a ULONG to the output array updates currentPos but not realSize
38,277
private int readUShort ( int pos ) { int ret = output [ pos ] ; if ( ret < 0 ) { ret += 256 ; } ret = ret << 8 ; if ( output [ pos + 1 ] < 0 ) { ret |= output [ pos + 1 ] + 256 ; } else { ret |= output [ pos + 1 ] ; } return ret ; }
Read a unsigned short value at given position
38,278
private void pad4 ( ) { int padSize = currentPos % 4 ; for ( int i = 0 ; i < padSize ; i ++ ) { output [ currentPos ++ ] = 0 ; realSize ++ ; } }
Create a padding in the fontfile to align on a 4 - byte boundary
38,279
private long getLongCheckSum ( int start , int size ) { int remainder = size % 4 ; if ( remainder != 0 ) { size += remainder ; } long sum = 0 ; for ( int i = 0 ; i < size ; i += 4 ) { int l = ( output [ start + i ] << 24 ) ; l += ( output [ start + i + 1 ] << 16 ) ; l += ( output [ start + i + 2 ] << 16 ) ; l += ( output [ start + i + 3 ] << 16 ) ; sum += l ; if ( sum > 0xffffffff ) { sum = sum - 0xffffffff ; } } return sum ; }
Get the checksum as a long
38,280
public void setText ( String value ) { this . value = value ; if ( cursorPos > value . length ( ) ) { cursorPos = value . length ( ) ; } }
Set the value to be displayed in the text field
38,281
public void setCursorPos ( int pos ) { cursorPos = pos ; if ( cursorPos > value . length ( ) ) { cursorPos = value . length ( ) ; } }
Set the position of the cursor
38,282
public void setMaxLength ( int length ) { maxCharacter = length ; if ( value . length ( ) > maxCharacter ) { value = value . substring ( 0 , maxCharacter ) ; } }
Set the length of the allowed input
38,283
protected void doPaste ( String text ) { recordOldPosition ( ) ; for ( int i = 0 ; i < text . length ( ) ; i ++ ) { keyPressed ( - 1 , text . charAt ( i ) ) ; } }
Do the paste into the field overrideable for custom behaviour
38,284
protected void doUndo ( int oldCursorPos , String oldText ) { if ( oldText != null ) { setText ( oldText ) ; setCursorPos ( oldCursorPos ) ; } }
Do the undo of the paste overrideable for custom behaviour
38,285
public static FontData getPlain ( String familyName ) { FontData data = ( FontData ) plain . get ( familyName ) ; return data ; }
Get the plain version of a family name
38,286
public static FontData getBold ( String familyName ) { FontData data = ( FontData ) bold . get ( familyName ) ; return data ; }
Get the bold version of the font
38,287
public static FontData getBoldItalic ( String familyName ) { FontData data = ( FontData ) bolditalic . get ( familyName ) ; return data ; }
Get the bold italic version of the font
38,288
public static FontData getItalic ( String familyName ) { FontData data = ( FontData ) italic . get ( familyName ) ; return data ; }
Get the italic version of the font
38,289
public static FontData getStyled ( String familyName , int style ) { boolean b = ( style & Font . BOLD ) != 0 ; boolean i = ( style & Font . ITALIC ) != 0 ; if ( b & i ) { return getBoldItalic ( familyName ) ; } else if ( b ) { return getBold ( familyName ) ; } else if ( i ) { return getItalic ( familyName ) ; } else { return getPlain ( familyName ) ; } }
Get a styled version of a particular font family
38,290
private static void processFontDirectory ( File dir , ArrayList fonts ) { if ( ! dir . exists ( ) ) { return ; } if ( processed . contains ( dir ) ) { return ; } processed . add ( dir ) ; File [ ] sources = dir . listFiles ( ) ; if ( sources == null ) { return ; } for ( int j = 0 ; j < sources . length ; j ++ ) { File source = sources [ j ] ; if ( source . getName ( ) . equals ( "." ) ) { continue ; } if ( source . getName ( ) . equals ( ".." ) ) { continue ; } if ( source . isDirectory ( ) ) { processFontDirectory ( source , fonts ) ; continue ; } if ( source . getName ( ) . toLowerCase ( ) . endsWith ( ".ttf" ) ) { try { if ( statusListener != null ) { statusListener . updateStatus ( "Processing " + source . getName ( ) ) ; } FontData data = new FontData ( new FileInputStream ( source ) , 1 ) ; fonts . add ( data ) ; String famName = data . getFamilyName ( ) ; if ( ! families . contains ( famName ) ) { families . add ( famName ) ; } boolean bo = data . getJavaFont ( ) . isBold ( ) ; boolean it = data . getJavaFont ( ) . isItalic ( ) ; if ( ( bo ) && ( it ) ) { bolditalic . put ( famName , data ) ; } else if ( bo ) { bold . put ( famName , data ) ; } else if ( it ) { italic . put ( famName , data ) ; } else { plain . put ( famName , data ) ; } } catch ( Exception e ) { if ( DEBUG ) { System . err . println ( "Unable to process: " + source . getAbsolutePath ( ) + " (" + e . getClass ( ) + ": " + e . getMessage ( ) + ")" ) ; } if ( statusListener != null ) { statusListener . updateStatus ( "Unable to process: " + source . getName ( ) ) ; } } } } }
Process a directory potentially full of fonts
38,291
public static FontData [ ] getAllFonts ( ) { if ( fonts == null ) { fonts = new ArrayList ( ) ; String os = System . getProperty ( "os.name" ) ; File [ ] locs = new File [ 0 ] ; if ( os . startsWith ( "Windows" ) ) { locs = win32 ; } if ( os . startsWith ( "Linux" ) ) { locs = linux ; } if ( os . startsWith ( "Mac OS" ) ) { locs = macos ; } for ( int i = 0 ; i < locs . length ; i ++ ) { File loc = locs [ i ] ; processFontDirectory ( loc , fonts ) ; } if ( os . startsWith ( "Linux" ) ) { locateLinuxFonts ( new File ( "/etc/fonts/fonts.conf" ) ) ; } } return ( FontData [ ] ) fonts . toArray ( new FontData [ 0 ] ) ; }
Get all the fonts available
38,292
private static void locateLinuxFonts ( File file ) { if ( ! file . exists ( ) ) { System . err . println ( "Unable to open: " + file . getAbsolutePath ( ) ) ; return ; } try { InputStream in = new FileInputStream ( file ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) ) ; ByteArrayOutputStream temp = new ByteArrayOutputStream ( ) ; PrintStream pout = new PrintStream ( temp ) ; while ( reader . ready ( ) ) { String line = reader . readLine ( ) ; if ( line . indexOf ( "DOCTYPE" ) == - 1 ) { pout . println ( line ) ; } } in = new ByteArrayInputStream ( temp . toByteArray ( ) ) ; DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; Document document = builder . parse ( in ) ; NodeList dirs = document . getElementsByTagName ( "dir" ) ; for ( int i = 0 ; i < dirs . getLength ( ) ; i ++ ) { Element element = ( Element ) dirs . item ( i ) ; String dir = element . getFirstChild ( ) . getNodeValue ( ) ; if ( dir . startsWith ( "~" ) ) { dir = dir . substring ( 1 ) ; dir = userhome + dir ; } addFontDirectory ( new File ( dir ) ) ; } NodeList includes = document . getElementsByTagName ( "include" ) ; for ( int i = 0 ; i < includes . getLength ( ) ; i ++ ) { Element element = ( Element ) dirs . item ( i ) ; String inc = element . getFirstChild ( ) . getNodeValue ( ) ; if ( inc . startsWith ( "~" ) ) { inc = inc . substring ( 1 ) ; inc = userhome + inc ; } locateLinuxFonts ( new File ( inc ) ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; System . err . println ( "Unable to process: " + file . getAbsolutePath ( ) ) ; } }
Locate the linux fonts based on the XML configuration file
38,293
public FontData deriveFont ( float size , int style ) { FontData original = getStyled ( getFamilyName ( ) , style ) ; FontData data = new FontData ( ) ; data . size = size ; data . javaFont = original . javaFont . deriveFont ( style , size ) ; data . upem = upem ; data . ansiKerning = ansiKerning ; data . charWidth = charWidth ; return data ; }
Derive a new version of this font based on a new size
38,294
public int getKerning ( char first , char second ) { Map toMap = ( Map ) ansiKerning . get ( new Integer ( first ) ) ; if ( toMap == null ) { return 0 ; } Integer kerning = ( Integer ) toMap . get ( new Integer ( second ) ) ; if ( kerning == null ) { return 0 ; } return Math . round ( convertUnitToEm ( size , kerning . intValue ( ) ) ) ; }
Get the kerning value between two characters
38,295
private static void checkProperty ( ) { if ( ! pngLoaderPropertyChecked ) { pngLoaderPropertyChecked = true ; try { AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { String val = System . getProperty ( PNG_LOADER ) ; if ( "false" . equalsIgnoreCase ( val ) ) { usePngLoader = false ; } Log . info ( "Use Java PNG Loader = " + usePngLoader ) ; return null ; } } ) ; } catch ( Throwable e ) { } } }
Check PNG loader property . If set the native PNG loader will not be used .
38,296
public static LoadableImageData getImageDataFor ( String ref ) { LoadableImageData imageData ; checkProperty ( ) ; ref = ref . toLowerCase ( ) ; if ( ref . endsWith ( ".tga" ) ) { return new TGAImageData ( ) ; } if ( ref . endsWith ( ".png" ) ) { CompositeImageData data = new CompositeImageData ( ) ; if ( usePngLoader ) { data . add ( new PNGImageData ( ) ) ; } data . add ( new ImageIOImageData ( ) ) ; return data ; } return new ImageIOImageData ( ) ; }
Create an image data that is appropriate for the reference supplied
38,297
public String read ( FontFileReader in ) throws IOException { tag [ 0 ] = in . readTTFByte ( ) ; tag [ 1 ] = in . readTTFByte ( ) ; tag [ 2 ] = in . readTTFByte ( ) ; tag [ 3 ] = in . readTTFByte ( ) ; in . skip ( 4 ) ; offset = in . readTTFULong ( ) ; length = in . readTTFULong ( ) ; String tagStr = new String ( tag , "ISO-8859-1" ) ; return tagStr ; }
Read Dir Tab return tag name
38,298
private void addEnableControl ( String text , ItemListener listener ) { JCheckBox enableControl = new JCheckBox ( "Enable " + text ) ; enableControl . setBounds ( 10 , offset , 200 , 20 ) ; enableControl . addItemListener ( listener ) ; add ( enableControl ) ; controlToValueName . put ( enableControl , text ) ; valueNameToControl . put ( text , enableControl ) ; offset += 25 ; }
Add a control for enablement
38,299
public void itemStateChangedHandler ( ItemEvent e ) { String valueName = ( String ) controlToValueName . get ( e . getSource ( ) ) ; LinearInterpolator value = ( LinearInterpolator ) valueMap . get ( valueName ) ; if ( e . getStateChange ( ) == ItemEvent . SELECTED ) { value . setActive ( true ) ; editor . registerValue ( value , valueName ) ; } else { value . setActive ( false ) ; editor . removeValue ( valueName ) ; } }
Notificaiton that one of the configuration option has changed state