
* Making a new Entity subclass

TODO

** Making a very basic new Entity

TODO

*** The init() function

TODO

*** The update() function

TODO

*** Making it move

TODO

** Making it save and load

TODO

*** The save() function

TODO

*** The initFromSave() function

TODO

** Making a subclass based off of this one

TODO

* Entity class Reference

Everything that does anything useful (besides terrain tiles) is based
off the Entity class.

In Lua terms, it's actually just a table with a bunch of functions in
it. It has a piece of userdata that refers to the actual C++ class
instance of the ScriptEntity class that it represents. If this is nil,
it is assumed to be either something that's dead, or not an instance
of the class (the class definitions and class instances are otherwise
pretty much the same - just Lua tables).

Subclassing is possible (see [[createSubClass]]()). This will create a new
table with the index part of the metatable set up to point back to the
first class. The result being that anything that's not defined for the
"child" table falls back on the parent table.

When you need to call a base class's version of a function in the
child class on itself, do this:

#+BEGIN_SRC lua
  function ChildClass:someFunction()
  
     -- Do the parent class's version first...
     ParentClass.someFunction(self);
  
     -- Now do whatever this class was going to do...
  
     -- (snip)
  
  end
#+END_SRC

Note the "." instead of a ":" for the scope. When you use ":", it
automatically passes in the class itself as the first parameter (named
"self" inside the function). If we were to do that here, it would pass
in the ParentClass table itself as the self parameter. But we WANT to
pass in the ChildClass instance as the self parameter. So use "." and
pass in the self parameter manually, from the exising self paramter
inside this function's scope.

** Built-in functions that you can call

Subclass stuff off of this for in-game objects (baddies, powerups,
doors, switches, etc).

