Scripting

From Divinity Engine Wiki
Revision as of 17:25, 8 September 2017 by Rimevan (talk | contribs)
Jump to: navigation, search

Introduction

The scripting system is currently used for the behaviour of characters and items. For characters this is only part of the behaviour, as many more systems are influencing this in the following priority:

  • Story: executing Osiris Tasks
  • Dialogs: dialog behaviour and animations
  • Statuses: dying, frozen, petrified, ...
  • Scripts: executing the current reaction or scriptframe

Scripts are the lowest priority and will only execute if none of the other systems want to do something. For items it's a lot simpler, as the scripting system is the only thing that influences the items behaviour.

Sections

Before any section in a script, we can INCLUDE files. When you INCLUDE a file, you're telling the system to parse that file first.

INIT

In the INIT section you can declare global variables and inherit from other scripts. Global variables always start with % and can be accessed and modified everywhere (including other scripts, osiris, and in code). There are also EXTERN variables, which are exposed when you assign a script to an object so you can change the value for local instances of the script. The INIT section also contains the special variable '__Me', which contains the owner of the script. This is a character or item depending on the script type. Code will automatically fill this variable.
Inheritance is done with the USING keyword and copies everything from the other script into the current script. This includes all global variables, reactions, scriptframes, and events. You can use USING SHARED if you intend to overwrite reactions, events, or scriptframes.
An example INIT section:

INIT
     USING SHARED Base
     CHARACTER:__Me
     CHARACTER:%AnotherCharacter=null
     FLOAT3:%CurrentPosition=null
     EXTERN INT:%CanRun=1

If you want to override a specific reaction, event, or scriptframe you have to specify this with the OVERRIDE keyword:

REACTION TestReaction, 5 OVERRIDE
EVENT TestEvent OVERRIDE
SCRIPTFRAME TestFrame OVERRIDE

If needed, you can also only inherit specific reactions, events, orscriptframes:

USING ScriptName REACTION ReactionName,NewPriority
USING ScriptName EVENT EventName
USING ScriptName SCRIPTFRAME ScriptFrameName

BEHAVIOUR

This section contains the actual behaviour of the object. It solely consists of a whole bunch of reactions, of which only 1 reaction can be active at the same time. The current reaction gets selected based on its priority and its CHECK. The priority defines how much it wants to be executed and the CHECK decided whether its possible to be executed. The reaction with the highest priority whose CHECK succeeds will be selected for execution:

  • The whole list of reactions is always sorted from HIGH to LOW priorities.
  • We then check in that order all the reactions with a higher priority of the current reaction and see if their CHECK succeeds.
  • As soon as a higher priority reaction's CHECK succeeds, it interrupts the current reaction and will start executing.

Important note: only the CHECKs of higher priority reactions are evaluated every frame. This means that the current reaction's CHECK is NOT reevaluated while it's executing! It could become invalid during the execution. This is also true when calling Reset(): execution simply restarts at the beginning of the current reaction without evaluating the CHECK conditions again.

On top of the priority and CHECKs there's also the USAGE keyword. A reaction needs to specify a USAGE context. You can pick the following USAGE contexts:

  • USAGE COMBAT: can only be executed during combat when its the turn of the object
  • USAGE WAITING: can only be executed during combat when waiting for its turn
  • USAGE PEACE: can only be executed when not in combat
  • USAGE ALL: can always be executed

A reaction can have its own local variables. These variables have to start with an underscore and can only be accessed within the reaction itself.

As soon as a reaction is interrupted, the INTERRUPT event will be called immediately and you can execute some code to for example Reset the reaction. You can catch all INTERRUPTS or only specific interrupts (like the movement failed interrupt) and execute actions on the interrupt. If you catch a specific interrupt event you have the possibility to fill in variables for the event:

  • An underscore ('_'): this variable is not relevant for the event, it will not prevent the event from firing
  • A constant (e.g. "TestString") or a global variable: the variable has to be equal to this constant, otherwise the event will not be executed
  • A local variable: this variable will get filled with the variable from the event

Some examples:

OnEnteredCombat(__Me, _) // Only catch the event when __Me entered combat, the second variable one is irrelevant
OnEnteredCombat(_, %GlobalItemVariable) // Only catch the event when %GlobalItemVariable entered combat, the first variable is irrelevant
OnEnteredCombat(_LocalCharacterVariable, _) // Always catches the event, and _LocalCharacterVariable contains the character that entered combat. BEWARE: _LocalCharacterVariable can be null if an item entered combat

The actions during an interrupt are limited to immediate/simple actions, which can be executed immediately (e.g. CharacterMoveTo() is not allowed). Keep in mind though that a reaction can be interrupted for many reasons:

  • Higher priority reaction takes over.
  • Other system takes over: statuses/dialog/story
  • An exception was thrown in the script: e.g. pathfinding failed, ...
  • The object got culled (more details on culling can be found later on this page)

Important note: if a reaction gets interrupted and later gets resumed, it will continue executing where it got interrupted! (unless "Reset" was called in the INTERRUPT handler, in which case it will begin from the start again)

An example BEHAVIOUR section:

BEHAVIOUR
REACTION TestReaction, 5 // Priority 5
USAGE PEACE
VARS
     CHARACTER:_TestCharacter
CHECK "(c1|!c2)&!c3" // Reaction can be executed when one of the first 2 conditions passes, and the third condition doesn't pass
     IsInSurface(__Me, SurfaceOil)
     IsInDangerousSurface(__Me)
     CharacterIsFloating(__Me)
ACTIONS
     CharacterFleeFromSurface()
INTERRUPT
ON
     OnMovementFailed(_) // Only when interrupted by a failed movement
ACTIONS
     Reset()

STORY

There are specific story "reactions" called scriptframes. These are almost exactly the same as reactions, but they don't have a priority or CHECK block. They are managed by Story (Osiris) and can be SET or INJECTED. We keep a stack of all currently set scriptframes. If something is on the stack, the current REACTION always gets interrupted! The stack is the highest priority and comes before BEHAVIOUR reactions! Example of stack behaviour:

  • When you push something, it is put on the top of the stack.
  • When you pop, the top scriptframe is removed (happens when it finished executing)

In our case:
If you SET a scriptframe the stack gets cleared (Abort!) and the new scriptframe gets pushed on the stack.
If you INJECT a scriptframe, it will just push a copy of it on the stack. You can keep injecting the same scriptframe on the stack and it will be executed multiple times.
As soon as the TOP scriptframe is finished, it pops from the stack and the one below it starts/resumes executing.

Just like with reactions, if you INJECT a new scriptframe and there was already a scriptframe on the stack active, it will get interrupted and later resume where it was before. The syntax for writing a SCRIPTFRAME is exactly the same as a REACTION (except for the lack of priority and CHECK, and the fact that they need to be in the STORY section).

EVENTS

This section contains all the events that we want to catch. Events are always immediately and completely executed! It cannot take multiple frames: it's a blocking call and will execute and return immediately when it's done. Even when the object is culled or offstage will it execute its events. Events are always thrown to all objects in the current level. An event can be thrown from code, osiris, or from script itself.
In a reaction or scriptframe, each frame only 1 action gets executed at most. Let's take a piece of script from a REACTION:

Set(%TargetPos,%Enemy)
CharacterEvent(%Enemy,"Attack!") 
CharacterMoveTo(%TargetPos)

In the example above, the first 2 lines will take 2 frames (1 frame per line). The third one will take as long as it takes for the character to move to the target position. However, in an event the actions get executed immediately. Even if it was 100 actions with IFs and WHILEs, it would be executed as it was 1 action. For that reason, you cannot use actions in events that need time (Sleep, CharacterMoveTo, ...). Additionally, the number of actions an event can execute is limited. If you exceed the limit, Osiris will log an error and exit the event. In fact, let me amaze you even more. If you throw a CharacterEvent in an event, that spawns a new event and is thrown on every character and item... even all those events are executed immediately before it gets to the next line.

Just like INTERRUPTs in REACTIONs, EVENTs have to react on something (INTERRUPTs can and EVENTs must). The syntax is equal as well (more information on the event variables can be found in the REACTION INTERRUPT section).
An example EVENTS section:

EVENT TestInitEvent
ON
     OnInit()
ACTIONS
     IF "!c1"
          IsEqual(%Archetype,null)
     THEN
          CharacterSetArchetype(__Me,%Archetype)
          Set(%Archetype,null)
     ENDIF

Lists

Lists are a special parameter type and contain multiple parameters of a single type.

Important note: Lists are more convenient, but they are slower than normal parameters. They also have a limited size, so don't try to fill them with thousands of entries.

Declaring a list:

LIST<INT>:%TestListInt // Fine
LIST<CHARACTER>:%TestListCharacter // Fine
LIST<LIST<INT>>:%TestListNested // Error, can't nest lists

Adding entries:

ListAdd(%TestListInt, 0) // Fine
ListAdd(%TestListInt, {0;1;2}) // Error, trying to add a FLOAT3 to an INT LIST

Removing entries: indices start at 1, and end at the list size. All entries after the removed entry will be shifted to the left:

ListRemove(%TestListInt, 1) // Fine, assuming that the list has 1 or more entries
ListRemove(%TestListInt, 0) // Error, invalid index

Setting or getting entries:

ListSet(%TestListInt, 1, %AnInt) // Fine
ListGet(%TestListInt, 1, %AnInt)

ListSet(%TestListInt, 1, %ACharacter) // Error, trying to set a CHARACTER in an INT LIST
ListGet(%TestListInt, 1, %ACharacter)

ListSet(%TestListInt, 0, %AnInt) // Error, invalid index
ListGet(%TestListInt, 0, %AnInt)

Getting the list size:

ListGetSize(%TestList, %ListSize)

Clearing a list:

ListClear(%TestList)

Important note: Lists currently do not support EXTERN, constants, and STRING , meaning that the following lines will not work in scripts and result in an error during script build:

LIST<INT>:%TestList = {1, 2, 3, 4, 5} // Using a constant to initialize
ListGetSize({1, 2, 3, 4}, %ListSize) // Using a constant in an action call
EXTERN LIST<INT>:%TestList = {1, 2} // Using EXTERN and using a constant to initialize
LIST<STRING>:%TestString // Using STRING as the type