Skip to content

Instantly share code, notes, and snippets.

@OmerMor
Last active October 4, 2020 11:25
Show Gist options
  • Save OmerMor/3490296ec7cd7bfe45e7689fed35779c to your computer and use it in GitHub Desktop.
Save OmerMor/3490296ec7cd7bfe45e7689fed35779c to your computer and use it in GitHub Desktop.
SCI Kernel Functions
SCI Kernel Functions
====================
SCI Overview
This document details the capabilities of the Script Interpreter (sci) and
the interface to those capabilities through the Script programming
language. Before getting into the specific functions we'll take a look at
how sci operates in order to provide a background for the function
explanations.
When sci starts up, one of the first things that it does is set up two
memory spaces for memory management. One is the heap, and consists of an
area smaller than 64K which can be addressed by 16 bit offsets. This is
used for script code, variables, objects, lists, and other relatively small
things which we wish to access quickly. When allocating memory from the
heap, a pointer is returned, which is just the offset of the allocated
memory within the heap. Things which exist in the heap are at fixed
locations -- they are not affected by garbage collection.
The other memory space, hunk space, is much larger (128K or more, depending
on the target machine) and is used to hold resources: views, pictures, text,
background save areas, and anything else to which we do not need the access
speed of 16 bit pointers. When a resource is loaded or allocated, sci
returns a handle, which is a 16 bit pointer to a location in the heap which
contains a 32 bit pointer to the resource. Since all resource access is
through a handle, sci can do garbage collection in hunk space -- when there
is not enough memory to load a resource, sci will rearrange the currently
loaded resources in an attempt to create a large enough block of memory for
the new resource. If the garbage collection is unable to create enough
memory for the resource, sci will begin purging the least recently used
resources from hunk space until there is enough room. Purging resources
creates no problem, as any attempt to access a resource which is not in
memory will cause it to be loaded. With garbage collection and automatic
resource purging/loading, it is virtually impossible to run out of memory --
the worst condition which is likely to occur is constant disk access.
Once sci has initialized the memory management, graphics, etc., it turns
control over to the Script pseudo-machine (pmachine), which loads script 0
and starts executing pseudo-code (pcode) with entry 0 in that script. From
this point on, the pmachine executes the pcode produced by the sc compiler,
making calls to the kernel routines in the interpreter to do things such as
draw pictures, animate characters, etc.
Interfaces to the kernel are in kernel.sh. In the following descriptions,
remember that any of the arguments can be an arbitrarily complex expression
(including for example another kernel function call).
Many of the functions described here are never called directly, but are
hidden in object methods (described in Script Classes for Adventure Games).
These calls are given here for completeness and in case they are needed for
writing new classes.
Resource Functions
Resources are the various components of a game: views, pictures, scripts,
etc. and, except for the MEMORY resource, reside on disk, waiting to be
loaded when needed. Resources are handled automatically by the kernel, but
two functions are provided to allow the programmer a bit more control over
how the handling is done.
(Load resType resID)
Loads a resource of type resType and ID (number) resID into hunk space.
While any attempt to use a resource which is not loaded will cause the
resource to be loaded, it is not generally a good idea to rely on this
as it may cause a disk-access delay in the midst of a crucial animation
sequence. It is best to do an explicit Load of all resources during
the initialization phase of a room to insure that everything is in
memory. The resource types are:
VIEW
PICTURE
SCRIPT
SOUND
MEMORY (used internally by the kernel)
VOCAB (used internally by the kernel)
FONT
Example:
(Load SCRIPT curRoom)
loads the script whose number is in the variable curRoom into memory.
(UnLoad resType resID)
Purges the resource of type resType and ID (number) resID from hunk
space. This is not normally needed, as the kernel will automatically
purge the least recently used resource when it doesn't have enough
memory to load a new resource. This function is provided for a
situation in which it is advantageous to override this automatic
purging. Such a situation is unlikely.
Example:
(UnLoad SOUND EXPLOSION)
purges the sound whose number is EXPLOSION from memory.
List Functions
Lists play a crucial role in Script code, being the basic component out of
which such classes as Collection, List, and Set are built. The kernel list
(or kList, as it is known), is simply a block of memory with pointers to the
first and last kNodes (kernel nodes) of the list. The kNodes are doubly
linked, each having a pointer to both the previous and next node in the
list. The nodes also have a key and a value associated with them. The
value is the item being stored in the list (an integer, an object ID, etc.)
and the key is a means for looking up the value.
For better or worse, all of the kernel's internal functions for handling
lists are available to the Script programmer. Not all of them may be
useful.
(NewList)
Returns a pointer to a new kList with no elements.
(DisposeList kList)
Dispose of a kList. This involves disposing of all kNodes in the list
(but not any objects pointed to by the kNode value), then disposing of
the kList header itself.
(NewNode)
Returns a pointer to a new kNode.
(FirstNode kList)
Returns a pointer to the first node in kList, or NULL if kList is
empty. Note that what gets returned is a pointer to a kNode, not the
value stored in the kNode.
(LastNode kList)
Returns a pointer to the last node in kList, or NULL if kList is empty.
Note that what gets returned is a pointer to a kNode, not the value
stored in the kNode.
(InitList kList)
Initialize kList to be an empty list. This simply zeros the pointers
to the first and last nodes of the list. If the list is not empty,
this will leave the former contents of the list lying around with no
way of accessing them.
(EmptyList kList)
Returns TRUE if kList is empty, FALSE otherwise.
(NextNode kNode)
Returns the node which follows kNode in a list or NULL if kNode is the
last node in the list. Note that this returns the kNode, not the value
of that node.
(PrevNode kNode)
Returns the node which precedes kNode in a list or NULL if kNode is the
first node in the list. Note that this returns the kNode, not the
value of that node.
(IsFirstNode kNode)
Returns TRUE if kNode is the first kNode in a list, FALSE otherwise.
(IsLastNode kNode)
Returns TRUE if kNode is the last kNode in a list, FALSE otherwise.
(SetKey kNode key)
Set the key of kNode to key.
(GetKey kNode)
Get the key value of kNode.
(NodeValue kNode)
Return the node value of kNode.
(DeleteNode kList kNode)
Remove kNode from kList and return any memory it may have occupied to
the system. This does not dispose of whatever may be pointed to by the
kNode's value.
(AddAfter kList kNode aNode [key])
Add aNode to kList immediately following kNode (which had better be an
element of kList). If key is present, set the key of aNode to its
value. Returns aNode.
(AddBefore kList kNode aNode [key])
Add aNode to kList immediately before kNode (which had better be an
element of kList). If key is present, set the key of aNode to its
value. Returns aNode.
(AddToFront kList kNode [key])
Add kNode to the front of kList. If key is present, set the key of
kNode to its value. Returns kNode.
(MoveToFront kList kNode)
Move kNode to the front of kList. (kNode had better be an element of
kList.) Returns kNode.
(AddToEnd kList kNode [key])
Add kNode to the end of kList. If key is present, set the key of kNode
to its value. Returns kNode.
(MoveToEnd kList kNode)
Move kNode to the end of kList. (kNode had better be an element of
kList.) Returns kNode.
(FindKey kList key)
Return the first kNode in kList to have key as its key, or NULL if
there is no node with the key.
(DeleteKey kList key)
Delete the first kNode in kList which has key as its key. Return TRUE
if a node was deleted, FALSE if no node with the given key was found.
(NodeKey kNode)
Return the key for kNode. If no key was set, this may be garbage.
Object Functions
These functions are low-level functions for manipulating and getting
information about objects.
(Clone instance/class)
Return the object ID of a copy of instance/class. This copy has the
same property values and the same methods as instance/class. The
properties can be changed, the methods cannot.
(DisposeClone object)
Dispose of object if it was created with the Clone function, leave it
alone otherwise. This does not dispose of any objects which may have
their IDs in a property of object -- you must do that before calling
DisposeClone.
(IsObject object)
Returns TRUE if object is an object or class, FALSE otherwise. Useful
for testing to see that something is an object before sending a message
to it in a situation in which you can't be guaranteed that a value is
an object ID.
(CanUnderstand object selector)
Returns TRUE if selector is a valid selector for object, i.e. if
selector is the name of a property or method of object.
(ShowObjs withID)
Display all static and dynamic objects which are currently in the heap.
If withID is TRUE, show the object IDs as well.
System Functions
(ScriptID script [entry])
Return the object ID for the object which at entry number entry in the
publics table of script number script. This will load the script if it
is not already in memory. If entry is not present, this returns the ID
of entry number 0 of script.
(DisposeScript script)
While resources loaded into hunk space are automatically disposed of
when no longer used, when a script is loaded it is loaded into the heap
and remains there until disposed of by DisposeScript. This disposes of
script number script and should be called when you no longer need the
script.
(Wait n)
Wait until n timer ticks (1/60th of a second) have passed since the
last call to Wait. This is used to keep animation running at a
constant speed -- each pass through the main loop ends with a call to
Wait, so the main loop is executed at most once in a given time
interval. The standard value of n is 6, leading to animation every
1/10th of a second. If more than n ticks have occurred since the last
call to Wait, it returns immediately. The return value of Wait is the
number of ticks more than n since the last call.
(RestartGame)
This function resets the system to the state it had at the beginning of
the game, allowing the user to restart the game without rebooting it.
(GetTime [realTime])
With no arguments, returns the low word of the number of ticks (1/60th
of a second) since the game was booted. With an argument, returns real
system time in the format:
HHHH/MMMMMM/SSSSSS
String Functions
Strings in Script are kept in arrays, with two characters per array element.
Thus, when allocating space for a string of 40 characters, you only need to
allocate an array of 20 elements.
(ReadNumber string)
Returns the integer value represented by string.
(Format stringPtr formatStr arg1 arg2 ...)
Similar to C's sprintf. Formats a string in the storage space pointed
to by stringPtr based on the format string formatStr and the arguments
arg1, arg2, etc. Formatting commands embedded in formatStr are like
those of sprintf: they consist of the '%' character followed by
optional justification and field width characters followed by a
conversion character which tells how the corresponding argument is to
be converted to a string. Between the '%' and the conversion
character, there may be a
minus sign, indicating that the string representing the argument
is to be right justified (rather than the default of left
justified) in its field
number, indicating the width of the field (in characters) in which
the argument is to be printed.
The conversion characters supported are:
d Print the corresponding argument as a signed decimal integer.
u Print the corresponding argument as an unsigned decimal
integer.
x Print the corresponding argument as a hexadecimal number.
c The corresponding argument is taken to be the ASCII
representation of a character, which is printed.
s The corresponding argument is assumed to be a pointer to a
null terminated string, which is printed.
Examples:
If we have declared str somewhere as [str 40] (an 80 character string),
then
(Format @str "x:%4d y:%-4d" 23 45) -> "x:23 y: 45"
(Format @str "This is a %s." "test") -> "This is a test."
(StrCmp str1 str2)
Compares the null-terminated strings pointed to by str1 and str2.
Returns 0 if the strings are the same, 1 if str1 is greater than str2
(i.e. if the first character of str1 which does not match the
corresponding character of str2 is greater than the character in str2),
and -1 if str1 is less than str2.
(StrLen str)
Returns the number of characters in the null terminated string pointed
to by str.
(StrCpy str1 str2)
Copies the string pointed to by str2 to the storage pointed to by str1.
There had better be enough room in str1's storage to hold str2 -- there
is no checking.
(StrCat str1 str2)
Concatenates str2 to the end of str1. Str1 had better have enough
storage.
(StrEnd str)
Returns a pointer to the NULL which terminates str. This is useful for
Formatting a string on the end of another, rather than Formatting to a
temporary string and then using StrCat.
Picture Functions
(DrawPic picNum [showStyle])
Clear the background screen, then draw picture number picNum in it.
The picture will not be brought to the screen until the first Animate
call following the DrawPic. The optional showStyle specifies the
manner in which the kernel will bring the picture to the screen --
current possibilities are horizontal wipe, vertical wipe, and dissolve.
These are not yet available from the Script language.
(Show what)
Displays a given screen (visual, priority, or control) based on the
value of what. This can be used for debugging to see why an actor is
not able to enter a given area or why priorities aren't working
properly. The values of what are one of
VMAP (visual screen -- you're generally displaying this)
PMAP (priority screen -- objects will have their priorities
displayed, and animation will continue on this screen)
CMAP (control screen -- animation is stopped pending a
keystroke when this screen is displayed, since you wont
be able to see the Actors)
(PicNotValid)
Returns TRUE or FALSE depending on whether or not the picture window
needs updating.
Animation Functions
(Animate cast)
Cast is a kList of members of the cast (Actors and Props which are on
the screen). Animate updates the on-screen views and positions of all
members of the cast to correspond to the current state of their
properties. If a picture has been drawn since the last Animate, the
entire screen is updated. Certain bits in the signal properties of the
objects allow an object to be erased and removed from the cast or tell
Animate to leave the object in the cast but not to update it (in order
to gain speed when an object isn't changing).
(CanBeHere actor [dx dy])
Checks to see that an Actor can be in a certain position. Checks all
pixels in actor's base rectangle (the baseRect property) to see if any
are on pixels which have the controls specified by actor's illegalBits
property. If the actor is on illegal controls, CanBeHere returns
FALSE. Otherwise it returns TRUE. If the optional dx and dy arguments
are present, the baseRect is offset by these amounts before the check
is made.
(NumLoops actor)
Returns the number of loops in the current view of actor.
(NumCels actor)
Returns the number of cels in the current loop and view of actor.
(SetNowSeen actor)
Set the nowSeen rectangle of actor based on actor's current cel.
(CelWide view loop cel)
Return the width (in pixels) of cel cel of loop loop of view view.
(CelHigh view loop cel)
Return the height (in pixels) of cel cel of loop loop of view view.
(OnControl x y [rx ly])
Return a bit-mapped word which represents the control in the background
screen at the point x, y. If the optional rx, ly are specified, the
word has the bit set for each control which is within the rectangle
(x, y) - (rx, ly).
(DrawCel view loop cel left top priority)
Draw cel cel of loop loop of view view. Put the upper left corner of
the cel at (left, top). The cel should be at priority priority.
Input Functions
(GetEvent eventMask event)
Checks the input buffer for an input event of type specified by
eventMask. Returns FALSE if there are none. If an event exists, it
fills in the event record of the event instance whose ID is in event
and returns TRUE.
The types of events which may be specified in eventMask are:
mouseDown a mouse button was pressed
mouseUp a mouse button was released
keyDown a key was pressed
keyUp a key was released
menuStart the menu request key was hit
menuHit a menu item was selected
direction a direction event was received
These event types may be 'or'ed together to request multiple event
types. The symbolic value
allEvents
requests any event type.
(Parse stringPtr)
Parses the string pointed to by stringPtr and returns TRUE if the
kernel could parse the string, FALSE otherwise. The kernel can parse
the string if all the words in the string are in the game's vocabulary
(the file vocab.000) and the sentence structure is one recognized by
the kernel's parser.
(Said saidStr)
Checks to see if the parsed input sentence matches the input specified
by saidStr (to be documented later). Returns TRUE if the input matched
saidStr, FALSE otherwise.
Menu Functions
A Script MenuBar consists of a List of Menus, each of which is a List of
MItems (see Script Classes for Adventure Games). The menu bar is the line
at the top of the screen which contains the names of each of the menus. A
menu is the drop-down list of menu items which can be selected.
(DrawMenuBar menuList)
Draw the menu bar represented by the kList menuList on the top line of
the screen in the system font (font 0).
(MenuSelect menuList)
Drop down the first (leftmost) menu in the menu bar represented by
menuList and let the user select an item from the menu bar using cursor
keys. If the user presses ESC, return FALSE; if the user presses
ENTER, return the object ID of the item selected.
(MouseSelect menuList)
Drop down the appropriate menu (pointed to by the mouse) from the menu
bar represented by menuList and let the user select an item from the
menu with the mouse. If the user releases the mouse button when a menu
item is not highlighted, return 0; otherwise, return the object ID of
the highlighted item.
(DrawStatus str)
Replace the menu bar with a status line which consists of the string
str. If str is 0, discard the status line, showing the menu bar once
again. (Note that the user can still activate the menus by pressing
the mouse button with the cursor on the status line or by pressing the
menu selection key.)
Window and Text Functions
These functions deal with the main picture window, dialog windows, and
writing text to those windows.
(GetPort)
Returns the current grafPort.
(SetPort grafPort)
Sets the current grafPort to grafPort.
(GlobalToLocal event)
Convert the coordinates in the event object event from global (screen)
to local (window) coordinates. Event coordinates are always returned
in global coordinates, so this call is necessary to convert to the
coordinates within the current window.
(LocalToGlobal event)
The reverse of GlobalToLocal -- converts the coordinates in event from
the local window coordinates to global screen coordinates.
(TextSize rectPtr text font width)
Fills in the rectangle (an array of four elements) which is pointed to
by rectPtr with the bounding coordinates of the box which will hold
text printed in the font font. If width is non-zero, it is the maximum
width of the rectangle.
(Display text [at: x y] [font: f] [color: c] [back: b] [style: s])
Writes text to the current grafPort. The optional parameters are:
at: x y Position the upper left corner of the first
character of text at coordinates x, y in the
grafPort.
font: f Write the text in font f.
color: c Set the foreground color of the characters to c.
back: b Set the background color of the characters to b.
style: s Set the style of the characters to s. S may be one
of TPLAIN (plain text), TDIMMED (dimmed text) and
TBOLD (bold text).
Arithmetic Functions
(Random min max)
Returns a random number n such that 0 < min <= n <= max.
(Abs number)
Returns the absolute value of the signed integer number.
(Sqrt number)
Returns the square root of number, which is assumed to be unsigned.
(GetDistance x1 y1 x2 y2)
Returns the distance between the two points determined by (x1, y1) and
(x2, y2).
(GetAngle x1 y1 x2 y2)
Returns the angle between the two points determined by (x1, y1) and
(x2, y2). The angle is measured in degrees and is between 0 and 359
degrees.
Debugging Functions
There a number of functions designed for debugging Script programs by
providing information about the state of the program.
(SetDebug)
Pop up the debugging window. At the top of the window, in red, is the
name (if any) of the object self. Below it is the op-code about to be
executed. In columns on the right side of the window are the top five
values on the stack and the top five parameters. On the left are the
contents of the accumulator (acc), the address of the next instruction
(the instruction pointer, or ip), and the address of the top of the
stack (the stack pointer, or sp).
A number of instructions may be issued while in the debugger:
alt-D Put the debugging window away. This also can be used to
pop the debugging window up while the program is
running.
q Quit. Exit to DOS. Using alt-D to pop up the debugger
and q to quit will generally get you out of the program
even if your code is broken.
s Toggle the send stack on/off.
Enter Step to the next instruction, tracing into the procedure
or method referenced by a call or send instruction.
Tab Step to the next instruction treating a call or a send
as an indivisible instruction (don't trace into them).
tn Display the value of temporary variable number n.
ln Display the value of local variable number n.
gn Display the value of global variable number n.
i Open an inspector window, allowing you to inspect the
values of the properties of objects. See InspectObj
below.
(InspectObj object)
Open an inspector window on object. This displays the property names
and values for the object. Typing 'i' when this is displayed prompts
for a property name, whose value will be displayed either as a number,
string, or another object depending on what it is. If another object,
'i' can be typed again to inspect its properties, and so on until the
interpreter runs out of stack.
(ShowSends)
Show the current send stack. This allows you to see how you got where
you are. Entries in the display are of the form (object selector:)
where object is the object to which a message whose selector was
selector: was sent. The top line in the display is the most recent
send, the line below that is the send to the method which made that
send, and so on to the bottom line, which is the initial send from the
main loop in the base script.
(LargestPtr)
Returns the size (in bytes) of the largest block of memory available in
the heap.
(LargestHandle)
Return the size (in bytes) of the largest hunk available in hunk space.
If the largest available hunk is greater than 64K, returns 64K.
(FreeHeap)
Return the amount of memory (in bytes) which is free in the heap.
(FreeHunk)
Return the amount of memory (in paragraphs, or 16 byte blocks) which is
free in hunk space.
(ShowFree)
Displays the free memory blocks in the heap in the form
number-of-bytes@address.
(CSClear)
(CSEnable)
(CSDisable)
Rather esoteric functions provided in order to use the CodeSifter
execution profiler.
(StopWatch n)
If n is non-zero, start the stopwatch. If n is zero, stop the
stopwatch and return the number of 60th of a second ticks since it was
started.
File Functions
These functions allow access to some of the MS-DOS file functions. They are
best accessed through the File class.
(FOpen filename [mode])
Opens the file whose name is filename and returns a handle to it. The
optional parameter mode may be either fAppend, in which case the file
pointer will be positioned at the end of the file for appending, or
fTrunc, in which case the file will be truncated to zero length. If
mode is not specified, fAppend is assumed. If there is an error in
opening the file, a value of -1 is returned.
(FWrite handle string)
Write the text pointed to by string to the file whose handle is handle.
(FClose handle)
Close the file whose handle is handle.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment