spritekit-0.7.0.0: Cocoa SpriteKit for Haskell

Copyright[2014] Manuel M T Chakravarty
LicenseBSD3
MaintainerManuel M T Chakravarty <chak@justtesting.org>
Stabilityexperimental
Safe HaskellNone
LanguageHaskell98

Graphics.SpriteKit

Contents

Description

Cocoa SpriteKit for Haskell

Concepts:

  • SpriteKit node trees are represented as conventional algebraic datatypes in Haskell.
  • For rendering, Haskell node trees are converted to native SKNode trees. For animated scenes, where all animation is driven by Haskell, the conversion of updated scenes works by updating the previous SKNode tree.
  • For interactive scenes and scenes using SceneKit's actions or physics, the Haskell scene code gets called with a Haskell tree representing the current SKNode tree, which, after Haskell side processing, is converted to an SKNode tree again by updating the version that was passed to the Haskell code.

Synopsis

Basic geometry and similar

Basic temporal definition

Basic geometry definitions

type GFloat

Arguments

 = Double

FIXME: need to be set in dependence on the definition of CGFloat resp CGFLOAT_IS_DOUBLE

Graphics float (which is a Float or Double depending on whether we are on a 32 or 64 bit architecture)

data Point

Point in a two-dimensional coordinate system.

Constructors

Point 

Fields

pointX :: !GFloat
 
pointY :: !GFloat
 

data Size

Size of a two-dimensional geometry entity.

Constructors

Size 

data Rect

Location and size of a rectangle.

Constructors

Rect 

Fields

rectOrigin :: !Point
 
rectSize :: !Size
 

data Vector

Two-dimensional vector.

Constructors

Vector 

Fields

vectorDx :: !GFloat
 
vectorDy :: !GFloat
 

pointZero :: Point

Point at (0, 0).

Marshalling functions (internal)

pointToCGPoint :: Point -> IO CGPoint

cgPointToPoint :: CGPoint -> IO Point

sizeToCGSize :: Size -> IO CGSize

cgSizeToSize :: CGSize -> IO Size

rectToCGRect :: Rect -> IO CGRect

cgRectToRect :: CGRect -> IO Rect

vectorToCGVector :: Vector -> IO CGVector

cgVectorToVector :: CGVector -> IO Vector

Color representation

Colour representation

newtype Color

Representation of colour values.

Constructors

Color SKColor 

Colours in the sRGBA colour space

colorWithRGBA :: Float -> Float -> Float -> Float -> Color

Create colour with the specified red, green, blue, and alpha channel values in the sRGB colour space.

rgbaOfColor :: Color -> (Float, Float, Float, Float)

Extract the red, green, blue, and alpha channel values of a colour in the sRGB colour space.

Standard colours

Marshalling support (internal)

newtype SKColor

Constructors

SKColor (ForeignPtr SKColor) 

Bit images and textures

Images

data Image

Instances

Marshalling functions (internal)

newtype NSUIImage

SpriteKit texture representation

newtype Texture

A SpriteKit texture object

Constructors

Texture SKTexture 

Texture creation

textureWithImageNamed :: FilePath -> Texture

Create a texture from an image in the app bundle (either a file or an image in a texture atlas) or external file.

A placeholder image is used if the specified image cannot be loaded.

In case of a relative name, the look up behaviour varies between a compiled application bundle and running in the interpreter. In case of a compiled application bundle, the standard SpriteKit bundle behaviour applies. In case of executing in the interpreter, we first look for assets relative to the current working directory.

textureWithImage :: Image -> Texture

Create a texture from the given image.

textureWithRectInTexture :: Rect -> Texture -> Texture

Create a texture from a subset of an existing texture.

The original and new texture share the same texture data. In further call to the same function, the rectangle is again specified in terms of the *original* texture.

Texture properties

textureSize :: Texture -> Size

The size of the texture.

textureRect :: Texture -> Rect

The rectangle (in the unit coordinate space) that defines the portion of the texture used to render its image.

The default is (0,0) — (1,1), but it may be different for textures created with textureWithRectInTexture.

Marshalling support

newtype SKTexture

Vector paths

Core Graphics path representation

