idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
3,400
private boolean checkObjectId ( int dtx , int dty ) { final int tw = transformable . getWidth ( ) / map . getTileWidth ( ) ; final int th = transformable . getHeight ( ) / map . getTileHeight ( ) ; for ( int tx = dtx ; tx < dtx + tw ; tx ++ ) { for ( int ty = dty ; ty < dty + th ; ty ++ ) { final Collection < Integer > ids = mapPath . getObjectsId ( tx , ty ) ; if ( ! ids . isEmpty ( ) && ! ids . contains ( id ) ) { return false ; } } } return mapPath . isAreaAvailable ( this , dtx , dty , tw , th , id ) ; }
Check if the object id location is available for the pathfindable .
3,401
private void onArrived ( ) { destinationReached = true ; moving = false ; path = null ; moveX = 0.0 ; moveY = 0.0 ; sharedPathIds . clear ( ) ; for ( final PathfindableListener listener : listeners ) { listener . notifyArrived ( ) ; } }
Called when destination has been reached and any movement are done .
3,402
private Force getMovementForce ( double x , double y , double dx , double dy ) { double sx = 0.0 ; double sy = 0.0 ; if ( dx - x < 0 ) { sx = - getSpeedX ( ) ; } else if ( dx - x > 0 ) { sx = getSpeedX ( ) ; } if ( dy - y < 0 ) { sy = - getSpeedX ( ) ; } else if ( dy - y > 0 ) { sy = getSpeedX ( ) ; } if ( Double . compare ( sx , 0 ) != 0 && Double . compare ( sy , 0 ) != 0 ) { sx *= PathfindableModel . DIAGONAL_SPEED ; sy *= PathfindableModel . DIAGONAL_SPEED ; } return new Force ( sx , sy ) ; }
Get the movement force depending of the current location and the destination location .
3,403
private int getMaxStep ( ) { if ( path != null ) { final int steps ; if ( pathStopped ) { steps = currentStep ; } else { steps = path . getLength ( ) ; } return steps ; } return 0 ; }
Get total number of steps .
3,404
private void updatePlaying ( double extrp ) { current += speed * extrp ; if ( Double . compare ( current , last + FRAME ) >= 0 ) { current = last + HALF_FRAME ; checkStatePlaying ( ) ; } }
Update play mode routine .
3,405
private void checkStatePlaying ( ) { if ( ! reverse ) { if ( repeat ) { state = AnimState . PLAYING ; current = first ; } else { state = AnimState . FINISHED ; } } else { state = AnimState . REVERSING ; } }
Check state in playing case .
3,406
private void updateReversing ( double extrp ) { current -= speed * extrp ; if ( Double . compare ( current , first ) <= 0 ) { current = first ; if ( repeat ) { state = AnimState . PLAYING ; current += 1.0 ; } else { state = AnimState . FINISHED ; } } }
Update in reverse mode routine .
3,407
public double getMovementCost ( Pathfindable pathfindable , int tx , int ty ) { return mapPath . getCost ( pathfindable , tx , ty ) ; }
Get the cost to move through a given location .
3,408
private boolean isValidLocation ( Pathfindable mover , int stx , int sty , int dtx , int dty , boolean ignoreRef ) { boolean invalid = dtx < 0 || dty < 0 || dtx >= map . getInTileWidth ( ) || dty >= map . getInTileHeight ( ) ; if ( ! invalid && ( stx != dtx || sty != dty ) ) { invalid = mapPath . isBlocked ( mover , dtx , dty , ignoreRef ) ; } return ! invalid ; }
Check if a given location is valid for the supplied mover .
3,409
private int updateNeighbour ( Pathfindable mover , int dtx , int dty , Node current , int xp , int yp , int maxDepth ) { int nextDepth = maxDepth ; final double nextStepCost = current . getCost ( ) + getMovementCost ( mover , current . getX ( ) , current . getY ( ) ) ; final Node neighbour = nodes [ yp ] [ xp ] ; if ( nextStepCost < neighbour . getCost ( ) ) { open . remove ( neighbour ) ; closed . remove ( neighbour ) ; } if ( ! open . contains ( neighbour ) && ! closed . contains ( neighbour ) ) { neighbour . setCost ( nextStepCost ) ; neighbour . setHeuristic ( getHeuristicCost ( xp , yp , dtx , dty ) ) ; nextDepth = Math . max ( maxDepth , neighbour . setParent ( current ) ) ; open . add ( neighbour ) ; } return nextDepth ; }
Update the current neighbor on search .
3,410
public static int getTransparency ( Transparency transparency ) { Check . notNull ( transparency ) ; final int value ; if ( Transparency . OPAQUE == transparency ) { value = java . awt . Transparency . OPAQUE ; } else if ( Transparency . BITMASK == transparency ) { value = java . awt . Transparency . BITMASK ; } else if ( Transparency . TRANSLUCENT == transparency ) { value = java . awt . Transparency . TRANSLUCENT ; } else { throw new LionEngineException ( transparency ) ; } return value ; }
Get the image transparency equivalence .
3,411
public static BufferedImage getImage ( InputStream input ) throws IOException { final BufferedImage buffer = ImageIO . read ( input ) ; if ( buffer == null ) { throw new IOException ( "Invalid image !" ) ; } return copyImage ( buffer ) ; }
Get an image from an input stream .
3,412
public static void saveImage ( BufferedImage image , OutputStream output ) throws IOException { ImageIO . write ( image , "png" , output ) ; }
Save image to output stream .
3,413
public static BufferedImage applyMask ( BufferedImage image , int rgba ) { final BufferedImage mask = copyImage ( image ) ; final int height = mask . getHeight ( ) ; final int width = mask . getWidth ( ) ; for ( int y = 0 ; y < height ; y ++ ) { for ( int x = 0 ; x < width ; x ++ ) { final int col = mask . getRGB ( x , y ) ; final int flag = 0x00_FF_FF_FF ; if ( col == rgba ) { mask . setRGB ( x , y , col & flag ) ; } } } return mask ; }
Apply a mask to an existing image .
3,414
public static BufferedImage rotate ( BufferedImage image , int angle ) { final int width = image . getWidth ( ) ; final int height = image . getHeight ( ) ; final int transparency = image . getColorModel ( ) . getTransparency ( ) ; final Rectangle rectangle = new Rectangle ( 0 , 0 , width , height ) ; rectangle . rotate ( angle ) ; final BufferedImage rotated = createImage ( rectangle . getWidth ( ) , rectangle . getHeight ( ) , transparency ) ; final Graphics2D g = rotated . createGraphics ( ) ; optimizeGraphicsSpeed ( g ) ; g . rotate ( Math . toRadians ( angle ) , rectangle . getWidth ( ) / 2.0 , rectangle . getHeight ( ) / 2.0 ) ; final double ox = rectangle . getWidth ( ) - ( double ) width ; final double oy = rectangle . getHeight ( ) - ( double ) height ; final double cos = UtilMath . cos ( angle ) ; final double sin = UtilMath . sin ( angle ) ; final double angleOffsetX = sin * ox + cos * oy ; final double angleOffsetY = - sin * oy + cos * ox ; g . drawImage ( image , null , ( int ) ( ( ox - angleOffsetX ) / 2.0 ) , ( int ) ( ( oy - angleOffsetY ) / 2.0 ) ) ; g . dispose ( ) ; return rotated ; }
Rotate an image with an angle in degree .
3,415
public static BufferedImage flipHorizontal ( BufferedImage image ) { final int width = image . getWidth ( ) ; final int height = image . getHeight ( ) ; final BufferedImage flipped = createImage ( width , height , image . getColorModel ( ) . getTransparency ( ) ) ; final Graphics2D g = flipped . createGraphics ( ) ; optimizeGraphicsSpeed ( g ) ; g . drawImage ( image , 0 , 0 , width , height , width , 0 , 0 , height , null ) ; g . dispose ( ) ; return flipped ; }
Apply an horizontal flip to the input image .
3,416
public static Cursor createHiddenCursor ( ) { final Toolkit toolkit = Toolkit . getDefaultToolkit ( ) ; final Dimension dim = toolkit . getBestCursorSize ( 1 , 1 ) ; final BufferedImage c = createImage ( Math . max ( 1 , dim . width ) , Math . max ( 1 , dim . height ) , java . awt . Transparency . BITMASK ) ; final BufferedImage buffer = applyMask ( c , Color . BLACK . getRGB ( ) ) ; return toolkit . createCustomCursor ( buffer , new Point ( 0 , 0 ) , "hiddenCursor" ) ; }
Create a hidden cursor .
3,417
public static void createBufferStrategy ( java . awt . Canvas component , GraphicsConfiguration conf ) { try { component . createBufferStrategy ( 2 , conf . getBufferCapabilities ( ) ) ; } catch ( final AWTException exception ) { Verbose . exception ( exception ) ; component . createBufferStrategy ( 1 ) ; } }
Create the buffer strategy using default capabilities .
3,418
public static void optimizeGraphicsQuality ( Graphics2D g ) { g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; g . setRenderingHint ( RenderingHints . KEY_ALPHA_INTERPOLATION , RenderingHints . VALUE_ALPHA_INTERPOLATION_QUALITY ) ; g . setRenderingHint ( RenderingHints . KEY_COLOR_RENDERING , RenderingHints . VALUE_COLOR_RENDER_QUALITY ) ; g . setRenderingHint ( RenderingHints . KEY_DITHERING , RenderingHints . VALUE_DITHER_ENABLE ) ; g . setRenderingHint ( RenderingHints . KEY_FRACTIONALMETRICS , RenderingHints . VALUE_FRACTIONALMETRICS_ON ) ; g . setRenderingHint ( RenderingHints . KEY_RENDERING , RenderingHints . VALUE_RENDER_QUALITY ) ; g . setRenderingHint ( RenderingHints . KEY_INTERPOLATION , RenderingHints . VALUE_INTERPOLATION_NEAREST_NEIGHBOR ) ; g . setRenderingHint ( RenderingHints . KEY_TEXT_ANTIALIASING , RenderingHints . VALUE_TEXT_ANTIALIAS_ON ) ; }
Enable all graphics improvement . May decrease overall performances .
3,419
public static void optimizeGraphicsSpeed ( Graphics2D g ) { g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_OFF ) ; g . setRenderingHint ( RenderingHints . KEY_ALPHA_INTERPOLATION , RenderingHints . VALUE_ALPHA_INTERPOLATION_SPEED ) ; g . setRenderingHint ( RenderingHints . KEY_COLOR_RENDERING , RenderingHints . VALUE_COLOR_RENDER_SPEED ) ; g . setRenderingHint ( RenderingHints . KEY_DITHERING , RenderingHints . VALUE_DITHER_DISABLE ) ; g . setRenderingHint ( RenderingHints . KEY_FRACTIONALMETRICS , RenderingHints . VALUE_FRACTIONALMETRICS_OFF ) ; g . setRenderingHint ( RenderingHints . KEY_RENDERING , RenderingHints . VALUE_RENDER_SPEED ) ; g . setRenderingHint ( RenderingHints . KEY_INTERPOLATION , RenderingHints . VALUE_INTERPOLATION_NEAREST_NEIGHBOR ) ; g . setRenderingHint ( RenderingHints . KEY_TEXT_ANTIALIASING , RenderingHints . VALUE_TEXT_ANTIALIAS_OFF ) ; }
Disable all graphics improvement . May increase overall performances .
3,420
public static boolean same ( String groupA , String groupB ) { final boolean result ; if ( groupA != null && groupB != null ) { result = groupA . equals ( groupB ) ; } else if ( groupA == null && groupB == null ) { result = true ; } else { result = false ; } return result ; }
Check if tiles groups are same .
3,421
public static TaskFuture start ( Config config , Class < ? extends Sequencable > sequenceClass , Object ... arguments ) { Check . notNull ( config ) ; Check . notNull ( sequenceClass ) ; Check . notNull ( arguments ) ; final Runnable runnable = ( ) -> handle ( config , sequenceClass , arguments ) ; final Thread thread = new Thread ( runnable , Constant . ENGINE_NAME ) ; final AtomicReference < Throwable > reference = new AtomicReference < > ( ) ; thread . setUncaughtExceptionHandler ( ( t , e ) -> { reference . set ( e ) ; Verbose . exception ( e ) ; Engine . terminate ( ) ; } ) ; thread . start ( ) ; return ( ) -> check ( thread , reference ) ; }
Start the loader with an initial sequence .
3,422
private static void handle ( Config config , Class < ? extends Sequencable > sequenceClass , Object ... arguments ) { final Screen screen = Graphics . createScreen ( config ) ; try { screen . start ( ) ; screen . awaitReady ( ) ; final Context context = new ContextWrapper ( screen ) ; Sequencable nextSequence = UtilSequence . create ( sequenceClass , context , arguments ) ; while ( nextSequence != null ) { final Sequencable sequence = nextSequence ; final String sequenceName = sequence . getClass ( ) . getName ( ) ; Verbose . info ( SEQUENCE_START , sequenceName ) ; sequence . start ( screen ) ; Verbose . info ( SEQUENCE_END , sequenceName ) ; nextSequence = sequence . getNextSequence ( ) ; sequence . onTerminated ( nextSequence != null ) ; } } finally { screen . dispose ( ) ; } }
Handle the sequence with its screen until no more sequence to run .
3,423
private static void check ( Thread thread , AtomicReference < Throwable > reference ) { try { thread . join ( ) ; } catch ( final InterruptedException exception ) { Thread . currentThread ( ) . interrupt ( ) ; throw new LionEngineException ( exception , ERROR_TASK_STOPPED ) ; } final Throwable throwable = reference . get ( ) ; if ( throwable != null ) { Engine . terminate ( ) ; if ( throwable instanceof LionEngineException ) { throw ( LionEngineException ) throwable ; } throw new LionEngineException ( throwable ) ; } }
Check thread execution by waiting its end and re - throw exception if has .
3,424
protected void decodeMessage ( byte type , byte from , byte dest , DataInputStream buffer ) throws IOException { final NetworkMessage message = decoder . getNetworkMessageFromType ( type ) ; if ( message != null ) { final int skip = 3 ; if ( buffer . skipBytes ( skip ) == skip ) { message . decode ( type , from , dest , buffer ) ; messagesIn . add ( message ) ; } } }
Decode a message from its type .
3,425
private static boolean isAnnotated ( Feature feature ) { for ( final Class < ? > current : feature . getClass ( ) . getInterfaces ( ) ) { if ( current . isAnnotationPresent ( FeatureInterface . class ) ) { return true ; } } return feature . getClass ( ) . isAnnotationPresent ( FeatureInterface . class ) ; }
Check if feature is annotated in its direct parents .
3,426
public < C extends Feature > C get ( Class < C > feature ) { final Feature found = typeToFeature . get ( feature ) ; if ( found != null ) { return feature . cast ( found ) ; } throw new LionEngineException ( ERROR_FEATURE_NOT_FOUND + feature . getName ( ) ) ; }
Get a feature from its class or interface .
3,427
private void checkTypeDepth ( Feature feature , Class < ? > current ) { for ( final Class < ? > type : current . getInterfaces ( ) ) { if ( type . isAnnotationPresent ( FeatureInterface . class ) ) { final Feature old ; if ( ( old = typeToFeature . put ( type . asSubclass ( Feature . class ) , feature ) ) != null ) { throw new LionEngineException ( ERROR_FEATURE_EXISTS + feature . getClass ( ) + AS + type + WITH + old . getClass ( ) ) ; } checkTypeDepth ( feature , type ) ; } } final Class < ? > parent = current . getSuperclass ( ) ; if ( parent != null ) { checkTypeDepth ( feature , parent ) ; } }
Check annotated features parent recursively .
3,428
public int increase ( double extrp , int increase ) { final int current = getCurrent ( ) ; final double increased = current + increase * extrp ; set ( increased ) ; if ( increased > max ) { return max - current ; } return increase ; }
Increase current value . The current value will not exceed the maximum .
3,429
public int decrease ( double extrp , int decrease ) { final int remain = getCurrent ( ) ; final double decreased = remain - decrease * extrp ; set ( decreased ) ; if ( decreased < 0 ) { return remain ; } return decrease ; }
Decrease current value . The current value will not be lower than 0 .
3,430
private void set ( double value ) { cur = value ; if ( ! overMax && cur > max ) { cur = max ; } if ( cur < Alterable . MIN ) { cur = Alterable . MIN ; } }
Set current value . The current value will be fixed between 0 and the maximum .
3,431
static void reduceTransitive ( Collection < GroupTransition > transitive ) { final Collection < GroupTransition > localChecked = new ArrayList < > ( transitive . size ( ) ) ; final Collection < GroupTransition > toRemove = new ArrayList < > ( ) ; final Iterator < GroupTransition > iterator = transitive . iterator ( ) ; GroupTransition first = iterator . next ( ) ; while ( iterator . hasNext ( ) ) { final GroupTransition current = iterator . next ( ) ; localChecked . add ( current ) ; if ( current . getOut ( ) . equals ( first . getOut ( ) ) ) { toRemove . addAll ( localChecked ) ; localChecked . clear ( ) ; if ( iterator . hasNext ( ) ) { first = iterator . next ( ) ; } } } transitive . removeAll ( toRemove ) ; toRemove . clear ( ) ; }
Reduce transitive by removing internal cycles .
3,432
public void load ( ) { transitives . clear ( ) ; for ( final String groupIn : mapGroup . getGroups ( ) ) { for ( final String groupOut : mapGroup . getGroups ( ) ) { if ( ! groupIn . equals ( groupOut ) ) { findTransitives ( groupIn , groupOut ) ; } } } }
Load transitive data .
3,433
public Collection < GroupTransition > getTransitives ( String groupIn , String groupOut ) { final GroupTransition transition = new GroupTransition ( groupIn , groupOut ) ; if ( ! transitives . containsKey ( transition ) ) { return Collections . emptyList ( ) ; } return transitives . get ( transition ) ; }
Get the transitive groups list to reach a group from another .
3,434
public Collection < TileRef > getDirectTransitiveTiles ( Transition transition ) { final String groupOut = transition . getOut ( ) ; final Collection < GroupTransition > currentTransitives = getTransitives ( transition . getIn ( ) , groupOut ) ; if ( currentTransitives . size ( ) != 2 ) { return Collections . emptySet ( ) ; } final GroupTransition groupTransition = currentTransitives . iterator ( ) . next ( ) ; return mapTransition . getTiles ( new Transition ( transition . getType ( ) , groupTransition . getOut ( ) , groupOut ) ) ; }
Get the associated tiles with the direct transitive transition .
3,435
private void findTransitives ( String groupIn , String groupOut ) { final GroupTransition groupTransition = new GroupTransition ( groupIn , groupOut ) ; if ( ! transitives . containsKey ( groupTransition ) ) { transitives . put ( groupTransition , new ArrayList < GroupTransition > ( ) ) ; } final Collection < GroupTransition > localChecked = new HashSet < > ( ) ; final Collection < GroupTransition > found = transitives . get ( groupTransition ) ; final Deque < GroupTransition > collect = new ArrayDeque < > ( ) ; checkTransitive ( groupIn , groupIn , groupOut , localChecked , collect , true ) ; if ( collect . size ( ) >= MINIMUM_TRANSITION_FOR_CYCLE ) { reduceTransitive ( collect ) ; } found . addAll ( collect ) ; localChecked . clear ( ) ; }
Find transitive groups .
3,436
private boolean checkTransitive ( String groupStart , String groupIn , String groupEnd , Collection < GroupTransition > localChecked , Deque < GroupTransition > found , boolean first ) { boolean ok = false ; for ( final String groupOut : mapGroup . getGroups ( ) ) { final GroupTransition transitive = new GroupTransition ( groupIn , groupOut ) ; final boolean firstOrNext = first && groupIn . equals ( groupStart ) || ! first && ! groupIn . equals ( groupOut ) ; if ( firstOrNext && ! localChecked . contains ( transitive ) ) { localChecked . add ( transitive ) ; final boolean nextFirst = countTransitions ( groupStart , transitive , groupEnd , found , first ) ; if ( groupOut . equals ( groupEnd ) ) { ok = true ; } else { checkTransitive ( groupStart , groupOut , groupEnd , localChecked , found , nextFirst ) ; } } } return ok ; }
Check transitive groups .
3,437
private boolean countTransitions ( String groupStart , GroupTransition transitive , String groupEnd , Deque < GroupTransition > found , boolean first ) { final String groupIn = transitive . getIn ( ) ; final String groupOut = transitive . getOut ( ) ; int count = 0 ; for ( final Transition transition : mapTransition . getTransitions ( ) ) { final boolean valid = groupIn . equals ( transition . getIn ( ) ) && groupOut . equals ( transition . getOut ( ) ) ; if ( valid && ! groupOut . equals ( groupStart ) && ! groupIn . equals ( groupEnd ) ) { count ++ ; } } if ( count >= VALID_TRANSITIONS && ( found . isEmpty ( ) || found . getLast ( ) . getOut ( ) . equals ( groupIn ) ) ) { found . add ( transitive ) ; return false ; } return first ; }
Count the number of transitions and check if pass is still first or not . Add valid transitive to list .
3,438
public boolean readBoolean ( boolean defaultValue , String attribute ) { return Boolean . parseBoolean ( getValue ( String . valueOf ( defaultValue ) , attribute ) ) ; }
Read a boolean .
3,439
public int readInteger ( int defaultValue , String attribute ) { return Integer . parseInt ( getValue ( String . valueOf ( defaultValue ) , attribute ) ) ; }
Read an integer .
3,440
public long readLong ( long defaultValue , String attribute ) { return Long . parseLong ( getValue ( String . valueOf ( defaultValue ) , attribute ) ) ; }
Read a long .
3,441
public float readFloat ( float defaultValue , String attribute ) { return Float . parseFloat ( getValue ( String . valueOf ( defaultValue ) , attribute ) ) ; }
Read a float .
3,442
public double readDouble ( double defaultValue , String attribute ) { return Double . parseDouble ( getValue ( String . valueOf ( defaultValue ) , attribute ) ) ; }
Read a double .
3,443
public Map < String , String > getAttributes ( ) { final NamedNodeMap map = root . getAttributes ( ) ; final int length = map . getLength ( ) ; final Map < String , String > attributes = new HashMap < > ( length ) ; for ( int i = 0 ; i < length ; i ++ ) { final Node node = map . item ( i ) ; attributes . put ( node . getNodeName ( ) , node . getNodeValue ( ) ) ; } return attributes ; }
Get all attributes .
3,444
public boolean hasChild ( String child ) { final NodeList list = root . getChildNodes ( ) ; for ( int i = 0 ; i < list . getLength ( ) ; i ++ ) { final Node node = list . item ( i ) ; if ( node . getNodeName ( ) . equals ( child ) ) { return true ; } } return false ; }
Check if node has the following child .
3,445
void normalize ( String expression ) { final XPath xPath = XPathFactory . newInstance ( ) . newXPath ( ) ; try { final NodeList nodeList = ( NodeList ) xPath . evaluate ( expression , document , XPathConstants . NODESET ) ; for ( int i = 0 ; i < nodeList . getLength ( ) ; ++ i ) { final Node node = nodeList . item ( i ) ; node . getParentNode ( ) . removeChild ( node ) ; } } catch ( final XPathExpressionException exception ) { Verbose . exception ( exception ) ; } }
Normalize document .
3,446
private void write ( String attribute , String content ) { Check . notNull ( attribute ) ; Check . notNull ( content ) ; try { root . setAttribute ( attribute , content ) ; } catch ( final DOMException exception ) { throw new LionEngineException ( exception , ERROR_WRITE_ATTRIBUTE + attribute + ERROR_WRITE_CONTENT + content ) ; } }
Write a data to the root .
3,447
public void save ( Media media ) { Check . notNull ( media ) ; try ( OutputStream output = media . getOutputStream ( ) ) { final Transformer transformer = DocumentFactory . createTransformer ( ) ; normalize ( NORMALIZE ) ; writeString ( Constant . XML_HEADER , Constant . ENGINE_WEBSITE ) ; final DOMSource source = new DOMSource ( root ) ; final StreamResult result = new StreamResult ( output ) ; final String yes = "yes" ; transformer . setOutputProperty ( OutputKeys . INDENT , yes ) ; transformer . setOutputProperty ( OutputKeys . STANDALONE , yes ) ; transformer . setOutputProperty ( PROPERTY_INDENT , "4" ) ; transformer . transform ( source , result ) ; } catch ( final TransformerException | IOException exception ) { throw new LionEngineException ( exception , media , ERROR_WRITING ) ; } }
Save an XML tree to a file .
3,448
public Xml createChild ( String child ) { Check . notNull ( child ) ; final Element element = document . createElement ( child ) ; root . appendChild ( element ) ; return new Xml ( document , element ) ; }
Create a child node .
3,449
public void add ( XmlReader node ) { Check . notNull ( node ) ; final Element element = node . getElement ( ) ; document . adoptNode ( element ) ; root . appendChild ( element ) ; }
Add a child node .
3,450
public void removeChildren ( String children ) { getChildren ( children ) . stream ( ) . map ( Xml :: getElement ) . forEach ( root :: removeChild ) ; }
Remove all children .
3,451
public Xml getChild ( String name ) { Check . notNull ( name ) ; final NodeList list = root . getChildNodes ( ) ; for ( int i = 0 ; i < list . getLength ( ) ; i ++ ) { final Node node = list . item ( i ) ; if ( node instanceof Element && node . getNodeName ( ) . equals ( name ) ) { return new Xml ( document , ( Element ) node ) ; } } throw new LionEngineException ( ERROR_NODE + name ) ; }
Get a child node from its name .
3,452
public Collection < Xml > getChildren ( String name ) { Check . notNull ( name ) ; final Collection < Xml > nodes = new ArrayList < > ( 1 ) ; final NodeList list = root . getChildNodes ( ) ; for ( int i = 0 ; i < list . getLength ( ) ; i ++ ) { final Node node = list . item ( i ) ; if ( name . equals ( node . getNodeName ( ) ) ) { nodes . add ( new Xml ( document , ( Element ) node ) ) ; } } return nodes ; }
Get the list of all children with this name .
3,453
public Collection < Xml > getChildren ( ) { final Collection < Xml > nodes = new ArrayList < > ( 1 ) ; final NodeList list = root . getChildNodes ( ) ; for ( int i = 0 ; i < list . getLength ( ) ; i ++ ) { final Node node = list . item ( i ) ; if ( node instanceof Element ) { nodes . add ( new Xml ( document , ( Element ) node ) ) ; } } return nodes ; }
Get list of all children .
3,454
@ SuppressWarnings ( "unchecked" ) public static < T > T createReduce ( Class < T > type , Object ... params ) throws NoSuchMethodException { Check . notNull ( type ) ; Check . notNull ( params ) ; final Class < ? > [ ] paramTypes = getParamTypes ( params ) ; final Queue < Class < ? > > typesQueue = new ArrayDeque < > ( Arrays . asList ( paramTypes ) ) ; final Queue < Object > paramsQueue = new ArrayDeque < > ( Arrays . asList ( params ) ) ; boolean stop = false ; while ( ! stop ) { final int typesLength = typesQueue . size ( ) ; final Class < ? > [ ] typesArray = typesQueue . toArray ( new Class < ? > [ typesLength ] ) ; for ( final Constructor < ? > constructor : type . getDeclaredConstructors ( ) ) { final Class < ? > [ ] constructorTypes = constructor . getParameterTypes ( ) ; if ( constructorTypes . length == typesLength && ( typesLength == 0 || hasCompatibleConstructor ( typesArray , constructorTypes ) ) ) { return create ( type , ( Constructor < T > ) constructor , paramsQueue . toArray ( ) ) ; } } stop = paramsQueue . isEmpty ( ) ; typesQueue . poll ( ) ; paramsQueue . poll ( ) ; } throw new NoSuchMethodException ( ERROR_NO_CONSTRUCTOR_COMPATIBLE + type . getName ( ) + ERROR_WITH + Arrays . asList ( paramTypes ) ) ; }
Create a class instance with its parameters . Use a compatible constructor with the following parameters reducing parameter types array as a queue until empty in order to find a constructor .
3,455
@ SuppressWarnings ( "unchecked" ) public static < T > Constructor < T > getCompatibleConstructor ( Class < T > type , Class < ? > ... paramTypes ) throws NoSuchMethodException { Check . notNull ( type ) ; Check . notNull ( paramTypes ) ; for ( final Constructor < ? > current : type . getDeclaredConstructors ( ) ) { final Class < ? > [ ] constructorTypes = current . getParameterTypes ( ) ; if ( constructorTypes . length == paramTypes . length && ( paramTypes . length == 0 || hasCompatibleConstructor ( paramTypes , constructorTypes ) ) ) { return ( Constructor < T > ) current ; } } throw new NoSuchMethodException ( ERROR_NO_CONSTRUCTOR_COMPATIBLE + type . getName ( ) + ERROR_WITH + Arrays . asList ( paramTypes ) ) ; }
Get a compatible constructor with the following parameters .
3,456
public static < T > T getMethod ( Object object , String name , Object ... params ) { Check . notNull ( object ) ; Check . notNull ( name ) ; Check . notNull ( params ) ; try { final Class < ? > clazz = getClass ( object ) ; final Method method = clazz . getDeclaredMethod ( name , getParamTypes ( params ) ) ; setAccessible ( method , true ) ; @ SuppressWarnings ( "unchecked" ) final T value = ( T ) method . invoke ( object , params ) ; return value ; } catch ( final NoSuchMethodException | InvocationTargetException | IllegalAccessException exception ) { if ( exception . getCause ( ) instanceof LionEngineException ) { throw ( LionEngineException ) exception . getCause ( ) ; } throw new LionEngineException ( exception , ERROR_METHOD + name ) ; } }
Get method and call its return value with parameters .
3,457
public static < T > T getField ( Object object , String name ) { Check . notNull ( object ) ; Check . notNull ( name ) ; try { final Class < ? > clazz = getClass ( object ) ; final Field field = getDeclaredFieldSuper ( clazz , name ) ; setAccessible ( field , true ) ; @ SuppressWarnings ( "unchecked" ) final T value = ( T ) field . get ( object ) ; return value ; } catch ( final NoSuchFieldException | IllegalAccessException exception ) { throw new LionEngineException ( exception , ERROR_FIELD + name ) ; } }
Get the field by reflection .
3,458
public static void setAccessible ( AccessibleObject object , boolean accessible ) { Check . notNull ( object ) ; if ( object . isAccessible ( ) != accessible ) { java . security . AccessController . doPrivileged ( ( PrivilegedAction < Void > ) ( ) -> { object . setAccessible ( accessible ) ; return null ; } ) ; } }
Set the object accessibility with an access controller .
3,459
public static Collection < Class < ? > > getInterfaces ( Class < ? > object , Class < ? > base ) { Check . notNull ( object ) ; Check . notNull ( base ) ; final Collection < Class < ? > > interfaces = new ArrayList < > ( ) ; Class < ? > current = object ; while ( current != null ) { final Deque < Class < ? > > currents = new ArrayDeque < > ( filterInterfaces ( current , base ) ) ; final Deque < Class < ? > > nexts = new ArrayDeque < > ( ) ; while ( ! currents . isEmpty ( ) ) { nexts . clear ( ) ; interfaces . addAll ( currents ) ; checkInterfaces ( base , currents , nexts ) ; currents . clear ( ) ; currents . addAll ( nexts ) ; nexts . clear ( ) ; } current = current . getSuperclass ( ) ; } return interfaces ; }
Get all declared interfaces from object .
3,460
private static Field getDeclaredFieldSuper ( Class < ? > clazz , String name ) throws NoSuchFieldException { try { return clazz . getDeclaredField ( name ) ; } catch ( final NoSuchFieldException exception ) { if ( clazz . getSuperclass ( ) == null ) { throw exception ; } return getDeclaredFieldSuper ( clazz . getSuperclass ( ) , name ) ; } }
Get the field by reflection searching in super class if needed .
3,461
private static void checkInterfaces ( Class < ? > base , Deque < Class < ? > > currents , Deque < Class < ? > > nexts ) { currents . stream ( ) . map ( Class :: getInterfaces ) . forEach ( types -> Arrays . asList ( types ) . stream ( ) . filter ( type -> base . isAssignableFrom ( type ) && ! type . equals ( base ) ) . forEach ( nexts :: add ) ) ; }
Store all declared valid interfaces into next .
3,462
private static boolean hasCompatibleConstructor ( Class < ? > [ ] paramTypes , Class < ? > [ ] constructorTypes ) { for ( int i = 0 ; i < paramTypes . length ; i ++ ) { if ( constructorTypes [ i ] . isAssignableFrom ( paramTypes [ i ] ) ) { return true ; } } return false ; }
Check if there is a compatible constructor for the types .
3,463
private static Media getMediaDpi ( Media media ) { Check . notNull ( media ) ; final DpiType current = dpi ; if ( current == null || current == DpiType . MDPI ) { return media ; } return getClosestDpi ( current , media ) ; }
Get the associated DPI media .
3,464
private static Media getClosestDpi ( DpiType current , Media media ) { final Media mediaDpi = Medias . getWithSuffix ( media , current . name ( ) . toLowerCase ( Locale . ENGLISH ) ) ; final Media closest ; if ( mediaDpi . exists ( ) ) { closest = mediaDpi ; } else if ( current . ordinal ( ) > 0 ) { closest = getClosestDpi ( DpiType . values ( ) [ current . ordinal ( ) - 1 ] , media ) ; } else { closest = media ; } return closest ; }
Get the associated DPI media closest to required DPI .
3,465
public static synchronized Media create ( String ... path ) { if ( loader . isPresent ( ) ) { return factoryMedia . create ( separator , loader . get ( ) , path ) ; } return factoryMedia . create ( separator , resourcesDir , path ) ; }
Create a media .
3,466
public static synchronized void setResourcesDirectory ( String directory ) { if ( directory == null ) { resourcesDir = Constant . EMPTY_STRING + getSeparator ( ) ; } else { resourcesDir = directory + getSeparator ( ) ; } loader = Optional . empty ( ) ; }
Define resources directory . Root for all medias . Disable the load from JAR .
3,467
public static synchronized Media getWithSuffix ( Media media , String suffix ) { Check . notNull ( media ) ; Check . notNull ( suffix ) ; final String path = media . getPath ( ) ; final int dotIndex = path . lastIndexOf ( Constant . DOT ) ; if ( dotIndex > - 1 ) { return Medias . create ( path . substring ( 0 , dotIndex ) + Constant . UNDERSCORE + suffix + path . substring ( dotIndex ) ) ; } return Medias . create ( path + Constant . UNDERSCORE + suffix ) ; }
Get the media with an additional suffix just before the dot of the extension if has .
3,468
public static synchronized File getJarResources ( ) { if ( ! loader . isPresent ( ) ) { throw new LionEngineException ( JAR_LOADER_ERROR ) ; } final Media media = Medias . create ( Constant . EMPTY_STRING ) ; final String path = media . getFile ( ) . getPath ( ) . replace ( File . separator , Constant . SLASH ) ; final String prefix = loader . get ( ) . getPackage ( ) . getName ( ) . replace ( Constant . DOT , Constant . SLASH ) ; final int jarSeparatorIndex = path . indexOf ( prefix ) ; final String jar = path . substring ( 0 , jarSeparatorIndex ) ; return new File ( jar ) ; }
Get the running JAR resources . Load from JAR must be enabled .
3,469
private void unSelectAll ( ) { final int n = selected . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { selected . get ( i ) . onSelection ( false ) ; } selected . clear ( ) ; }
Unselect all elements .
3,470
private static Charset getCharset ( String charset ) { try { return Charset . forName ( charset ) ; } catch ( final UnsupportedCharsetException exception ) { Verbose . exception ( exception ) ; return Charset . defaultCharset ( ) ; } }
Get the charset .
3,471
public final ByteArrayOutputStream encode ( ) throws IOException { final ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; buffer . write ( type ) ; buffer . write ( clientId ) ; buffer . write ( clientDestId ) ; encode ( buffer ) ; return buffer ; }
Encode the message .
3,472
public final void decode ( byte type , byte from , byte dest , DataInputStream buffer ) throws IOException { this . type = type ; clientId = from ; clientDestId = dest ; decode ( buffer ) ; }
Decode the message from the data .
3,473
void robotMove ( int nx , int ny ) { oldX = x ; oldY = y ; x = nx ; y = ny ; wx = nx ; wy = ny ; mx = x - oldX ; my = y - oldY ; moved = true ; }
Move mouse with robot .
3,474
void robotTeleport ( int nx , int ny ) { oldX = nx ; oldY = ny ; x = nx ; y = ny ; wx = nx ; wy = ny ; mx = 0 ; my = 0 ; moved = false ; }
Teleport mouse with robot .
3,475
void update ( ) { mx = x - oldX ; my = y - oldY ; oldX = x ; oldY = y ; }
Update movement record .
3,476
public static List < ActionRef > imports ( Configurer configurer ) { Check . notNull ( configurer ) ; return imports ( configurer . getRoot ( ) ) ; }
Create the action data from configurer .
3,477
public static List < ActionRef > imports ( Xml root ) { Check . notNull ( root ) ; if ( ! root . hasChild ( NODE_ACTIONS ) ) { return Collections . emptyList ( ) ; } final Xml node = root . getChild ( NODE_ACTIONS ) ; return getRefs ( node ) ; }
Create the action data from node .
3,478
public static Xml exports ( Collection < ActionRef > actions ) { Check . notNull ( actions ) ; final Xml node = new Xml ( NODE_ACTIONS ) ; for ( final ActionRef action : actions ) { final Xml nodeAction = node . createChild ( NODE_ACTION ) ; nodeAction . writeString ( ATT_PATH , action . getPath ( ) ) ; if ( action . hasCancel ( ) ) { nodeAction . writeBoolean ( ATT_CANCEL , true ) ; } for ( final ActionRef ref : action . getRefs ( ) ) { exports ( nodeAction , ref ) ; } } return node ; }
Export the action node from config .
3,479
private static List < ActionRef > getRefs ( Xml node ) { final Collection < Xml > children = node . getChildren ( NODE_ACTION ) ; final List < ActionRef > actions = new ArrayList < > ( children . size ( ) ) ; for ( final Xml action : children ) { final String path = action . readString ( ATT_PATH ) ; final boolean cancel = action . readBoolean ( false , ATT_CANCEL ) ; actions . add ( new ActionRef ( path , cancel , getRefs ( action ) ) ) ; } return actions ; }
Get all actions and their references .
3,480
private static void exports ( Xml node , ActionRef action ) { final Xml nodeAction = node . createChild ( NODE_ACTION ) ; nodeAction . writeString ( ATT_PATH , action . getPath ( ) ) ; for ( final ActionRef ref : action . getRefs ( ) ) { exports ( nodeAction , ref ) ; } }
Export the action .
3,481
public void keyPressed ( KeyEvent event ) { lastKeyName = event . getName ( ) ; lastCode = Integer . valueOf ( event . getCode ( ) ) ; if ( ! keys . contains ( lastCode ) ) { keys . add ( lastCode ) ; } }
Notify key pressed .
3,482
public void keyReleased ( KeyEvent event ) { lastKeyName = EMPTY_KEY_NAME ; lastCode = NO_KEY_CODE ; final Integer key = Integer . valueOf ( event . getCode ( ) ) ; keys . remove ( key ) ; pressed . remove ( key ) ; }
Notify key released .
3,483
protected void addMessage ( String message ) { messages . add ( message ) ; messageCount ++ ; if ( messageCount > messagesQueueMax ) { messages . remove ( ) ; messageCount -- ; } }
Add a new message .
3,484
private void sendValidatedMessage ( ) { final String msg = message . toString ( ) ; if ( canSendMessage ( msg ) ) { addNetworkMessage ( new NetworkMessageChat ( type , getClientId ( ) . byteValue ( ) , msg ) ) ; } message . delete ( 0 , message . length ( ) ) ; }
Send validated message .
3,485
public boolean includes ( double value ) { return Double . compare ( value , min ) >= 0 && Double . compare ( value , max ) <= 0 ; }
Check if value is inside range min and max included .
3,486
public static Xml exports ( SizeConfig config ) { Check . notNull ( config ) ; final Xml node = new Xml ( NODE_SIZE ) ; node . writeInteger ( ATT_WIDTH , config . getWidth ( ) ) ; node . writeInteger ( ATT_HEIGHT , config . getHeight ( ) ) ; return node ; }
Export the size node from data .
3,487
private void addPoint ( Point point , Collidable collidable ) { final Integer group = collidable . getGroup ( ) ; if ( ! collidables . containsKey ( group ) ) { collidables . put ( group , new HashMap < Point , Set < Collidable > > ( ) ) ; } final Map < Point , Set < Collidable > > elements = collidables . get ( group ) ; if ( ! elements . containsKey ( point ) ) { elements . put ( point , new HashSet < Collidable > ( ) ) ; } elements . get ( point ) . add ( collidable ) ; }
Add point . Create empty list of not existing .
3,488
private void checkGroup ( Entry < Point , Set < Collidable > > current ) { final Set < Collidable > elements = current . getValue ( ) ; for ( final Collidable objectA : elements ) { checkOthers ( objectA , current ) ; } }
Check elements in group .
3,489
private void checkPoint ( Collidable objectA , Map < Point , Set < Collidable > > acceptedElements , Point point ) { final Set < Collidable > others = acceptedElements . get ( point ) ; for ( final Collidable objectB : others ) { if ( objectA != objectB ) { final List < Collision > collisions = objectA . collide ( objectB ) ; for ( final Collision collision : collisions ) { toNotify . add ( new Collided ( objectA , objectB , collision ) ) ; } } } }
Check others element at specified point .
3,490
private void addPoints ( int minX , int minY , int maxX , int maxY , Collidable collidable ) { addPoint ( new Point ( minX , minY ) , collidable ) ; if ( minX != maxX && minY == maxY ) { addPoint ( new Point ( maxX , minY ) , collidable ) ; } else if ( minX == maxX && minY != maxY ) { addPoint ( new Point ( minX , maxY ) , collidable ) ; } else if ( minX != maxX ) { addPoint ( new Point ( minX , maxY ) , collidable ) ; addPoint ( new Point ( maxX , minY ) , collidable ) ; addPoint ( new Point ( maxX , maxY ) , collidable ) ; } }
Add point and adjacent points depending of the collidable max collision size .
3,491
protected void actionGoingToResources ( ) { if ( checker . canExtract ( ) ) { for ( final ExtractorListener listener : listeners ) { listener . notifyStartExtraction ( resourceType , resourceLocation ) ; } state = ExtractorState . EXTRACTING ; } }
Action called from update extraction in goto resource state .
3,492
protected void actionExtracting ( double extrp ) { if ( extractable == null || extractable . getResourceQuantity ( ) > 0 ) { if ( extractable != null ) { progress += Math . min ( extractable . getResourceQuantity ( ) , speed * extrp ) ; } else { progress += speed * extrp ; } final int curProgress = Math . min ( ( int ) Math . floor ( progress ) , extractionCapacity ) ; if ( curProgress > lastProgress ) { extract ( curProgress ) ; } } }
Action called from update extraction in extract state .
3,493
protected void actionGoingToWarehouse ( ) { if ( checker . canCarry ( ) ) { for ( final ExtractorListener listener : listeners ) { listener . notifyStartDropOff ( resourceType , lastProgress ) ; } speed = dropOffPerSecond / rate . getAsInt ( ) ; state = ExtractorState . DROPOFF ; } }
Action called from update extraction in goto warehouse state .
3,494
protected void actionDropingOff ( double extrp ) { progress -= speed * extrp ; final int curProgress = ( int ) Math . floor ( progress ) ; if ( curProgress <= 0 ) { for ( final ExtractorListener listener : listeners ) { listener . notifyDroppedOff ( resourceType , lastProgress ) ; } startExtraction ( ) ; } }
Action called from update extraction in drop off state .
3,495
private void extract ( int curProgress ) { if ( extractable != null ) { extractable . extractResource ( curProgress - lastProgress ) ; } for ( final ExtractorListener listener : listeners ) { listener . notifyExtracted ( resourceType , curProgress ) ; } lastProgress = curProgress ; if ( curProgress >= extractionCapacity ) { progress = extractionCapacity ; lastProgress = extractionCapacity ; state = ExtractorState . GOTO_WAREHOUSE ; for ( final ExtractorListener listener : listeners ) { listener . notifyStartCarry ( resourceType , lastProgress ) ; } } }
Perform extraction .
3,496
public GeneratorParameter add ( Preference preference ) { preferences . add ( preference ) ; Collections . sort ( preferences ) ; return this ; }
Add a preference .
3,497
void setFilter ( Filter filter ) { this . filter = Optional . ofNullable ( filter ) . orElse ( FilterNone . INSTANCE ) ; transform = getTransform ( ) ; }
Set the filter to use .
3,498
void initResolution ( Resolution source ) { Check . notNull ( source ) ; setSystemCursorVisible ( cursorVisibility . booleanValue ( ) ) ; this . source = source ; screen . onSourceChanged ( source ) ; final int width = source . getWidth ( ) ; final int height = source . getHeight ( ) ; final Resolution output = config . getOutput ( ) ; if ( FilterNone . INSTANCE . equals ( filter ) && width == output . getWidth ( ) && height == output . getHeight ( ) ) { buf = null ; transform = null ; } else { buf = Graphics . createImageBuffer ( width , height ) ; transform = getTransform ( ) ; final Graphic gbuf = buf . createGraphic ( ) ; graphic . setGraphic ( gbuf . getGraphic ( ) ) ; } }
Initialize resolution .
3,499
void setSystemCursorVisible ( boolean visible ) { if ( screen == null ) { cursorVisibility = Boolean . valueOf ( visible ) ; } else { if ( visible ) { screen . showCursor ( ) ; } else { screen . hideCursor ( ) ; } } }
Set the system cursor visibility .