Functions of the Entity class (and everything subclassed off of it:

*** boolean getDead()

Returns true if the Entity has died, or otherwise become invalid.

*** number getSpriteScale()

Returns the scaling value of the sprite.

*** setSpriteScale(number scale)

Sets the scaling value of the sprite.

*** setSpriteAngle(number angle)

Sets rotation of the sprite when drawn. (Rotates around the center of
the Entity, as determined by getPosition().)

*** setSpriteFrame(number x1, number y1, number x2, number y2)

Set the area from the texture to use to draw. Also affects the drawn
size of the sprite. Coordinates are pixel coordinates of the top left
(x1, y1) and bottom right (x2, y2) with 0, 0 behind the upper left
corner of the image.

*** setBlocker(boolean blocker)

Sets whether or not this blocks Entities that have the blockable flag
set. (Think: Doors, platforms, etc.)

*** setSize(number width, number height)

Set the size of the Entity's collision box. Entity's location is the
CENTER of this box.

*** number getBounciness()

Get the bounciness factor (multiplier for returned energy upon a
collision).

*** number getLabelFontHeight()

Get the height of the font used in the label for this. Possibly to be
deprecated.

*** setOnGround(boolean onGround)

This flag is normally set by the physics system, but can be manually
set. Used to determine if the Entity is standing on the ground as
opposed to falling or flying.

*** number, number, number getColor()
*** setColor(number r, number g, number b)
*** testFunc()
*** init()
*** number getAlpha()
*** setSpriteOffset(number x, number y)
*** setLabelFont(string fontname)
*** die()
*** setEditorVisibleOnly(boolean editorVisibleOnly)
*** number getSpriteAngle()
*** boolean getOnGround()
*** boolean getEditorVisibleOnly()
*** number, number getPos()
*** setLabel(string label)
*** setGravityInfluence(number influence)
*** setLayer(number layer)

*** getForceUpdate
*** setForceUpdate
*** getLabelFont
*** getIgnoreBlockDown
*** setBlockable
*** getAge
*** setIgnoreBlockDown
*** setAlpha
*** getSpriteOffset
*** setFlashing
*** setVel
*** getGravityInfluence
*** create
*** setPos
*** getFlashing
*** getSize
*** getBlockable
*** getOnScreen
*** getLabel
*** getLayer
*** getSpriteFrame
*** getName
*** getBlocker
*** setDepth
*** setBounciness

*** setName(string name)

Set the name of this Entity. Terrible things will happen if the name
is already in use by something else.

*** table createSubClass()

Create a new subclass based off this class.

*** number getDepth()

Get the Z-value to use to sort this Entity.

Note: Z-values that are not equal to zero will be sorted in a
potentially time-consuming operation. Use when necessary to make
something that absolutely must be in front or behind something else.

*** setSpriteBottomCenter(number x, number y)

Set the bottom-center of the sprite in the sprite image. This will
align the bounding box's bottom and center with the specified point in
the sprite image.

This essentially does a bit of math and calls [[setSpriteOffset]]() with
appropriate calculated values. So to work, this MUST be called AFTER
[[setTexture]]() and [[setSpriteFrame]](). Otherwise it cannot (accurately)
figure out the offset!

*** setTexture(string filename)

Set the texture to use for displaying this Entity.

Textures must be .tga files or .metatex files and must be in a game's
"textures" directory.

*** string getTexture()

Get the texture to use for this Entity.

Note that this may result in an empty string if the Entity's current
texture was simply not found.

*** number, number getVel()

Get the current velocity.

Returns the x and y distance that this Entity will move in one frame.

*** setFlipVertical
*** setFlipHorizontal
*** getFlipVertical
*** getFlipHorizontal
*** getLinkTarget
*** setLinkTarget
*** getAllLinkTargets
*** addLinkTarget
*** setIsLight
*** getIsLight
*** setFullbright
*** getFullbright

** Functions that can be defined by the user that get called by the system

*** collided(string name)

Called when an Entity collides with another Entity.

name - Name of the other entity. See entitiesByName to determine the
Entity that was collided with from this.

*** collidedWithWorld()

Called when an Entity collides with the static world (a tile, or a
piece of terrain geometry).

*** destruct()

Called when an Entity dies.

*** init()

Called when the Entity is created unless initFromSave can be used to
load save data.

*** table save()

Called when saving. The editor will call this when saving a level and
the game will save it when using saveEntitites().

Most Entity data that exists on the C++ side is saved. That is
everything that needs to be get and set using the accessor functions
in the Lua API. Arbitrary data on the Entity's table is NOT saved!
Anything you want saved must be added to the table you return from
THIS function.

Furthermore, try to limit your saved values to sane data
types. Functions can't go in the table and you'll probably make
everything explode if you try. Tables will recurse to child tables,
but a unique copy of each table will be saved for each
Entity. (Multiple entities saving a link to the same table will load
as each Entity having its own copy.)

Do not try to refer to other Entities in this table except by
NAME. Linking to the other table directly with a reference will NOT
give you the desired result.

*** initFromSave(table)

Called instead of init() when an Entity is created from saved
data. The table passed into this should be identical to the one
returned from the save() call when the Entity was saved. Should be
pretty easy to just stick all the data back in place.

It's okay to call init() from this one if you want to set up any
default values that aren't in the table.

Variables that can be defined with special meanings on the Entity:

*** update()

Called every frame by the system, as long as the Entity is near the
screen, or the forceUpdate flag is set.

This is called in what should be considered a non-determinant order
for Entities. Collision events also happen in between these calls.

*** postUpdate()

Called every frame with the same conditions as update(), but with the
difference of it being guaranteed to be called AFTER all update()
calls and collision functions. Use for when something absolutely must
happen after something else, but in the same frame.

Good use: A camera must follow the player, but always set its position
after the player's location has been updated for the frame. Otherwise
the character and screen will not appear to move smoothly as the
updates will happen sometimes before and sometimes after the move
itself.

*** editorProperties

Anything in here that's a string, boolean, or number will show up in
the editor's inspector view, allowing it to be modified directly in
the editor. There is no callback to alert an Entity as to when this
happens, and the value is changed right inside the table.

Example: A teleporter where it is helpful to be able to set a
different destination for each instance, or a switch/door combo where
each instance has a unique target.

* Global function reference

TODO: Document all this crap.

All of these are functions that you can call directly without an
Entity or sub-class of it.

** Built-in globals

*** saveEntities
*** saveTable
*** loadEntities
*** loadTable
*** loadTiles
*** preloadSound
*** reloadTextures

*** writeConsole(string text)

Write some text to the console. This will go to the console tab in the
editor and stdout in the system console.

Make sure you use "\n" as a newline, or the output won't get flushed
and won't show up.

Warning: It is inadvisable to try to use this to narrow down a
crash. The output of this function is buffered and flushed in a
separate thread. If something is causing an issue, it could actually
crash before having a chance to flush the output.

*** registerSpawn(string name)

Register an Entity subclass to appear in the editor's Entity Palette
tab.

Not all Entities need to have this set and it'd probably clutter
everything up to have unimportant stuff here.

Parameters:

name - Name of the class, as a string.

Example:

#+BEGIN_SRC lua
HerpDerp = Entity:createSubClass(); registerSpawn("HerpDerp");
#+END_SRC

*** registerScenery

*** getJoyAxis

Deprecated. Don't use this in new code.

Replaced by getControlValue().

*** getJoyButton

Deprecated. Don't use this in new code.

Replaced by getControlBoolValue().

*** getCameraPos
*** setCameraPos
*** number, number getScreenSize()

Get the width and height of the screen.

*** include(string filename)

Executes the Lua script named filename.

*** loadTiles
*** loadEntities
*** saveEntities

*** clearLayer(number layer, [string exception1, string exception2, ...])

Kills everything in the specified layer, except for the specified
entity names.

*** clearTiles
*** setTile
*** getTile
*** worldSpaceToTileSpace
*** tileSpaceToWorldSpace
*** getBoxTouchesWorld
*** getEntsTouchingBox(layer, x1, y1, x2, y2)

*** playSound(string filename)

Loads (if not loaded yet) and plays the specified sound file.

Sound files must be in .ogg format.

The sound files must be in the game's "sounds" directory.

*** preloadSound(string filename)

Preloads a sound without playing it. The sound will sit around in
memory for a bit before being automatically purged for non-use if it
isn't played.

Note that this doesn't actually cause it to load in the background or
anything fancy like that, but it can be used to ensure a sound stays
in memory by calling it regularly.

FIXME: Make it load in the background.

The sound files must be in the game's "sounds" directory.

*** startMusic(string filename)

Start an ogg file looping in the background. Replaces whatever was
playing as music before.

The music files must be in the game's "music" directory.

*** stopMusic()

Stop the currently playing music.

*** number getGravity()

Get the gravity in pixels of acceleration per frame.

*** setGravity(number gravity)

Set the gravity in pixels of acceleration per frame. (Default 2.)

*** saveTable(string fileName, table thingToSave)

Saves a table to an XML file in the save directory. Doesn't support
all data types! Supports tables, strings, numbers, booleans, nils, and
functions (compiled bytecodes) as keys and values.

*** table loadTable(string fileName)

Loads a table saved with saveTable.

*** setSaveName
*** getSaveName
*** getSaveList
*** setExclusiveUpdatesThisFrame

*** unnameDeadEntities()

Renames all dead entities to deadEnt_###. This can be done in places
where we can't actually delete an Entity from memory (it might be in
an important place in the call stack or something might be referring
to it) but we need it to be out of the way.