type Path = [PathElement]

Description of a graphics path.

data PathElement

Elementary components of a graphics path.

The constructors AddLineToPoint, AddQuadCurveToPoint, AddCurveToPoint may not start a graphics path.

Constructors

MoveToPoint !Point

Starts a new subpath at the given point.

AddLineToPoint !Point

Adds a line from the current to the given point.

AddQuadCurveToPoint !Point !Point

Adds a quadratic curve with control and destination point.

AddCurveToPoint !Point !Point !Point

Adds a cubic curve with two control and one destination point.

CloseSubpath

Closes and completes the current subpath. FIXME: we might to add field names (esp useful for the quadratic and cubic curves)

Marshalling functions (internal)

newtype CGPath

Constructors

CGPath (ForeignPtr CGPath) 

Nodes and scenes

SpriteKit node representation

data Directive node

Specification of changes that should be made to a node's actions.

Constructors

RunAction (Action node) (Maybe String)

Initiate a new action, possibly named.

RemoveActionForKey String

Remove a named action.

RemoveAllActions

Remove all current actions.

data Node u

Tree structure of SpriteKit nodes that are used to assemble scenes, parameterised by the type of user data u.

FIXME: or should we factorise into a two-level structure? (but that would make it awkward to use record updates)

Constructors

Node 

Fields

nodeName :: Maybe String

