View source

class flaxen.Flaxen extends Engine

Available on all platforms

The core engine.

Flaxen blends an entity/component system with a Haxe-based game engine, powered by HaxePunk and Ash. The core of Flaxen is built over the HaxePunk engine, and maintains a reference to Ash.

Typically you will extend this class:

class MyFlaxenApp extends Flaxen
{
    public static function main()
    {
        new MyFlaxenApp();
    }

    override public function ready()
    {
        // Setup here...
        var entity:Entity = newEntity("player"); 
        ...
    }
}

But you may also instantiate it directly, with the caveat that HaxePunk is not fully initialized until Flaxen.getApp().ready returns true. (Needs to be tested)

class MyFlaxenApp
{
    public var f:Flaxen;
    public static function main()
    {
		    f = new Flaxen();
		    f.newActionQueue()
			    .waitForProperty(f.getApp(), "ready", true)
			    .call(ready);
    }

    public function ready()
    {
        // Setup here...
        var entity:Entity = f.newEntity("player"); 
        ...
    }
}

Flaxen responds to the following Haxe flags. These can be set with -DflagName or <haxeflag name="flagName"/>.

    console - Includes the HaxePunk console; press ` to open; be sure to include assets/console
   profiler - Includes the ProfileSystem; press P to log profile stats
forceBuffer - Forces software buffering when using CPP targets

Class Fields

static var actionQueuePrefix:String

The prefix put before automatically named entities holding action queues

static var applicationName:String

The entity name holding the Application component

static var entityPrefix:String

The prefix put before automatically named new entities

static var globalAudioName:String

The name of the entity holding the GlobalAudio component

static var markerPrefix:String

The prefix put before automatically named markers

static var markerToEntityPrefix:String

The prefix put before marker names when converting to entity names

static var profilerName:String

The name of the entity holding the ProfileStats component

static var tweenPrefix:String

The prefix put before automatically named entities holding tweens

static var wrapperPrefix:String

The prefix put before automatically named wrapped entities

Instance Fields

var ash:Engine

The Ash engine; access this for direct manipulation of entities in Ash; READ-ONLY

var baseHeight:Int

The base screen height; READ-ONLY

var baseWidth:Int

The base screen width; READ-ONLY

var layoutOffset:Position

The current layout offset; READ-ONLY

var layoutOrientation:Orientation

The current layout orientation; READ-ONLY

var options:FlaxenOptions

The options Flaxen was initialized with; READ-ONLY

function new(?optionsOrWidth:Dynamic, ?height:Int, ?fps:Int, ?fixed:Bool, ?smoothing:Bool, ?earlySystems:Array<Class<FlaxenSystem>>, ?lateSystems:Array<Class<FlaxenSystem>>):Void

Creates a new Flaxen instance. If subclassed, this should be called by super() in your subclass constructor. Flaxen can be configured with several arguments, or by use of a FlaxenOptions object. You can leave width/height as 0 to have the HaxePunk buffer match the window dimensions.

optionsOrWidth

Either a FlaxenOptions object (which invalidates the rest of the parameters) or the desired screen width

height

The desired screen width

fps

The desired frame rate, in frames-per-second; defaults to 60

fixed

Supply false for a variable framestep (the default), or true for a fixed framestep

smoothing

Supply true for pixel smoothing which is slower but smoother

earlySystems

Override the default early systems (ModeSystem)

lateSystems

Override the default late systems (ActionSystem, TweenSystem, RenderingSystem, AudioSystem)

function addComponent(ref:EntityRef, component:Dynamic, ?clazz:Class<Dynamic> = null, ?compulsory:Bool = true):Entity

Adds the component to the entity. This is essentially the same as Ash's Entity.add method, but it can accept string names for the entity reference, and tests for null components. On failure, returns null, or if compulsory throws an exception. This could be because you passed a string entity reference that failed lookup, or you supplied a null component or entity.

ref

An entity object, or the string name of such an object

component

The component instance to add

clazz

To force Ash to treat this component as having a different class, supply that class here (see ash.core.Entity.add()); defaults to null

compulsory

If true, throws exception instead of returning false

returns

The entity the component was added to, or null if entity could not be determined

function addComponents(ref:EntityRef, components:Array<Dynamic>):Entity

Adds multiple components to an entity. Throws exception if string entity ref lookup fails.

ref

An entity object, or the string name of such an object

components

An array of component instances

returns

The entity to which the components were added

function addDependent(parentRef:EntityRef, childRef:EntityRef):Void

Creates a lifecycle dependency between entities. When the parent entity is destroyed, all of its dependent children will be destroyed immediately after.

parentRef

An entity object representing the parent, or the string name of such an object

childRef

An entity object representing the dependent, or the string name of such an object

function addEntity(entity:Entity):Entity

Adds an free entity object to Ash. Throws an exception if the entity is null or an entity with the same name already exists in Ash.

entity

The entity object to add to Ash

returns

The same entity

function addLayout(layout:Layout):Layout

Registers a new layout. Make sure you set Layout.current to portrait or landscape to start.

name

The name of the Layout

returns

The Layout object supplied, right back atcha

function addSet(ref:EntityRef, setName:String):Entity

Installs/adds a set of components to the entity. The ComponentSet is specified by name and must have been previously defined by newComponentSet().

ref

An entity object, or the string name of such an object

setName

The name of a ComponentSet, previously defined by newComponentSet.

returns

The Entity manipulated

function addSystem(system:FlaxenSystem, ?group:FlaxenSystemGroup):Flaxen

Systems operate in the order that they are added to their FlaxenSystemGroup. Early systems process first, then user systems, then standard systems. Unless you have a good reason, you probably want to leave it in the Standard group. You can add your own or predefined systems this way.

  • TODO: Revisit system groups. I did it this way because I wasn't certain that Ash would process Systems with the same priority in the order they were added. If I verify this is the case, I can change this to a more robust priority model.

system

The FlaxenSystem to add

group

The FlaxenSystemGroup to add the system to, defaults to Standard

returns

Flaxen

function addSystems(systems:Array<Dynamic>, ?group:FlaxenSystemGroup):Void

Adds a bunch of FlaxenSystems at once to the system group specified.

systems

An array of FlaxenSystem instances

group

The FlaxenSystemGroup to add these systems to, defaults to Standard

function countEntities():Int

Counts all of the entities in the Ash system.

returns

The total number of entites in the Ash engine

function countNodes<T>(nodeClass:Class<T>):Int

Counts the nodes that match the supplied Node class

nodeClass

A class that extends Node, see ash.core.Node<TNode>

returns

The total number of entites matched by the node

function fluidResize():Void

Performs a fluid resize, which means it determines the optimal layout (tall/wide) based on the screen dimensions. It applies scaling as needed to fit the application onto the stage, and updates all layouts with their changed properties.

function fullScaleResize():Void

Same as the default HaxePunk resize handler The screen is stretched out to fill the stage

function getAllEntities():Array<Entity>

Returns an array of ALL entities in Ash.

returns

An array of all entities.

function getApp():Application

Returns the Application component. If it does not exist, it is created.

The application is a universal entity storing the current game mode, and whether or not this mode has been initialized. The application entity is protected from removal when transitioning.

See ModeSystem.

function getComponent<T>(ref:EntityRef, component:Class<T>, ?compulsory:Bool = true):T

Returns the component from an entity. The entity can be free, but if you pass the string name of an entity, it must exist in Ash. Throws exception if compulsory is true and entity name lookup fails or component not be found

ref

An entity object, or the string name of such an object

compulsory

Determines if an exception is thrown (true) or null is returned (false) upon any failure

returns

The component requested, or null if the component could not be found

function getComponentSet(name:String):ComponentSet

Returns a component set. Throws an exception if the set cannot be found.

setName

The name of a ComponentSet, previously defined by newComponentSet.

returns

The component set found

function getComponentSetKeys():Iterator<String>

Iterates over the component set names. For debugging.

returns

A String iterator of component set names.

function getEntities<T>(nodeClass:Class<T>):Array<Entity>

Returns an array of all entities that match the supplied node.

nodeClass

A class that extends Node, see ash.core.Node<TNode>

returns

An array of all entities matched by the node

function getEntity(name:String, ?compulsory:Bool = true):Entity

Looks up an entity by name, and returns it. If the name could looked up, throws an exception if compulsory, otherwise returns null.

ref

The string name of an entity object to look up

returns

The entity asked for, f the named entity exists in Ash, otherwise null

function getGlobalAudio():GlobalAudio

Returns the global audio object. Creates the object if it does not yet exist. Use it to set global volume, mute, or stop audio after a cutoff.

returns

The GlobalAudio object

function getLayout(name:String):Layout

Returns the Layout defined by the supplied name, or throws an exception if it could not be found.

name

The name of the Layout

returns

The matching Layout object

function getMouseCell(ref:EntityRef, rows:Int, cols:Int):{y:Int, x:Int}

Given an entity with an image that represents a grid, returns the cell coordinates being pointed at by the mouse, or null if the mouse position lies outside of the image.

ref

An entity object, or the string name of such an object

rows

The number of rows in the grid

cols

The number of columns in the grid

returns

An anonymous object {x,y} indicating the cell pointed at, or null if the entity is not pointed at

function getOneEntity<T>(nodeClass:Class<T>, ?compulsory:Bool = true):Entity

When expecting exactly one node, this returns the one entity matching the supplied node.

nodeClass

A class that extends Node, see ash.core.Node<TNode>

compulsory

If true, throws exception if no entities found or more than one found

returns

The matching entity, or any matching entity (arbtirary) if multiple match, or null if none match

function hasComponent<T>(ref:EntityRef, component:Class<T>):Bool

Returns true if the entity exists and has the indicated component. If you supply a string, the named entity must exist or it will throw an exception. However, if you supply an entity, it can be a free entity. Throws an exception if the string ref could not be looked up

ref

An entity object, or the string name of such an object

component

The class of a component, e.g. Position

returns

True if the entity contains the component indicated; otherwise returns false

function hasEntity(ref:EntityRef):Bool

Returns true if the supplied entity reference is in Ash's engine. It does a lookup in Ash by the name supplied (if the ref is a string) or the entity's name (if the ref is an entity). This will also return false if the entity is a "free entity".

ref

An entity object, or the string name of such an object

returns

True if the entity exists in the Ash engine, false if it's an name that can't be looked up or a free entity

function hasMarker(name:String):Bool

Returns true if a marker exists. See newMarker.

name

The marker name

returns

True if the marker exists otherwise false

function hitTest(ref:EntityRef, x:Float, y:Float):{yOffset:Float, xOffset:Float, width:Float, height:Float}

Entity hit test, does not currently respect the Scale component nor the ScaleFactor component. Returns an object with the x/y offset of the clickpoint and image dimensions, respective to the position. Returns null if the position does not fall within the entity.

ref

An entity object, or the string name of such an object

x

An absolute x position; in screen-space

y

An absolute y position; in screen-space

returns

An anonymous object {xOffset,yOffset,width,height} indicating the relative position and the entity dimensions; or null if x,y does not intersect with the object

function isPressed(ref:EntityRef, ?minAlpha:Float = 1.0):Bool

Rough button (or any item) click checker; does not handle layering or entity ordering An entity is pressed if the mouse is being clicked, the cursor is within the rectangular dimensions of the entity, and the entity has full alpha (or as specified).

ref

An entity object, or the string name of such an object

minAlpha

Ignores clicks if the Alpha of the entity is below this minimum; defaults to full alpha (off)

returns

True if the entity is being clicked on

function newActionQueue(?autoStart:Bool = true, ?name:String):ActionQueue

Creates a new ActionQueue puts it into a new Entity. See ActionQueue. This entity will be destroyed when the queue completes.

autoStart

If true (default), the queue will run immediately

name

An optional name or pattern; see newEntity for naming

returns

An ActionQueue instance; you can find the enclosing entity with getEntity(aq.name)

function newChildEntity(parentRef:EntityRef, childName:String):Entity

Creates a child entity and makes it dependent on the parent entity The parent may be specified by name or by passing the Entity itself.

parentRef

An entity object representing the parent, or the string name of such an object

childName

The name of the child, or a naming pattern; see newEntity for naming

returns

The new child entity

function newComponentSet(name:String):ComponentSet

Creates or replaces a new ComponentSet object, indexed by name Component sets are collections of steps that transform entities. Commonly, it is a way to add sets of components to entities. Steps can create new component instances, reuse shared components, inject components from other sets or entities, execute functions, or remove components.

See ComponentSet for details.

name

A unique name for the set.

returns

The component set

function newEntity(?name:String, ?addToAsh:Bool = true):Entity

Creates a new entity and (by default) adds it to the Ash engine.

If you do not provide a name for the entity, a unique name will be generated. (See ash.core.Entity.name.)

You may a include the "#" symbol in your name and it will be replaced with the number of entities that were previously created by this method. This pattern naming is useful for debugging; e.g., "ball#" will generate entities named ball0, ball1, ball2, etc.

You may pass false for addToAsh to make a "free" entity, which you can add later using addEntity.

name

A name or name pattern for the new entity (optional)

addToAsh

If true, adds the new entity to the Ash engine; otherwise, returns a free entity

function newLayout(name:String, portaitX:Float, portraitY:Float, landscapeX:Float, landscapeY:Float):Layout

function newMarker(?name:String):String

Generates a new named marker, if it doesn't already exist.

Markers are entities with no content, identified by a unique name. They can be used ad-hoc controls: systems can check for the existence of a marker as permission to do some behavior. Since markers are essentially just strings, you are advised to define them in constants.

All marker entities instances are distinguishable from other entities because they start with a marker prefix (see markerToEntityPrefix).

  • TODO: For processing options, add a static Marker instance to these entities.
name

An optional marker name; if one is not supplied, a name will be generated for you

returns

The marker name; if you did not supply a name, or if your name included a #, this is the actual name generated

function newSetEntity(setName:String, ?entityName:String, ?addToAsh:Bool = true):Entity

Convenience method, creating new entity and installing component set in one If a name is not provided, a unique one will be generated using the setName as a prefix.

setName

The name of a ComponentSet, previously defined by newComponentSet.

entityName

An optional name or pattern to assign to the new entity; see newEntity

returns

The entity created

function newSound(file:String, ?loop:Bool = false, ?volume:Float = 1, ?pan:Float = 0, ?offset:Float = 0):Entity

Creates a new Sound and puts it into a new Entity. See Sound. This entity will be destroyed when the tween completes.

  • TODO This has an inconsistent return. Modify Sound to include a name attribute, and return the Sound instance here.
file

The path to the sound asset; ex. "sound/beep.wav"

loop

If true, the sound loops continuously; defaults to false

volume

From 0 (mute) to 1 (default, full volume)

pan

From -1 (left pan) to 1 (right pan); defaults to 0 (center)

offset

The number of seconds from the start of the sound to skip; defaults to 0

returns

The enclosing Entity

function newTween(duration:Float, ?easing:EasingFunction, ?loop:LoopType, ?autoStart:Bool = true, ?name:String):Tween

Creates a new Tween and puts it into a new Entity. See Tween. This entity will be destroyed when the tween completes. The returned tween must be configured with what to tween using Tween.addTarget or Tween.to calls. For example, newTween(10).to(position, "x", 10);

duration

The duration of the tween in seconds

easing

An optional easing function; see Easing; defaults to Linear

loop

An optional loop type; see LoopType; defaults to None

autoStart

If true (default), the tween will begin immediately

name

An optional name or pattern; see new Entity for naming

returns

The Tween instance; you can find the enclosing entity with getEntity(tween.name)

function newWrapper(component:Dynamic, ?name:String, ?addToAsh:Bool = true):Entity

Creates an entity and adds the specified component to it. If name is not supplied, it will be given a wrapper prefix. By default, the entity is added to Ash.

component

The component instance to wrap into an entity.

name

An optional name or pattern; see newEntity for naming

addToAsh

If true, adds the new entity to the Ash engine; otherwise, returns a free entity

returns

The new entity

function nonScalingResize():Void

An alternate resizing algorithm. The screen is not scaled.

function ready():Void

Override this to start your game. This method is called by FlaxenScene when the Scene has initialized and is ready for user configuration. (That's you. You're the user.)

function removeComponent<T>(ref:EntityRef, component:Class<T>, ?compulsory:Bool = true):Bool

Removes the component from the entity. This is essentially the same as Ash's Entity.remove method, but it returns true/false, throws exceptions instead of returning false if compulsory is set, and can accept string names for the entity reference. Throws exception if compulsory and the component was not found in the entity, or the entity lookup failed.

ref

An entity object, or the string name of such an object

component

The component class to remove; note this is a class reference and not an instance reference

compulsory

If true, throws exception instead of returning false

returns

True if the component was removed, otherwise false

function removeDependents(ref:EntityRef):Void

Destroys all dependents of the entity. Does not remove the entity itself, just its dependents.

ref

An entity object, or the string name of such an object

function removeEntities<T>(?nodeClass:Class<T>):Int

Removes all entities that match the supplied node.

nodeClass

A class that extends Node, see ash.core.Node<TNode>

returns

The number of entities removed

function removeEntity(ref:EntityRef, ?compulsory:Bool = true):Bool

Looks up an entity and removes it from Ash.

ref

An entity object, or the string name of such an object

compulsory

If true (default), throws exception if ref does not reference a known Entity in Ash

returns

True if the ref was found and removed; otherwise false

function removeMarker(name:String):Void

Removes the named marker, if it exists. See newMarker.

name

The marker name

function removeSystemByClass<TSystem>(clazz:Class<TSystem>):Flaxen

Removes a system, based on Class name.

To remove a specific system instance, use ash.removeSystem.

clazz

The name of the system, e.g., MovementSystem

returns

Flaxen

function removeTransitionedEntities(?matching:String = null, ?excluding:String = null):Void

You can add a Transitional to an entity and specify a kind in it. This is a classification. You can then use this method to remove all entities having or lacking specific kind values.

var trans = new Transitional(Play, "fx");
e.add(trans);
removeTransitionedEntities("fx"); // remove all fx entities
matching

The name of the kind of entity you want to remove

excluding

The name of the kind of entity to exclude from this removal

function resetEntity(ref:EntityRef):Entity

Removes all components from an entity. The entity can be a free entity. Throws exception if the string ref could not be looked up.

ref

An entity object, or the string name of such an object

returns

The entity emptied

function resolveComponent<T>(ref:EntityRef, component:Class<T>, ?args:Array<Dynamic>):T

Ensures that the named entity exists and contains the specified component. If the named entity does not exist, it is created. If the component is lacking, it is created with the parameters specified. Regardless, the component is returned. Throws an exception if the ref or component is null.

ref

An entity object, or the string name of an entity you want to resolve

component

The name of a component class to resolve

args

An array of arguments to be passed to the component if it needs to be constructed

returns

The resolved component

function resolveEntity(name:String):Entity

If an entity with this name exists in Ash, returns that entity. Otherwise this adds a new, empty entity to Ash with this supplied name. Use this method when you don't know if the entity has been already created, but if hasn't, you want to ensure it does now. Throws exception if name is invalid or null.

name

The name of the entity to resolve

returns

The entity found

function restartMode():Void

Queues up a self-transition to the current mode; causes the stop handler to execute, eliminates unprotected entities, then executes the start handler. See setMode.

function setHandler(handler:FlaxenHandler, ?mode:ApplicationMode):Flaxen

Sets up all mode callbacks in one shot. Create a subclass of FlaxenHandler and override the functions you want. You cannot "unset" a handler once set. If a mode is not supplied, the mode defaults to Default, which is the mode that runs when the application bootstraps. If the mode is Always, the handlers are run in all modes, after the primary handlers run. See ModeSystem.

In this example, when Play mode is entered, handler1.start() will be called, followed by handler2.start():

setHandler(handler1, Play); 
setHandler(handler2, Always); 
handler

A FlaxenHandler instance, this is a class you create

mode

An optional ApplicationMode that determines when these callbacks runs

returns

The Flaxen instance

function setMode(mode:ApplicationMode):Void

Queues up a transition to the new mode; causes the current mode's stop handler to execute, eliminates unprotected entities, then executes new mode's start handler. See ModeSystem.

mode

The ApplicationMode to transition to

function setStartCallback(callback:ModeCallback, ?mode:ApplicationMode):Flaxen

Adds a function that is called when an application mode is started. Also see setHandler.

callback

A function that accepts Flaxen and returns nothing

mode

An optional ApplicationMode that determines when this callback runs

returns

The Flaxen instance

function setStopCallback(callback:ModeCallback, ?mode:ApplicationMode):Flaxen

Adds a function that is called when an application mode is stopped. Also see setHandler.

callback

A function that accepts Flaxen and returns nothing

mode

An optional ApplicationMode that determines when this callback runs

returns

The Flaxen instance

function setUpdateCallback(callback:ModeCallback, ?mode:ApplicationMode):Flaxen

Adds a function that is called regularly only during a specific application mode. Generally this is intended for handling input, but you could also use it just as an update function. See UpdateSystem for more information. Also see setHandler.

callback

A function that accepts Flaxen and returns nothing

mode

An optional ApplicationMode that determines when this callback runs

returns

The Flaxen instance

function stopSound(file:String):Void

Stops all instances of a specific sound from playing, based on the path to the sound. If you want to stop a single instance, maintain a reference to the Sound entity (or component) and set the component's stop property to true.

file

The path to the sound asset; ex. "sound/beep.wav"

function stopSounds():Void

Stops all currently playing sounds. Sounds are not stopped until the AudioSystem processes them.

function updateLayouts():Void

Swaps the current layout with the alternate layout Usually this is because the screen orientation has changed