ID:2101373
 
Alright, most of you have read that I've sort of been working in Ue4 recently. I've got a lot of stuff on my plate, what with doing HVAC repair this summer at about 40 hours a week and a number of pressing concerns on my mind about things that I always meant to write down that I know about DM that I've never taken the time to do.

That said, Movement is one of my biggest issues with DM as an engine that is pushing me away. It's certainly good enough to create solid games, but it's one of the biggest issues to a power-user that wants to craft something that controls well and isn't hacked together.

We're in for a long journey. If you can't read code and don't understand the built-in movement system, here's a basic rundown of how it all works:

Terms:
  density - density affects how objects determine what is "solid" or not. Two solid objects cannot move through one another by default. A non-solid object can move through solid objects by default. In other words, BOTH objects must be dense in order for blockages to occur.

  locality - locality refers to the property of having a discrete location.

    /atom does not have locality
    /area does not have locality
    /turf does not have locality
    /atom/movable has locality
    /obj has locality
    /mob has locality
    /image has locality
    every other type in DM does not have locality

  spacial - spacial refers to the property of being a space where things are laid out in reference to one another. Objects with a spacial property will exist with reference to one another when in a spacial atom. Atoms that are not spacial can contain other objects, but the objects that they contain have no spacial correlation to one another. We can call this "on map".

    /turf is the only spacial atom subtype.

  null space - Any atom without locality is in null space. Null space is an empty area where all objects live if they lack locality or they are merely not currently assigned a location. We can call this "off map"

  unsafe movement - Movement contains a series of hooks that make your life easier for tracking ingress and egress of objects with locality or spacial properties. An unsafe movement is a movement that does not call any of these functions. A safe movement is one that calls all of these functions.

  step - A step is a movement by less or equal to the number of pixels defined on a movable's step_size variable.

  jump - A jump is a movement by greater than the number of pixels defined on a movable's step_size variable.

  teleport - A teleport is a movement between disconnected localities. This means that it is a jump between Z-levels on the map, or from the map into the contents of an object that lacks locality, or from a non-locality object onto the map, or from null space to the map, or from the map to null space. A teleport is only distinct from a jump because I say so. The hook structure of Move() calls is different in this case. This is why I say it is distinct.

  gliding - Gliding is a client-side animation that attempts to smooth out tile-based movement, making stepping objects slide according to glide_size every visual frame. Every movable object can only be gliding one at a time. This means that any movement or change in positional appearance (glide_size, dir, loc, step_x, step_y, etc.) may override the existing glide and cause the movable to instantly teleport to their final destination. Glides can only occur over a single tile and thus can only occur in exactly 8 distinct angles.

  bounds - Bounds refer to what portion of the movable atom is dense. The visual area of an atom can be larger than its actual physical coverage. bound_width, bound_height, bound_x, and bound_y can be changed to make this bounding region occupy a different space relative to the bottom-left corner of the movable.

  translation - Translation refers to moving something according to X,Y offsets in either pixels or tiles.

  projection - Projection refers to moving something according to an angular and distance component, using trigonometry to retrieve the X,Y coordinates of the final translation.

  movement delay - movement delay refers to how long between movements the character is prevented from moving.

  self movement - self movement is a concept of a movement that occurs when something attempts to move by itself (A fish swimming or a person walking, etc.) under its own power. This is distinct from a directed movement.

  directed movement - directed movement is a concept of a movement that occurs by the power of another object (A person being dragged, a boulder being pushed, an object slipping on ice, etc.). This is distinct from a self movement.

  directional step - a directional step is a movement that takes a direction (N, S, E, W, NE, NW, SE, SW) and a distance as an argument. This is transformed into a translation using simple logic.

  Bump - a bump is when an object fails to finish a movement because it reached an object or location that would not allow overlap or entry.

  Bumped - when an object fails to finish a movement because of an obstacle, the object that was the obstacle is considered to have been "Bumped".

  Cross - when an object attempts to overlap another one in a spacial area. Antonym of Uncross

  Uncross - when an object attempts to stop overlapping another one in a spacial area. Anytonym of Cross

  Crossed - when an object successfully overlaps another one in a spacial area. Antonym of Uncrossed

  Uncrossed - when an object successfully stops overlapping another one in a spacial area. Antonym of Crossed

  Enter - when an object attempts to move into a spacial location or container. Antonym of Exit.

  Exit - when an object attempts to move out of a spacial location or container. Antonym of Enter.

  Entered - when an object successfully moves into a spacial location or container. Antonym of Exited.

  Exited - when an object successfully moves out of a spacial location or container. Antonym of Entered.

  Enter - when an object successfully moves into a spacial location or container. Antonym of Exit.

  walk - A movement that repeats regularly.

  peek-in - when an object peeks over the edge of another object from the inside. Antonym of peek-out.

  peek-out - when an object peeks out over the edge of another object from the outside. Antonym of peek-in.

  envelop - when an object fully overlaps another object. Antonym of escape.

  escape - when an object fully stops overlapping another object. Antonym of escape.

  edge-slide - when an object fails to move but continues to slide along the edge of its blockage.
Alright, so with the terms out of the way: Let's talk problems. Why is BYOND's default movement system a problem?

Well, it's too generalized for one. It's naive second. It's also extremely difficult to get metadata out of many of the built in procs without a herculean amount of reworking.

In pixel movement mode, BYOND's movements will refire every time that the step distance exceeds the bounding width or height. This means that every movement is broken up into max(ceil(abs(ox)/bound_width),ceil(abs(oy)/bound_height)) separate individual movements. This causes Cross()/Uncross()/Uncrossed()/Crossed() calls to refire more than once because larger steps can cause multiple movements to occur, some of the objects that are concerned with movement will not properly be culled from the incoming list of objects and tiles we are moving across.

If multiple objects exist on a tile, and only one of them is dense, Bump() will be called even on the objects that aren't technically blocking the movement.

step() functions return the wrong values according to Move().

step()/walk() functions are not overridable, so if you want to change how movement works at the core level, you can't use them. This makes working with a codebase you haven't written violate an awful lot of expectations that newer programmers would have that are familiar with the core.

locations are specified in x:step_x,y:step_y,z coordinates. The functions that require these values do not adjust them properly and there exists a massive amount of feature gap regarding these values like structs that make storing them easy.

You cannot easily get the direction a Bump() occurs from.

You cannot easily get information about obstacles encountered during the last movement.

Built-in pathfinding does not respect Enter()/Exit() rules.

Built-in pathfinding does not return paths, but instead refires every single frame it is used, giving players no option to automatically implement naive or self-adjusting pathfinding without fully writing their own pathfinding solution. Documentation doesn't even warn you about this. The naive will just assume that BYOND is slow upon using pathfinding.

Cross()/Uncross()/Crossed()/Uncrossed() are not built in as separate hooks. They are built in as part of a turf's enter/exit procs. This makes overriding the built-in Enter()/Exit() functions immensely problematic because you can't distinguish between the turf's default behavior and overlapping during a supercall. If at any point, you override Enter() or Exit() without performing a supercall, you lose the built-in behavior of checking objects and have to rewrite it manually further down in the chain. The logic for checking which objects will collide or won't is immensely non-trivial because of massive, glaring, 7+ year unaddressed feature gaps in the engine.

Bounding boxes are singular and movable atoms cannot be parented together. There are almost no engines where this is impossible without writing your own code.

I could go on, but I don't want to complain for too long.
So let's tackle reciprocity and improving density calculations.

Most game engines have collision channels that allow for multiple different kinds of density to coexist. This will break pathfinding, so beware.


Implementing reciprocity:

Reciprocity is a concept where an action concerning two objects will give both a mutual a say in whether an action succeeds or fails and both objects will be notified when an action occurs. BYOND's movement system lacks reciprocity, making the embedding of behavior tend to go in the wrong place. For instance, you might want something to happen when a player bumps into a certain object. But the only function that is called on a bump is Bump() for the object that moves. The object that was bumped into doesn't know that it has happened by default.

Similarly, a movable atom is never informed when it enters or exits a location or when it overlaps or stops overlapping an object.

Reciprocity is important for maintainable codebases and makes localizing the code for a new feature much easier. When you are working in environments like SS13's where many developers are touching many things, you need to be able to ensure that your changes are modular. If the behavior for a prototype winds up touching a dozen other object prototypes, you are going to resort to really ugly hacks like using the global root path hack to assure that code stays local and winds up in the right place (which the majority of the SS13 codebases have resorted to thanks to bad practices spread by programmers who didn't deeply understand DM making assumptions about how it works while maintaining a very volatile but understandable separation from those who did understand DM.)

atom
proc
Bumped(atom/movable/o)
set waitfor = 0

Enter(atom/movable/o,atom/oldloc)
return o.onEnter(src,oldloc,..())

Exit(atom/movable/o,atom/newloc)
return o.onExit(src,newloc,..())

Entered(atom/movable/o,atom/oldloc)
o.onEntered(src,oldloc)
..()

Exited(atom/movable/o,atom/newloc)
o.onExited(src,newloc)
..()

movable
Cross(atom/movable/o)
return o.onCross(src,..())

Uncross(atom/movable/o)
return o.onUncross(src,..())

Crossed(atom/movable/o)
o.onCrossed(src)
..()

Uncrossed(atom/movable/o)
o.onUncrossed(src)
..()

Bump(atom/o)
o.Bumped(src)
..()

proc
onEnter(atom/o,atom/oldloc,retval)
set waitfor = 0
return retval

onExit(atom/o,atom/newloc,retval)
set waitfor = 0
return retval

onEntered(atom/o,atom/oldloc)
set waitfor = 0

onExited(atom/o,atom/newloc)
set waitfor = 0

onCross(atom/movable/o,retval)
set waitfor = 0
return retval

onUncross(atom/movable/o,retval)
set waitfor = 0
return retval

onCrossed(atom/movable/o)
set waitfor = 0

onUncrossed(atom/movable/o)
set waitfor = 0


Okay, a few things here to go over:

Origin Hook -> Response Hook

Permissive:

  Enter() -> onEnter()
  Exit() -> onExit()
  Cross() -> onCross()
  Uncross() -> onUncross()

Behavior:
  Entered() -> onEntered()
  Exited() -> onExited()
  Crossed() -> onCrossed()
  Uncrossed() -> onUncrossed()
  Bump() -> Bumped()

The origin hook is called normally by Move(). The response hook is called from the origin hook and the return value of the origin hook is fed through as the final positional argument of the response hook. This allows the response hook to know what the origin hook permitted. The retval argument is only valid on permissive response hooks (onCross()/onUncross()/onEnter()/onExit())

onCrossed()/onUncrossed()/onEntered()/onExited()/Bumped() are behavior hooks. They do not return any values by default.

All of these functions are set to not wait for slept instructions just like all other movement-related functions (Move() refuses to be slept), so any return values must be set before the sleep otherwise the default value (null) will be returned and any return values after the sleep will no longer be part of the callstack.


Collision channels:

Collision channels allow us to avoid writing a metric buttload of hard-to-maintain and easily breakable Enter()/Exit() overrides. This makes for cleaner, smarter code that is more responsive, faster, and easier to understand. You need to understand binary to use this feature well.

#define COLLIDE_WORLD       1
#define COLLIDE_MOBS 2
#define COLLIDE_PLAYERS 4
#define COLLIDE_PROJECTILES 8
//supports up to 16 flags (2^15 maximum value). You can expand this by creating multiple flag/mask variables and extending the collision logic. You probably shouldn't need to though.

#define COLLIDE_ALL 15 //remember to update whenever you expand the collision flag set. Should be the OR of all values together, or 2^X-1 where X is the number of flags that have been defined.

atom
var
collision_layer = COLLIDE_WORLD //what collision layer(s) this object's bounding area counts as.
movable
var
collision_mask = COLLIDE_ALL //what the movable collides with.


Alright, now let's start overriding the hooks we set up earlier. The new logic pattern for collision is:

!(obstacle.density&&mover.density&&obstacle.collision_layer&movable.collision_mask)


Both objects must be dense and at least one collision channel must match for objects to collide with something. If one of these factors is not applicable, the permissive function will return true. We need to implement a hack though to prevent some default behavior from messing everything up. I'll explain it once you've seen the code.

var/list/movable_blockages = 0

//BEGIN HACK
turf
Enter(atom/movable/o,atom/oldloc)
if(density&&o.density)
if(!(collision_layer&o.collision_mask))
density = 0 //fool the engine into thinking that this turf isn't dense
. = ..()
density = 1 //tell it to you know, cut it out. wipe the value... with a cloth.
return .
return ..()
//END HACK

atom
movable
Cross(atom/movable/o)
return o.onCross(src,!(density&&o.density&&o.collide_mask&collide_layer))

area
Enter(atom/movable/o,atom/oldloc)
return o.onEnter(src,!(density&&o.density&&o.collide_mask&collide_layer))


The hack I mentioned earlier makes sure that the turf doesn't erroneously prevent movement. This can only happen when both the turf and the movable are dense but don't share any collision channels in common. The built-in implementation is just a hot god damn mess and I've complained about it loudly for a while.


If you don't want reciprocity (in other words: you are an idiot) you could use this alternative:

var/list/movable_blockages = 0

//BEGIN HACK
turf
Enter(atom/movable/o,atom/oldloc)
if(density&&o.density)
if(!(collision_layer&o.collision_mask))
density = 0 //fool the engine into thinking that this turf isn't dense
. = ..()
density = 1 //tell it to you know, cut it out. wipe the value... with a cloth.
return .
return ..()
//END HACK

atom
movable
Cross(atom/movable/o)
return !(density&&o.density&&o.collide_mask&collide_layer)

area
Enter(atom/movable/o,atom/oldloc)
return !(density&&o.density&&o.collide_mask&collide_layer)



Essentials:

Let's add a few other essentials that are pixel/tile movement agnostic while we're at it:

atom
movable
proc
canMove(atom/NewLoc,Dir=0,Step_x=0,Step_y=0)
set waitfor = 0
return 1

Moved(atom/OldLoc,oDir,oSx,oSy)
set waitfor = 0

Move(atom/NewLoc,Dir=0,Step_x=0,Step_y=0)
var/oLoc = loc, oDir = dir, oSx = step_x, oSy = step_y
. = canMove(arglist(args))&&..()
if(.||dir!=oDir)
Moved(OldLoc,oDir,oSx,oSy)


The above snippet includes a new built-in function for overriding pre-movement testing. This allows you to do some neat things that are pretty standard more simply, such as only allowing movement if the player is facing that direction, or preventing movement based on a movement delay, etc. It also allows you to more efficiently override the movement behavior of mobs without having to worry so much about screwing up the entire movement function and unknowingly breaking about a billion things.

Moved() allows you to build post-movement behavior more reliably as well as get information about the mover's relative change in location and more. It does happen to fire in the case of a simple change in direction and in some cases of failed movements due to bumps, so make sure you check the delta distance based on the old and current locations if you really depend on movement having happened for your override.

atom
movable
proc
Translate(x,y,Dir=0) //you need to be careful with this in tile-movement
set waitfor = 0
var/nx = x*TILE_WIDTH+step_x+bound_x, ny = y*TILE_HEIGHT+step_y+bound_y
var/turf/nl = locate(clamp(x/TILE_WIDTH,1,world.maxx),clamp(y/TILE_HEIGHT,1,world.maxy),z)
return Move(nl,Dir,nx-nl.x*TILE_WIDTH,ny-nl.y*TILE_HEIGHT)