For example, before loading new entities from XML so that the loaded
Entities don't have names conflicting with stuff that's already dead.

*** reloadTextures()

Forces all textures and shaders to reload and recompile. Useful for
working on sprites and shader code without completely restarting the
app.

Note that this won't load any changes from a run of the spritepacker
tool unless you [[include]]() the newly modified autogen_spritedefs.lua
file again, and even THAT won't fix anything that has already set its
sprite and isn't coded to update its sprite bounds. For example, a
static piece of scenery that gets its sprite set in its init()
function.

*** string getRealFile(string filename)

Get the "real" file name for the given file name.

This will take into consideration the current save directory, the game
directory, and the common game directory and return the path to one of
those that it finds that exists.

If nothing is found to exist, it will return an empty string.

It will return the actual path from the current working directory -
not one of the game-relative paths. This makes it useful for
interacting with other libraries and the UI toolset (which doesn't
recognize the save/game/common hierarchy).

This DOES still transparently handle .poop files, so the returned path
can actually be referring to something that only exists in an
archive. This path is usable for any system built into the engine
(such as the UI), but will screw up horribly if you try to pass it to
something that doesn't recognize .poop files.

*** setSubtractiveFade
*** setAdditiveFade

*** setControlName(number controlNumber, string name)

Set a control number (whatever you want from 0 to 256, but don't leave
gaps of undefined ones) to a specific name for the keybind setup
screen.

*** number getControlValue(number controlNumber)

Gets the value for a given keybind. Must be something that was set
with setControlName.

This returns a value from 0 to 32768 for analog inputs, or just 0 or
32768 for binary ones (like buttons instead of axes).

*** boolean getControlBoolValue(number controlNumber)   

Same as getControlValue, but tests against a deadzone and returns true
or false based on whether it's beyond that.

Use for binary controls like buttons (so analog axes can be mapped to
them without worrying).

*** boolean getMouseButton(number button)

Get the state (true = held) of a given mouse button. Button number
mouse be 0 - 4.

*** number, number getMousePos()

Get the position (in world space) of the mouse cursor.

*** number getNumLayers()

Get the number of layers.

*** number getLayerByName(string name)

Get a layer's number by its name.

** Global values

*** Entity

The main Entity table to subclass from.

*** entitiesByName

Table of every instanced Entity, indexed by name. Do not change this
table directly. Entity may be retrieved from it by name.

** Programmer/designer-defined globals

*** worldUpdate()

Called every frame.

*** worldPostUpdate()

Called every frame AFTER Entity updates and collision is handled, but
before stuff is drawn.

*** handleMouseDown(x, y, button)

Called by the engine every time a mouse button is pressed. World space
coordinates.

*** handleMouseUp(x, y, button)

Called by the engine every time a mouse button is released. World
space coordinates.

*** handleMouseMotion(x, y)

Called by the engine every time the mouse is moved. World space
coordinates.

Does not (yet) get called when the camera moves (moving the effective
position of the mouse cursor in world space).