Optional node identifier (doesn't have to be unique)

nodePosition :: Point

The position of the node in its parent's coordinate system.

nodeZPosition :: GFloat

The height of the node relative to its parent (default: 0.0)

nodeXScale :: GFloat

Scaling factor multiplying the width of a node and its children (default: 1.0)

nodeYScale :: GFloat

Scaling factor multiplying the height of a node and its children (default: 1.0)

nodeZRotation :: GFloat

Euler rotation about the z axis (in radians; default: 0.0)

nodeChildren :: [Node u]
 
nodeActionDirectives :: [Directive (Node u)]
 
nodeSpeed :: GFloat

Speed modifier for all actions in the entire subtree (default: 1.0)

nodePaused :: Bool

If True all actions in the entire subtree are skipped (default: False).

nodeUserData :: u

Application specific information (default: uninitialised!)

nodeForeign :: Maybe SKNode

Internal

Label 

Fields

nodeName :: Maybe String

Optional node identifier (doesn't have to be unique)

nodePosition :: Point

The position of the node in its parent's coordinate system.

nodeZPosition :: GFloat

The height of the node relative to its parent (default: 0.0)

nodeXScale :: GFloat

Scaling factor multiplying the width of a node and its children (default: 1.0)

nodeYScale :: GFloat

Scaling factor multiplying the height of a node and its children (default: 1.0)

nodeZRotation :: GFloat

Euler rotation about the z axis (in radians; default: 0.0)

nodeChildren :: [Node u]
 
nodeActionDirectives :: [Directive (Node u)]
 
nodeSpeed :: GFloat

Speed modifier for all actions in the entire subtree (default: 1.0)

nodePaused :: Bool

If True all actions in the entire subtree are skipped (default: False).

nodeUserData :: u

Application specific information (default: uninitialised!)

nodeForeign :: Maybe SKNode

Internal

labelText :: String

Text displayed by the node.

labelFontColor :: Color

The colour of the label (default: white).

labelFontName :: Maybe String

The font used for the label.

labelFontSize :: GFloat

The size of the font used in the label (default: 32pt).

Shape 

Fields

nodeName :: Maybe String

Optional node identifier (doesn't have to be unique)

nodePosition :: Point

The position of the node in its parent's coordinate system.

nodeZPosition :: GFloat

The height of the node relative to its parent (default: 0.0)

nodeXScale :: GFloat

Scaling factor multiplying the width of a node and its children (default: 1.0)

nodeYScale :: GFloat

Scaling factor multiplying the height of a node and its children (default: 1.0)

nodeZRotation :: GFloat

Euler rotation about the z axis (in radians; default: 0.0)

nodeChildren :: [Node u]
 
nodeActionDirectives :: [Directive (Node u)]
 
nodeSpeed :: GFloat

Speed modifier for all actions in the entire subtree (default: 1.0)

nodePaused :: Bool

If True all actions in the entire subtree are skipped (default: False).

nodeUserData :: u

Application specific information (default: uninitialised!)

nodeForeign :: Maybe SKNode

Internal

shapePath :: Path

Graphics path as a series of shapes or lines.

shapeFillColor :: Color

The color used to fill the shape (default: clear == not filled).

shapeLineWidth :: GFloat

The width used to stroke the path (default: 1.0; should be <= 2.0).

shapeGlowWidth :: GFloat

Glow extending outward from the stroked line (default: 0.0 == no glow).

shapeAntialiased :: Bool

Smooth stroked path during drawing? (default: True).

shapeStrokeColor :: Color

Colour used to stroke the shape (default: white; clear == no stroke).

Sprite 

Fields

nodeName :: Maybe String

Optional node identifier (doesn't have to be unique)

nodePosition :: Point

The position of the node in its parent's coordinate system.

nodeZPosition :: GFloat

The height of the node relative to its parent (default: 0.0)

nodeXScale :: GFloat

Scaling factor multiplying the width of a node and its children (default: 1.0)

nodeYScale :: GFloat

Scaling factor multiplying the height of a node and its children (default: 1.0)

nodeZRotation :: GFloat

Euler rotation about the z axis (in radians; default: 0.0)

nodeChildren :: [Node u]
 
nodeActionDirectives :: [Directive (Node u)]
 
nodeSpeed :: GFloat

Speed modifier for all actions in the entire subtree (default: 1.0)

nodePaused :: Bool

If True all actions in the entire subtree are skipped (default: False).

nodeUserData :: u

Application specific information (default: uninitialised!)

nodeForeign :: Maybe SKNode

Internal

spriteSize :: Size

The dimensions of the sprite, in points.

spriteAnchorPoint :: Point

The point in the sprite that corresponds to the node’s position. ^In unit coordinate space; default: (0.5,0.5); i.e., centered on its position.

spriteTexture :: Maybe Texture
 
spriteColorBlendFactor :: GFloat

Default = 0 (spriteColor is ignored when drawing texture) ^value >0 means texture is blended with spriteColour before being drawn

spriteColor :: Color

The sprite’s color.

type TimedUpdate node = node -> GFloat -> node

Function that computes an updated tree, given the time that elapsed since the start of the current animation.

The result will be ignored if the new node is not derived from the old node — i.e, it must be the same kind of node and it must preserve the nodeForeign field.

Action directives

runAction :: Action userData -> Directive userData

Initiate a new action.

runActionWithKey :: Action userData -> String -> Directive userData

Initiate a new action and give it a name.

If an action with the same name is currently underway on a node that receives this action, the old action is removed first.

removeActionForKey :: String -> Directive userData

Instructs to remove any action with the give name.

removeAllActions :: Directive userData

Instructs to remove all actions from any node that receives this directive.

Generic SpriteKit node functionality

node :: [Node userData] -> Node userData

Create a node that combines multiple child nodes, but doesn't have a visual representation of its own.

Label nodes

labelNodeWithFontNamed :: String -> Node userData

Creates a label node without any text, but using the specified font.

labelNodeWithText :: String -> Node userData

Creates a label node with the given text (set in 32pt Helvetica Neue Ultralight).

Shape nodes

shapeNodeWithPath :: Path -> Node userData

Creates a shape node from a graphics path relative to the nodes origin.

Sprite nodes

spriteWithColorSize :: Color -> Size -> Node userData

Create a coloured sprite of a given size.

spriteWithImageNamed :: FilePath -> Node userData

Create a texture sprite from an image in the app bundle (either a file or an image in a texture atlas).

A placeholder image is used if the image cannot be loaded.

spriteWithTexture :: Texture -> Node userData

Create a textured sprite from an in-memory texture.

spriteWithTextureSize :: Texture -> Size -> Node userData

Create a textured sprite from an in-memory texture, but also set an explicit size (instead of using the texture's size).

spriteWithTextureColorSize :: Texture -> Color -> Size -> Node userData

Create a textured sprite from an in-memory texture, but also set an explicit size (instead of using the texture's size).

NB: To colourise the texture, you also need to set the colorBlendFactor field of the sprite.

Internal marshalling support

newtype SKNode

Constructors

SKNode (ForeignPtr SKNode) 

nodeToSKNode :: Node userData -> IO SKNode

addChildren :: Bool -> SKNode -> [Node userData] -> IO ()

addActionDirectives :: SKNode -> [Directive userData] -> IO ()

updateChildren :: SKNode -> [Node userData] -> [Node userData] -> IO ()

Scene representation

data Scene sceneData nodeData

SpriteKit scene description.

Constructors

Scene 

Fields

sceneName :: Maybe String

Optional scene node identifier (doesn't have to be unique)

sceneChildren :: [Node nodeData]
 
sceneActionDirectives :: [Directive (Scene sceneData nodeData)]
 
sceneSpeed :: GFloat

Speed modifier for all actions in the entire subtree (default: 1.0)

sceneData :: sceneData

Application specific information (default: uninitialised!)

scenePaused :: Bool

If True all actions in the entire subtree are skipped (default: False).

sceneAnchorPoint :: Point

Point in the view’s frame that corresponds to the scene’s origin in unit coordinate space (default: (0, 0) == lower-left corner of the view's frame).

sceneSize :: Size

Dimensions of the scene in points.

sceneScaleMode :: SceneScaleMode

How the scene is defined to the enclosing view (default: SceneScaleModeFill).

sceneBackgroundColor :: Color

Background colour (default: RGBA 0.15, 0.15, 0.15, 1.0).

sceneUpdate :: Maybe (SceneUpdate sceneData nodeData)

Called once per frame before any other updates to the scene (default: Nothing).

sceneHandleEvent :: Maybe (EventHandler sceneData)

Event handler for the scene (default: Nothing).

type EventHandler userData = Event -> userData -> Maybe userData

Event handler that given an input event and node data decides whether to handle the event and how to update the node data.

If the handler chooses not to handle the presented event, it returns Nothing. In this case, the event will be forwarded to the next item in the responder chain.

Scene creation

sceneWithSize :: Size -> Scene sceneData nodeData

A new scene of the given size.

Marshalling functions (internal)

sceneToSKNode :: Scene sceneData nodeData -> IO SKNode

sceneToForeignPtr :: Scene sceneData nodeData -> IO (ForeignPtr SKNode)

Actions animating nodes

SpriteKit actions

data ActionSpecification node

Specification of an action that can be applied to a SpriteKit node.

Most actions will be animated over time, given a duration.

Constructors

MoveBy !Vector

Move relative to current position (reversible).

MoveTo !Point

Move to an absolute position (irreversible).

MoveToX !GFloat

Move horizontally to an absolute x-position (irreversible).

MoveToY !GFloat

Move vertically to an absolute y-position (irreversible).

FollowPath Path !Bool !Bool

Follow path, maybe use relative offsets & maybe orient according to path (reversible).

FollowPathSpeed Path !Bool !Bool !GFloat

As above, but specifying speed in points per sec (reversible; OS X 10.10+ & iOS 8+).

RotateByAngle !GFloat

Rotate by a relative value, in radians (reversible).

RotateToAngle !GFloat

Rotate counterclockwise to an absolute angle, in radians (irreversible).

RotateToAngleShortestUnitArc !GFloat !Bool

Rotate to an absolute angle. If second argument '== True', in the direction resulting in the smallest rotation; otherwise, interpolated (irreversible).

SpeedBy !GFloat

Changes how fast the node executes actions by a relative value (reversible).

SpeedTo !GFloat

Changes how fast the node executes actions to an absolute value (irreversible).

ScaleBy !GFloat !GFloat

Relative change of x and y scale values (reversible).

ScaleTo !GFloat !GFloat

Change x and y scale values to an absolute values (irreversible).

ScaleXTo !GFloat

Change x scale value to an absolute value (irreversible).

ScaleYTo !GFloat

Change y scale value to an absolute value (irreversible).

Unhide

Makes a node visible (reversible; instantaneous; OS X 10.10+ & iOS 8+).

Hide

Hides a node (reversible; instantaneous; OS X 10.10+ & iOS 8+).

FadeIn

Changes the alpha value to 1.0 (reversible).

FadeOut

Changes the alpha value to 0.0 (reversible).

FadeAlphaBy !GFloat

Relative change of the alpha value (reversible).

FadeAlphaTo !GFloat

Change the alpha value to an absolute value (irreversible).

ResizeByWidthHeight !GFloat !GFloat

Adjust the size of a sprite (reversible).

ResizeToHeight !GFloat

Change height of a sprite to an absolute value (irreversible).

ResizeToWidth !GFloat

Change width of a sprite to an absolute value (irreversible).

ResizeToWidthHeight !GFloat !GFloat

Change width and height of a sprite to an absolute value (irreversible).

SetTexture Texture !Bool

Change a sprite's texture, maybe resizing the sprite (irreversible; instantaneous; ^without resizing only OS X 10.10+ & iOS 7.1+).

AnimateWithTextures [Texture] !TimeInterval !Bool !Bool

Animate setting the textures, pausing by the given time interval between textures. Rotate to an absolute angle. If second argument '== True', in the direction resulting second Bool is True, the original texture is restored (reversible).

ColorizeWithColor Color !GFloat

Animate a sprite's color and blend factor (irreversible).

ColorizeWithColorBlendFactor !GFloat

Animate a sprite's blend factor (irreversible).

PlaySoundFileNamed String !Bool

Play a sound, maybe waiting until the sound finishes playing (irreversible).

RemoveFromParent

Removes the animated node from its parent (irreversible; instantaneous).

RunActionOnChildWithName (Action node) String

Run an action on a named child node (reversible; instantaneous).

Group [Action node]

Run all actions in the group in parallel (reversible).

Sequence [Action node]

Run all actions in the group in sequence (reversible).

RepeatActionCount (Action node) !Int

Repeat an action a fixed number of times (reversible).

RepeatActionForever (Action node)

Repeat an action undefinitely (reversible).

WaitForDuration !TimeInterval

Waits for the action's duration +/- half the given range value (irreversible).

CustomAction (TimedUpdate node)

Repeatedly invoke the update function over the action duration (irreversible).

data Action node

SpriteKit action.

NB: actionTimingFunction not yet supported.

Constructors

Action 

Fields

actionSpecification :: ActionSpecification node

Determines the action to be performed.

actionReversed :: !Bool

Reverses the behaviour of another action (default: False).

actionSpeed :: !GFloat

Speed factor that modifies how fast an action runs (default: 1.0).

actionTimingMode :: ActionTimingMode

Determines the action timing (default: ActionTimingLinear).

actionTimingFunction :: Maybe ActionTimingFunction

Customises the above timing mode (OS X 10.10+ & iOS 8+).

actionDuration :: !TimeInterval

Duration required to complete an action (default: 0.0 == immediate).

data ActionTimingMode

Determines the temporal progression of an action.

type ActionTimingFunction = Float -> Float

Projects an input value between 0.0 and 1.0, inclusive, to another value between 0.0 and 1.0 to indicate the temporal progression of an action. The input 0.0 must be mapped to 0.0, and 1.0 to 1.0. Inbetween those bounds, the timing function can adjust the timing of the action.

action :: ActionSpecification node -> Action node

Construct an action.

Convenience functions to construct specifications of the same name

moveBy :: Vector -> Action node

moveTo :: Point -> Action node

moveToX :: GFloat -> Action node

moveToY :: GFloat -> Action node

speedBy :: GFloat -> Action node

speedTo :: GFloat -> Action node

scaleBy :: GFloat -> Action node

scaleTo :: GFloat -> Action node

hide :: Action node

unhide :: Action node

fadeIn :: Action node

fadeOut :: Action node

animateWithTexturesTimePerFrame :: [Texture] -> TimeInterval -> Action node

animateWithTextures is a shorthand for convenience.

animateWithTextures :: [Texture] -> TimeInterval -> Action node

animateWithTextures is a shorthand for convenience.

colorizeWithColorColorBlendFactor :: Color -> GFloat -> Action node

colorizeWithColor is a shorthand for convenience.

colorizeWithColor :: Color -> GFloat -> Action node

colorizeWithColor is a shorthand for convenience.

playSoundFileNamedWaitForCompletion :: String -> Bool -> Action node

playSoundFileName is a shorthand for convenience.

playSoundFileNamed :: String -> Bool -> Action node

playSoundFileName is a shorthand for convenience.

group :: [Action node] -> Action node

groupActions is to be symmetric with sequenceActions.

groupActions :: [Action node] -> Action node

groupActions is to be symmetric with sequenceActions.

sequence :: [Action node] -> Action node

sequenceActions is for convenience in the face of sequence.

sequenceActions :: [Action node] -> Action node

sequenceActions is for convenience in the face of sequence.

repeatActionCount :: Action node -> Int -> Action node

customAction :: TimedUpdate node -> Action node

Perform the given update function once per frame for the given duration. If the duration is 0, the function is only invoked once.

The node on which the action is run is passed to the update function and gets replaced by the updated node.

FIXME: We need to document the tree merging algorithm.

Marshalling support (internal)

newtype SKAction

Constructors

SKAction (ForeignPtr SKAction) 

Instances

data TimedUpdateBox node

Constructors

TimedUpdateBox (TimedUpdate node) 

User events

Event information

data Event

Cocoa events.

NB: Not all event types are supported. Usually, because they would require functionality from other parts of Cocoa, which are not supported here (yet).

Constructors

KeyEvent 

Fields

eventLocationInNode :: !Point

Location within the SpriteKit node receiving the event. , eventModifierFlags :: ?? -- ^Modifier keys that were in effect at the time of the event.

eventTimestamp :: !TimeInterval

Time when the event occured in seconds since system startup.

keyEventType :: KeyEvent

The specific type of key event.

keyEventCharacters :: String

Characters associated with receiving key-up or key-down events.

keyEventCharactersIgnoringModifiers :: String

Ditto, ignoring the effect of modifier keys, except for Shift.

keyEventIsARepeat :: !Bool

Whether event is a repeat caused by the user holding a key down.

keyEventKeyCode :: !Word16

Hardware-independent, virtual keycode.

MouseEvent 

Fields

eventLocationInNode :: !Point

Location within the SpriteKit node receiving the event. , eventModifierFlags :: ?? -- ^Modifier keys that were in effect at the time of the event.

eventTimestamp :: !TimeInterval

Time when the event occured in seconds since system startup.

mouseEventType :: MouseEvent

The specific type of mouse event.

mouseEventNumber :: !Int

Event identifier (increasing counter of mouse events).

mouseEventButtonNumber :: !Int

Number of the button used in some mouse events.

mouseEventClickCount :: !Int

Number of mouse clicks for a mouse event

mouseEventPressure :: !Float

Value from 0 through 1 indicating pressure for some devices.

EnterExitEvent 

Fields

eventLocationInNode :: !Point

Location within the SpriteKit node receiving the event. , eventModifierFlags :: ?? -- ^Modifier keys that were in effect at the time of the event.

eventTimestamp :: !TimeInterval

Time when the event occured in seconds since system startup.

enterExitEventType :: EnterExitEvent

The specific type of a tracking-rectangle or cursor-update event.

enterExitEventNumber :: !Int

Event identifier (increasing counter of mouse events). , enterExitTrackingNumber :: Int , enterExitUserData :: ??

OtherEvent 

Fields

eventLocationInNode :: !Point

Location within the SpriteKit node receiving the event. , eventModifierFlags :: ?? -- ^Modifier keys that were in effect at the time of the event.

eventTimestamp :: !TimeInterval

Time when the event occured in seconds since system startup.

otherEventType :: OtherEvent

The specific type of a tracking-rectangle or cursor-update event. , otherEventSubtype :: Int16 , otherEventData1 :: Int , otherEventData2 :: Int

Instances

data EnterExitEvent

Constructors

CursorUpdate

FIXME: not yet supported

data OtherEvent

Constructors

Periodic

FIXME: not yet supported

Marshalling functions (internal)

mouseEvent :: Point -> Double -> CLong -> Int -> Int -> Int -> Float -> Event

Internal