Project(ang,dist,Dir=0) //don't use this in tile-movement
if(!dist) dist = step_size
var/nx = x*TILE_WIDTH+step_x+bound_x+cos(ang)*dist, ny = y*TILE_HEIGHT+step_y+bound_y+sin(ang)*dist
var/turf/nl = locate(clamp(x/TILE_WIDTH,1,world.maxx),clamp(y/TILE_HEIGHT,1,world.maxy),z)
return Move(nl,Dir,nx-nl.x*TILE_WIDTH,ny-nl.y*TILE_HEIGHT)

Step(dir,dist,facing=0) //you need to be careful with this in tile-movement
if(!dist) dist = step_size
var/mx = dir&EAST : 1 : dir&WEST ? -1 : 0, my = dir&NORTH : 1 : dir&SOUTH ? -1 : 0
var/nx = x*TILE_WIDTH+step_x+bound_x+mx*dist, y*TILE_HEIGHT+step_y+bound_y+my*dist
var/turf/nl = locate(clamp(x/TILE_WIDTH,1,world.maxx),clamp(y/TILE_HEIGHT,1,world.maxy),z)
return Move(nl,Dir,nx-nl.x*TILE_WIDTH,ny-nl.y*TILE_HEIGHT)


These functions give you quick and dirty means of doing pixel projection, translation, and step offsets and allow you to use overridden arguments unlike the built-in functions. The built-in functions should have NEVER been made global scope because of the arguments. step(), step_to(), step_toward() are just not well thought out or user-friendly and yet another of the things that should never have existed in the first place. >=(


ForceMove()

Now let's get to the most important part of snippet set #1. ForceMove(). A lot of times you want to move a player forcibly from one place to another. If you ever set the location of an object by assignment, Entered() and Exited(), Crossed() and Uncrossed() are no longer reliable ways of keeping track of objects that are currently on/in something. This means that once you have done this a single time, the only way to reliably figure out if something is on top of something else is via costly polling via bounds() or in contents checks. This is one of the major reasons that my approaches and my code don't work with the majority of BYOND games in existence. It's because almost everyone does this one thing that leads to massive headaches and problems down the line and the vast majority of you continue to do it, defending the practice ad populum without even the slightest clue why you are wrong. I cannot be held responsible for demolishing your argument and then refusing to put up with your passive-aggressive butthurtedness every time we ever interact int he future if you try to tell me I'm wrong about this. I'm not wrong about this. My approach is better even if it performs worse. Deal with it.

What is ForceMove() exactly? It's a means of forcing movement by ensuring that Entered()/Exited()/Crossed()/Uncrossed()/Moved() are called, but Enter()/Exit()/onEnter()/onExit() are not. Any time you'd manually set the location of an object, you will want to use this function. ForceMove() should always be considered a teleport, never a step or a jump.

atom
movable
proc
ForceMove(atom/NewLoc,Dir=0,Step_x=0,Step_y=0)
var/OldLoc = loc, oDir = dir, oSx = step_x, oSy = step_y
if(!Dir) Dir = dir
if(isturf(NewLoc)&&isturf(loc))
if(z==NewLoc.z)
var/dx = (x*TILE_WIDTH+step_x) - (NewLoc.x*TILE_WIDTH+Step_x), dy = (y*TILE_HEIGHT+step_y) - (NewLoc.y*TILE_HEIGHT+Step_y)
if(!dx&&!dy)
if(dir!=Dir)
dir = Dir
Moved(OldLoc,oDir,oSx,oSy)
return 1
else
return 0
else if(loc==NewLoc)
if(dir!=Dir)
dir = Dir
Moved(OldLoc,oDir,oSx,oSy)
return 1
else
return 0

var/list/olocs, list/nlocs
var/list/oareas = list(), list/nareas = list()
var/list/oobjs, list/nobjs

olocs = locs
if(isturf(loc))
for(var/turf/t in olocs)
oareas |= t.loc
oobjs = obounds(src)||list()
oobjs -= locs
else
oobjs = list()

loc = NewLoc
dir = Dir
step_x = Step_x
step_y = Step_y

nlocs = locs
if(isturf(loc))
nlocs = locs
for(var/turf/t in nlocs)
nareas |= t.loc
nobjs = obounds(src)||list()
nobjs -= locs
else
nobjs = list()

var/list/xareas = oareas-nareas, list/eareas = nareas-oareas
var/list/xlocs = olocs-nlocs, list/elocs = nlocs-olocs
var/list/xobjs = oobjs-nobjs, list/eobjs = nobjs-oobjs

for(var/area/a in xareas)
a.Exited(src,loc)
for(var/turf/t in xlocs)
t.Exited(src,loc)
for(var/atom/movable/o in xobjs)
o.Uncrossed(src)

for(var/area/a in eareas)
a.Entered(src,OldLoc)
for(var/turf/t in elocs)
t.Entered(src,OldLoc)
for(var/atom/movable/o in eobjs)
o.Crossed(src)

Moved(OldLoc,oDir,oSx,oSy)
return 1


Of course, ForceMove() is more or less a duplication of Move(). It returns 1 if the mover was actually relocated in any way or changed directions. It will return 0 if the forced movement would have no effect (IE currently in the position being forced to move to. Either way, it should be considered successful. The need to test the forced movement probably isn't there, but whatever. Distinguishing between the two cases could in theory happen, so why not?

Now for those among you that like shortcuts, there may be a situation where you want to force a translation, a projection, or a step:

atom
movable
proc
ForceTranslate(x,y,Dir=0) //you need to be careful with this in tile-movement
set waitfor = 0
var/nx = x*TILE_WIDTH+step_x+bound_x, ny = y*TILE_HEIGHT+step_y+bound_y
var/turf/nl = locate(clamp(x/TILE_WIDTH,1,world.maxx),clamp(y/TILE_HEIGHT,1,world.maxy),z)
return ForceMove(nl,Dir,nx-nl.x*TILE_WIDTH,ny-nl.y*TILE_HEIGHT)

ForceProject(ang,dist,Dir=0) //don't use this in tile-movement
if(!dist) dist = step_size
var/nx = x*TILE_WIDTH+step_x+bound_x+cos(ang)*dist, ny = y*TILE_HEIGHT+step_y+bound_y+sin(ang)*dist
var/turf/nl = locate(clamp(x/TILE_WIDTH,1,world.maxx),clamp(y/TILE_HEIGHT,1,world.maxy),z)
return ForceMove(nl,Dir,nx-nl.x*TILE_WIDTH,ny-nl.y*TILE_HEIGHT)

ForceStep(dir,dist,facing=0) //you need to be careful with this in tile-movement
if(!dist) dist = step_size
var/mx = dir&EAST : 1 : dir&WEST ? -1 : 0, my = dir&NORTH : 1 : dir&SOUTH ? -1 : 0
var/nx = x*TILE_WIDTH+step_x+bound_x+mx*dist, y*TILE_HEIGHT+step_y+bound_y+my*dist
var/turf/nl = locate(clamp(x/TILE_WIDTH,1,world.maxx),clamp(y/TILE_HEIGHT,1,world.maxy),z)
return ForceMove(nl,Dir,nx-nl.x*TILE_WIDTH,ny-nl.y*TILE_HEIGHT)



Rebounding:

For the final feature from snippet set #1, we're going to implement a reliable way to change an object's bounding box dynamically while keeping the object in place according to an anchor and calling the proper Crossed()/Uncrossed()/Entered()/Exited() hooks: the Rebound() function:

atom
movable
proc
Rebound(x,y,width,height,anchor=SOUTHWEST,offset=0)
if(isturf(loc))
var/list/oareas = list(), olocs = locs, omovs = obounds(src)-olocs
for(var/turf/t in olocs)
oareas |= t.loc

var/wx = src.x*TILE_WIDTH+step_x+substep_x+bound_x, wy = src.y*TILE_HEIGHT+step_y+substep_y+bound_y
var/ow = bound_width, oh = bound_height
var/oLoc = loc
var/oSx = step_x+substep_x
var/oSy = step_y+substep_y

if(offset)
if(x!=null) bound_x += x
if(y!=null) bound_y += y
if(width) bound_width += width
if(height) bound_height += height
else
if(x!=null) bound_x = x
if(y!=null) bound_y = y
if(width) bound_width = width
if(height) bound_height = height

if(anchor&EAST)
wx = clamp(wx+ow-bound_width,TILE_WIDTH,(world.maxx+1)*TILE_WIDTH-bound_width+bound_x)
else if(!(anchor&WEST))
wx = clamp(wx+(ow-bound_width)/2,TILE_WIDTH,(world.maxx+1)*TILE_WIDTH-bound_width+bound_x)

if(anchor&NORTH)
wy = clamp(wy+oh-bound_height,TILE_HEIGHT,(world.maxy+1)*TILE_HEIGHT-bound_height+bound_y)
else if(!(anchor&SOUTH))
wy = clamp(wy+(oh-bound_height)/2,TILE_HEIGHT,(world.maxy+1)*TILE_HEIGHT-bound_height+bound_y)

loc = locate(wx/TILE_WIDTH,wy/TILE_HEIGHT,z)
wx -= src.x*TILE_WIDTH
wy -= src.y*TILE_HEIGHT
step_x = wx
step_y = wy
substep_x = wx-step_x
substep_y = wy-step_y

var/list/nareas = list(), nlocs = locs, nmovs = obounds(src)-nlocs
for(var/turf/t in nlocs)
nlocs |= t.loc
var/xareas = oareas-nareas, xlocs = olocs-nlocs, xmovs = omovs-nmovs
var/eareas = nareas-oareas, elocs = nlocs-olocs, emovs = nmovs-omovs

for(var/atom/movable/o in xmovs)
o.Uncrossed(src)
for(var/turf/t in xlocs)
t.Exited(src,loc)
for(var/area/a in xareas)
a.Exited(src,loc)
for(var/area/a in eareas)
a.Entered(src,oLoc)
for(var/turf/t in elocs)
t.Entered(src,oLoc)
for(var/atom/movable/o in emovs)
o.Crossed(src,oLoc)

Moved(oLoc,dir,oSx,oSy,null)
else if(offset)
if(x!=null) bound_x += x
if(y!=null) bound_y += y
if(width) bound_width += width
if(height) bound_height += height
else
if(x!=null) bound_x = x
if(y!=null) bound_y = y
if(width) bound_width = width
if(height) bound_height = height


Rebound() takes the following arguments: x, y, width, height, anchor, offset. x and y are the bound_x and bound_y operands. width and height around the bound_width and bound_height operands. anchor is the point that the bounding box will stay anchored to. use a direction or 0 (specifies centered) to set the anchor. offset determines whether the x and y values are offsets. If this is true, x,y,width, and height will all be added to the current bounding box. Otherwise, the default action is to change to the values specified. If x,y,width, or height are null, the current values will be used. Additionally, if width or height are 0 or negative, the current values will be used.

To summarize:

All of these functions should have been built into BYOND from day #1. They aren't and that's just you know, kind of sad because the realization of these functions is the culmination of 15 years using the engine, exploring how it works, and finding its weak spots. Every other game engine in existence provided this level of functionality from launch. There's just no sense in calling this an engine for beginners when someone who has mastered the language and the environment inside and out has to bring this level of customization to bear in order to make the environment bearable to work in.
Metadata:

Now that we've totally upended the garbage heap that is the built-in movement functions, let's pull some information out of them. This section relates to getting metadata from movement functions that will help us to achieve a reasonable means of figuring out what happened during a movement. Sometimes you need to know what an object bumped into during a movement. Sometimes you need to figure out how far a mob moved during a movement. Other times you need to know how far the player was attempting to move after a movement. None of this information is readily available to you by default. We're going to fix that and we're going to do it as cleanly as possible. Fair warning, this uses some hacks to prevent circular references persisting when they aren't needed. You need to be aware of how garbage collection works to use some parts of this and you really need to understand the scheduler before you start trying to get reliable information about movement metadata from the systems I'm setting up.

atom
movable
var/tmp
//only reliable in the same frame as movement.
moving_flags
moving_dir
list/moving_obstacles
moving_x
moving_y

//always reliable
moved_x = 0
moved_y = 0


These are the new variables we're going to be implementing. moving_ prefixed variables refer to the current ongoing movement and should only be checked inside of movement-related procs. Once the Moved() has returned, these are no longer valid. That includes inside of spawned or slept child calls from within any movement-related functions. moving_obstacles can be checked just after the movement ends, but only within the same frame. So cache the data if you need it later on downstream by Copy()ing it into another variable. Don't rely on the data hanging around or the list contents referring to the same movement.

Here's why: To ensure that garbage collection doesn't get ruined by our metadata, we need to implement a function that will cull the metadata of all movers at the start of the next frame.

var/move_tracker/move_tracker = new/move_tracker()

move_tracker
var
list/movers = list()
proc
Tick()
set waitfor = 0
while(1)
for(var/atom/movable/o in movers)
o.moving_flags = null
o.moving_dir = null
o.moving_obstacles.len = 0
o.moving_x = null
o.moving_y = null
movers.len = 0
sleep()
New()
Tick()


The move_tracker datum will keep track of all movables that have moved in the current frame and set their moving_ prefixed variables to null.

Let's start adding some of this metadata tracking:

#define MOVE_STEP 1
#define MOVE_JUMP 2
#define MOVE_TELEPORT 4

atom
movable
Move(atom/NewLoc,Dir=0,Step_x=0,Step_y=0)
if(moving_obstacles&&moving_obstacles.len) moving_obstacles.len = 0
if(isturf(loc)&&isturf(NewLoc)&&z==NewLoc.z)
moving_x = (NewLoc.x*TILE_WIDTH+Step_y) - (x*TILE_WIDTH+step_x); moving_y = (NewLoc.y*TILE_HEIGHT+Step_y) - (y*TILE_WIDTH+step_y)
moving_dir = 0
if(moving_x>0) moving_dir |= EAST
else if(moving_x<0) moving_dir |= WEST
if(moving_y>0) moving_dir |= NORTH
else if(moving_y<0) moving_dir |= SOUTH
if(max(abs(moving_x),abs(moving_y))>=step_size+1)
moving_flags = MOVE_JUMP
else
moving_flags = MOVE_STEP
else
moving_x = 1#INF; moving_y = 1#INF
moving_dir = 0
moving_flags = MOVE_TELEPORT
return ..()

Bump(atom/o)
if(!moving_obstacles)
moving_obstacles = list()
else
moving_obstacles |= o
..()

Moved(atom/OldLoc,oDir,oSx,oSy)
moved_x = (x*TILE_WIDTH+step_x) - (OldLoc.x*TILE_WIDTH+oSx); moved_y = (y*TILE_HEIGHT+step_y) - (OldLoc.y*TILE_HEIGHT+oSy)
..()

ForceMove(atom/NewLoc,Dir=0,Step_x=0,Step_y=0)
moving_x = 1#INF; moving_y = 1#INF
moving_dir = 0
moving_flags = MOVE_TELEPORT
return ..()


This metadata is damn useful. Take advantage of it instead of constantly homebrewing your own patterns over and over again. This will tell you most everything you would probably want to know. moving_x/y could be used to get the angle of the attempted movement for calculating rebounds and impact velocities. moved_x/y would be used to calculate how much of a step is left to continue attempting in cases where movement should fail and then continue (like edge sliding). moving_dir can be used to prevent entry from a particular side of an object on Cross()/Uncross()/Enter()/Exit() without having to actually figure out the direction per-object, making such calculations much more efficient and less repetitive.

moving_flags could be useful for preventing Crossed()/Uncrossed()/Entered()/Exited() calls from doing certain things when certain objects teleport, step, or jump onto them. This is a common pattern that many would argue that my ForceMove() implementation makes more difficult. This is why the metadata is useful. If you were to step on a teleporter that uses Crossed() to detect what objects to teleport, ForceMove() would cause an infinite loop of teleportations without the metadata telling you that the player was forcibly moved into place and thus shouldn't be teleported.


Movement delays:

Movement delays are one of the most common things you can do in DM. In order to make a professional looking tile game, you need movement delays. You can probably get away without them in a pixel movement game TBH. But there's a downside to movement delays. If you implement a naive solution, you can't make the object respond to external forces or teleport it around during a delay. Don't worry fam, I got you covered. This is a hard modification to the call structure of the Move() proc. Get ready for the difficulty spike and breaking changes. They aren't going to stop from here.

#define MOVE_DIRECTED 8
atom
movable
var
move_delay = 0
tmp
next_move = 0
last_move = -1#INF

Move(atom/NewLoc,Dir=0,Step_x=0,Step_y=0,Source=src) //this isn't a simple override. You need to implement this into the structure of the move function yourself.
if(Source!=src) moving_flags |= MOVE_DIRECTED

canMove(atom/NewLoc,Dir=0,Step_x=0,Step_y=0,Source=src)
if(moving_flags&MOVE_DIRECTED)
return !hascall(Source,"canDirect")||Source:canDirect(src,NewLoc,Dir,Step_x,Step_y) //reciprocal permissive function
else if(next_move>world.time)
return 0
return 1

Moved(atom/OldLoc,oDir=0,oSx=0,oSy=0,Source=src)
if(moving_flags&MOVE_DIRECTED)
hascall(Source,"Directed")&&Source:Directed(src,OldLoc,oDir,oSx,oSy) //reciprocal behavioral function
else
last_move = world.time
next_move = last_move+move_delay

proc
canDirect(atom/movable/o,atom/NewLoc,Dir=0,Step_x=0,Step_y=0)
return 1

Directed(atom/movable/o,atom/OldLoc,oDir=0,oSx=0,oSy=0)


Directed() is called on an object when it is the source of another movement. It is the equivalent of Moved(). canDirect() is similar, but it is the equivalent of canMove().


Smoothed gliding:

Smoothed gliding is for tile-based games only. A move_delay is REQUIRED for this to work properly.

atom/movable
appearance_flags = LONG_GLIDE
Move(atom/NewLoc,Dir=0,Step_x=0,Step_y=0) //you need to implement this into your Move() function. This is not a proper override.
if(moving_flags&MOVE_STEP)
var/mframes = max(ceil(move_delay/world.tick_lag),1)
glide_size = step_size / mframes


Note that you will need to multiply delays by SQRT2 and remove LONG_GLIDE if you want diagonal movements to delay properly.


Move Queries:

Breaking changes ahoy! Movement querying allows you to check if something will successfully move into place. This changes a lot of the built-in guts of the movement functions and you need to know how it works. What we're going to do is add return values to Entered()/Exited()/Crossed()/Uncrossed() and Moved(). If it returns 0 that means that the behavior function should not actually do anything. This makes it so that your downstream overrides can target or ignore queried behavior calls selectively.

atom
Entered(atom/movable/o,atom/oldloc)
if(o.moving_flags&MOVE_TEST) return 0
//perform your default actions here
return 1

Exited(atom/movable/o,atom/newloc)
if(o.moving_flags&MOVE_TEST) return 0
//perform your default actions here
return 1

movable
Crossed(atom/movable/o)
if(o.moving_flags&MOVE_TEST) return 0
//perform your default actions here
return 1

Uncrossed(atom/movable/o)
if(o.moving_flags&MOVE_TEST) return 0
//perform your default actions here
return 1

Move(atom/NewLoc,Dir=0,Step_x=0,Step_y=0,Source=src,Flags=0)
moving_flags = Flags
//perform your default actions here

Moved(atom/OldLoc,oDir=0,oSx=0,oSy=0,Source=src,Flags=0)
moved_x = (x*TILE_WIDTH+step_x) - (OldLoc.x*TILE_WIDTH+oSx); moved_y = (y*TILE_HEIGHT+step_y) - (OldLoc.y*TILE_HEIGHT+oSy)
if(moving_flags&MOVE_TEST)
loc = OldLoc
step_x = oSx
step_y = oSy
dir = oDir
return 0
//perform your default actions here
return 1

Bump(atom/o)
if(!moving_obstacles)
moving_obstacles = list()
else
moving_obstacles |= o
if(moving_flags&MOVE_TEST)
return 0
//perform your default actions here
return 1


This might be a bit tough to understand the reason behind, but it's by far the easiest way to implement proper movement querying without reimplementing BYOND's entire native movement system as a separate proc and maintaining multiple similar rulesets for different movement subsets.


Centering:

This is another highly useful, but fairly low effort set of functions you will find useful. Centering functions. These functions will attempt to force an object to move to a location based on the center of another atom. These should only be used if you are using pixel movement:

atom
movable
proc
CenterOn(atom/movable/ref,Dir=0,Source=null,Delay=0)
if(ref.z)
var/cx = ref.x*TILE_WIDTH
var/cy = ref.y*TILE_HEIGHT
if(istype(ref))
cx += ceil(ref.step_x+ref.bound_width/2-bound_width/2)
cy += ceil(ref.step_y+ref.bound_height/2-bound_height/2)
else
cx += TILE_WIDTH/2
cy += TILE_HEIGHT/2
var/turf/t = locate(clamp(cx/TILE_WIDTH,1,world.maxx),clamp(cy/TILE_HEIGHT,1,world.maxy),ref.z)
ForceMove(t,Dir||ref.dir,cx-t.x*TILE_WIDTH,cy-t.y*TILE_HEIGHT)

CenterTranslate(atom/movable/ref,ox,oy,Dir=0,Source=null,Delay=0)
if(ref.z)
var/cx = ref.x*TILE_WIDTH+ox
var/cy = ref.y*TILE_HEIGHT+oy
if(istype(ref))
cx += ref.step_x+ref.bound_x+ref.bound_width/2-bound_width/2-bound_x
cy += ref.step_y+ref.bound_y+ref.bound_height/2-bound_height/2-bound_y
else
cx += TILE_WIDTH/2
cy += TILE_HEIGHT/2
var/turf/t = locate(clamp(cx/TILE_WIDTH,1,world.maxx),clamp(cy/TILE_HEIGHT,1,world.maxy),ref.z)
ForceMove(t,Dir,cx-t.x*TILE_WIDTH,cy-t.y*TILE_HEIGHT)

CenterProject(atom/movable/ref,ang,dist,Dir=0,Source=null,Delay=0)
if(ref.z)
var/cx = ref.x*TILE_WIDTH+cos(ang)*dist
var/cy = ref.y*TILE_HEIGHT+sin(ang)*dist
if(istype(ref))
cx += ref.step_x+ref.bound_width/2-bound_width/2
cy += ref.step_y+ref.bound_height/2-bound_height/2
else
cx += TILE_WIDTH/2
cy += TILE_HEIGHT/2
var/turf/t = locate(clamp(cx/TILE_WIDTH,1,world.maxx),clamp(cy/TILE_HEIGHT,1,world.maxy),ref.z)
ForceMove(t,Dir,cx-t.x*TILE_WIDTH,cy-t.y*TILE_HEIGHT)


It only gets crazier and more involved from here. I still need to cover subpixel movement, sliding movement and atomic parentage, but the end is within sight if you can stick with it.
Reserved for set #3
Reserved for set #4
Reserved for set #5
I don't know if "/atom/movable has locality" is really valid.
In a bug report Lummox explained to some of us tgstation13 SS13 devs that our /atom/movable subtypes were internally /obj, as in to Byond they were /obj, but they lacked the /obj path, so I would say here that /obj has locality, not /atom/movable.
I *suppose* you're just writing it out to cover all bases, but it'd be nice to label it as a special case of /obj (and the same with /atom being a special case of /turf)

Also I excitedly await the rest of this snippet.
This should be hawt. I was planning on playing around with unreal too near the end of summer since it's now free, would look good on a resume and gives some nice experience
This should be hawt.

Don't count on it. Code Dump means: "Semi-functional, but unpolished".

I don't know if "/atom/movable has locality" is really valid.

True in a way, but /obj, /mob, and /image all have locality and they all inherit that behavior from /atom/movable's core structure. It's just easier to think about the polymorphic cascade and consider /atom/movable derived types as being a compiler quirk.
Sets #1 and #2 have been written out and separated into their constituent parts.

Those of you that are fluent in code are going to have to work out a lot of my reasoning for yourself and explain it to those who aren't. I don't really have time/energy to explain a lot of things any more in depth than I already have.

Please take advantage of this and other coming braindumps because I'm tying up loose ends and trying to write down all the things that I've accumulated over the years for you guys' benefit. I won't be around as much as I have been the past few years and I'd like to leave without taking a huge chunk of this knowledge to the grave.
Is there a particular reason you use waitfor as you do?

Alright, most of you have read that I've sort of been working in Ue4 recently.

Are you working on releasing something? That's the idea I get based on your reasons stated.
Is there a particular reason you use waitfor as you do?

All movement-related procs are internally set to waitfor = 0. My reciprocals therefore mimic this behavior. sleep() is incorrect in movement-related procs: Move()/Enter()/Exit()/Entered()/Exited()/Crossed()/ Uncrossed()/Cross()/Uncross()/Bump(). Therefore their reciprocals inherit this behavior.

spawn() can be correct in these functions, but the occasion where it is is rarer than when it isn't.

Are you working on releasing something?

Yep, but it's not ready to show.
            if(!moving_obstacles)
moving_obstacles = list()
else
moving_obstacles |= o


Is this in error? I think you meant moving_obstacles = list(o).

Also fixed the syntax in some variables used in Step():

    var/mx = dir&EAST ? 1 : dir&WEST ? -1 : 0
var/my = dir&NORTH ? 1 : dir&SOUTH ? -1 : 0


Edit: I'm also catching on to your use of len. Useful alternative for when I would have normally used Cut().
A typo in your first post?

escape - when an object fully stops overlapping another object. Antonym of escape.
One nitpick is that "spacial" is actually spelled "spatial"
And "spacial" looks like you typo'd special