Index

   1. What is PixTudio?
   2. General
      2.1. Porting to your chosen system
   3. Language
      3.1. Processes and functions
      3.2. Control structures
      3.3. Unclassified
   4. Modules
      4.1. Official Modules
            4.1.0.1. Globals
            4.1.0.2. Functions
         4.1.1. Functions
         4.1.2. Constants
         4.1.3. Functions
         4.1.4. Functions
         4.1.5. Functions
         4.1.6. Functions
      4.2. List of Functions
      4.3. List of Constants
      4.4. List of Globals
      4.5. List of Locals
   5. Functions
      5.1. Crypt
      5.2. Debug
      5.3. Drawing
      5.4. Files
      5.5. Fonts
      5.6. Fpg
      5.7. Graphical effects
      5.8. Joystick
      5.9. Maps
      5.10. Math
      5.11. Memory
      5.12. Palettes
      5.13. Pathfind
      5.14. Process interaction
      5.15. Program interaction
      5.16. Regions
      5.17. Screen
      5.18. Scrolls
      5.19. Sorting
      5.20. Sound
      5.21. Strings
      5.22. Texts
      5.23. Time
   6. Variables
      6.1. Global variables
      6.2. Local variables
   7. Constants


What is PixTudio?

PixTudio is an Open Source 2D game engine and scripting language that originated as a fork of BennuGD. The project puts an emphasis on mobile gaming but it perfectly suitable for 2D game creation for the desktop, too. The scripting language is easy to understand and makes use of co-routines, called processes.

The game engine is, also, highly portable and should compile directly in Windows, Linux, OS X, Android & iOS but past versions of the code where compiled for multiple console systems (including Nintendo's Wii). It should also work with varying grades of effort in other Unices, Haiku or even newer console systems, given that an SDL2 port exists for the platform in question.



General


Porting to your chosen system

This is a general guide for getting your Bennu game onto your chosen system.

At the time of writing this stable ports and porting processes exist for these OS or platforms:

  • Windows
  • Linux
  • OS X (Intel)
  • Android
  • iOS

Starting Out

Instructions on compiling PixTudio here



Language

List of pages about the PixTudio language.

The pages listed here are mostly about the syntax of the language. In the ['general' category] are pages describing how the language works, with all its different aspects.




Processes and functions

subroutine

Definition

A subroutine is a program segment that can be called and used by any other bit of the program. So basically, if there's something that you want to do quite a lot in your program, then you can write a subroutine for it and then just call this subroutine every time you want to to that.

In PixTudio this is achieved by the use of functions and processes


function

Syntax

Function <returntype> <name> ( [ <parameters> ] )
[ Public
   [ <public variables> ]
End ]
[ Private
   [ <private variables> ]
End ]
Begin
   [ <function code> ]
[ OnExit
   [ <exit code> ]
]
End

Description

Function is a reserved word used to start the code of a function.

A function is a subroutine to which one or more of the following apply:

The difference between a function and a process is that the calling process or function waits until the function is completed. When a process or function calls a process, it doesn't wait. This means that, even when the called function contains frame statements, the calling function or process still waits for the function to finish. This is shown in this tutorial.

Example

    Function int addInts( int a , int b )
    Private // Declare private variables here
    Begin // Start the main functioncode
        return a+b;
    End // End the main functioncode

addInts(3,6); will return 9. One can see that the function does indeed:

  • receive parameters.
  • act on the parameters.
  • return a value.

process

Syntax

Process <name> ( [ <parameters> ] )
[ Public
   [ <public variables> ]
]
[ Private
   [ <private variables> ]
]
Begin
   [ <main code> ]
[OnExit
   [ <OnExit code> ]
]
End

Description

Process is a reserved word used to start the code of a process. If name is Main, that process will be started at the start of the program.

A process is a subroutine to which one or more of the following apply:

In addition to these possibilities, a process always has a frame; statement. The difference between a function and a process is a process is treated as a separate thread. This means one can't let a process return a value like a function, as the father process continues its code as well, as soon as the process hits a frame; statement or when the code is done. When that happens, the process 'returns' its ProcessID and continues the code (in the next frame).

When the frame; statement is reached in the code, a number of other local variables are defined or updated not only of the new process, but also of related processes. These are:

  • The father variable of the new process.
  • The son variable of the father process (updated).
  • The bigbro variable of the new process.
  • The smallbro variable of the processes called by the father immediately before the new process was called (updated).
  • The son and smallbro variables are also defined of the new process, but do not yet carry values.

When there are no more processes alive, the program ends.

Local variables as parameters

When a process is declared with parameters that are actually local variables, arguments for these parameters will initialise those local variables. This may sound strange, but an example will clear things up.

For example, consider the local variables x, y, z, file and graph. To create a process to move a game sprite around, you can declare it as follows:

process Ship (x,y,z,file,graph)
begin

    // move left 1 pixel per frame
    repeat
        x -= 1; // move 1 pixel to the left
        frame; // this process is done for this frame, wait for the next
    until (x<0);

end

Calling the process with e.g. Ship(300,100,5,0,1); will have the Ship appear at the coordinates (300,100) on Z-Level 5 with the Sprite No.1 in the file number 0. The ship will move left until it leaves the screen. You can change movement by changing the x/y value of the process and animate the ship by changing the graph value.

Example

Process SpaceShip( int x, int y, int angle, int maxspeed, int maxturnspeed)
Public // Declare public variables here
Private // Declare private variables here
    int speed;
Begin // Start the main processcode
    graph = new_map(20,20,8);
    map_clear(0,graph,rgb(0,255,255));
    Loop
        speed+=key(_up)*(speed<maxspeed)-key(_down)*(speed>-maxspeed);
        angle+=(key(_left)-key(_right))*maxturnspeed;
        advance(speed);
        frame;
    End
OnExit // Start the exit code
    unload_map(0,graph);
End // End the main processcode

Now one can call this process for example by doing the following.

Process Main()
Begin
    SpaceShip(100, 100, 0, 20, 5000);
    Repeat
        frame;
    Until(key(_ESC))
    let_me_alone();
End

And when the SpaceShip process ends -because the code reaches the End or some other process sent an s_kill signal- the OnExit code starts.

In this example it will unload the memory used for the created graphic. If there is no OnExit code, the process will just end without performing any special action.

This will make a SpaceShip with a cyan coloured block, able to move around the screen.


argument

Definition

An argument is the value passed on when calling a function or process. The variable and its value inside the definition of a function or process is called a parameter.

Example

    Function int my_proc( int parameter )
    Begin
        //statements
        return 0;
    End
    Process Main()
    Private
        int argument = 3;
    Begin
        my_proc( argument );
        my_proc( 4);
    End

See also


parameter

Description

A parameter is the variable and its value inside the definition of a function or process that is received from the calling environment. The value passed on when calling the function or process is called an argument.

If a parameter is named like a local variable, the value passed to it will be assigned to that local variable for a process. This means that passed arguments will modify the local variable. This is commonly used for x, y and graph local variables, but can also be used for alpha, angle and others.

Notes

There currently is a limit of 15 parameters that can be used per function or process.

Example

    Process Main()
    Private
        int argument = 3;
    Begin
        my_proc( argument );
    End
    Process my_proc( int parameter )
    Begin
        //statements
    End

See also



Control structures

if

Syntax

IF ( <condition> )
   [ <code> ]
( ELSEIF ( <condition> )
   [ <code> ] ) 
[ ELSE
   [ <code> ] ]
END

Description

if statements are used to control the flow of your program by means of checking conditions.

    if( <condition1> )
        // code1
    elseif( <condition2> )
        // code2
    elseif( <condition3> )
        // code3
    else
        // code4
    end
    // code5

The action that will be performed depends on the conditions:

  • If at the time the program reaches this if codeblock condition1 evaluates as true, then code1 will be executed and then code5.
  • If condition1 evaluates to false, the program will evaluate the next elseif and check if it is true or false: if condition2 evaluates as:
    • true, code2 and then code5 is executed.
    • false, the program will check the next elseif and do the same thing over.

If all other conditions evaluate to false and an else condition is present, the code in the else block will be executed. This code block thus acts as a default action that will be performed when no other condition is true.

The if statement must be closed with an end statement.

Example

Execute function

This is a little example of how to make a function perform a certain task depending on a command.

Function int execute(String command, int* params)
Begin

    if( command == "SEND" )
        NET_Send(atoi(params[0]),params[1]);
    elseif( command == "RECV" )
        NET_Recv(atoi(params[0]));
    elseif( command == "INIT" )
        NET_Init(atoi(params[0]),atoi(params[1]),atoi(params[2]));
    elseif( command == "QUIT" )
        NET_Quit();
    else
        // error: command unknown
        return -1;
    end

    return 0;

End

Movement

Movement with Ifs.

Loop
    if(key(_up))    y-=5; end
    if(key(_down))  y+=5; end
    if(key(_left))  x-=5; end
    if(key(_right)) x+=5; end
End

Of course, this is faster:

Loop
    y += 5 * (key(_down )-key(_up  ));
    x += 5 * (key(_right)-key(_left));
End

for (MISSING)

from (MISSING)

repeat (MISSING)

until (MISSING)

while (MISSING)

break (MISSING)

switch

Syntax

Switch ( <value> ) ( Case <value> : [ <code> ] End ) [ Default: [ <code> ] End ] End

Description

A switch is used to control the flow of a program by means of comparing a value to other values and executing the code associated with the correct value.

switch ( <value> )
    case <value1>:
        // code1
    end
    case <value2>:
        // code2
    end
    default:
        // code3
    end
end

When the switch is reached it will compare value with the values in the cases, going from top to bottom. When a case matches, that code is executed and the switch is exited. This is different from the switch in C and probably more languages, because there the switch is only exited when a break is reached or when the switch ends. In Bennu there is no break; for the switch, though.

A value in a case can also be a range: <lowervalue>..<uppervalue>. Both the lowervalue and the uppervalue are part of the range.

You can also specify multiple values in a case, separated by a comma: <value1>,<value2>,...<code>. These values can also be ranges.

Example

A scoretext function. Notice the default: when the points can be 0..100, that code should never be executed. However, an error can occur and blurting an error to the user is not that fancy, so this is a way of showing to the programmer there is an error, but still the user gets some message. In such cases, default can be handy. Of course that code could just as easily have been put under the switch with the same result, in this case, because every case does a return.

Function String scoretext( int points )
Begin

    Switch( points )
        Case 100:
            return "Perfect!";
        End
        Case 90..100:
            return "Awesomely cool, dude!";
        End
        Case 80..90:
            return "You're getting the hang of it!";
        End
        Case 60..80:
            return "Not too shabby, mate.";
        End
        Case 50..60:
            return "Practice some more.";
        End
        Case 30..50:
            return "Dude...weak.";
        End
        Case 1..30:
            return "That's just awful";
        End
        Case 0:
            return "No points? n00b!";
        End
        Default:
            return "I dunno what you did, but...";
        End
    End

End

loop (MISSING)

frame

Syntax

Frame [ ( <percentage> ) ] ;

Description

The frame; command tells the interpreter when a process is done for one game cycle. When the frame; is reached, the screen is updated. If there are several processes running, the screen is updated once every process has reached its frame; statement.

It is commonly used in loops of processes that should do something like moving around by a certain amount of pixels per game cycle (or per frame).

A possibility is to adjust the amount of cycles to wait. frame(100); would wait one cycle (100%), same as frame;. However frame(200); will wait two cycles (200% means the frame statement provides for 200% frame). So frame(50); will wait a half cycle or otherwise said, it will make a loop run twice per frame.

Example

Process Main()
Begin

    square();

    Repeat
        frame;
    Until(key(_ESC))

    exit();

End

Process square()
Begin

    graph = new_map(5,5,16);
    map_clear(0,graph,rgb(255,255,255));

    Loop
        x += 2 * (key(_right)-key(_left));
        frame; //<-vital part
    End

End

This example process would give you a square you can move around the screen by 2 pixel before it gets showed again, before the game cycle is over, before the frame; happens. If there would be no frame; in the loop, it would just run forever and the interpreter would wait forever for the frame;, which would result in freezing.


jmp

Syntax

jmp <label> ;

Description

The jmp command jumps to the given label inside a function. Unlike the call command, there is nothing more to it.

Example

import "mod_say"

Process Main()
Begin

    say(my_function(1));

End

Function my_function(int value)
Private
    int ret;
Begin

    Jmp real_begin;

jumping:
    ret = 300;
    return;

real_begin:
    ret = 100;
    if(value == 1)
        Call jumping;
    end
    ret += 200;
    return ret;

End

Used in example: process, function, jmp, call, return

The output of this example is 500, when value is 1. This example show 500 because the input value is a one and it causes that goes to the jumping label inserting a 300 and adding a 200 after.


call

Syntax

call <label> ;

Description

The call command jumps to the given label inside a function or process until it comes across a return statement. When this happens, it jumps back to call statement and resumes after it.

Example

import "mod_say"

Process Main()
Begin

    say(my_function(1));

End

Function my_function(int value)
Private
    int ret;
Begin

    Jmp real_begin;

jumping:
    ret = 300;
    return;

real_begin:
    ret = 100;
    if(value == 1)
        Call jumping;
    end
    ret += 200;
    return ret;

End

Used in example: process, function, jmp, call, return

The output of this example is 500, when value is 1. This example show 500 because the input value is a one and it causes that goes to the jumping label inserting a 300 and adding a 200 after.


clone

Syntax

Clone

: <sentences>

End

Description

The clone command creates a copy of the actual process which is called a "child process." The original process is then called the "parent process".

Only the child process will run the sentences between the keyword CLONE and the keyword END.

Example

import "mod_key";
import "mod_map";
import "mod_video";
import "mod_proc";

Process Main()
Begin

    squares();

    repeat
        frame;
    until(key(_ESC));

    let_me_alone();

End

Process squares()
Private
    int advance;
Begin

    graph = map_new(5,5,16);
    map_clear(0,graph,rgb(255,0,255));
    advance = 1;

    clone
        graph = map_clone( 0, graph );
        map_clear(0,graph,rgb(255,255,255));
        advance = 2;
    end

    loop
        x += advance;
        frame;
    end
    map_unload(0,graph);

End

Used in example: key(), map_new(), map_clear(), rgb(), map_unload() This example shows two squares. One is the child process, that is the white, and the other is the parent process.



Unclassified

Array

Definition

<datatype> <array name>[<upperlimit>] [= <values>]

Arrays are datatypes, consisting of a range of variables of the same type. The range is 0..upperlimit, meaning there are upperlimit+1 elements in the array.

The initializing values start at the first (0th) element and go up from there.

Example

Mutliple ints

int lottery[9]; // an array of 10 ints

Use them like:

lottery[0] = 1;
lottery[5] = 35;
lottery[1] = lottery[5];

Multiple types

Consider, using Type:

Type _point;
    float x;
    float y;
End

_point point[2] = 1,2,// an array of 3 points at positions (1,2), (3,4) and (5,6)
                  3,4,
                  5,6;

Use them like:

point[0].x = 0;
point[1].y = 54.2;
point[2].x = point[0].x;
point[1].x = point[2].y = 23.2;

Multiple structs

See Struct.


Byte

Definition

BYTE

Bytes are whole numbers ranging from 0 to 2^8-1 ( 0 to 255 ). This is because a byte uses 8 bits (1 byte) to denote its value. A byte is the smallest datatype directly accessible in nowadays memory.


Const

Syntax

Const
    constants
End

Description

Const is a reserved word used to initiate the declaration of constants. Terminating the declaration block with an End is needed when the Const statement is not used in conjunction with the main code of the Program.

When declaring constants inside this construct, it's now allowed to explicitly name the type of the constant, i.e. you only have to assign the constant the value you want.

For a list of predefined constants, see this page.

Example

Const // Declare constants here
    myInt = 4;
    myString = "hello";
End

Process Main()
Begin
End

Const // Declare constants here
End

Continue (MISSING)

Debug

Syntax

Debug ;

Description

Debug is a reserved word used to tell PixTudio to go into debug mode, only if the DCB was compiled with debug information (compiler option -g). If the module mod_debug was imported as well, the console is immediately invoked and one can begin tracing from the debug statement.

Here's a handy page about debugging a Bennu program.

Example

    Function int debug_warning(string warning)
    Begin
        say("Warning: " + warning);
        debug;
        return 0;
    End

Used in example: say(), debug


Declare

Syntax

Declare [ Function | Process ] [ {returntype} ] {name} ( [ {parameters} ] )

Private
   {private variables}
End
Public
    {public variables}
End

Description

Declare is a reserved word used to declare a [process] before its actual code. This can be useful if the function or process needs to be known before it is actually defined, like when the function returns something other than an [int] or when the [publics] of the process need to be accessed before the definition. By default, the returntype of a process or function is an [int].

When using this statement, a few things can be defined about the process/function:

  • If it's a process or function
  • Its returntype
  • The parameters of the process or function
  • The public variables of the process or function
  • The private variables of the process or function

The first three are defined when using the statement Declare, while the last two are defined within the Declare block.

Example

    Declare Process example_process()
        Public // Declare public variables for the process example_process
            int public_int;
            string public_string;
        End
    /*  The Process definition handles this section
        Private // Declare private variables for the process example_process
            int private_int;
        End
    */
    End

    Declare Function string example_function( int param_int)
        Private // Declare private variables for the process example_process
            int private_int;
        End
    End

    Process example_process();
    /* The Declare handles this section.
    Public
        int public_int;
        string public_string;
    */
    Private
        int private_int;
    Begin
        Loop
            frame;
        End
    End

    Function string example_function( int param_int)
    Begin
        return "";
    End

Dup

Syntax

Dup [ ( {value} ) ] ;

Description

The dup(value); return a space data filled with the given value. For example a 10 dup(0) return an array of 10 elements, all with a zero value.

Example 1

    import "mod_say";

    global
        array[] = 10 dup(0);

    begin
        say ( sizeof(array)/sizeof(array[0]) );
    end

This example prints 10 because the size of array is ten and the size of the first element is one.

Example 2

    import "mod_say";

    global
        int array[5] = 1 , 4 dup(0);
        int arrayPosition;
    begin
        for ( arrayPosition = 0 ; arrayPosition < 5 ; arrayPosition = arrayPosition + 1 )
            say ( array[arrayPosition] );
        end
    end

This example prints:

1 0 0 0 0

As it duplicates "0" four times in the array data.


Float

Definition

FLOAT

Floats are floating point numbers ranging from about -10^38.53 to about 10^38.53. This is achieved by dividing 32 bits (4 bytes) in a certain way, with a certain precision. A float is used for operations in which both very large and small numbers are used, while rounding is not permitted. Unlike ints or shorts, a float actually has decimal digits. Their accuracy is about 7 decimal digits.


Global

Syntax

Global
    {global variables}
End

Description

Global is a reserved word used to initiate the declaration of global variables. Terminating the declaration block with an End is needed when the Global is not used in conjunction with the main code of the Program.

For a list of predefined global variables, see this page.

Example

    Global // Declare global variables here
    End

    Process Main()
    Begin
    End

    Global // Declare global variables here
    End

Goto

Equals to Jmp


Import

Syntax

import "{module name}"

Description

Imports a PixTudio module named module name into the program, which allows the usage of additional functionality in a PixTudio program.

Example

    import "mod_say"
    import "my_dll";

    Process Main()
    Begin
    End

Include

Syntax

include "{filename}"

Description

When the compiler reaches an include statement, it continues compilation at the included file and when it's done resumes compiling from the statement right after the include. In other words, these files contain code that gets inserted at the place of inclusion.

This is very handy for breaking up your code into pieces. The handling of video in one include file, audio in another, game logic in another, etc. This makes code more maintainable and understandable; moreover it makes code reusable. The video handling include file you made for one game can be used for another game (if it was coded in a generic fashion) without spitting through the whole sourcecode of the first game.

Also headers can be used to import modules and possibly give a little more functionality to that module.

Example

main.prg

    // The code in "bar.inc" will be inserted here:
    include "bar.inc"

    import "mod_say"

    Process Main()
    Private
        int barcode;
    Begin
        barcode = bar();
        say(barcode);
    End  

bar.inc

    import "mod_rand"

    Function int bar()
    Begin
        return rand(0,10);
    End

Used in example: include, import, write_int(), key()


Int

Definition

INT

Ints (short for integer, meaning wholes), are whole numbers ranging from -2^31 to 2^31-1 ( -2147483648 to 2147483647 ). This is because an integer uses 32bits (4 bytes) to denote its value using the Two's complement system.


Local

Syntax

Local
    {local variables}
End

Description

Local is a reserved word used to initiate the declaration of local variables. Terminating the declaration block with an End is needed when the Local is not used in conjunction with the main code of the Program.

For a list of predefined local variables, see this page.

Example

    Local // Declare local variables here
    End

    Process Main()
    Begin
    End

    Local // Declare local variables here
    End

Offset (MISSING)

OnExit (MISSING)

Pointer

Syntax

Declaration of a pointer:

{datatype} POINTER {pointername};

Assignment of a value to the location pointed to:

POINTER {pointername} = {value};

Concept

Pointers, are used to point to a location in memory. It uses 32 bits (4 bytes) so it can map 4GB of memory into bytes. Pointers can point to any datatype: ints, shorts, strings or even usermade datatypes.

However, using a struct pointer my_pointer is pointless, because the compiler has no knowledge of the elements inside the struct pointing to, since it doesn't know which struct is meant, so this is invalid. MyStruct pointer my_pointer, where MyStruct is an existing struct, is also not valid, because MyStruct is not a datatype. The only way to have something like a struct pointer my_pointer is to use Type as seen in the example.

Example

    import "mod_say"

    Type _point
        int x;
        int y;
    End

    Type _person
        string name;
        int age;
    End

    Global
        _person Person;
    End

    Process Main()
    Private
        int my_int;
        int* my_int_pointer;
        _point myPoint;
        _person* personPointer; // possible, because _person is infact a datatype
        //Person* personPointer; // not possible, because Person is not a datatype
    Begin

        my_int_pointer = &my_int;

        my_int = 3;
        say(my_int);
        say(*my_int_pointer);

        *my_int_pointer = 4;
        say(my_int);
        say(*my_int_pointer);

        setXY(&myPoint);
        say(myPoint.x);
        say(myPoint.y);

        personPointer = &Person;
        personPointer.name = "Mies";
        say(Person.name);
        say(personPointer.name);

    End

    Function int setXY(_point* p)
    Begin
        p.x = 3; // this is actually (*p).x = 3, but . can be used like this
        p.y = 5; // this is actually (*p).y = 5, but . can be used like this
        return 0;
    End

Used in example: say(), key(), Type, Global, Private, point

The & (offset) operator, when used with pointers, returns a void pointer to a variable. In the example it returns an int pointer to the variable my_int. The * (pointer) operator, when used with pointers, makes it so the pointer variable is not accessed, but the variable it's pointing to. In the example it changes access from my_int_pointer to my_int.


Private

Syntax

Private
    {private variables}
End

Description

Private is a reserved word used to initiate the declaration of private variables. Terminating the declaration block with an End is not necessary, but is possible. Parameters of a function or process will be considered a private variable with the initiated value of the passed argument.

Example

    Process My_Process();
    Public
    Private // Declare private variables here
    Begin
    End

Program

Syntax

Program {programname};

Description

Program is a reserved word used to begin your program. It's not needed to start a program with it.

It should be noted that this is for backwards compatibility only, because it doesn't actually do anything.

Example

    Program example; // Name this program "example", which doesn't really matter

    Process Main() // This process is started when the program is started
    Begin
    End

When the End of the main code is reached, the program exits, if there are no processes alive anymore, which is logical, as PixTudio quits when there are no processes running and Main is a process as well. This process is just like any other process with the addition it gets called when the program starts. This means that you can also call the process using main().


Public

Syntax

Public
    {public variables}
End

Description

Public is a reserved word used to initiate the declaration of public variables. Terminating the declaration block with an End is not necessary, but is possible.

Example

    Process My_Process();
    Public // Declare public variables here
    Private
    Begin
    End

Return

Definition

Return {value};

Return is a reserved word used to return a value in a function. The returned value must be of the datatype specified as the returndatatype (see Function). By default, the returntype of a process or function is an int. When this statement is reached, the function in which it resides will stop execution and return the specified value. If a value was not specified, the ProcessID will be returned.

Example

    Function string example_function()
    Private
        string s;
    Begin
        s = "Some string";
        return s;
    End

Used in example: Function, Private, Begin, End, Return, String


Word or Short

Definition

SHORT or WORD

Shorts or Words are whole numbers ranging from 0 to 2\^16-1 ( 0 to 65535 ). This is because a short or word uses 16 bits (2 bytes) to denote its value.


Sizeof

Syntax

INT sizeof ( {datatype} )

Description

Calculates the size of a block of memory. Returns the size in bytes.

Parameters

Returns

INT : The size of the data type, in bytes.

Definition

The sizeof() operator is used to calculate the size of datatypes. This is important for creating dynamic data structures wich are created with the functions alloc(), calloc() and realloc(). These three functions allocate space in bytes. For instance, an int in bennu is 4 bytes long. When dealing with data structures of self-defined types, it can be tedious to calculate the exact size manually. But this is not the only reason, for instance, when a linked list is created, the struct may be changed by the programmer, and in that case the size changes. By using sizeof(), you can avoid the problems of allocating too few or too much space.

Further reading

General article about the use of sizeof

Example

    // import modules
    IMPORT "mod_say";
    IMPORT "mod_debug";
    IMPORT "mod_mem";

    // user defined data type, should be 29 bytes in size.
    TYPE custom_datatype;
       int cat;
       int dog;

       byte kind;

       char name[19];
    END

    GLOBAL
      STRUCT custom_datatype2;
         char name[19];
         STRUCT animal[9];
            char remarks[255];

            int age;
            int speed;

            byte kind;
            byte fur_color;
            byte sound;    
            byte num_legs;
            bool can_fly;
            bool has_horns;
         END

      END

      int var1;             // 4 bytes
      byte var2;            // 1 byte
      float var3;           // 4 bytes

      char text1[4]="hello";     // 5 bytes
      string text2="world";       // 4 bytes, is sort of pointer thingy 

      int integer_array[255];      // (0-255), 256 x 4 bytes = 1024 bytes

    PROCESS main();

    BEGIN

       say("");
       say("");
       say("sizeof() demonstration");
       say("");
       say("");
       say ("the size of custom_datatype: "+sizeof(custom_datatype)+" is bytes");
       say ("the size of custom_datatype2: "+sizeof(custom_datatype2)+" is bytes");
       say ("the size of var1: "+sizeof(var1)+" is bytes");
       say ("the size of var2: "+sizeof(var2)+" is bytes");
       say ("the size of var3: "+sizeof(var3)+" is bytes");
       say ("the size of text1: "+sizeof(text1)+" is bytes");
       say ("the size of text2: "+sizeof(text2)+" is bytes");
       say ("the size of int_array: "+sizeof(integer_array)+" is bytes");

    END

Used in example: alloc(), calloc(), realloc(), struct, type, say(), Global


String

Definition

STRING

Strings are a sort of character array, combining characters to form text. Because the length of a string is dynamic, adding them is done easily. Single and double quotes can be used to create strings.

Example

    Program strings;
    Private
        String name;
        String surname;
    Begin
        name = "Yo";
        surname = "Momma";

        say(name + " " + surname + " has entered.");
        say('User logged on: "' + name + " " + surname + '"');

        Repeat
            frame;
        Until(key(_ESC))

    End

Used in example: say(), key()

Notes

There are some things to be aware of with strings of the "string" data type:

  • Do not manually allocate data structures with strings in them (more specifically, don't use [alloc]() on them).
  • Do not use memmove() or memcopy() on string variables or structures/arrays containing them.
  • PixTudio strings are integer identifiers, so using sizeof with them is pointless, as it will always return the size of an int. This is because bennu creates it's own internal database for strings, and therefore it is simply an identifier.
  • Internally, the string data itself is a character array delimited with a NULL character, just like an ANSI / C string.
  • The memory for these strings is managed by bennu, thus manual memory operations on them can cause harm on bennu's internal string managment.
  • All local/private/public strings are automatically released (freed) when processes/functions die or exit.

However, if you want to do some manual memory managment on strings you can:

  • Create a simple character array yourself.

If you want to create a string list:

  • You can create a linked list of processes using their Father and Son fields to create the links.
  • Use textfiles.
  • Create on big string in combination with an array that contains information about substrings.
  • Create an array of character arrays.

Struct

Definition

Struct {struct name}
    {Members}
End

Structs are datatypes able to contain variables of all datatypes.

To address a member of a struct, use the . operator: {structname}.{membername}. Like all datatypes, one can have a whole range of them, as displayed in the example (also see Array).

There are two ways to fill a struct on declaration:

  • Per member
  • Afterwards, like Arrays.

See the examples on how to do it.

Example

Structs can be handy for many aspects of programming.

Grouping of variables

This is for clarity and to avoid colliding variable names.

    Struct Fileinfo
        String name;
        String path;
    End

Note that the struct fileinfo is a predefined global variable.

Maybe you want to group some other data, like settings of the screen:

    Struct Window
        int width = 320;
        int height = 200;
        int depth = 8;
    End

or (using other initializing syntax):

    Struct Window
        int width;
        int height;
        int depth;
    End = 320,200,8;

This example can also be done by defining your own type.

Multiple identical data groups

    Struct Ship[9]
        int x;
        int y;
        int speed;
        int angle;
    End

There are 10 Ships now. The data can be accessed like:

    Ship[0].speed++;
    Ship[8].angle = 0;

Type

Datatype declaration

Definition

Type {name}
    {variables}
End

Creates a new datatype. It's handled as if it were a struct, so the declared variables are members of the struct.

While it's a convention to use a _ as first character in the name of a datatype, it's not mandatory.

When used as an argument in a function or process, the parameter is not a copy, but the variable itself, as shown in the first example, and any change made to the parameter is also changed in the argument. It's more elegant to use a pointer though, as it also displayed.

Example

A file with name and path. Note that the assignment myFile2 = myFile; makes a copy of myFile and throws it into myFile2, which is normal. But when it's used as an argument in a function, the parameter is not a copy but the _file itself.

    Type _file
        String path;
        String name;
    End

    Process Main()
    Private
        _file myFile;
        _file myFile2;
    Begin

        myFile.path = "C:\";
        myFile.name = "autoexec.bat";
        say("1: " + myFile.path + myFile.name);

        myFile2 = myFile;
        myFile2.name = "config";
        say("1: " + myFile.path + myFile.name);
        say("2: " + myFile2.path + myFile2.name);

        setName(myFile,"pagefile");
        say("1: " + myFile.path + myFile.name);

        setName2(&myFile2,"pagefile");
        say("2: " + myFile2.path + myFile2.name);

        Repeat
            frame;
        Until(key(_ESC))

    End

    Function setName(_file f, string name)
    Begin
        f.name = name;
    End

    Function setName2(_file* f, string name)
    Begin
        f.name = name; // this is actually (*f).name = name, but . can be used like this
    End

Used in example: say(), key(), Pointer

A point with x and y.

    // Declare the type _point
    Type _point
        float x;
        float y;
    End

    // Declare the function distance(), because the function returns a datatype
    // other than int, so it needs to be declared before usage.
    Declare float distance(_point a,_point b)
    End

    Process Main()
    Private
        _point p1,p2;
    Begin

        p1.x = 15.3;
        p1.y = 34.9;
        p2.x = 165.4;
        p2.y = 137.2;

        write(0,0,0,0,"Distance: " + distance(p1,p2));
        drw_line(p1,p2);

        Repeat
            frame;
        Until(key(_ESC))

    End

    Function float distance(_point a, _point b)
    Begin
        return sqrt( (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
    End

    Function int drw_line(_point a, _point b)
    Begin
        return draw_line( a.x , a.y , b.x , b.y );
    End

Used in example: write(), key(), sqrt(), draw_line()

ProcessType

Definition

Type {processname}

Acquires the processTypeID of a processType or function. This can be useful for example with get_id() and signal().

Example

    Program example;
    Private
        proc proc_id; //int could be used too
    Begin

        // Start 3 proc's
        proc();
        proc();
        proc();

        // Display all alive proc's
        y = 0;
        while( (proc_id=get_id(type proc)) )
            write(0,0,(y++)*10,0,"proc: " + proc_id);
        end

        // Wait for key ESC
        Repeat
            frame;
        Until(key(_ESC))

    End

    Process proc()
    Begin
        Loop
            frame;
        End
    End

Used in example: get_id(), write(), key()


Varspace

Definition

VARSPACE

A varspace is a datatype of any datatype. When a function, like sort() or fread(), has a parameter of type varspace, it means it needs a variable of any type.


Void

Definition

VOID

PixTudio doesn't have voids as such. But when we look at for example the function free(), we see that you can pass it a void pointer. This means, that you can pass it a pointer of whatever type you want; an int pointer, word pointer or even a pointer pointer. So in this case, void means "any".



Modules

Modules add extra functionality to [PixTudio], as PixTudio on its own is just a language and a virtual machine. The default modules contain the basics you need to make a game: video, audio, input, etc. More advanced external libraries are available, like network and 3D rendering.

Enabling a module is easy, using [import]:

import "<modulename>"

Some external libraries use a header (.[INC]) instead, so use [include]:

include "<includename>"


Official Modules

mod_debug

[Up to Modules]


Debug module. Adds the capacity to open the [Bennu console].

Usage


mod_dir

[Up to Modules]


Directory module, adding control over the current working directory and the file system.

Usage



Globals

Fileinfo

[Up to Global Variables]


Definition

Struct Fileinfo

Fileinfo is a [global variable] [struct], containing information about a file/directory entry, lastly returned by [glob]().

Members


Member name - Description STRING path - The path to the file/directory (without the name of the file/directory). STRING name - The name of the file/directory. INT directory - [true]: whether the file/directory is a directory or not INT hidden - [true]: whether the file is hidden or not INT readonly - [true]: whether the file is read only or not INT size - The size in bytes of the file/directory. STRING created - The date when the file/directory was created. *. Not available in Unix/Linux** STRING modified - The date when the file/directory was last modified. * STRING accessed - The date when the file/directory was last accessed. * STRING statechg - The date when the file/directory's inode was last modified. *. Only in Unix/Linux**


* - The strings created and modified are in the format: DD/MM/YYYY hh:mm.

** - In Unix/Linux the creation time is not stored. Instead it has a change time (ctime) that indicate when changes to the file or directory's inode (owner, permissions, etc.) were made.



Functions

Cd()

Definition

STRING cd ( [<STRING folder>] )

Sets the current path of execution if folder was specified and returns it.

Note that it is highly recommended to use [chdir]() for changing the current path of execution, as cd() will make [Bennu] crash when a folder is specified and the returned path of execution is used in the Bennu program. Just using cd() without a folder is not a problem.

Parameters


STRING folder - The folder to be entered from the current path of execution or a new path of execution.


Returns

STRING : The current path of execution.

Example

import "mod_dir"
import "mod_say"
import "mod_key"

Process Main()
Begin

    say(cd());
    say(chdir(".."));
    say(cd());

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [cd](), [say]()


Chdir()

Definition

INT chdir ( <STRING directoryname> )

Sets the current path of execution.

Parameters


STRING directoryname - The name of the directory to be entered from the current path of execution or a new path of execution.


Returns

INT : Success


0 - Setting of current path of execution succeeded. !0 - Setting of current path of execution failed.


Example

import "mod_dir"
import "mod_say"
import "mod_key"

Process Main()
Begin

    say(CD());
    ChDir("..");
    say(CD());

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [cd](), [say]()


Mkdir()

Definition

INT mkdir ( <STRING directoryname> )

Creates a new directory in the current path of execution with a certain name.

Parameters


STRING directoryname - The name of the directory to be created.


Returns

INT : Success


0 ([false]) - Creating a new directory with the specified name failed. !0 ([true]) - Creating a new directory with the specified name succeeded.



Rmdir()

Definition

INT rmdir ( <STRING directoryname> )

Removes (deletes) the directory in the current path of execution with a certain name.

Parameters


STRING directoryname - The name of the directory to be removed (deleted).


Returns

INT : Success


0 ([false]) - Removing the directory with the specified name failed. !0 ([true]) - Removing the directory with the specified name succeeded.



Glob()

Definition

STRING glob ( <STRING criteria> )

Gets a single filename or directoryname matching the criteria. If the same criteria is specified, it keeps returning new items on subsequent calls until it can't find any more, in which case it returns "". When different criteria are specified, the search is 'reset'. To reset the search without returning an item, use "" as criteria.

After a call to glob(), the global struct [fileinfo] is filled with information about the last file/directory entry returned.

Parameters


STRING criteria - The search criteria to which the returned filenames apply. "" to reset search.


Returns

STRING : Filename or directoryname


"" - No (new) file/directory entries. !"" - The name of a file/directory entry matching the search criteria.


Notes

The search criteria can hold many criteria: the folder in which you want to look, simple requirements for filenames, such as extensions, and directory names. A few examples:


* - Returns the filename of any file/directory in the current directory. *.dat - Returns the filename of any file/directory with extension .dat in the current directory. MyDir/* - Returns the filename of any file/directory in MyDir\ relative to the current directory. C:/Program Files/* - Returns the filename of any file/directory in C:\Program Files\*.


Example

import "mod_dir"

Process Main()
Private
    String filename;
Begin

    // method one:
    Loop
        filename = Glob("levels/*.tul"); // Looks for a file in the relative folder
                                         // "levels" that has the file extension "tul".
        if(filename!="")
            load_level(filename); // load_level() would load the level file
        else
            break;
        end

    End

    //Reset search
    glob("");

    // method two:
    While( (filename = Glob("levels/*.tul")) != "" )
        load_level(filename);
    End

End

Both methods result in the same, but the second one is less code.


rm()

Definition

INT rm ( <STRING filename> )

Removes (deletes) the file specified with filename.

Parameters


STRING filename - The name of the file to be removed (deleted).


Returns

INT : Success


0 ([false]) - Removing the file with the specified name failed. !0 ([true]) - Removing the file with the specified name succeeded.



Diropen()

Definition

INT diropen ( <STRING folder> )

Open a directory for read it, returns handle id.

Parameters


STRING folder - The folder to open for read.


Returns

INT : The handle of the opened directory.


0 - There was an error. >0 - The handle of the opened directory.



Dirclose()

Definition

INT dirclose ( <INT handleId> )

Close a directory using a given handle id obtained with [diropen]().

Parameters


INT handleId - The handle id of a directory.


Returns

INT : The handle of the opened directory.


0 - There was an error. 1 - The directory was closed successfully.



Dirread()

Definition

STRING dirread ( <INT handle> )

Given a path with wildcards ('*' or '?' characters), returns the first file that matches and, in every next call, all matching files found until no more files exists. It then returns NIL. Presumebly it's somewhat similair to [glob]. Also you can read multiple directories with different search criteria. This is usefull for filemanagers and dialogboxes, when you only want to list files of a specific type.

Parameters


INT handle - The id of the folder opened with [Diropen].


Returns

'''STRING ''' : The filename that matches with the wildcard search pattern.

Example

IMPORT "mod_dir";
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_key";

GLOBAL

int dir_id[9];

string dir_result[9];

string directory1="c:\windows\*.exe";
string directory2="c:\windows\*.dll";
string directory3="c:\windows\*.txt";

PROCESS main();

BEGIN

   dir_id[0]=diropen(directory1);
   dir_id[1]=diropen(directory2);
   dir_id[2]=diropen(directory3);

   /* print all exe files */
   say("");
   say("dirread test");
   say("");
   say("");
   say("the directory is: "+directory1);
   say("");
   say("reading directory.....");
   say("");  
   REPEAT

      IF (key(_esc))
         say("<aborted>");
         BREAK;
      END
      // read the dir
      dir_result[0]=dirread(dir_id[0]);     
      say(dir_result[0]);

   FRAME;
   UNTIL (dir_result[0]=="")

   /* print all dll files */
   say("");
   say("dirread test");
   say("");
   say("");
   say("the directory is: "+directory2);
   say("");
   say("reading directory.....");
   say("");
   REPEAT

      IF (key(_esc))
         say("<aborted>");
         BREAK;
      END
      // read the dir
      dir_result[1]=dirread(dir_id[1]);     
      say(dir_result[1]);

   FRAME;
   UNTIL (dir_result[1]=="")

   /* print all txt files */
   say("");
   say("dirread test");
   say("");
   say("");
   say("the directory is: "+directory3);
   say("");
   say("reading directory.....");
   say("");
   REPEAT

      IF (key(_esc))
         say("<aborted>");
         BREAK;
      END
      // read the dir
      dir_result[2]=dirread(dir_id[2]);     
      say(dir_result[2]);

   FRAME;
   UNTIL (dir_result[2]=="")

   say("closing the directory");
   dirclose(dir_id[0]);
   dirclose(dir_id[1]);
   dirclose(dir_id[2]);

END

Used in example: [say](), [Diropen]().


Get_base_path()

Definition

STRING get_base_path ( )

Use this function to get the directory where the application was run from. This is where the application data directory is.

In macOS (and iOS), if the application is in a ".app" bundle, the function will return the path to the app's resources directory (Game.app/Contents/Resources/).

Returns

STRING : The path to the directory where the application was run from. If the base path cannot be found, an empty string will be returned.

Example

IMPORT "mod_dir";
IMPORT "mod_say";

PROCESS main();
BEGIN
    say("Base path: " + get_base_path());
END

Get_pref_path()

Definition

STRING get_pref_path ( <STRING company>, <STRING appname> )

Use this function to get the preferences dir for the described application. This is where the game can store preferences and savegames. If the folder does not exist, it will be created for you.

In android systems, your app must be assigned a single identifier in the form of org.pixtudio.sampleapp. In this case, org.pixtudio should be the value for company and sampleapp the value for appname.

Parameters

Parameter name Explanation
STRING company The name of your company or development group.
STRING appname The name of this app.

Returns

STRING : The path to the preferences directory. If the base path cannot be found, an empty string will be returned.

Example

IMPORT "mod_dir";
IMPORT "mod_say";

PROCESS main();
BEGIN2
    say("Pref path: " + get_pref_path("org.pixtudio", "sampleapp"));
END

mod_draw

[Up to Modules]


Primitive [drawing] module, adding drawing of primitive and pixels.

Usage



Functions

Drawing_map()

Definition

INT drawing_map ( <INT fileID> , <INT graphID> )

Tells [Bennu] to draw the coming [drawings] on a certain [graphic].

In order to draw with a certain z value again, [drawing_z]() can be used.

Parameters


INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] to draw on.


Returns

INT : [true]


Drawing_color()

Definition

INT drawing_color ( <INT color> )

Tells [Bennu] to draw the coming [drawings] in a certain color.

Parameters


INT color - The color to be drawn in (see [rgb]()).


Returns

INT : [true]


Draw_line()

Definition

INT draw_line( <INT x0> , <INT y0> , <INT x1> , <INT y1> )

Draws a line from point (x0,y0) to point (x1,y1).

Parameters


INT x0 - The x coordinate of one point of the line. INT y0 - The y coordinate of one point of the line. INT x1 - The x coordinate of the other point of the line. INT y1 - The y coordinate of the other point of the line.


Returns

INT : [DrawID]


-1 - Error. 1 - If drawn after [drawing_map](). !-1&&!1 - The [DrawID] created.



Draw_rect()

Definition

INT draw_rect ( <INT x0> , <INT y0> , <INT x1> , <INT y1> )

Draws a non-filled rectangle with corners (x0,y0), (x0,y1), (x1,y0) and (x1,y1).

Parameters


INT x0 - The x coordinate of one corner of the non-filled rectangle. INT y0 - The y coordinate of one corner of the non-filled rectangle. INT x1 - The x coordinate of the diagonally opposite corner of the non-filled rectangle. INT y1 - The y coordinate of the diagonally opposite corner of the non-filled rectangle.


Returns

INT : [DrawID]


-1 - Error. 1 - If drawn after [drawing_map](). !-1&&!1 - The [DrawID] created.



Draw_box()

Definition

INT draw_box ( <INT x0> , <INT y0> , <INT x1> , <INT y1> )

Draws a filled rectangle with corners (x0,y0), (x0,y1), (x1,y0) and (x1,y1).

Parameters


INT x0 - The x coordinate of one corner of the filled rectangle. INT y0 - The y coordinate of one corner of the filled rectangle. INT x1 - The x coordinate of the diagonally opposite corner of the filled rectangle. INT y1 - The y coordinate of the diagonally opposite corner of the filled rectangle.


Returns

INT : [DrawID]


-1 - Error. 1 - If drawn after [drawing_map](). !-1&&!1 - The [DrawID] created.



Draw_circle()

Definition

INT draw_circle ( <INT x> , <INT y> , <INT radius> )

Draws a non-filled circle with center (x0,y0) and radius radius.

Parameters


INT x - The x coordinate of one center of the non-filled circle. INT y - The y coordinate of one center of the non-filled circle. INT radius - The radius of the non-filled circle.


Returns

INT : [DrawID]


-1 - Error. 1 - If drawn after [drawing_map](). !-1&&!1 - The [DrawID] created.



Draw_fcircle()

Definition

INT draw_fcircle ( <INT x> , <INT y> , <INT radius> )

Draws a filled circle with center (x0,y0) and radius radius.

Parameters


INT x - The x coordinate of one center of the filled circle. INT y - The y coordinate of one center of the filled circle. INT radius - The radius of the filled circle.


Returns

INT : [DrawID]


-1 - Error. 1 - If drawn after [drawing_map](). !-1&&!1 - The [DrawID] created.



Draw_curve()

Definition

INT draw_curve ( <INT x0> , <INT y0> , <INT x1> , <INT y1> , <INT x2> , <INT y2> , <INT x3> , <INT y3> , <INT smoothness> )

Draws a curve starting at the point (x0,y0), ending at the point (x3,y3) and influenced by the points (x1,y1) and (x2,y2) with a certain level of smoothness.

Parameters


INT x0 - The x coordinate of the starting point of the curve. INT y0 - The y coordinate of the starting point of the curve. INT x1 - The x coordinate of the first influence point of the curve. INT y1 - The x coordinate of the first influence point of the curve. INT x2 - The x coordinate of the second influence point of the curve. INT y2 - The x coordinate of the second influence point of the curve. INT x3 - The x coordinate of the end point of the curve. INT y3 - The y coordinate of the end point of the curve. INT smoothness - The smoothness with which the line will be drawn from 1 to 15, 15 being the smoothest.


Returns

INT : [DrawID]


-1 - Error. 1 - If drawn after [drawing_map](). !-1&&!1 - The [DrawID] created.


Example

import "mod_draw"
import "mod_video"
import "mod_mouse"
import "mod_map"

GLOBAL
scr_width = 640, scr_height=480;
End;

Process main()
Begin
    /* Check that we can set the video mode before actually setting it */
    if(!mode_is_ok(scr_width, scr_height, 16, MODE_WINDOW))
        return -1;
    end;
    set_mode(scr_width, scr_height, 16, MODE_WINDOW);

    /* Draw three long bezier lines with different colors and smoothnesses */
    drawing_map(0, 0);
    drawing_color(rgb(255, 0, 0));
    draw_curve(0, scr_height/4, scr_width/4, 0, 3*scr_width/4, 2*scr_height/4,
               scr_width, scr_height/4, 1);
    drawing_color(rgb(0, 255, 0));
    draw_curve(0, 2*scr_height/4, scr_width/4, scr_height/4, 3*scr_width/4,
               3*scr_height/4, scr_width, 2*scr_height/4, 3);
    drawing_color(rgb(0, 0, 255));
    draw_curve(0, 3*scr_height/4, scr_width/4, 2*scr_height/4, 3*scr_width/4,
               4*scr_height/4, scr_width, 3*scr_height/4, 15);

    while(! mouse.left)
        FRAME;
    end;

    // Delete all the lines
    delete_draw(0);
End;

Used in example: [mode_is_ok](), [set_mode](), [drawing_map]() [drawing_color](), [draw_curve](), [delete_draw]()


Drawing_z()

Definition

INT drawing_z ( <INT z> )

Tells [Bennu] to draw the coming [drawings] on a certain z value.

In order to draw on a certain [graphic] again, [drawing_map]() can be used.

Parameters


INT z - The z value to be drawn on.


Returns

INT : [true]


Delete_draw()

Definition

INT delete_draw ( <INT DrawID> )

Deletes a certain [drawing] from the screen.

Parameters


INT DrawID - [DrawID] to be deleted.


Returns

INT : [true]

Notes

Delete_draw\ deletes all drawings from the screen.


Drawing_alpha()

Definition

INT drawing_alpha ( <INT alpha> )

Tells [Bennu] to draw the coming [drawings] value

Note: there currently is a 'bug' that makes drawing objects (draw commands with no map as target) have their alpha value altered too. This is to be changed.

Parameters


INT alpha - The alpha value to be drawn with.


Returns

INT : [true]


Drawing_stipple()

Definition

INT drawing_stipple ( <INT stipples> )

Tells [Bennu] which pixels to draw of the coming [drawings].

This is done by passing a 32bit value, each bit representing a pixel. Bit 0 represents the first pixels drawn, bit 1 represents the second, etc. When a 33rd pixel is to be drawn or not, bit 0 is checked and the cycle starts over. This means a value of 0xFFFFFFFF (=2^32-1) means normal operation, meaning all the pixels will be drawn.

Note that this works only for non-filled drawings. For [draw_curve](), the pattern is not always visible for the higher smoothness levels.

Parameters


INT stipples - Which pixels to draw, repetitive 32bits.

Returns

INT : [true]

Example

Program example;         
Private
//    int draw_id;
Begin

    // Draw in background
    drawing_map(0,background);

    // Set stipplemode to display every other pixel.
    // binary code 0101 0101 0101 0101 0101 0101 0101 0101
    // hex code 55555555h
    drawing_stipple(55555555h);

    // Draw two lines
    draw_line(10,10,190,10);
    draw_line(11,12,190,12);

    // Draw this funky pattern
    // binary code 0011 1100 0111 1100 1010 0001 1101 0011
    // hex code 3C7CA1D3h
    drawing_stipple(3C7CA1D3h);

    // Draw two lines
    draw_line(10,20,190,20);
    draw_line(11,22,190,22);

    // Draw a circle
    draw_circle(100,100,50);

    // Draw a rectangle
    draw_rect(50,50,150,150);

    // Draw some lines
    draw_line( 50, 50,100,150);
    draw_line(100,150,150, 50);
    draw_line( 50,150,100, 50);
    draw_line(100, 50,150,150);

    // Draw two curves: one with high smoothness (bit pattern not visible) and one with low smoothness
    draw_curve( 200,200,
                100,200,
                100,150,
                300,100,15);
    draw_curve( 200,200,
                100,200,
                100,150,
                300,100,1);

    // Draw a filled circle
    draw_fcircle(20,180,15);

    // Draw a filled rectangle
    draw_box(50,180,80,195);

    // Wait for key ESC
    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [drawing_map](), [draw_line](), [draw_circle](), [draw_rect](), [draw_curve](), [draw_fcircle](), [draw_box]()

This will result in something like:\


Put_pixel()

Definition

INT put_pixel ( <INT x> , <INT y> , <INT color> )

Draws a single colored [pixel] on the [background]. Is equivalent to [map_put_pixel] ( 0, 0, x, y, color ).

Parameters


INT x - Where on the background's x-axis to put the pixel. INT y - Where on the background's y-axis to put the pixel. INT color - What [color] to draw.


Returns

INT : [true]

Example

import "mod_video"
import "mod_map"
import "mod_wm"
import "mod_draw"
import "mod_rand";

Process Main()
Private
    int i;
    int direction;
end
Begin

    // Set the mode to 16bit and some res
    set_mode(320,200,16);

    // Create a blue-ish square map
    graph = new_map(20,20,16);
    map_clear(0,graph,rgb(50,100,150));
    y=100;
    x=10;

    // Puts 100 yellow-ish pixels in random places in the background
    for(i=0; i<100; i++)
        put_pixel(rand(0,320),rand(0,200),rgb(255,255,55));
    end

    Repeat
        x=x+direction; 
        if (x>=310) direction=-3; end 
        if (x<=10) direction=3; end
        frame;
    Until(exit_status)

End

Used in example: [set_mode](), [new_map](), [rand]()


get_pixel()

Definition

INT get_pixel ( <INT x> , <INT y> )

Returns the [color] of the specified [pixel]. Is equivalent to [map_get_pixel]( 0, 0, x, y ).

Parameters


INT x - The X-coordinate of the [pixel] the color is wanted. INT y - The Y-coordinate of the [pixel] the color is wanted.


Returns

INT : The color

Example

import "mod_video"
import "mod_wm"
import "mod_draw"
import "mod_map";
import "mod_screen";
import "mod_mouse";

Process Main()

Begin

    set_mode(640,480,16); 

    // Creates a white box as mouse's cursor
    mouse.graph = new_map(20,20,16);
    map_clear(0,mouse.graph,rgb(255,255,255));

    // This area will show the pixel's color behind the cursor
    graph=new_map(100,50,16);
    x=50;
    y=25; 

    //Puts the background
    put_screen(0,load_png("image.png"));  

    Repeat
        map_clear(0,graph,get_pixel(mouse.x,mouse.y));
        frame;
    Until(exit_status)

End

Used in example: [set_mode](), [new_map](), [put_screen](), [get_pixel]()


map_get_pixel()

Definition

INT map_get_pixel ( <INT fileID> , <INT graphID> , <INT x> , <INT y> )

Returns the [color] on the specified [graphic] of the specified [pixel].

Parameters


INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] to get the pixel from. INT x - The X-coordinate of the [pixel] the color is wanted. INT y - The Y-coordinate of the [pixel] the color is wanted.


Returns

INT : The color


-1 - Error: invalid map; invalid; invalid pixel; invalid color depth of map. Note: in 32bit graphs this can be a color too. !-1 - The color.



map_put_pixel()

Definition

INT map_put_pixel ( <INT fileID> , <INT graphID> , <INT x> , <INT y> , <INT color> )

Draws a single colored [pixel] on a [graph].

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to draw on. INT x - Where on the graph's x-axis to put the pixel. INT y - Where on the graph's y-axis to put the pixel. INT color - What [color] to draw.


Returns

INT : [true]

Errors


Invalid map - Map doesn't exist. Unsupported color depth - Destination graph is of an unsupported colordepth.


Example

import "mod_video"
import "mod_map"
import "mod_screen"
import "mod_wm"
import "mod_draw"

Process Main()
Private
    int map;
    int i;
Begin

    // Set the mode to 16bit and some res
    set_mode(320,200,16);

    // Create a blue-ish square map
    map = new_map(100,100,16);
    map_clear(0,map,rgb(50,100,150));

    // Puts 100 yellow-ish pixels in random places in the graphic
    for(i=0; i<100; i++)
        map_put_pixel(0,map,rand(0,100),rand(0,100),rgb(255,255,55));
    end

    // Puts the map in the center of the screen
    put(0,map,160,100);

    Repeat
        frame;
    Until(exit_status)

End

Used in example: [set_mode](), [new_map](), [map_put_pixel](), [rand]()


mod_effects

[Up to Modules]


Graphical effects module, adding effects applicable to [graphics].

Usage


mod_file

[Up to Modules]


Files module, adding control over individual files (reading, writing, etc).

Usage



Constants

O_READ (MISSING)

O_READWRITE (MISSING)

O_RDWR (MISSING)

O_WRITE (MISSING)

O_ZREAD (MISSING)

O_ZWRITE (MISSING)

SEEK_CUR (MISSING)

SEEK_END (MISSING)

SEEK_SET (MISSING)


Functions

save()

Definition

INT save ( <STRING filename> , <VARSPACE data> )

Saves the data from the specified variable to the specified file.

Parameters


STRING filename - The name of the file that will be saved. VARSPACE data - The variable (of any [datatype]) that will be saved in a file.


Returns

INT : The number of bytes written to the file.

Notes

Attempting to use "?","*","<",">" or "|" in a filename will result in no file at all on Windows, while using ":" in a filename results in everything from the ":" and beyond being cut off from the file name and the resulting file will be of size 0.

Using the characters "/" or "\" in the filename (without directories that can be accessed that way) results in everything from this character and before being cut off from the filename. The file will be saved successfully nonetheless.

Example

Program test;
Global
    struct My_struct
        Level_number="99";
        string Map_name="Amazing map";
    End
Begin
        Save("myfile.sav",My_struct); // The content of My_struct is saved in myfile.sav
        Write(0,10,10,0,"Data saved!");

    While (!key(_ESC))
        Frame;
    End
End

Used in example: [save](), [key]()


load()

Definition

INT load ( <STRING filename> , <VARSPACE data> )

Loads the data read from the specified file into the specified variable.

Parameters


STRING filename - The name of the file to be loaded. VARSPACE data - The variable (of any [datatype]) in which the data read from the file will be loaded.


Returns

INT : The number of bytes read from the file.

Notes

To check whether a file exists before it is loaded, [file_exists]() can be used.

Example

Program test;
Global
    struct My_struct
        Level_number;
        string Map_name;
    End
Begin
    If (file_exists("myfile.sav")) 
        Load("myfile.sav",My_struct);            // Content from myfile.sav is loaded into My_struct
        Write(0,10,10,0,My_struct.level_number); // A variable from the loaded struct is shown on screen
        Write(0,10,20,0,My_struct.map_name);     // Another variable loaded is shown on screen
    Else
        Write(0,10,10,0,"File couldn't be loaded, it doesn't exist.");
    End

    While (!key(_esc))
        Frame;
    End
End

Used in example: [file_exists](), [load](), [key]()


fopen()

Definition

INT fopen ( <STRING filename> , <INT mode> )

Opens a file on the hard drive for reading or writing.

Parameters


STRING filename - The filename of the file you wish to open (including extension and possible path). INT mode - The mode with which to access the file (see [Readwrite_modes]).


Returns

INT : [FileHandle]


0 - Could not load. !0 - The identifier of the file now opened for reading/writing.


Example

Process loadthing(STRING loadpath);
Private
    int handle;   // handle for the loaded file 
    int druppels; // here's where the loaded data go
Begin

    handle=fopen(loadpath,O_READ); // opens the file in reading mode
    fread(handle,druppels);        // reads from the file and puts the data in druppels
    fclose(handle);                // zipping up after business is done
    write(0,0,0,0,druppels);       // shows the value of druppels

End

Used in example: [fread](), [fclose]()


fclose()

Definition

INT fclose ( <INT filehandle> )

Unloads a file previously loaded with [fopen]().

Parameters


INT filehandle - The [FileHandle]().


Returns

INT: [true]

Example

Process loadthing(STRING loadpath);
Private
    int handle;   // handle for the loaded file 
    int druppels; // here's where the loaded data go
Begin

    handle=fopen(loadpath,O_READ); // opens the file in reading mode
    fread(handle,druppels);        // reads from the file and puts the data in druppels
    fclose(handle);                // zipping up after business is done
    write(0,0,0,0,druppels);       // shows the value of druppels
End

Used in example: [fopen](), [fread]()


fread()

Definition

INT fread ( <INT filehandle> , <VARIABLE data> )

INT fread ( <VOID POINTER data_pos> , <INT length> , <INT filehandle> )

Reads the information from a file loaded with [fopen]() to the variable data.

The second version reads length bytes to the memory pointed to by data_pos.

Parameters


INT filehandle - The [FileHandle](). VARIABLE data - The data to read from the file (any type of variable). It will be loaded into this variable. VOID POINTER data_pos - The pointer to which the bytes read will be written to. INT length - The number of bytes to read from the specified file.


Returns

INT : The number of bytes read from the file.

Example

Process loadthing(STRING loadpath);
Private
    int handle;   // handle for the loaded file 
    int druppels; // here's where the loaded data go
Begin

    handle=fopen(loadpath,O_READ); // opens the file in reading mode
    fread(handle,druppels);        // reads from the file and puts the data in druppels
    fclose(handle);                // zipping up after business is done
    write(0,0,0,0,druppels);       // shows the value of druppels

End

Used in example: [fopen](), [fclose]()


fwrite()

Definition

INT fwrite ( <INT filehandle> , <VARIABLE data> )

INT fwrite ( <VOID POINTER data_pos> , <INT length> , <INT filehandle>)

Writes the variable data to a file loaded with [fopen].

to be extended...

Parameters


INT filehandle - Identifier of the file loaded with [fopen]. VARIABLE data - The data to write to the file (any type of variable).


Returns

INT : The number of bytes written to the file.

Example

Process writething(STRING loadpath);
Private
    handle;   // handle for the loaded file 
    druppels; // the data to write to the file

Begin

    druppels=rand(1,10);

    handle=fopen(loadpath,O_WRITE); // opens the file in writing mode
    fwrite(handle,druppels);        // writes the druppels variable to the file
    fclose(handle);                 // zipping up after business is done

End

Used in example: [fopen](), [fclose]()


fseek()

Definition

INT fseek ( <INT filehandle> , <INT position> , <INT seek_mode> )

Sets the byte offset (reading position) of a certain file. This means where a function will start reading in that file.

Parameters


INT filehandle - The [FileHandle](). INT position - Number of bytes from the point indicated by seek_mode. INT seek_mode - Set the offset relative to a certain point (see [seek modes]).


Returns

INT: The new reading position.


frewind()

Definition

UNDEFINED frewind ( <INT filehandle> )

Sets the byte offset (reading position) to the begin of a certain file. This is similair to using:

fseek(file_id,0,SEEK_SET);

Parameters


INT filehandle - The [FileHandle]().


Returns

INT


1 - The begin position of the file.


See also

[fseek]()


ftell()

Definition

INT ftell ( <INT filehandle> )

Returns the current reading position of a certain file.

The reading position can be altered by [fseek]().

Parameters


INT filehandle - The [FileHandle]().


Returns

INT: The current reading position of the specified file.


fflush()

Definition

INT fflush ( <INT filehandle> )

Clears internal data buffers for the file associated with the filehandle. The file has to be opened for output with the [Readwrite_modes]. This function comes from the standard C library, this is a miscellaneous function.

Parameters


INT filehandle - The [FileHandle]().


Returns

INT : - the status result of the action.


EOF (-1) - an error was detected, or end of file has been reached. 0 - normal condition, everything is fine.



flength()

Definition

INT flength ( <INT filehandle> )

Gives back the size of a certain file.

Parameters


INT filehandle - The [FileHandle]().


Returns

INT: The size of the file in bytes.


fputs()

Definition

INT fputs ( <INT filehandle> , <STRING line> )

Writes a line to a certain file.

Parameters


INT filehandle - The [FileHandle]().


Returns

INT: Number of bytes written.


0 - There was an error. >0 - Number of bytes written.


Notes

The character '\' will be put in front of every newline character, so that [fgets]() reads the lines like they were written.


fgets()

Definition

STRING fgets ( <INT filehandle> )

Reads a line from a certain file and returns it. Subsequent calls will return the next line, until the end of the file is reached.

Parameters


INT filehandle - The [FileHandle]().


Returns

STRING: The line read.

Notes

The returned string normally does not contain the '\n' or '\r','\n' charactersets.

When a line ends with the character '\', the next line will be joined with the current one, changing the '\' character to a '\n' character.

If you want to read multiple lines from a textfile, put this function in a loop.


feof()

Definition

INT feof ( <INT filehandle> )

Checks if the end of a certain file is reached.

Parameters


INT filehandle - The [FileHandle]().


Returns

INT: [true]: Whether the end of the specified file is reached.


file()

: This is about the [filetype]. Did you mean the local variable [file] or the function [file]()?


[Up to Filetypes]


Description

A file is a container for [graphics], identified by a non-negative [integer] (0 or higher). It holds all information about the contained graphics ([pixels], [width], [depth], name, etc). Each of these graphics have a unique identifier inside the file (positive [int]).

A file can be created for example by loading an [FPG] (Fichero Para Gráficos, meaning "file for graphics") into it, by using [fpg_load](), which creates a new file with the graphics from the loaded FPG and returns a unique identifier. Another option is to create a new, empty one by using [fpg_new](). Don't let the name fpg_new() fool you: fpg_new() has nothing to do with the filetype FPG. This is because the FPG format is only for files and not for internal use. There are more ways to load graphics into a file.

A file can be used by using the [local variable] or by using the identifier in the various [functions] with a file parameter.

Don't forget to unload it with [fpg_unload]() after use.

Example

import "mod_map"
import "mod_grproc"
import "mod_key"
import "mod_wm"

Global
    int file_id;
    int file_id2;
End

Process Main()
Begin

    // Load FPG
    file_id = load_fpg("example.fpg");
    file_id2 = load_fpg("example2.fpg");

    // Set locals for display of graph
    file = file_id;
    graph = 1;
    x = y = 50;

    // assign Ship to use example2.fpg
    Ship(300,100,5,file_id2,1); // undefined in this sample

    Repeat
        frame;
    Until(key(_ESC)||exit_status)

End

Used in example: [load_fpg](), [key], [file]. [process]

Media in example: [example.fpg]

Note: nothing will be seen unless you have an [FPG] "example.fpg" with a [graphic] with ID 1.


fexists()

Syntax

INT fexists ( <STRING filename> )

Description

Checks if a certain file exists.

Also called [file_exists]().

Parameters


STRING filename - The file to be checked for existence, including a possible path.


Returns

INT : [true]: the existence of the file.


[true] - The specified file exists. [false] - The specified file doesn't exist.


Example

import "mod_file"
import "mod_say"

Process Main()
Begin

    say("> C:\Windows\notepad.exe > " + fexists("C:\Windows\notepad.exe")); // A filename with
                                                                            // absolute path
    say("> SDL.dll > " + fexists("SDL.dll")); // A filename without a path
    say("> SomeNonExistingFile > " + fexists("SomeNonExistingFile")); // A nonexisting file

End

Used in example: [say](), [fexists]()


fmove()

Definition

INT fmove ( <STRING source_file>, <STRING target_file> )

Renames files, from the bennu source code: files.c.

Parameters


STRING source_file - The source file. STRING target_file - The target file.


Returns

INT : [true]: the status result of the action.


[true] - The action was a success. [false] - The action failed.



dirname() (MISSING)

basename() (MISSING)

mod_grproc

[Up to Modules]


[Graphical] module.

Usage



Functions

Advance()

Definition

INT advance ( <INT distance> )

Moves the [calling] [process] forward by distance units in the direction of the process' [angle].

This function is influenced by the [local variables] and [resolution].

Parameters


INT distance - Distance to advance in units.


Returns


INT : Returns [true] if failed.

Example

import "mod_grproc"
import "mod_map"
import "mod_wm" // for exit_status
import "mod_key" // for key()
import "mod_proc"

Process Main()
Private
    int my_proc;
Begin

    proc(); //create a new process
    proc2(); //create a new process

    Repeat
        frame;
    Until(key(_ESC) || exit_status)

OnExit

    signal(my_proc,S_KILL);

End

Process proc()
Begin

    // Create a cyan square and assign it to 'graph'
    graph = map_new(100,100,8);
    map_clear(0,graph,rgb(0,255,255));

    // Set starting position
    x = 50;
    y = 50;

    // This loop makes this process advance 3 pixels every frame
    Loop
        advance(3); // advance 3 pixels
        frame;
    End

End

Process proc2()
Begin

    // Set resolution to 100
    resolution = 100;

    // Create a cyan square and assign it to 'graph'
    graph = map_new(100,100,8);
    map_clear(0,graph,rgb(0,255,255));

    // Set starting position
    x = 50*resolution;
    y = 150*resolution;

    // This loop makes this process advance 3/100 pixels every frame
    Loop
        advance(3); // advance 3/100 pixels
        frame;
    End

OnExit

    map_unload(0,graph);

End

Used in example: [key](), [map_new](), [rgb](), [map_unload](), [exit_status], [x], [resolution]


Xadvance()

Definition

INT xadvance ( <INT angle> , <INT distance> )

Moves a process a certain distance in a certain direction.

Parameters


INT angle - The [angle] in which to move the process, in thousandths of a degree. INT distance - The distance to move the process, in pixels.


Returns

INT : Successrate


[true] - Success. [false] - Error.


Example

Program example;
Global
    myproc;

Begin

    myproc=proc();

    Loop
        frame;
    End
End

Process proc();
Begin

    x=100;
    y=100;

    Loop
        xadvance(90000,10); //moves the process vertically (90 degrees) 10 pixels
        frame;
    End

End

get_angle()

Definition

INT get_angle ( <INT processID> )

Returns the [angle] between the coordinates of a certain [process] and the process calling [get_angle]().

Parameters


INT processID - The other [process].


Returns

INT : The wanted [angle].


-1 - An error may have occurred: invalid [process]. !-1 - The wanted [angle].


Example

Program angling;
import "mod_grproc"//modules
import "mod_proc"
import "mod_wm"
import "mod_key"
import "mod_video"
import "mod_map"
import "mod_draw"
import "mod_text"
Const
    screen_width     = 320;
    screen_height    = 200;
    screen_depth     = 8;
    screen_fps       = 60;
    screen_frameskip = 0;
Global
    int distance;
    int tempID;
Begin

    // Set the screen mode
    set_mode(screen_width,screen_height,screen_depth);
    set_fps(screen_fps,screen_frameskip);

    // Change this to see what happens
    resolution = 100;

    // Create mouse graph and start mousepointer
    x = new_map(20,20,screen_depth);
    map_clear(0,x,rgb(255,0,0));
    mousepointer(0,x);

    // Create arrow, assign to graph
    graph = new_map(30,30,screen_depth);
    drawing_map(0,graph);
    drawing_color(rgb(0,255,0));
    draw_line( 0,29,29,30/2);
    draw_line( 0, 0,30,30/2);

    // Set position
    x = screen_width /2 * resolution;
    y = screen_height/2 * resolution;

    // Display distance
    write(0,0,0,0,"Distance:");
    write_int(0,60,0,0,&distance);

    // Always point to the mouse
    Repeat
        // Get the angle and distance between this process' coordinates and those of mousegraph.
        // We can use TYPE and get_id() here, because usually there would only be one
        // mousepointer and one always.
        tempID = get_id(type mousepointer);
        angle = get_angle(tempID);
        distance = get_dist(tempID);
        frame;
    Until(key(_esc))

End

/**
 * Follows the mouse coordinates. x is always mouse.x and y is always mouse.y
 * for processes with priority <1. The graphic of this process will be a certain graphic.
 * int file     - The fileID of the file where the graphic is located
 * int graph    - The graphID of the graphic to be used for this process
 */
Process mousepointer(int file,int graph)
Begin
    // Set the priority to 1, because we first want to have the correct coordinates of
    // the mouse set in this process. Then after that other process can use those coordinates.
    priority = 1;
    // Obtain father's resolution
    resolution = father.resolution;
    // Loop
    Loop
        // Obtain X and Y coordinates of the mouse and adjust for resolution
        // (mouse.y and mouse.y have an unchangeable resolution of 1)
        x = mouse.x * resolution;
        y = mouse.y * resolution;
        frame;
    End
End

Used in example: [set_mode](), [new_map](), [drawing_map](), [drawing_color](), [draw_line](), [write_int](), [get_angle](), [get_dist], [mouse], [y], [priority]

This example could also be done with [fget_angle](), which is easier and doesn't require an extra [process].

It could look something like:\ http://wwwhome.cs.utwente.nl/~bergfi/fenix/wiki/get_angle.PNG


get_dist()

Definition

INT get_dist ( <INT processID> )

Returns the distance between the coordinates of a certain [process] and the process calling [get_dist](). The distance returned is converted to the [resolution] of the process calling [get_dist]().

Parameters


INT processID - The other [process].


Returns

INT : The wanted distance.


-1 - An error occurred: invalid [process]. !-1 - The wanted distance.


Example

Program angling;
Const
    screen_width     = 320;
    screen_height    = 200;
    screen_depth     = 8;
    screen_fps       = 60;
    screen_frameskip = 0;
Global
    int distance;
    int tempID;
Begin

    // Set the screen mode
    set_mode(screen_width,screen_height,screen_depth);
    set_fps(screen_fps,screen_frameskip);

    // Change this to see what happens
    resolution = 100;

    // Create mouse graph and start mousepointer
    x = new_map(20,20,screen_depth);
    map_clear(0,x,rgb(255,0,0));
    mousepointer(0,x);

    // Create arrow, assign to graph
    graph = new_map(30,30,screen_depth);
    drawing_map(0,graph);
    drawing_color(rgb(0,255,0));
    draw_line( 0,29,29,30/2);
    draw_line( 0, 0,30,30/2);

    // Set position
    x = screen_width /2 * resolution;
    y = screen_height/2 * resolution;

    // Display distance
    write(0,0,0,0,"Distance:");
    write_int(0,60,0,0,&distance);

    // Always point to the mouse
    Repeat
        // Get the angle and distance between this process' coordinates and those of mousegraph.
        // We can use TYPE and get_id() here, because usually there would only be one
        // mousepointer and one always.
        tempID = get_id(type mousepointer);
        angle = get_angle(tempID);
        distance = get_dist(tempID);
        frame;
    Until(key(_esc))

End

/**
 * Follows the mouse coordinates. x is always mouse.x and y is always mouse.y
 * for processes with priority <1. The graphic of this process will be a certain graphic.
 * int file     - The fileID of the file where the graphic is located
 * int graph    - The graphID of the graphic to be used for this process
 */
Process mousepointer(int file,int graph)
Begin
    // Set the priority to 1, because we first want to have the correct coordinates of
    // the mouse set in this process. Then after that other process can use those coordinates.
    priority = 1;
    // Obtain father's resolution
    resolution = father.resolution;
    // Loop
    Loop
        // Obtain X and Y coordinates of the mouse and adjust for resolution
        // (mouse.y and mouse.y have an unchangeable resolution of 1)
        x = mouse.x * resolution;
        y = mouse.y * resolution;
        frame;
    End
End

Used in example: [set_mode](), [new_map](), [drawing_map](), [drawing_color](), [draw_line](), [write_int](), [get_angle](), [get_dist], [mouse], [y], [priority]

This example could also be done with [fget_dist](), which is easier and doesn't require an extra [process]. It also give a much more accurate distance when the [resolution] is >1.

Resolution is 100:


http://wwwhome.cs.utwente.nl/~bergfi/fenix/wiki/get_angle.PNG VS http://wwwhome.cs.utwente.nl/~bergfi/fenix/wiki/fget_angle.PNG [get_angle]()



Collision()

Definition

INT collision ( <INT processID|processTypeID> )

Checks if a [process] collided with the process calling Collision().

When a [processTypeID] is specified, there could be multiple fitting collisions. In this case, collision() returns a [processID] on each subsequent call, until it returns 0. This can be reset by use of the [frame]; statement, and in such case, frame(0); can be handy.

Parameters


INT processID processTypeID - The ProcessID of the process or the ProcessTypeID of the type of processes to be checked.

Returns

INT : The ID of the collided process.


0 - No collision >0 - The processID of the process colliding with the current process


Example

Process SpaceShip( int file , int graph , int x , int y , int angle , int maxspeed , int maxturnspeed )
Private
    int speed;
    int collisionID;
    string text;
Begin
    write_string(0,0,0,0,&text);
    Loop
        // Handle movement
        speed+=key(_up)*(speed<maxspeed)-key(_down)*(speed>-maxspeed);
        angle+=(key(_left)-key(_right))*maxturnspeed;
        advance(speed);
        // Handle collision
        if( (collisionID = collision(type main)))
            text = "collision with: " + collisionID;
        else
            text = "no collision";
        end
        frame;
    End
End

Process Main()
Private
    int map;
Begin

    // Create the graph for the ship
    map = new_map(20,20,8);
    map_clear(0,map,rgb(0,255,255));

    // Create the graph for the Main process
    graph = new_map(50,50,8);
    map_clear(0,graph,rgb(255,255,0));

    // Position the main process and create the ship
    x = y = z = 100;
    SpaceShip(0,map,100,100,0,20,5000);

    Repeat
        frame;
    Until(key(_ESC))

    let_me_alone();

End

Used in example: [write_string](), [key](), [new_map](), [advance](), [let_me_alone], [type]


Collision_box()

Definition

INT collision_box ( <INT processID|processTypeID> )

Checks if a [process] collided with the process calling Collision_box().

When a [processTypeID] is specified, there could be multiple fitting collisions. In this case, collision_box() returns a [processID] on each subsequent call, until it returns 0. This can be reset by use of the [frame]; statement, and in such case, frame(0); can be handy.

The diference between collision_box and [collision] is that collision_box only checks the distance with the edges of the processes, on the other side collision() check pixel by pixel between these processes. Consequently, collision_box() is faster, but is more accurate collision().

Parameters


INT processID processTypeID - The ProcessID of the process or the ProcessTypeID of the type of processes to be checked.

Returns

INT : The ID of the collided process.


0 - No collision >0 - The processID of the process colliding with the current process


Example

Process SpaceShip( int file , int graph , int x , int y , int angle , int maxspeed , int maxturnspeed )
Private
    int speed;
    int collisionID;
    string text;
Begin
    write_string(0,0,0,0,&text);
    Loop
        // Handle movement
        speed+=key(_up)*(speed<maxspeed)-key(_down)*(speed>-maxspeed);
        angle+=(key(_left)-key(_right))*maxturnspeed;
        advance(speed);
        // Handle collision_box
        if( (collisionID = collision_box(type main)))
            text = "collision with: " + collisionID;
        else
            text = "no collision";
        end
        frame;
    End
End

Process Main()
Private
    int map;
Begin

    // Create the graph for the ship
    map = new_map(20,20,8);
    map_clear(0,map,rgb(0,255,255));

    // Create the graph for the Main process
    graph = new_map(50,50,8);
    map_clear(0,graph,rgb(255,255,0));

    // Position the main process and create the ship
    x = y = z = 100;
    SpaceShip(0,map,100,100,0,20,5000);

    Repeat
        frame;
    Until(key(_ESC))

    let_me_alone();

End

Used in example: [write_string](), [key](), [new_map](), [advance](), [let_me_alone], [type]


Collision_circle()

Definition

INT collision_circle ( <INT processID|processTypeID> )

Checks if a [process] collided with the process calling Collision_circle().

When a [processTypeID] is specified, there could be multiple fitting collisions. In this case, collision_cirlce() returns a [processID] on each subsequent call, until it returns 0. This can be reset by use of the [frame]; statement, and in such case, frame(0); can be handy.

The diference between collision_circle and [collision] is that collision_circle only checks the distance with a circle in the edges of the processes, on the other side collision() check pixel by pixel between these processes. Consequently, collision_circle() is faster, but less accurate than collision().

Parameters


INT processID processTypeID - The ProcessID of the process or the ProcessTypeID of the type of processes to be checked.

Returns

INT : The ID of the collided process.


0 - No collision >0 - The processID of the process colliding with the current process


Example

Process SpaceShip( int file , int graph , int x , int y , int angle , int maxspeed , int maxturnspeed )
Private
    int speed;
    int collisionID;
    string text;
Begin
    write_string(0,0,0,0,&text);
    Loop
        // Handle movement
        speed+=key(_up)*(speed<maxspeed)-key(_down)*(speed>-maxspeed);
        angle+=(key(_left)-key(_right))*maxturnspeed;
        advance(speed);
        // Handle collision_box
        if( (collisionID = collision_circle(type main)))
            text = "collision with: " + collisionID;
        else
            text = "no collision";
        end
        frame;
    End
End

Process Main()
Private
    int map;
Begin

    // Create the graph for the ship
    map = new_map(20,20,8);
    map_clear(0,map,rgb(0,255,255));

    // Create the graph for the Main process
    graph = new_map(50,50,8);
    map_clear(0,graph,rgb(255,255,0));

    // Position the main process and create the ship
    x = y = z = 100;
    SpaceShip(0,map,100,100,0,20,5000);

    Repeat
        frame;
    Until(key(_ESC))

    let_me_alone();

End

Used in example: [write_string](), [key](), [collision_circle](), [new_map](), [advance](), [let_me_alone], [type]


Get_real_point()

Definition

INT get_real_point( <INT controlpoint> , <INT POINTER x> , <INT POINTER y> )

Finds the actual position on the screen of the calling [process] and the specified [controlpoint] on this graphic. All process-related variables are taken into account, like [x], even [ctype]. These coordinates are then assigned to the variables pointed to by x and y.

Parameters


INT controlpoint - The [controlpoint] on the process' graphic of which the actual position is wanted. INT POINTER x - A pointer to an integer to which the X-coordinate will be assigned. INT POINTER y - A pointer to an integer to which the Y-coordinate will be assigned.


Returns

INT : Successrate


[false] - Error: no graphic; invalid controlpoint; [true] - Success.



mod_joy

[Up to Modules]


Joystick module.

Usage



Functions

Joy_axes() (MISSING)

Joy_num_axes() (MISSING)

Joy_get_axis() (MISSING)

Joy_buttons() (MISSING)

Joy_name()

Syntax

STRING joy_name ( <INT JoyID> )

Description

Returns the name of the specified [joystick]. This is a string describing the specified joystick, mostly used for the brand and model of the joystick.

Parameters


INT JoyID - The [JoyID].


Returns

STRING : The name of the [joystick].


Joy_num_buttons() (MISSING)

Joy_number()

Syntax

INT joy_number ( )

Description

Returns the number of joysticks present in the system.

Also called [joy_numjoysticks](). The previous name [number_joy]() is deprecated.

Returns

INT : The number of joysticks present in the system.


Joy_select()

Syntax

INT joy_select ( <INT JoyID> )

Description

Select the joystick with id equals to JoyID. The old name [select_joy]() is deprecated.

Parameters


INT JoyID - The [JoyID].


Returns

INT : The ID of the selected joystick number.


Joy_get_button() (MISSING)

Joy_get_position() (MISSING)

Joy_num_hats() (MISSING)

Joy_num_balls() (MISSING)

Joy_get_hat() (MISSING)

Joy_get_ball() (MISSING)

Joy_get_accel() (MISSING)

mod_key

[Up to Modules]


Keyboard module.

Usage



Functions

Key()

Definition

INT key( <INT scancode> )

Checks if a certain key is being pressed.

Parameters


INT scancode - The [scancode] of the key to be checked.


Returns

INT : [true]: Whether the key is being pressed.

Notes

Take a look at the [scancodes] for a complete list.

Example

Program input_test;
Begin

    While( !key(_esc) )

        delete_text(ALL_TEXT);

        if( key(_left) && !key(_right) )  
            write(0,160,120,4, "LEFT");
        end;

        if( key(_right) && !key(_left) ) 
            write(0,160,120,4, "RIGHT"); 
        end;

        frame;

    End;

    exit();

End

Used in example: [delete_text](), [write](), [ALL_TEXT]

This will output the words LEFT or RIGHT according to the keys you press, or it will quit the program once ESCAPE is pressed.


mod_map

[Up to Modules]


Maps module.

Usage


mod_math

[Up to Modules]


Math module.

Usage


mod_mem

[Up to Modules]


Memory module.

Usage


mod_mouse

[Up to Modules]


Mouse module.

Usage


mod_path

[Up to Modules]


Pathfind module.

Usage


mod_proc

[Up to Modules]


Process interaction and manipulation module.

Usage


mod_rand

[Up to Modules]


Random number generator module.

Usage


mod_regex

[Up to Modules]


Regular expressions module.

Usage


mod_say

[Up to Modules]


Say (printf) module.

Usage


mod_screen

[Up to Modules]


Screen module.

Usage


mod_scroll

[Up to Modules]


Scroll module.

Usage


mod_sort

[Up to Modules]


Sorting module.

Usage


mod_sound

[Up to Modules]


Sound module.

Usage


mod_string

[Up to Modules]


String manipulation module.

Usage


mod_sys

[Up to Modules]


System communication module.

Usage


mod_text

[Up to Modules]


Text module.

Usage


mod_time

[Up to Modules]


Time module.

Usage


mod_timers

[Up to Modules]


Timers module.

Usage


mod_video

[Up to Modules]


Video module.

Usage


mod_wm

[Up to Modules]


Window Manager module.

Usage



List of Functions

Abs()

Definition

FLOAT abs ( <FLOAT value> )

Returns the absolute value of value.

Parameters


FLOAT value - The value.


Returns

FLOAT : The absolute value of value.

Example

Global
    float value1;
    int value2;
End

Process Main()
Begin

    write_float(0,0, 0,0,&value1);
    write_int(0,0,10,0,&value2);

    value1 = abs(3);
    value2 = abs(-4);

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [write_float](), [write_int](), [key]()


Acos()

Syntax

FLOAT acos ( <FLOAT value> )

Description

Returns the arccosine of a certain value.

This [function] performs an arccosine calculation on a certain value and returns an [angle] between and including 0 and 180000 (0-180º).

Parameters


FLOAT value - The value to be performed an arccosine calculation on.


Returns

FLOAT : The arccosine result of the specified value, an angle between and including 0 and 180000 (0-180º).

Notes

The [angle] value returned by this function is in thousandths of degrees, as most angles within [Bennu] are.

To read about all aspects of trigonometry, you can visit Wikipedia's Trigonometric function page.


Alloc()

Syntax

VOID POINTER alloc ( <INT size> )

Description

Allocates a [block of memory] of a certain size. Returns a pointer to the newly allocating memory block, or [NULL] on failure.

Also called [mem_alloc]().

Parameters


INT size - The size of the to be allocated memory in [bytes].


Returns

VOID POINTER : Pointer to the first element of the allocated memory block.


[NULL] - There was are an error allocating the memory, like insufficient memory available. ![NULL] - Pointer to the first element of the allocated memory block.


Example

import "mod_mem"
import "mod_say"

Process Main()
Private
    byte* pbyte;
    word* pword;
    int* pint;
    int elements = 10;
    int i;
Begin

    // Allocate memory
    pbyte = alloc(elements);
    pword = alloc(elements*sizeof(*pword)); // note the sizeof() here, this is possible!
    pint  = alloc(elements*sizeof(int));

    // Reset memory to 0's
    memset (pbyte,0,elements);
    memsetw(pword,0,elements); // same as  memset(pword,0,elements*sizeof(word));
                               // because value-parameter is 0.
    memseti(pint ,0,elements); // same as  memset(pint,0,elements*sizeof(int));
                               // because value-parameter is 0.

    // Write numbers to bytes and ints
    for(i=0; i<elements; i++)
        pbyte[i]  = 133; // pbyte[i] is the same as *(pbyte+i)
        *(pint+i) = 4555; // pint[i] is the same as *(pint+i)
    end

    // Write numbers to words
    memsetw(pword,345,elements);

    // Show numbers
    for(i=0; i<elements; i++)
        say("byte["+i+"] = " + *(pbyte+i));
        say("word["+i+"] = " + pword[i]);
        say("int ["+i+"] = " + pint[i]);
    end

OnExit

    // Free the used memory
    free(pbyte);
    free(pword);
    free(pint);

End

Example 2

The following three examples show the difference in size, when array's are created. Note the use of the [sizeof]() operator, to calculate the amount of bytes required for the data type. You can also allocate user defined types and even structs. Be carefull with strings though, as they show up as 4 bytes, but in the case of strings, you get a [pointer] (start adress) of the [string], wich is a 4 byte integer.


Example 1 - array of 10 (4 byte) integers Example 2 - array of 10 (1 byte) byte (could also be char) Example 3 - array of 10 (2 byte) short integers


// Some general remarks with manual memory managment, ALWAYS free data after use, and test if an
// allocation was successfull with IF (p_test_array2==NULL). When one of these memory allocation
// functions returns a NULL, the allocation was NOT sucessfull, and any kind of unpredicatable things
// can happen. With manual memory managment, you'll have to really know what you're doing, as the slightest
// mistake can cause crashes and unpredicatable behaviour, wich is one of the dangers with using pointers.

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_mem";

 /*
    alloc(int size);
    returns: void pointer
    purpose: create a block of memory, of a certain size, the returned pointer indicates the start adress of this block.
*/

GLOBAL

int pointer p_first_array;    // 10 elments, created with alloc(), 10 integers       (4 byte elements)
byte pointer p_second_array;  // 10 elments, created with alloc(), 10 bytes          (1 byte elements)
short pointer p_third_array;  // 10 elments, created with alloc(), 10 short integers (2 byte elements)

int elements=10;            // initial array size

int count;                  // general purpose loop counter

PROCESS main();

BEGIN

    // Allocate memory (10 integers), this way we create an array of integers from (0-9, so 10 elements)
    // The alloc() function works with bytes. It is always good practice to use the sizeof() operator, because
    // you'd have to know exactly how many bytes make up a particulair data. An integer is 4 bytes in bennu,
    // so for an array of 10 elements, you need to allocate 40 bytes. If you do "alloc(elements)",like in the
    // wiki, you only get 4 bytes! so that is totally too small for you array! always use this syntax:
    // 
    // alloc(sizeof(<data_type>)), or for arrays: alloc(elements*sizeof(<data_type>)). Note that <data_type> can 
    // also be a user-defined type.

    p_first_array=alloc(elements*sizeof(int));

    // check if the allocation succeeded
    IF (p_first_array==NULL)
       // allocation failed
       say("allocation failed!! p_first_array="+p_first_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_first_array ,0,elements);

       say("");
       say("");
       // print the array
       FOR (count=0; count<elements; count+=1)
           say("p_first_array["+count+"]="+p_first_array[count]);
       END

       say("");
       say("");
       say("the size of the array is "+(elements*sizeof(int))+" bytes");  
       say("");
       say("");
    END

    // now let's create an array of 10 bytes, the size of the array will be 10 * 1 byte =10 bytes
    p_second_array=alloc(elements*sizeof(byte));

    // check if the allocation succeeded
    IF (p_first_array==NULL)
       // allocation failed
       say("allocation failed!! p_second_array="+p_second_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_second_array ,0,elements);

       say("");
       say("");
       // print the array
       FOR (count=0; count<elements; count+=1)
           say("p_second_array["+count+"]="+p_second_array[count]);
       END

       say("");
       say("");
       say("the size of the array is "+(elements*sizeof(byte))+" bytes");  
       say("");
       say("");
    END

    // now let's create an array of 10 short integers, the size of the array will be 10 * 2 bytes =20 bytes
    p_third_array=alloc(elements*sizeof(short));

    // check if the allocation succeeded
    IF (p_first_array==NULL)
       // allocation failed
       say("allocation failed!! p_second_array="+p_third_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_third_array ,0,elements);

       say("");
       say("");
       // print the array
       FOR (count=0; count<elements; count+=1)
           say("p_third_array["+count+"]="+p_third_array[count]);
       END

       say("");
       say("");
       say("the size of the array is "+(elements*sizeof(short))+" bytes");  
       say("");
       say("");
    END    

ONEXIT

   // Free the used memory
   say("freeing old memory........");
   say("p_first_array...");
   free(p_first_array);
   say("ok");

   say("freeing old memory........");
   say("p_second_array...");
   free(p_second_array);
   say("ok");

   say("freeing old memory........");
   say("p_third_array...");
   free(p_third_array);
   say("ok");
END

Used in example: [alloc](), [memset](), [memseti](), [say](), [OnExit], [sizeof]


Asc()

Definition

BYTE asc ( <STRING character> )

Returns the [ASCII] value of the first character of the string character.

Parameters


STRING character - The string of which the ASCII value of the first character will be returned.


Returns

BYTE : The ASCII value of the first character of the string character.

Example

Program asciis;
Begin

    write(0,0, 0,0,asc("A"));
    write(0,0,10,0,asc("CAT"));

    Repeat
        frame;
    Until(key(_esc))

End

Used in example: [write]()


Asin()

Syntax

FLOAT asin ( <FLOAT value> )

Description

Returns the arcsine of a certain value.

This [function] performs an arcsine calculation on a certain value and returns an [angle] between and including -90000 and 90000 (-90-90º).

Parameters


FLOAT value - The value to be performed an arcsine calculation on.


Returns

FLOAT : The arcsine result of the specified value, an angle between and including -90000 and 90000 (-90-90º).

Notes

The [angle] value returned by this function is in thousandths of degrees, as most angles within [Bennu] are.

To read about all aspects of trigonometry, you can visit Wikipedia's Trigonometric function page.


Atan()

Syntax

FLOAT atan ( <FLOAT value> )

Description

Returns the arctangent of a certain value.

This [function] performs an arctangent calculation on a certain value and returns an [angle] between but not including -90000 and 90000 (-90-90º).

Parameters


FLOAT value - The value to be performed an arctangent calculation on.


Returns

FLOAT : The arctangent result of the specified value, an angle between but not including -90000 and 90000 (-90-90º).

Notes

The [angle] value returned by this function is in thousandths of degrees, as most angles within [Bennu] are.

To read about all aspects of trigonometry, you can visit Wikipedia's Trigonometric function page.


Atan2()

Syntax

FLOAT atan2 ( <FLOAT y> , <FLOAT x>)

Description

Returns the arctangent of a certain value. It is computed as the arc tangent of y/x. The signs of the arguments are used to perform the calculation.

This [function] performs an arctangent calculation on a certain value and returns an [angle] between but not including -180000 and 180000 (-180-180º).

Parameters


FLOAT y - The Y value to be performed an arctangent calculation on. FLOAT x - The X value to be performed an arctangent calculation on.


Returns

FLOAT : The arctangent result of the specified value, an angle between but not including -180000 and 180000 (-180-180º).

Notes

The [angle] value returned by this function is in thousandths of degrees, as most angles within [Bennu] are.

See also

[atan]()

To read about all aspects of trigonometry, you can visit Wikipedia's Trigonometric function page.

Wikipedia's Atan2 page.


Atof()

Definition

FLOAT atof ( <STRING str> )

Returns the [float] value of the number specified in a certain [string].

Parameters


STRING str - The string specifying a number of which the float value will be returned.


Returns

FLOAT : The float value of the number specified by the specified string.


Atoi()

Definition

INT atoi ( <STRING str> )

Returns the [int] value of the number specified in a certain [string].

Parameters


STRING str - The string specifying a number of which the int value will be returned.


Returns

INT : The [int] value of the number specified by the specified string.


Bdf_load()

Definition

INT bdf_load ( <STRING filename>, [ <POINTER id>] )

Loads a BDF font file into memory as a [font].

The previous name [load_bdf]() is deprecated.

Parameters


STRING filename - The filename of the bdf file that you wish to load (including extension and possible path). POINTER id - Optional parameter, for loading a font in the background.


Returns

INT : [graphID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The graphID of the newly created font.


the following applies for versions prior rc282:

INT : [FontID]


-1 - Error: file does not exist. 0 - Filename could not be obtained from the specified string (doesn't happen usually). >0 - The FontID.


Errors


Format not recognized - The format of the specified file could not be recognized.


Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_bdf("archivo_gordo.bdf", &idbdf);
      while(idbdf==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idbdf==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

Blur()

Definition

INT blur ( <INT fileID> , <INT graphID> , <BYTE mode> )

This will make the specified [graphic] blurry by using a specified mode. It manipulates the graphic directly.

Only 16bit graphics are supported on 16bit video mode.

Parameters


INT fileID - The [fileID] that holds the graphics. INT graphID - The [graphID] to convert. BYTE mode - The blur mode that is applied to the [graphic]).


Returns

INT


0 - Invalid graphic or non 16bit graphic used. 1 - Success.


[Blur modes]


Constant - Value - Description BLUR_NORMAL - 0 - single pixel: considers pixels located to the left and above of each pixel. BLUR_3X3 - 1 - 3x3: considers all 8 adjacent pixels. BLUR_5X5 - 2 - 5x5: considers the 24 pixels that surrounds each pixel. BLUR_5X5_MAP - 3 - 5x5 with additional map: Just as the previous one but using a temporary map.


Examples


Calloc()

Syntax

VOID POINTER calloc (<INT num> ,<INT size>)

Description

Allocates (creates) a [block of memory] of a certain size. Calloc is slightly different from alloc, as it is more natively suited for creating arrays. It also automatically initialises the data with zeros, so that the use of [memset]() or [memseti]() can be omitted. Returns a pointer to the newly allocating memory block, or [NULL] on failure.

Also called [mem_calloc]().

Parameters


INT num - The amount of elements to be created in [ints].


Returns

VOID POINTER : Pointer to the first element of the allocated memory block.


[NULL] - There was are an error allocating the memory, like insufficient memory available. ![NULL] - Pointer to the first element of the allocated memory block.


Example

// Some general remarks with manual memory managment, ALWAYS free data after use, and test if an
// allocation was successfull with IF (p_array==NULL). When one of these memory allocation
// functions returns a NULL, the allocation was NOT sucessfull, and any kind of unpredicatable things
// can happen. With manual memory managment, you'll have to really know what you're doing, as the slightest
// mistake can cause crashes and unpredicatable behaviour, wich is one of the dangers with using pointers.

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_mem";

/*
    calloc(int size,type);
    returns: void pointer
    purpose: create a block of memory, of a certain size, the returned pointer indicates the start adress of this block.
*/

GLOBAL

int pointer p_array;        // 10 elments, created with calloc()

int elements=10;            // initial array size

int count;                  // general purpose loop counter

PROCESS main();

BEGIN

    // Now let's use calloc to create an array, but calloc is a bit smarter then alloc. It's more suited to array's and
    // it even initializes all the data to 0 for you, so that you can omit the memset() function. In this case I 
    // kept memseti() in there, but you can omit it when using calloc(). But with alloc() you need to use it!

    // Note the small difference between alloc() and calloc().

    //p_array=alloc(elements*sizeof(int));
    p_array=calloc(elements,sizeof(int));   // 10 * 4 bytes (the size of an int)

    // check if the allocation succeeded
    IF (p_array==NULL)
       // allocation failed
       say("allocation failed!! p_array="+p_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       /*
       memseti(p_array ,0,elements); // not need for calloc();
       */

       say("");
       say("");
       // print the array
       FOR (count=0; count<elements; count+=1)
           say("p_array["+count+"]="+p_array[count]);
       END

       say("");
       say("");
       say("the size of the array is "+(elements*sizeof(int))+" bytes");
       say("");
       say("");
    END   

ONEXIT

   // Free the used memory
   say("freeing old memory........");

   say("p_array...");
   free(p_array);
   say("ok"); 

END

Used in example: [alloc](), [memset](), [memseti](), [say](), [OnExit], [sizeof]


Center_set()

Definition

INT center_set ( <INT FileID> , <INT GraphID> , <INT x> , <INT y>)

Allows you to change the center of a [graphic].

This function changes a graphic's center pixel, which is the pixel that is located on screen at the [graph]'s x and y coordinates. So changing this will influence the position on the screen.

The previous name [set_center]() is deprecated.

Parameters


INT FileID - The [FileID] containing the graphic INT GraphID - The [GraphID] to change the center of. INT x - The new horizontal center [coordinate] of the graphic. INT y - The new vertical center [coordinate] of the graphic.


Returns

INT : Successrate


-1 - Specified graphic is invalid. 1 - The center was set successfully.


Notes

You set the position of [control point] 0 in the graphic. This control point acts as the graphic's [coordinate] on screen. For example, if a graphic's center is set to 0,0 , then the upper left pixel of the graphic will be placed on screen at the graphic's coordinates. If no center is set, by default control point 0 is set to the graphics true geometric center.

Another key feature is that the graphic will rotate around its center, as set by this function, and any horizontal or vertical mirrors (set with [flags]) will flip at this point.

When a graphic is used as a [mouse] pointer, its center point is used for the mouse tip. Most mouse cursors in [Operating Systems] have a mouse with the tip in the upper left of the image. Therefore, for a standard mouse pointer in Bennu, you will have to set the center at 0,0 to enable mouse accuracy.

Example

import "mod_map"
import "mod_text"
import "mod_key"

Process Main()
Begin
    graph=png_load("set_center.png");    //Loads a 128x128 image as the graphic
    x=160;
    y=100;                               //Places the graphic in the centre of the screen
    write(0,0,0,0,"Press [1] to set center to 0,0");
    write(0,0,0,10,"Press [2] to set center to 64,64");
    Loop
        if(key(_1))   
            center_set(0,graph,0,0);
        end
        if(key(_2))
            center_set(0,graph,64,64);
        end
        angle+=100;                      //Rotates the graphic constantly
        frame;
    End
End

Used in example: [graph], [png_load](), [write]()

File(s) used in example: [set_center.png]


Chr()

Definition

STRING chr ( <BYTE ASCIIvalue> )

Returns the character associated with ASCIIvalue.

Parameters


BYTE ASCIIvalue - The [ASCII] value of which the character is wanted.


Returns

STRING : The character associated with ASCIIvalue.

Example

Program chars;
Begin

    write(0,0, 0,0,chr(65));
    write(0,0,10,0,chr(67));

    Repeat
        frame;
    Until(key(_esc))

End

Used in example: [write]()


Color_find()

Syntax

INT color_find ( <BYTE red> , <BYTE green> , <BYTE blue> )

Description

Match an RGB value to a particular palette index. This is usefull in 8 bit mode.

The previous name [find_color]() is deprecated.

Parameters


BYTE red - Level of red in the desired color from 0 to 255. BYTE green - Level of green in the desired color from 0 to 255. BYTE blue - Level of blue in the desired color from 0 to 255.


Returns

INT : Returns the palette inxed of the color that corresponds with the rgb combination.

Example

IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_key";
IMPORT "mod_map";
IMPORT "mod_video";
IMPORT "mod_wm";
IMPORT "mod_draw";
IMPORT "mod_screen";
IMPORT "mod_text";

GLOBAL

   int map_id;    // id code of the map to load

   int status;    // status for debugging

PROCESS main();

BEGIN

   set_mode(320,200,32);

   // load the map
   map_id=load_map("3COCHE.MAP");

   status=color_find(0,0,0);
   say("color: "+status);
   status=color_find(0,252,0);
   say("color: "+status);
   status=color_find(0,67,0);
   say("color: "+status);
   status=color_find(0,243,0);
   say("color: "+status);
   status=color_find(0,10,0);
   say("color: "+status);
   status=color_find(255,252,0);
   say("color: "+status);
   status=color_find(100,252,100);
   say("color: "+status);

END

Colors_get() (MISSING)

Colors_set() (MISSING)

Cos()

Syntax

FLOAT cos ( <FLOAT angle> )

Description

Returns the cosine of the specified angle.

This [function] performs a cosine calculation on a certain angle and returns a value between -1 and 1.

Parameters


FLOAT angle - [Angle], in thousandths of degrees. i.e. 75000 = 75º


Returns

FLOAT : The cosine result of the specified [angle].

Notes

The [angle] value used in this function should be in thousandths of degrees, as most angles within [Bennu] are.

To read about all aspects of trigonometry, you can visit Wikipedia's Trigonometric function page.

Example

Const
    screen_width  = 320;
    screen_height = 200;
    screen_border = 15;
End

Global
    float value;
End

Process Main()
Begin

    // Modes
    set_title("Cosine Graph");
    set_mode(screen_width,screen_height);

    // X axis
    for(x=1;x<=8;x++)
        write( 0,
               screen_border+x*(screen_width-screen_border)/8+3,
               screen_height-1,
               8,
               itoa(x*360/8 )+"^" );
    end
    draw_line(1,screen_height-screen_border,screen_width,screen_height-screen_border);

    // Y axis
    write(0,screen_border-1,20,5,"1");
    write(0,screen_border-1,screen_height/2,5,"0");
    write(0,screen_border-1,screen_height-20,5,"-1");
    draw_line(screen_border,1,screen_border,screen_height-1);

    // Draw tangent
    for(angle=0;angle<360;angle++)
        value=cos(angle*1000)*(screen_height/2-20);
        put_pixel( screen_border+angle*(screen_width-screen_border)/360,
                   screen_height/2-value,
                   rgb(255,255,255) );
        // screen_height/2-value because the screen's origin (0,0) is topleft instead of downleft.
    end

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [set_title](), [set_mode](), [draw_line](), [put_pixel]()

This will result in something like:\


Crypt_decrypt() (MISSING)

Crypt_del() (MISSING)

Crypt_encrypt() (MISSING)

Crypt_new() (MISSING)

Delete_text()

Definition

INT delete_text ( <INT TextID> )

Deletes a certain [text] from the screen.

Parameters


INT TextID - [TextID] to be deleted.


Returns

INT : [true]

Notes

[Delete_text]) deletes all text from the screen.

Example

Program test;
Global
    my_text;
Begin
    my_text = write(0,320/2,200/2,4,"Press space to delete this.");
    Repeat
        if (key(_space))
            if(my_text>0)
                delete_text(my_text);
                my_text = 0;
            end
        end
        Frame;
    Until(key(_esc))
End

Used in example: [write](), [textID]

This will result in something like:\


Exec()

Definition

INT exec ( <INT mode> , <STRING executable>, <INT number_of_arguments> , <STRING POINTER arguments> )

Executes the specified executable with the specified arguments in the specified mode.

Parameters


INT mode - The mode to call the executable ([_P_WAIT]). STRING executable - The executable to start. INT number_of_arguments - The number of arguments given with arguments STRING POINTER arguments - Pointer to an array of strings to be passed; number_of_arguments strings will be passed as arguments.


Returns

INT


-1 - Error. mode==_P_WAIT: - The exit status of the executable. mode==_P_NOWAIT: - The process ID of the executable. This is not a [ProcessID], it is a process ID of the operating system.


Notes

The mode parameter can be two things:


_P_WAIT - Wait for the executable to exit. _P_NOWAIT - Do not wait for the executable to exit.


Example

Open file.txt in notepad:

import "mod_sys"

Process Main()
Private
    string arg;
Begin
    arg = "file.txt";
    exec(_P_NOWAIT,"notepad.exe",1,&arg);
End

Used in example: [exec](), [pointer]


Exists()

Definition

INT Exists ( <INT processID|processTypeID> )

Checks if a [process] is alive, using its [processID] or checks if there is a process alive of a certain [processType], using its [processTypeID].

Parameters


INT processID processTypeID - The ProcessID of the process or the ProcessTypeID of the type of processes to be checked.

Returns

INT : The result of the check


0 (false) - The process with given processID is not alive or there are no processes alive of the given processTypeID. 1 (true) - The process with given processID is alive or there is at least one process alive of the given processTypeID.


Example

import "mod_proc"
import "mod_say"

Process Main()
Begin

    Proc();

    if(exists(id))
        say("I exist! (id)");
    end

    if(exists(0))
        say("0 exists!");
    else
        say("0 doesn't exist!");
    end

    if(exists(type proc))
        say("1- Proc exists!");
    else
        say("1- Proc doesn't exist!");
    end

    let_me_alone();

    if(exists(type proc))
        say("2- Proc exists!");
    else
        say("2- Proc doesn't exist!");
    end

End

Process Proc()
Begin
    Loop
        frame;
    End
End

Used in example: [exists](), [let_me_alone]()


Exit()

Definition

INT exit ( [<STRING message>] , [<INT code>] )

Exits the program. It can optionally pass a message or an error code thing.

Parameters


[STRING message] - A message to pass outside the program as it exits. [INT code] - A code to pass outside the program as it exits.


Returns

INT : [true]


Fade()

Definition

INT fade ( <INT red> , <INT green> , <INT blue> , <INT speed> )

Fades the screen from the current setting to the specified setting (red,green,blue) at the specified speed.

Parameters


INT red - Amount of red shown from 0 to 200. 100 is normal. INT green - Amount of red shown from 0 to 200. 100 is normal. INT blue - Amount of red shown from 0 to 200. 100 is normal. INT speed - The speed of the fade from 1 to 64.


Returns

INT : [true]

Notes

Standard RGB combinations:


(R,G,B) - Description (0,0,0) - Black out. (100,100,100) - Normal. (200,200,200) - White out.


The number of frames the fading will take can be calculated like this:

: frames = roundup( 64 / speed ) : speed = roundup( 64 / frames )

So:


Speed - Description <0 - Takes 1 frame. 0 - Pointless. 1 - Takes 64 frames. 2 - Takes 32 frames. 3 - Takes 22 frames. >=64 - Takes 1 frame.


See also [fade_on]() and [fade_off]().


Fade_music_in()

Definition

INT fade_music_in ( <INT songID> , <INT num_loops> , <INT ms> )

Fades the music in, stepping up the volume from silence to the main song volume, i.e. set by the [Set_song_volume]() function.

Parameters


INT songID - The identification code of the song, returned by [load_song](). INT num_loops - The number of loops, a value of -1 will be an infinite loop. INT ms - Microseconds of fading (the duration).


Returns

INT : Error.


-1 - Error: sound inactive.


See also

[Fade_music_off]().


Fade_music_off()

Definition

INT fade_music_off ( <INT ms> )

Fades off the song, played by [Play_song]().

Parameters


INT ms - Microseconds of fading (the duration).


Returns

INT : Error.


-1 - Error: sound inactive.


See also

[Fade_music_in]().


Fade_off()

Definition

INT fade_off ( )

Fades the screen from the current setting to black out.

This call is equivalent to [[fade]](0,0,0,16).

Returns

INT : [true]


Fade_on()

Definition

INT fade_on ( )

Fades the screen from the current setting to normal.

This call is equivalent to [[fade]](100,100,100,16).

Returns

INT : [true]


Fclose()

Definition

INT fclose ( <INT filehandle> )

Unloads a file previously loaded with [fopen]().

Parameters


INT filehandle - The [FileHandle]().


Returns

INT: [true]

Example

Process loadthing(STRING loadpath);
Private
    int handle;   // handle for the loaded file 
    int druppels; // here's where the loaded data go
Begin

    handle=fopen(loadpath,O_READ); // opens the file in reading mode
    fread(handle,druppels);        // reads from the file and puts the data in druppels
    fclose(handle);                // zipping up after business is done
    write(0,0,0,0,druppels);       // shows the value of druppels
End

Used in example: [fopen](), [fread]()


Feof()

Definition

INT feof ( <INT filehandle> )

Checks if the end of a certain file is reached.

Parameters


INT filehandle - The [FileHandle]().


Returns

INT: [true]: Whether the end of the specified file is reached.


Fexists()

Syntax

INT fexists ( <STRING filename> )

Description

Checks if a certain file exists.

Also called [file_exists]().

Parameters


STRING filename - The file to be checked for existence, including a possible path.


Returns

INT : [true]: the existence of the file.


[true] - The specified file exists. [false] - The specified file doesn't exist.


Example

import "mod_file"
import "mod_say"

Process Main()
Begin

    say("> C:\Windows\notepad.exe > " + fexists("C:\Windows\notepad.exe")); // A filename with
                                                                            // absolute path
    say("> SDL.dll > " + fexists("SDL.dll")); // A filename without a path
    say("> SomeNonExistingFile > " + fexists("SomeNonExistingFile")); // A nonexisting file

End

Used in example: [say](), [fexists]()


Fflush()

Definition

INT fflush ( <INT filehandle> )

Clears internal data buffers for the file associated with the filehandle. The file has to be opened for output with the [Readwrite_modes]. This function comes from the standard C library, this is a miscellaneous function.

Parameters


INT filehandle - The [FileHandle]().


Returns

INT : - the status result of the action.


EOF (-1) - an error was detected, or end of file has been reached. 0 - normal condition, everything is fine.



Fget_angle()

Definition

INT fget_angle ( <INT pointA-X> , <INT pointA-Y> , <INT pointB-X> , <INT pointB-Y> )

Returns the [angle] between two certain points. The returned angle will be ranging from 0 to 360000 (0-360º).

Parameters


INT pointA-X - The X-coordinate of point A. INT pointA-Y - The Y-coordinate of point A. INT pointB-X - The X-coordinate of point B. INT pointB-Y - The Y-coordinate of point B.


Returns

INT : The angle between point A and point B.

Notes

The [angle] value returned by this function is in thousandths of degrees, as most angles within [Bennu] are.

Example

Const
    screen_width     = 320;
    screen_height    = 200;
    screen_depth     = 8;
    screen_fps       = 60;
    screen_frameskip = 0;
End

Global
    int distance;
    int tempID;
End

Process Main()
Begin

    // Set the screen mode
    set_mode(screen_width,screen_height,screen_depth);
    set_fps(screen_fps,screen_frameskip);

    // Change this to see what happens
    resolution = 100;

    // Create mouse graph, assign to mouse.graph
    mouse.graph = new_map(20,20,screen_depth);
    map_clear(0,mouse.graph,rgb(255,0,0));

    // Create arrow, assign to graph
    graph = new_map(30,30,screen_depth);
    drawing_map(0,graph);
    drawing_color(rgb(0,255,0));
    draw_line( 0,29,29,30/2);
    draw_line( 0, 0,30,30/2);

    // Set position
    x = screen_width /2 * resolution;
    y = screen_height/2 * resolution;

    // Display distance
    write(0,0,0,0,"Distance:");
    write_int(0,60,0,0,&distance);

    // Always point to the mouse
    Repeat
        // Get the angle and distance between this process' coordinates and those of the mouse.
        angle    = fget_angle(x,y,mouse.x*resolution,mouse.y*resolution);
        distance = fget_dist (x,y,mouse.x*resolution,mouse.y*resolution);
        frame;
    Until(key(_esc))

End

Used in example: [set_mode](), [new_map](), [drawing_map](), [drawing_color](), [draw_line](), [write_int](), [fget_angle](), [fget_dist](), [resolution], [graph], [angle]

This example could also be done with [get_angle](), but that would be more work.

It could look something like:\


Fget_dist()

Definition

INT fget_dist ( <INT pointA-X> , <INT pointA-Y> , <INT pointB-X> , <INT pointB-Y> )

Returns the distance between two certain points.

Parameters


INT pointA-X - The X-coordinate of point A. INT pointA-Y - The Y-coordinate of point A. INT pointB-X - The X-coordinate of point B. INT pointB-Y - The Y-coordinate of point B.


Returns

INT : The distance between point A and point B.

Example

Program angling;
Const
    screen_width     = 320;
    screen_height    = 200;
    screen_depth     = 8;
    screen_fps       = 60;
    screen_frameskip = 0;
Global
    int distance;
    int tempID;
Begin

    // Set the screen mode
    set_mode(screen_width,screen_height,screen_depth);
    set_fps(screen_fps,screen_frameskip);

    // Change this to see what happens
    resolution = 100;

    // Create mouse graph, assign to mouse.graph
    mouse.graph = new_map(20,20,screen_depth);
    map_clear(0,mouse.graph,rgb(255,0,0));

    // Create arrow, assign to graph
    graph = new_map(30,30,screen_depth);
    drawing_map(0,graph);
    drawing_color(rgb(0,255,0));
    draw_line( 0,29,29,30/2);
    draw_line( 0, 0,30,30/2);

    // Set position
    x = screen_width /2 * resolution;
    y = screen_height/2 * resolution;

    // Display distance
    write(0,0,0,0,"Distance:");
    write_int(0,60,0,0,&distance);

    // Always point to the mouse
    Repeat
        // Get the angle and distance between this process' coordinates and those of the mouse.
        angle    = fget_angle(x,y,mouse.x*resolution,mouse.y*resolution);
        distance = fget_dist (x,y,mouse.x*resolution,mouse.y*resolution);
        frame;
    Until(key(_esc))

End

Used in example: [set_mode](), [new_map](), [drawing_map](), [drawing_color](), [draw_line](), [write_int](), [fget_angle](), [fget_dist](), [resolution], [graph], [angle]

This example could also be done with [get_dist](), but that would be more work. It also gives a much less accurate distance when the [resolution] is >1.

Resolution is 100:


{{Image image = get_angle.png caption = [get_angle]() }}



Fgets()

Definition

STRING fgets ( <INT filehandle> )

Reads a line from a certain file and returns it. Subsequent calls will return the next line, until the end of the file is reached.

Parameters


INT filehandle - The [FileHandle]().


Returns

STRING: The line read.

Notes

The returned string normally does not contain the '\n' or '\r','\n' charactersets.

When a line ends with the character '\', the next line will be joined with the current one, changing the '\' character to a '\n' character.

If you want to read multiple lines from a textfile, put this function in a loop.


File()

: This is about the [filetype]. Did you mean the local variable [file] or the function [file]()?


[Up to Filetypes]


Description

A file is a container for [graphics], identified by a non-negative [integer] (0 or higher). It holds all information about the contained graphics ([pixels], [width], [depth], name, etc). Each of these graphics have a unique identifier inside the file (positive [int]).

A file can be created for example by loading an [FPG] (Fichero Para Gráficos, meaning "file for graphics") into it, by using [fpg_load](), which creates a new file with the graphics from the loaded FPG and returns a unique identifier. Another option is to create a new, empty one by using [fpg_new](). Don't let the name fpg_new() fool you: fpg_new() has nothing to do with the filetype FPG. This is because the FPG format is only for files and not for internal use. There are more ways to load graphics into a file.

A file can be used by using the [local variable] or by using the identifier in the various [functions] with a file parameter.

Don't forget to unload it with [fpg_unload]() after use.

Example

import "mod_map"
import "mod_grproc"
import "mod_key"
import "mod_wm"

Global
    int file_id;
    int file_id2;
End

Process Main()
Begin

    // Load FPG
    file_id = load_fpg("example.fpg");
    file_id2 = load_fpg("example2.fpg");

    // Set locals for display of graph
    file = file_id;
    graph = 1;
    x = y = 50;

    // assign Ship to use example2.fpg
    Ship(300,100,5,file_id2,1); // undefined in this sample

    Repeat
        frame;
    Until(key(_ESC)||exit_status)

End

Used in example: [load_fpg](), [key], [file]. [process]

Media in example: [example.fpg]

Note: nothing will be seen unless you have an [FPG] "example.fpg" with a [graphic] with ID 1.


Filter()

Definition

INT filter ( <INT fileID> , <INT graphID> , <POINTER filter_table> )

This function allows the colors of a graphic to be filtered with a nummerical range, defined as an [array].

Parameters


INT fileID - The [fileID] that holds the graphics. INT graphID - The [graphID]. POINTER fileter_table - Pointer to a table [array]).


Returns

INT


0 - Invalid graphic or non 16bit graphic used. 1 - Success.


Example

/* Example converted from bennupack, fenix test section, 2 Medium\fenix test\Fenix Test3\Test_FILTER.prg */

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_map";
IMPORT "mod_effects";
IMPORT "mod_proc";
IMPORT "mod_grproc";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_screen";

GLOBAL
int fpg;
int png;
int filter[]=8,20,3,4,5,6,7,8,9,70;
//int filter[]=448,20,3,4,5,6,7,8,9,70,255,344,255,1,0,0;
//int filter[]=5,30,20,40,60,80,100,1,1,2,3;

PROCESS main();

BEGIN

  scale_mode=scale_normal2x; 
  set_mode(320,200,mode_16bits);

  fpg=load_fpg("FPG2.FPG");
  png=load_png("PNG-1.PNG");

  say("Filter test...");
  say("Press ESC to quit...");

  put_screen(fpg,1);

  bola(100,100,"Normal",0);
  bola(200,100,"Filtered",1);

  REPEAT
     FRAME;
  UNTIL (key(_esc))

  let_me_alone();
END

PROCESS bola(int x,int y,string txt,int use_filter);

BEGIN
  say(txt);
  size=200; 
  graph=map_clone(0,png);

  IF (use_filter==TRUE) 
     filter(0,graph,&filter); 
  END

  LOOP
    FRAME;
  END
END

Find()

Definition

INT find ( <STRING str> , <STRING searchstring> , [<INT startposition>] )

Returns the position of the firstly found appearance of a searchstring in str or -1 if not found. The starting position can be specified optionally.

Parameters


STRING str - The string in which to search. STRING searchstring - The string to search for. [INT startposition] - The position at which to start searching. Default is 0.


Returns

INT : The position of the firstly found appearance of searchstring in str or -1 if not found.

Example

In this example there's a very long string in wich we're going to look for 10 strings. Some of these are found (when the result is > -1), and others are deliberately bogus to show how you can detect if a string is not found. What you'll see, is that when you specify a start position greater then 0, and the word exists but your start position is behind the actual position of the first character of the word you're looking for, the function returns -1 (no match). If you specify 0 (the start of the string), you'll be safe, because it will return the fist occurance of the word or character when it exists in the string.

As you can see, the working of the find function works very similarly to the find and search/replace function that you get in most text editors.

#IFdef __VERSION__
IMPORT "mod_video";
IMPORT "mod_text";
IMPORT "mod_say";
IMPORT "mod_key";
IMPORT "mod_string";
IMPORT "mod_proc";
IMPORT "mod_map";
IMPORT "mod_draw";
IMPORT "mod_debug";
IMPORT "mod_sys";
IMPORT "mod_wm";
#ENDIF

GLOBAL

/* this is the big string in wich we're going to try the find() function on with a couple of tests. */
string string_to_find_in = "hello, world! this is a very long string in wich the 'find' function must find another string. let's try a few things.";

/* these are the strings we're going to test. */
string search_string0 = "wich";
string search_string1 = "wich";
string search_string2 = ".";
string search_string3 = "str";
string search_string4 = "hello";
string search_string5 = "find";
string search_string6 = "i don't exist in the string";
string search_string7 = "me neither";
string search_string8 = "must";
string search_string9 = "a";

/* return values for the tests. a return value of "-1" means that the string could not be found. */
int find_result0;
int find_result1;
int find_result2;
int find_result3;
int find_result4;
int find_result5;
int find_result6;
int find_result7;
int find_result8;
int find_result9;

/* we store the find positions here. */
int find_pos0;
int find_pos1;
int find_pos2;
int find_pos3;
int find_pos4;
int find_pos5;
int find_pos6;
int find_pos7;
int find_pos8;
int find_pos9;

PRIVATE

PROCESS main ();

PRIVATE

BEGIN

   /* experiment with these to try different results. */
   find_pos0 = 0;
   find_pos1 = 45;
   find_pos2 = 118;
   find_pos3 = 0;
   find_pos4 = 0;
   find_pos5 = 70;
   find_pos6 = 0;
   find_pos7 = 0;
   find_pos8 = 94;
   find_pos9 = 94;

   /* INT find ( <STRING str> , <STRING searchstring> , [<INT startposition>] ); */

   find_result0 = find (string_to_find_in, search_string0, find_pos0); /* search_string0 = "wich"; */

   find_result1 = find (string_to_find_in, search_string1, find_pos1); /* search_string1 = "wich"; */

   find_result2 = find (string_to_find_in, search_string2, find_pos2); /* search_string2 = "."; */

   find_result3 = find (string_to_find_in, search_string3, find_pos3); /* search_string3 = "str"; */

   find_result4 = find (string_to_find_in, search_string4, find_pos4); /* search_string4 = "hello"; */

   find_result5 = find (string_to_find_in, search_string5, find_pos5); /* search_string5 = "find"; */

   find_result6 = find (string_to_find_in, search_string6, find_pos6); /* search_string6 = "i don't exist in the string"; */

   find_result7 = find (string_to_find_in, search_string7, find_pos7); /* search_string7 = "me neither"; */

   find_result8 = find (string_to_find_in, search_string8, find_pos8); /* search_string8 = "must"; */

   find_result9 = find (string_to_find_in, search_string9, find_pos9); /* search_string9 = "a"; */

   /* 
             "hello, world! this is a very long string in wich the 'find' function must find another string. let's try a few things.";            
              |                                                                                                                    |
     char pos:0                                                                                                                    118
   */

   /* display the results in the console. */
   say("");
   say("looking for: '"+search_string0+"'");
   say ("search_string0 result: "+find_result0);
   IF (find_result0 == -1)
      say ("no match for: '"+search_string0+"' at the indicated position: "+find_pos0);
   ELSE
      say ("'"+search_string0+"'"+" found at position: "+find_result0);
   END

   say("");
   say("looking for: '"+search_string1+"'");
   say ("search_string1 result: "+find_result1);
   IF (find_result1 == -1)
      say ("no match for: '"+search_string1+"' at the indicated position: "+find_pos1);
   ELSE
      say ("'"+search_string1+"'"+" found at position: "+find_result1);
   END

   say("");
   say("looking for: '"+search_string2+"'");
   say ("search_string2 result: "+find_result2);
   IF (find_result2 == -1)
      say ("no match for: '"+search_string2+"' at the indicated position: "+find_pos2);
   ELSE
      say ("'"+search_string2+"'"+" found at position: "+find_result2);
   END

   say("");
   say("looking for: '"+search_string3+"'");
   say ("search_string3 result: "+find_result3);
   IF (find_result3 == -1)
      say ("no match for: '"+search_string3+"' at the indicated position: "+find_pos3);
   ELSE
      say ("'"+search_string3+"'"+" found at position: "+find_result3);
   END

   say("");
   say("looking for: '"+search_string4+"'");
   say ("search_string4 result: "+find_result4);
   IF (find_result4 == -1)
      say ("no match for: '"+search_string4+"' at the indicated position: "+find_pos4);
   ELSE
      say ("'"+search_string4+"'"+" found at position: "+find_result4);
   END

   say("");
   say("looking for: '"+search_string5+"'");
   say ("search_string5 result: "+find_result5);
   IF (find_result5 == -1)
      say ("no match for: '"+search_string5+"' at the indicated position: "+find_pos5);
   ELSE
      say ("'"+search_string5+"'"+" found at position: "+find_result5);
   END

   say("");
   say("looking for: '"+search_string6+"'");
   say ("search_string6 result: "+find_result6);
   IF (find_result6 == -1)
      say ("no match for: '"+search_string6+"' at the indicated position: "+find_pos6);
   ELSE
      say ("'"+search_string6+"'"+" found at position: "+find_result6);
   END

   say("");
   say("looking for: '"+search_string7+"'");
   say ("search_string7 result: "+find_result7);
   IF (find_result7 == -1)
      say ("no match for: '"+search_string7+"' at the indicated position: "+find_pos7);
   ELSE
      say ("'"+search_string7+"'"+" found at position: "+find_result7);
   END

   say("");
   say("looking for: '"+search_string8+"'");
   say ("search_string8 result: "+find_result8);
   IF (find_result8 == -1)
      say ("no match for: '"+search_string8+"' at the indicated position: "+find_pos8);
   ELSE
      say ("'"+search_string8+"'"+" found at position: "+find_result8);
   END

   say("");
   say("looking for: '"+search_string9+"'");
   say ("search_string9 result: "+find_result9);
   IF (find_result9 == -1)
      say ("no match for: '"+search_string9+"' at the indicated position: "+find_pos9);
   ELSE
      say ("'"+search_string9+"'"+" found at position: "+find_result9);
   END

END

Notes

A first character of a string is at position 0.


Finite()

Syntax

INT Finite ( <FLOAT number> )

Description

Checks if a given value is a finite number. This function is the opposite of the [Isinf]() function. It does not check for Not-A-Numbers. Use the [Isnan]() function for that.

Parameters


FLOAT number - The value to check.


Returns


INT FALSE - The value is an infinity. INT TRUE - The value is a finite number.


See also

Wikipedia page about the mathematical subject infinity.


Flength()

Definition

INT flength ( <INT filehandle> )

Gives back the size of a certain file.

Parameters


INT filehandle - The [FileHandle]().


Returns

INT: The size of the file in bytes.


Fmove()

Definition

INT fmove ( <STRING source_file>, <STRING target_file> )

Renames files, from the bennu source code: files.c.

Parameters


STRING source_file - The source file. STRING target_file - The target file.


Returns

INT : [true]: the status result of the action.


[true] - The action was a success. [false] - The action failed.



Fnt_load()

Definition

INT fnt_load ( <STRING filename>, [ <POINTER id>] )

Loads a [FNT] file into memory as a [font]. A font is usually with the extension .fnt.

The previous name [load_fnt]() is deprecated.

Parameters


STRING filename - The filename of the [FNT] file that you wish to load (including extension and possible path). POINTER id - Optional parameter, for loading a font in the background.


Returns

INT : [graphID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The graphID of the newly created font.


the following applies for versions prior rc282:

INT : [FontID]


-1 - Error: file does not exist. 0 - Filename could not be obtained from the specified string (doesn't happen usually). >0 - The FontID.


Errors


Format not recognized - The format of the specified file could not be recognized.


Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_fnt("archivo_gordo.fnt", &idfnt);
      while(idfnt==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idfnt==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

Fnt_new()

Definition

INT fnt_new ( <INT depth> )

Creates a new [font] with a certain color depth. There exists three variants of this function:

  • INT fnt_new ( <INT depth> )

  • INT fnt_new ( <INT charset> , <INT depth> )

  • INT fnt_new ( <INT file> , <INT graph>, <INT charset> , <INT width> , <INT height> , <INT first> , <INT last> , <INT flags> )

  • The first variant is a simple version wich uses the systemfont and the CP850 character set.

  • The second version allows the user to select a different characterset.

  • The third function allows custom fonts to made, from bitmaps in memory. It is similair to DIV gamestudio's font generator. In this variant, the depth cannot be set.

The previous name [new_fnt]() is deprecated.

Parameters


INT charset - The color characterset of the font, CHARSET_ISO8859 or CHARSET_CP850. INT depth - The color depth of the [glyphs] of the font. INT file - The [fileID] of the file wich contains the bitmaps with the letters. INT graph - The [graphID] of the bitmap wich contains the character set. INT width - The width of the [glyph]. INT height - The height of the [glyph]. INT first - The first character. INT last - The last character. INT flags - The kind of [glyph] width, NFB_VARIABLEWIDTH or NFB_FIXEDWIDTH.


Returns

INT : [FontID]


-1 - Error: could not create [font]. >=0 - The FontID.


Errors


Insufficient memory - There is insufficient memory available. This error doesn't occur often. Too many fonts - There are too many fonts loaded (255).


Example

IMPORT "mod_video";
IMPORT "mod_wm";
IMPORT "mod_text";
IMPORT "mod_map";
IMPORT "mod_key";

GLOBAL
   int a;
   int b;
   int c;

   int graph_id;

   int font_id1;
   int font_id2;

PROCESS main();    

BEGIN

    set_mode(640,480);

    graph_id=png_load("font.png");

    // new font, variable width
    font_id1=fnt_new(0,graph_id,CHARSET_ISO8859,16,16,0,255,NFB_VARIABLEWIDTH);

    write_int(font_id1,0,0,0,&a);
    write_int(font_id1,0,20,0,&b);
    write_int(font_id1,0,40,0,&c);
    write(font_id1,0,60,0,"hello world!");

    // new font, fixed width
    font_id2=fnt_new(0,graph_id,CHARSET_ISO8859,16,16,0,255,NFB_FIXEDWIDTH); 

    write_int(font_id2,0,100,0,&a);
    write_int(font_id2,0,120,0,&b);
    write_int(font_id2,0,140,0,&c);
    write(font_id2,0,160,0,"hello world!");

    // write texts in standard system font
    write_int(0,320,0,0,&a);
    write_int(0,320,20,0,&b);
    write_int(0,320,40,0,&c);
    write(0,320,60,0,"hello world!");

    WHILE (NOT key(_ESC) AND NOT exit_status)

        a++;
        b--;
        c*=2;

        IF (c==0) 
           c=1; 
        END

        FRAME;
    END
END

Used in example: [Png_load](), [Write]()

Notes

If only one argument is used, the CP850 character set is used. The charactermap is a bitmap, with the characters arranged in a grid. See this post


Fnt_save()

Definition

INT fnt_save ( <INT fontID> , <STRING filename> )

Saves a [font] as a file. A font is usually with the extension ".fnt".

If the specified filename contains no extension, ".fnt" is added to it.

The previous name [save_fnt]() is deprecated.

Parameters


INT fontID - The [fontID] to be saved. STRING filename - The name of the font file to be saved, including a possible path.


Returns

INT : Successrate


[false]. [true] - Font successfully saved.


Errors


Invalid fontID - The specified [fontID] was invalid. Unable to create file - The file could not be created. Font corrupt - The font trying to be saved is corrupt. Insufficient memory - There is insufficient memory available. This error doesn't occur often.



Fnt_unload()

Definition

INT fnt_unload ( <INT fontID> )

Unloads the specified [font] from memory.

The previous name [unload_fnt]() is deprecated.

Parameters


INT fontID - The [fontID] to unload.


Returns

INT : [false]


Fopen()

Definition

INT fopen ( <STRING filename> , <INT mode> )

Opens a file on the hard drive for reading or writing.

Parameters


STRING filename - The filename of the file you wish to open (including extension and possible path). INT mode - The mode with which to access the file (see [Readwrite_modes]).


Returns

INT : [FileHandle]


0 - Could not load. !0 - The identifier of the file now opened for reading/writing.


Example

Process loadthing(STRING loadpath);
Private
    int handle;   // handle for the loaded file 
    int druppels; // here's where the loaded data go
Begin

    handle=fopen(loadpath,O_READ); // opens the file in reading mode
    fread(handle,druppels);        // reads from the file and puts the data in druppels
    fclose(handle);                // zipping up after business is done
    write(0,0,0,0,druppels);       // shows the value of druppels

End

Used in example: [fread](), [fclose]()


Format()

Definition

STRING format ( <INT number> )

STRING format ( <FLOAT number> )

STRING format ( <FLOAT number>, <INT number>)

Formats nummerical data for use in a [string]. There are three variants of this function, the first one only formats integers, the second one a floating point number, and the third one uses a fixed number of decimals, as given with the second parameter.

Parameters


INT str - The number to format.



FLOAT str - The decimal number to format.


Returns

STRING : The string with the fomatted number.

Example

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_string";

GLOBAL

int count=400000;
float count2=2.50000;
float count3=456.0000;

PROCESS main();

BEGIN

   say("format test.");
   say("");
   say("");
   say(format(count));
   say(format(count2));
   say(format(count3));

   say(format(count2,0));
   say(format(count2,1));
   say(format(count2,2));
   say(format(count2,3));

   say(format(count3,0));
   say(format(count3,1));
   say(format(count3,2));
   say(format(count3,3));
END

The program outputs this list:

400,000
2.500000
456.000000
3
2.5
2.50
2.500
456
456.0
456.00
456.000

Notes

The format function seems to like US number formats, even on a european machine.


Fpg_add()

Fpg_del() (MISSING)

Fpg_exists()

Definition

INT fpg_exists ( <INT FileID> )

Checks if an FPG exists with the specified [FileID].

Parameters


INT FileID - The [FileID] to check for existence.


Returns

INT : Whether the [File] exists


[false] does not exist. [true] exists.



Fpg_load()

Definition

INT fpg_load ( <STRING filename>, [<INT POINTER> complete>] )

Loads a graphics library into your program.

This function loads the whole contents of an [FPG] graphics library into your project, enabling the contained [graphics] to be used in your program as [process]' graphs, screen backgrounds ([put_screen]()) or other graphics.

The previous name [load_fpg]() is deprecated.

Parameters


STRING filename - The filename of the FPG that you wish to load (including extension and possible path). [INT POINTER complete] - If this argument is specified the [FPG] on completion.


Returns

INT : [graphID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The [FileID] assigned to the archive.


the following applies for versions prior rc282:

INT : [FileID]


-1 - The specified archive could not be loaded. >=0 - The [FileID] assigned to the archive.


Errors


Archive not found - The specified archive could not be found.


Notes

Using an FPG file to contain all or some of the graphics used in a Bennu program is convenient, but isn't always the best way to load graphics. Other methods of loading graphics into your program include [load_map]() and [load_png]() which load individual graphic files. Graphics loaded individually will be given [FileID] 0 and a [GraphID] starting at 1000. This is because mod_map reserves room for the first FPG loaded (FPG files can contain 999 different graphics max.), sometimes referred to as the [system file] or [environment file].

The first FPG file loaded using mod_map returns and uses the [FileID] 0, which is reserved by mod_map for use as the [system file]. All extra FPG files loaded will have a different FileID, progressing from 1 upwards.

An FPG file holds all its contained graphs in memory simultaneously. Having a lot of large graphs being read from a single FPG file at once has been known to cause a slowdown.

Once an FPG file is no longer necessary to be held in the memory, its memory space can be released by using the function [unload_fpg](). It is not necessary to unload files at the termination of a program, as Bennu always releases all used memory at the end of program execution.

Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

     load_fpg("archivo_gordo.fpg", &idFpg);
      while(idFpg==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idFpg==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

      file=idFpg;

      graph = 7;

Example

Program example;
Global
    int my_fpg;
Begin
    my_fpg=load_fpg("test.fpg");   //Loads the FPG file into memory
    put_screen(my_fpg,1);          //Puts graphic with code 1 onto screen
    Repeat
        frame;
    Until(key(_esc))
    unload_fpg(my_fpg);
End

Used in example: [put_screen](), [unload_fpg]()


Fpg_new()

Definition

INT fpg_new ( )

Creates and initializes a new [file].

To add [graphics] to the created file, use the returned [fileID] in the function [fpg_add](). The file can be saved with [fpg_save](). To free a file, use [fpg_unload]().

The previous name [new_fpg]() is deprecated.

Returns

INT : [fileID]


-1 - Too many files or insufficient memory. >=0 - The fileID of the new file.


Errors


Insufficient memory - There is insufficient memory available. This error doesn't occur often.



Fpg_save()

Definition

INT fpg_save( <INT fileID> , <STRING filename> )

Saves a certain [file] to disk.

The previous name [save_fpg]() is deprecated.

Parameters


INT fileID - The [fileID] to save. STRING filename - The name of the [file].


Returns

INT : Success


[false]. [true] - Success.


Errors


Insufficient memory - There is insufficient memory available. This error doesn't occur often. Empty library - The specified [file]. Unsupported color depth - A [graphic] has an unsupported color depth. Differing color depths - An [FPG] of different color depths.



Fpg_unload()

Definition

INT fpg_unload ( <INT fileID> )

Unloads a certain [file] from memory.

Also called [fpg_del](). The previous name [unload_fpg]() is deprecated.

Parameters


INT fileID - The [fileID] to unload.


Returns

INT : [true]


Fputs()

Definition

INT fputs ( <INT filehandle> , <STRING line> )

Writes a line to a certain file.

Parameters


INT filehandle - The [FileHandle]().


Returns

INT: Number of bytes written.


0 - There was an error. >0 - Number of bytes written.


Notes

The character '\' will be put in front of every newline character, so that [fgets]() reads the lines like they were written.


Fread()

Definition

INT fread ( <INT filehandle> , <VARIABLE data> )

INT fread ( <VOID POINTER data_pos> , <INT length> , <INT filehandle> )

Reads the information from a file loaded with [fopen]() to the variable data.

The second version reads length bytes to the memory pointed to by data_pos.

Parameters


INT filehandle - The [FileHandle](). VARIABLE data - The data to read from the file (any type of variable). It will be loaded into this variable. VOID POINTER data_pos - The pointer to which the bytes read will be written to. INT length - The number of bytes to read from the specified file.


Returns

INT : The number of bytes read from the file.

Example

Process loadthing(STRING loadpath);
Private
    int handle;   // handle for the loaded file 
    int druppels; // here's where the loaded data go
Begin

    handle=fopen(loadpath,O_READ); // opens the file in reading mode
    fread(handle,druppels);        // reads from the file and puts the data in druppels
    fclose(handle);                // zipping up after business is done
    write(0,0,0,0,druppels);       // shows the value of druppels

End

Used in example: [fopen](), [fclose]()


Free()

Definition

INT free ( <VOID POINTER data> )

Frees a block of memory.

The pointer used must be a pointer to a previously allocated block of memory, else the behavior of free() is undefined.

Also called [mem_free]().

Parameters


VOID POINTER data - Pointer to the block of memory to be freed.


Returns

INT : [true]

Example

Program example;
Private
    byte pointer pbyte;
    word pointer pword;
    int  pointer pint;
    int elements = 10;
    int i;
Begin

    // Allocate memory
    pbyte = alloc(elements);
    pword = alloc(elements*sizeof(word));
    pint  = alloc(elements*sizeof(int));

    // Reset memory to 0's
    memset (pbyte,0,elements);
    memsetw(pword,0,elements); // same as  memset(pword,0,elements*sizeof(word));
                               // because value-parameter is 0.
    memset (pint ,0,elements*sizeof(int)); // There isn't a "memseti()", so we need to
                                           // set the individual bytes to 0. To change
                                           // ints to nonzero values, memset() can't be
                                           // used easily

    // Write numbers to bytes and ints
    for(i=0; i<elements; i++)
        pbyte[i]  = 133; // pbyte[i] is the same as *(pbyte+i)
        *(pint+i) = 4555; // pint[i] is the same as *(pint+i)
    end

    // Write numbers to words
    memsetw(pword,345,elements);

    // Show numbers
    for(i=0; i<elements; i++)
        say("byte["+i+"] = " + *(pbyte+i));
        say("word["+i+"] = " + pword[i]);
        say("int ["+i+"] = " + pint[i]);
    end

    Repeat
        frame;
    Until(key(_esc))

    // Free the used memory
    free(pbyte);
    free(pword);
    free(pint);

End

Used in example: [alloc](), [memset](), [sizeof](), [free]


Fremove()

Definition

INT fremove ( <STRING filename> )

Removes (deletes) files, from the bennu source code: files.c.

Parameters


STRING filename - The file to remove.


Returns

INT : [true]: the status result of the action.


[true] - The action was a success. [false] - The action failed.



Frewind()

Definition

UNDEFINED frewind ( <INT filehandle> )

Sets the byte offset (reading position) to the begin of a certain file. This is similair to using:

fseek(file_id,0,SEEK_SET);

Parameters


INT filehandle - The [FileHandle]().


Returns

INT


1 - The begin position of the file.


See also

[fseek]()


Fseek()

Definition

INT fseek ( <INT filehandle> , <INT position> , <INT seek_mode> )

Sets the byte offset (reading position) of a certain file. This means where a function will start reading in that file.

Parameters


INT filehandle - The [FileHandle](). INT position - Number of bytes from the point indicated by seek_mode. INT seek_mode - Set the offset relative to a certain point (see [seek modes]).


Returns

INT: The new reading position.


Ftell()

Definition

INT ftell ( <INT filehandle> )

Returns the current reading position of a certain file.

The reading position can be altered by [fseek]().

Parameters


INT filehandle - The [FileHandle]().


Returns

INT: The current reading position of the specified file.


Ftime()

Syntax

STRING ftime ( <STRING format> , <INT time> )

Description

Puts a certain time in a certain format.

It returns the specified [string], with certain keywords replaced with their corresponding values, according to the specified time (see [Notes]). The current time is fetched by use of the [function] [time]().

Parameters


STRING format - The format wanted. INT time - The time to be put in the formatted string.


Returns

STRING : The formatted string.

Notes

A list of keywords:


Keyword - Replaced by %a - the locale's abbreviated weekday name. %A - the locale's full weekday name. %b - the locale's abbreviated month name. %B - the locale's full month name. %c - the locale's appropriate date and time representation. %C - the century number (the year divided by 100 and truncated to an integer) as a decimal number [00-99]. %d - the day of the month as a decimal number [01,31]. %D - the same as %m/%d/%y. %e - the day of the month as a decimal number [1,31]; a single digit is preceded by a space. %h - the same as %b. %H - the hour (24-hour clock) as a decimal number [00,23]. %I - the hour (12-hour clock) as a decimal number [01,12]. %j - the day of the year as a decimal number [001,366]. %m - the month as a decimal number [01,12]. %M - the minute as a decimal number [00,59]. %n - a newline character. %p - the locale's equivalent of either a.m. or p.m. %r - the time in a.m. and p.m. notation; in the POSIX locale this is equivalent to %I:%M:%S %p. %R - the time in 24 hour notation (%H:%M). %S - the second as a decimal number [00,61]. %t - a tab character. %T - the time (%H:%M:%S). %u - the weekday as a decimal number [1,7], with 1 representing Monday. %U - the week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. %V - the week number of the year (Monday as the first day of the week) as a decimal number [01,53]. If the week containing 1 January has four or more days in the new year, then it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1. %w - the weekday as a decimal number [0,6], with 0 representing Sunday. %W - the week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. %x - the locale's appropriate date representation. %X - the locale's appropriate time representation. %y - the year without century as a decimal number [00,99]. %Y - the year with century as a decimal number. %Z - the timezone name or abbreviation, or by no bytes if no timezone information exists. %% - %.


Example

import "mod_timer"
import "mod_time"
import "mod_text"
import "mod_key"

Process Main()
Private
    String timestring; // The string holding the formatted time
Begin

    write_string(0,0,0,0,&timestring); // Display the timestring
    timer = 100; // Make it so it updates the timestring immediately

    Repeat
        if(timer>100) // Update the timestring every 1 second
            timer = 0;
            timestring = ftime("%d-%m-%Y %H:%M:%S",time());
        end
        frame;
    Until(key(_esc))

End

Used in example: [write_string](), [time](), [timer]


Ftoa()

Definition

STRING ftoa ( <FLOAT value> )

Returns a [string] containing a certain [float] value.

Parameters


'''FLOAT ''' value - The value the returned string will contain.


Returns

STRING : The string containing the specified value, including sign and decimal point.


Fwrite()

Definition

INT fwrite ( <INT filehandle> , <VARIABLE data> )

INT fwrite ( <VOID POINTER data_pos> , <INT length> , <INT filehandle>)

Writes the variable data to a file loaded with [fopen].

to be extended...

Parameters


INT filehandle - Identifier of the file loaded with [fopen]. VARIABLE data - The data to write to the file (any type of variable).


Returns

INT : The number of bytes written to the file.

Example

Process writething(STRING loadpath);
Private
    handle;   // handle for the loaded file 
    druppels; // the data to write to the file

Begin

    druppels=rand(1,10);

    handle=fopen(loadpath,O_WRITE); // opens the file in writing mode
    fwrite(handle,druppels);        // writes the druppels variable to the file
    fclose(handle);                 // zipping up after business is done

End

Used in example: [fopen](), [fclose]()


Get_angle()

Definition

INT get_angle ( <INT processID> )

Returns the [angle] between the coordinates of a certain [process] and the process calling [get_angle]().

Parameters


INT processID - The other [process].


Returns

INT : The wanted [angle].


-1 - An error may have occurred: invalid [process]. !-1 - The wanted [angle].


Example

Program angling;
import "mod_grproc"//modules
import "mod_proc"
import "mod_wm"
import "mod_key"
import "mod_video"
import "mod_map"
import "mod_draw"
import "mod_text"
Const
    screen_width     = 320;
    screen_height    = 200;
    screen_depth     = 8;
    screen_fps       = 60;
    screen_frameskip = 0;
Global
    int distance;
    int tempID;
Begin

    // Set the screen mode
    set_mode(screen_width,screen_height,screen_depth);
    set_fps(screen_fps,screen_frameskip);

    // Change this to see what happens
    resolution = 100;

    // Create mouse graph and start mousepointer
    x = new_map(20,20,screen_depth);
    map_clear(0,x,rgb(255,0,0));
    mousepointer(0,x);

    // Create arrow, assign to graph
    graph = new_map(30,30,screen_depth);
    drawing_map(0,graph);
    drawing_color(rgb(0,255,0));
    draw_line( 0,29,29,30/2);
    draw_line( 0, 0,30,30/2);

    // Set position
    x = screen_width /2 * resolution;
    y = screen_height/2 * resolution;

    // Display distance
    write(0,0,0,0,"Distance:");
    write_int(0,60,0,0,&distance);

    // Always point to the mouse
    Repeat
        // Get the angle and distance between this process' coordinates and those of mousegraph.
        // We can use TYPE and get_id() here, because usually there would only be one
        // mousepointer and one always.
        tempID = get_id(type mousepointer);
        angle = get_angle(tempID);
        distance = get_dist(tempID);
        frame;
    Until(key(_esc))

End

/**
 * Follows the mouse coordinates. x is always mouse.x and y is always mouse.y
 * for processes with priority <1. The graphic of this process will be a certain graphic.
 * int file     - The fileID of the file where the graphic is located
 * int graph    - The graphID of the graphic to be used for this process
 */
Process mousepointer(int file,int graph)
Begin
    // Set the priority to 1, because we first want to have the correct coordinates of
    // the mouse set in this process. Then after that other process can use those coordinates.
    priority = 1;
    // Obtain father's resolution
    resolution = father.resolution;
    // Loop
    Loop
        // Obtain X and Y coordinates of the mouse and adjust for resolution
        // (mouse.y and mouse.y have an unchangeable resolution of 1)
        x = mouse.x * resolution;
        y = mouse.y * resolution;
        frame;
    End
End

Used in example: [set_mode](), [new_map](), [drawing_map](), [drawing_color](), [draw_line](), [write_int](), [get_angle](), [get_dist], [mouse], [y], [priority]

This example could also be done with [fget_angle](), which is easier and doesn't require an extra [process].

It could look something like:\ http://wwwhome.cs.utwente.nl/~bergfi/fenix/wiki/get_angle.PNG


Get_desktop_size()

Syntax

INT get_desktop_size ( <INT POINTER width>, <INT POINTER height> )

Description

Get the desktop size.

Parameters


INT POINTER width - Pointer to where the desktop width will be written. INT POINTER height - Pointer to where the desktop height will be written.


Returns

INT : Successrate


[false] - Error. [true] - Ok.



Get_dist()

Definition

INT get_dist ( <INT processID> )

Returns the distance between the coordinates of a certain [process] and the process calling [get_dist](). The distance returned is converted to the [resolution] of the process calling [get_dist]().

Parameters


INT processID - The other [process].


Returns

INT : The wanted distance.


-1 - An error occurred: invalid [process]. !-1 - The wanted distance.


Example

Program angling;
Const
    screen_width     = 320;
    screen_height    = 200;
    screen_depth     = 8;
    screen_fps       = 60;
    screen_frameskip = 0;
Global
    int distance;
    int tempID;
Begin

    // Set the screen mode
    set_mode(screen_width,screen_height,screen_depth);
    set_fps(screen_fps,screen_frameskip);

    // Change this to see what happens
    resolution = 100;

    // Create mouse graph and start mousepointer
    x = new_map(20,20,screen_depth);
    map_clear(0,x,rgb(255,0,0));
    mousepointer(0,x);

    // Create arrow, assign to graph
    graph = new_map(30,30,screen_depth);
    drawing_map(0,graph);
    drawing_color(rgb(0,255,0));
    draw_line( 0,29,29,30/2);
    draw_line( 0, 0,30,30/2);

    // Set position
    x = screen_width /2 * resolution;
    y = screen_height/2 * resolution;

    // Display distance
    write(0,0,0,0,"Distance:");
    write_int(0,60,0,0,&distance);

    // Always point to the mouse
    Repeat
        // Get the angle and distance between this process' coordinates and those of mousegraph.
        // We can use TYPE and get_id() here, because usually there would only be one
        // mousepointer and one always.
        tempID = get_id(type mousepointer);
        angle = get_angle(tempID);
        distance = get_dist(tempID);
        frame;
    Until(key(_esc))

End

/**
 * Follows the mouse coordinates. x is always mouse.x and y is always mouse.y
 * for processes with priority <1. The graphic of this process will be a certain graphic.
 * int file     - The fileID of the file where the graphic is located
 * int graph    - The graphID of the graphic to be used for this process
 */
Process mousepointer(int file,int graph)
Begin
    // Set the priority to 1, because we first want to have the correct coordinates of
    // the mouse set in this process. Then after that other process can use those coordinates.
    priority = 1;
    // Obtain father's resolution
    resolution = father.resolution;
    // Loop
    Loop
        // Obtain X and Y coordinates of the mouse and adjust for resolution
        // (mouse.y and mouse.y have an unchangeable resolution of 1)
        x = mouse.x * resolution;
        y = mouse.y * resolution;
        frame;
    End
End

Used in example: [set_mode](), [new_map](), [drawing_map](), [drawing_color](), [draw_line](), [write_int](), [get_angle](), [get_dist], [mouse], [y], [priority]

This example could also be done with [fget_dist](), which is easier and doesn't require an extra [process]. It also give a much more accurate distance when the [resolution] is >1.

Resolution is 100:


http://wwwhome.cs.utwente.nl/~bergfi/fenix/wiki/get_angle.PNG VS http://wwwhome.cs.utwente.nl/~bergfi/fenix/wiki/fget_angle.PNG [get_angle]()



Get_distx()

Definition

INT get_distx ( <INT angle> , <INT distance> )

Returns the horizontal distance in pixels of a specified displacement.

This is the same as [[cos]](''angle'')*''distance''.

Parameters


INT angle - [Angle], in thousandths of degrees (90° = 90000). INT distance - Length (in pixels) to measure.


Returns

INT : The horizontal distance, in pixels, of a specified displacement.

Notes

This function returns the width of an imaginary rectangle who's opposite corners are the specified distance apart, at the specified [angle] from each other.

Example

Global
    xdist;
    ydist;
    dist;
    ang;
    mydraw;
End

Process Main()
Begin

    set_mode(640,480,16);
    set_fps (50,0);
    graph = new_map(3,3,16);
    map_clear(0,graph,rgb(0,255,0));
    x = 320;
    y = 240;

    set_text_color(rgb(0,0,0));
    write    (0,60, 0,2,"X Diff: ");
    write_int(0,60, 0,0,&xdist);
    write    (0,60,10,2,"Y Diff: ");
    write_int(0,60,10,0,&ydist);
    write    (0,60,20,2,"Angle: ");
    write_int(0,60,20,0,&ang);
    write    (0,60,30,2,"Distance: ");
    write_int(0,60,30,0,&dist);

    write    (0,10,40,0,"Left/right rotates your angle, up/down changes your distance");

    put(0,graph,x,y);
    drawing_background();

    repeat
        if(key(_up))
            dist++;
        end

        if(key(_down))
            dist--;
        end

        if(key(_left))
            ang-=1000;
        end

        if(key(_right))
            ang+=1000;
        end

        xdist = get_distx(ang,dist);
        ydist = get_disty(ang,dist);

        x = 320 + xdist;
        y = 240 + ydist;

        frame;

    until(key(_esc))

    let_me_alone();
    exit();

End

Process drawing_background()
Begin
    graph = new_map(640,480,16);
    set_ceter   (0,graph,0,0);
    map_clear    (0,graph,rgb(64,0,0));
    drawing_map  (0,graph);
    drawing_color(rgb(0,0,0));
    loop
        map_clear(0,graph,rgb(255,255,255));
        mydraw = draw_line(320,240,father.x,father.y);
        frame;
        delete_draw(mydraw);
    end
OnExit
    unload_map(0,graph);
End

Used in example: [set_mode](), [set_fps](), [set_text_color](), [write](), [put](), [get_distx](), [get_disty](), [let_me_alone](), [set_center](), [map_clear](), [drawing_map](), [drawing_color](), [draw_line](), [delete_draw](), [unload_map]()


Get_disty()

Definition

INT get_disty ( <INT angle> , <INT distance> )

Returns the vertical distance in pixels of a specified displacement.

This is the same as -[[sin]](''angle'')*''distance''.

Parameters


INT angle - [Angle], in thousandths of degrees (90° = 90000). INT distance - Length (in pixels) to measure.


Returns

INT : The vertical distance, in pixels, of a specified displacement.

Notes

This function returns the height of an imaginary rectangle who's opposite corners are the specified distance apart, at the specified [angle] from each other.

Example

Global
    xdist;
    ydist;
    dist;
    ang;
    mydraw;
End

Process Main()
Begin

    set_mode(640,480,16);
    set_fps (50,0);
    graph = new_map(3,3,16);
    map_clear(0,graph,rgb(0,255,0));
    x = 320;
    y = 240;

    set_text_color(rgb(0,0,0));
    write    (0,60, 0,2,"X Diff: ");
    write_int(0,60, 0,0,&xdist);
    write    (0,60,10,2,"Y Diff: ");
    write_int(0,60,10,0,&ydist);
    write    (0,60,20,2,"Angle: ");
    write_int(0,60,20,0,&ang);
    write    (0,60,30,2,"Distance: ");
    write_int(0,60,30,0,&dist);

    write    (0,10,40,0,"Left/right rotates your angle, up/down changes your distance");

    put(0,graph,x,y);
    drawing_background();

    repeat
        if(key(_up))
            dist++;
        end

        if(key(_down))
            dist--;
        end

        if(key(_left))
            ang-=1000;
        end

        if(key(_right))
            ang+=1000;
        end

        xdist = get_distx(ang,dist);
        ydist = get_disty(ang,dist);

        x = 320 + xdist;
        y = 240 + ydist;

        frame;

    until(key(_esc))

    let_me_alone();
    exit();

End

Process drawing_background()
Begin
    graph = new_map(640,480,16);
    set_ceter   (0,graph,0,0);
    map_clear    (0,graph,rgb(64,0,0));
    drawing_map  (0,graph);
    drawing_color(rgb(0,0,0));
    loop
        map_clear(0,graph,rgb(255,255,255));
        mydraw = draw_line(320,240,father.x,father.y);
        frame;
        delete_draw(mydraw);
    end
OnExit
    unload_map(0,graph);
End

Used in example: [set_mode](), [set_fps](), [set_text_color](), [write](), [put](), [get_distx](), [get_disty](), [let_me_alone](), [set_center](), [map_clear](), [drawing_map](), [drawing_color](), [draw_line](), [delete_draw](), [unload_map]()


Get_id()

Definition

INT get_id ( <INT processTypeID> )

Returns a [ProcessID] of a [process] of the specified [ProcessType]. On the next call of get_id() in the same process and in the same frame, the next process will be returned of the given type. After a [frame] statement, get_id() is reset and will return the first process of the given processType. When there are no more processes of a given type, which have not been returned, it will return 0.

get_id(0) returns processes of any type.

Parameters


INT processTypeID - The [processTypeID] to get the processes' processIDs of.


Returns

INT : The [processID] of a process of the given processType.


0 - There are no more processes of the given processType, which have not been returned. >0 - The [processID] of a process of the given processType.


Example

Program example;
Begin
    signaltype(type Monkey,s_kill);
End

/**
 * Empty process
 */
Process Monkey()
Begin
End

/**
 * Signals every process of type 't' the signal 'signal'.
 */
Function int signaltype(int t, int signal)
Begin
    while( (x=get_id(t)) ) // while there is an unprocessed process left and store that in 'x'
        signal(x,signal); // signal the process with processID 'x'.
    end
End

// Of course, the very observant of you already noticed that signaltype(my_type,my_signal)
// does the same thing as the function signal(my_type,my_signal), but this is just to
// illustrate the workings.

/**
 * Signals every process the signal 'signal'.
 */
Function int signalall(int signal)
Begin
    while( (x=get_id(0)) ) // while there is an unprocessed process left and store that in 'x'
        signal(x,signal); // signal the process with processID 'x'.
    end
End

// get_id(0) returns a process of any type. This is a possible implementation of a
// function which signals all existing processes. Note that this can be dangerous to use,
// as in some cases you might want one or two processes to stay alive.

Used in example: [signal]()


Get_joy_position() (MISSING)

Get_modes()

Syntax

POINTER get_modes ( <INT depth>, <INT flags> )

Description

Returns a pointer to an array of available screen dimensions for the given [depth] and [render flags], sorted largest to smallest.

Returns NULL if there are no dimensions available for a particular format, or -1 if any dimension is okay for the given format.

Parameters


INT depth - [Color depth]. INT flags - Mode of rendering. See [render flags].


Returns

POINTER : A pointer to an array of available screen dimensions

Example

import "mod_say";
import "mod_video";

Process Main()
Private
    int * modes;
Begin
    // Modes will point to an array whose values are acceptable values for resolution

    // Get 8bpp acceptable modes when in fullscreen
    modes = get_modes(8, MODE_FULLSCREEN);
    say ("8bit modes");
    say ("----------");
    if (!modes)
        say ("no video modes available!");
    elsif (modes == -1 )
        say ("any video mode available!");
    else
        while (*modes)
            say ("> " + *modes++ + " x " + *modes++ );
        end
    end
    say ("");

    // Get 16bpp acceptable modes when in fullscreen
    modes = get_modes(16, MODE_FULLSCREEN);
    say ("16bit modes");
    say ("-----------");
    if (!modes)
        say ("no video modes available!");
    elsif (modes == -1 )
        say ("any video mode available!");
    else
        while (*modes)
            say ("> " + *modes++ + " x " + *modes++ );
        end
    end
    say ("");

    // Get 24bpp acceptable modes when in fullscreen
    modes = get_modes(24, MODE_FULLSCREEN);
    say ("24bit modes");
    say ("-----------");
    if (!modes)
        say ("no video modes available!");
    elsif (modes == -1 )
        say ("any video mode available!");
    else
        while (*modes)
            say ("> " + *modes++ + " x " + *modes++ );
        end
    end
    say ("");

    // Get 32bpp acceptable modes when in fullscreen
    modes = get_modes(32, MODE_FULLSCREEN);
    say ("32bit modes");
    say ("-----------");
    if (!modes)
        say ("no video modes available!");
    elsif (modes == -1 )
        say ("any video mode available!");
    else
        while (*modes)
            say ("> " + *modes++ + " x " + *modes++ );
        end
    end
    say ("");

End

Used in example: [say](), [MODE_FULLSCREEN]


Get_pixel()

Definition

INT get_pixel ( <INT x> , <INT y> )

Returns the [color] of the specified [pixel]. Is equivalent to [map_get_pixel]( 0, 0, x, y ).

Parameters


INT x - The X-coordinate of the [pixel] the color is wanted. INT y - The Y-coordinate of the [pixel] the color is wanted.


Returns

INT : The color

Example

import "mod_video"
import "mod_wm"
import "mod_draw"
import "mod_map";
import "mod_screen";
import "mod_mouse";

Process Main()

Begin

    set_mode(640,480,16); 

    // Creates a white box as mouse's cursor
    mouse.graph = new_map(20,20,16);
    map_clear(0,mouse.graph,rgb(255,255,255));

    // This area will show the pixel's color behind the cursor
    graph=new_map(100,50,16);
    x=50;
    y=25; 

    //Puts the background
    put_screen(0,load_png("image.png"));  

    Repeat
        map_clear(0,graph,get_pixel(mouse.x,mouse.y));
        frame;
    Until(exit_status)

End

Used in example: [set_mode](), [new_map](), [put_screen](), [get_pixel]()


Get_status()

Definition

INT get_status ( <INT processID> )

Get the current status of a [ProcessID]. With this, you can check if a process is frozen, sleeping, dead, alive or non-existing.

Parameters


INT processID - The [ProcessID] signal was send to.


Returns

INT :


[false] - The specified processID does not exist (return status: 0). 1,2,3 or 4 - The state of the [processID].


Return states


0 - The specified process does not exist. 1 - The specified process is dead. 2 - The specified process is alive. 3 - The specified process is sleeping. 4 - The specified process is frozen.


Example

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_proc";
IMPORT "mod_grproc";
IMPORT "mod_key";

GLOBAL

  int proc1;
  int proc2;
  int proc3;
  int proc4;
  int proc5;

PROCESS main();

PRIVATE

BEGIN

   // create some processes
   proc1=dummy();
   proc2=dummy();
   proc3=dummy();
   proc4=dummy();

   // change the state
   signal(proc1,s_sleep);
   signal(proc2,s_freeze);
   signal(proc3,s_wakeup);
   signal(proc4,s_kill);

   // print the status of each instance            
   say("");
   say("status codes: ALIVE=2, SLEEP=3, FROZEN=4 ,DEAD=1, NON_EXISTING=0");
   say("");
   say("proc1 status: "+get_status(proc1)); // sleeping     (3)
   say("proc2 status: "+get_status(proc2)); // frozen       (4)
   say("proc3 status: "+get_status(proc3)); // alive        (2)
   say("proc4 status: "+get_status(proc4)); // dead         (1)
   say("proc5 status: "+get_status(proc5)); // not existing (0)

   LOOP

      // quit.
      IF (key(_esc))

         exit("",0);
      END
      FRAME;
   END
END

PROCESS dummy();

PRIVATE

BEGIN

   // endless loop
   LOOP
      FRAME;
   END
END

Used in example: [exit](), [key]


Get_text_color()

Definition

INT get_text_color( [<INT textID>] )

Gets the current text [color] (the [color] where texts will be written in).

Parameters

INT textID: The identification code of the text (optional parameter, introduced in version rc282).

Returns

INT: [color] the text will be written in, or 0 when there is a problem.

Notes

None.

Errors

<If someone knows, please edit!>

Example

Program test;
Global
    my_text;
    text_color;
Begin

    set_text_color( rgb(192,112,0) );
    text_color = get_text_color();

    write    (0,320/2    ,200/2,4,"The color of this text is:");
    write_int(0,320/2+100,200/2,4,&text_color);

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [set_text_color](), [write](), [key]()

This will result in something like:\


Get_timer()

Syntax

INT get_timer ( )

Description

Returns the time the program has been running in milliseconds.

Returns

INT : The time the program has been running in milliseconds.


Get_window_pos()

Syntax

INT get_window_pos ( <INT POINTER x>, <INT POINTER y>)

Description

Get the X and Y position of the window.

Parameters


INT POINTER x - Pointer to where the X-coordinate of the window will be written. INT POINTER y - Pointer to where the Y-coordinate of the window will be written.


Returns

INT : Successrate


[false] - The system is in fullscreen. [true] - Success ok.



Get_window_size()

Syntax

INT get_window_size ( <INT POINTER window_width> , <INT POINTER window_height> , <INT POINTER client_width> , <INT POINTER client_height> )

Description

Get the window and client size.

Parameters


INT POINTER window_width - Pointer to where the window width will be written. INT POINTER window_height - Pointer to where the window height will be written. INT POINTER client_width - Pointer to where the client width of window will be written. INT POINTER client_height - Pointer to where the client height of window will be written.


Returns

INT : Successrate


[false] - Error. [true] - Ok.


Example

import "mod_key"
import "mod_video"
import "mod_text"
import "mod_wm"
Global
    desktop_width = 640;
    desktop_height = 480;
    window_width = 0;
    window_height = 0;
    client_width = 0;
    client_height = 0;
End

Process Main()
Begin

    get_desktop_size(& desktop_width,& desktop_height);
    get_window_size ( & window_width,  &window_height , & client_width ,  & client_height );
    set_mode (desktop_width-window_width+client_width,desktop_height-window_height+client_height,32);
    set_window_pos(0,0);

    write(0,desktop_width/2,desktop_height/2+30,0,"ESC to exit");
    while (!key(_ESC) )
        frame;
    end
End

Used in example: [get_desktop_size](), [get_window_size](), [set_mode](), [set_window_pos](), [write]()


Getenv()

Definition

STRING getenv ( <STRING variablename> )

Returns the value of an environment variable (like PATH).

Parameters


STRING variablename - The name of the variable to get the value of.


Returns

STRING : The value of the variable.


"" - The variable is invalid or empty. !"" - The value of the variable.



Glob()

Definition

STRING glob ( <STRING criteria> )

Gets a single filename or directoryname matching the criteria. If the same criteria is specified, it keeps returning new items on subsequent calls until it can't find any more, in which case it returns "". When different criteria are specified, the search is 'reset'. To reset the search without returning an item, use "" as criteria.

After a call to glob(), the global struct [fileinfo] is filled with information about the last file/directory entry returned.

Parameters


STRING criteria - The search criteria to which the returned filenames apply. "" to reset search.


Returns

STRING : Filename or directoryname


"" - No (new) file/directory entries. !"" - The name of a file/directory entry matching the search criteria.


Notes

The search criteria can hold many criteria: the folder in which you want to look, simple requirements for filenames, such as extensions, and directory names. A few examples:


* - Returns the filename of any file/directory in the current directory. *.dat - Returns the filename of any file/directory with extension .dat in the current directory. MyDir/* - Returns the filename of any file/directory in MyDir\ relative to the current directory. C:/Program Files/* - Returns the filename of any file/directory in C:\Program Files\*.


Example

import "mod_dir"

Process Main()
Private
    String filename;
Begin

    // method one:
    Loop
        filename = Glob("levels/*.tul"); // Looks for a file in the relative folder
                                         // "levels" that has the file extension "tul".
        if(filename!="")
            load_level(filename); // load_level() would load the level file
        else
            break;
        end

    End

    //Reset search
    glob("");

    // method two:
    While( (filename = Glob("levels/*.tul")) != "" )
        load_level(filename);
    End

End

Both methods result in the same, but the second one is less code.


Glyph_get()

Definition

INT get_glyph ( <INT fontID> , <INT glyphID> )

Creates a new [graphic] containing the specified [glyph].

The previous name [get_glyph]() is deprecated.

Parameters


INT fontID - The [fontID] of the font the glyph is wanted. INT glyphID - The [glyphID] of the glyph in the specified font.


Returns

INT : [GraphID]


0 - Invalid font; Invalid glyph; could not create graphic; >0 - The graphID of the graphic containing the glyph.


See also

  • [set_glyph]()

Glyph_set()

Definition

INT glyph_set ( <INT fontID> , <INT glyphID> , <INT fileID> , <INT graphID> )

Sets the specified [glyph] of the specified [font]. The new glyph will be a copy of the specified [graphic] and thus it may be freed after the call.

The previous name [set_glyph]() is deprecated.

Parameters


INT fontID - The [fontID] of the font the glyph is to be set. INT glyphID - The [glyphID] of the glyph in the specified font. INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] to be copied.


Returns

INT : [false]

See also

  • [glyph_get]()

Graphic_info()

Definition

INT graphic_info ( <INT fileID> , <INT graphID> , <INT infotype> )

Gets some information about the [graph] specified. This function is also known as [Map_info]() and [Map_info_get]().

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to get information from. INT infotype - What [type of information] you want.


Returns

INT : Returns the information you want.\ If the specified graph was invalid it returns 0.\ If the specified infotype was not recognized it returns 1.

Example

Program keuken;
Local
    gxc;
    gyc;

Begin

    set_mode(640,480,16);

    graph=new_map(rand(50,150),rand(50,150),16); //makes a randomly proportioned red rectangle
    map_clear(0,graph,rgb(255,0,0));
    x=320;
    y=240;

    gxc=graphic_info(0,graph,G_X_CENTER);
    gyc=graphic_info(0,graph,G_Y_CENTER);  //finds the graphic's center coordinates

    map_put_pixel(0,graph,gxc,gyc,rgb(255,255,255)); //puts a white pixel in the center of the graphic

    Loop

        frame;
    End
End

Used in example: [set_mode](), [new_map](), [map_put_pixel]()


Graphic_set()

Definition

INT Graphic_set ( <INT fileID> , <INT graphID> , <INT info_type> , <INT value> )

Changes the x or y coordinate of the center pixel (controlpoint 0). This function is also known as [Map_info_set]().

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to get information from. INT info_type - What [type of information] you want to change, see note. INT value - The new x or y coordinate of the center pixel.


Returns

INT : Returns the information you want.\ If the specified graph was invalid it returns 0.\ If the specified infotype was not recognized it returns 1.

Notes

As infotype, only two options are valid:


G_X_CENTER - Change the x coordinate of the center pixel. G_Y_CENTER - Change the y coordinate of the center pixel.



Grayscale()

Definition

INT grayscale ( <INT fileID> , <INT graphID> , <BYTE method> )

This function will convert the specified [graphic] by using the specified method; see [notes] for the details.

Parameters


INT fileID - The [fileID] that holds the graphics. INT graphID - The [graphID] to convert. BYTE method - The method used (see [notes]).


Returns

INT


-1 - Invalid graphic. 1 - Success.


[Grayscale modes]


Constant - Value - Description GSCALE_RGB - 0 - changes the graphic to monochrome. GSCALE_R - 1 - changes the graphic to RED scale. GSCALE_G - 2 - changes the graphic to GREEN scale. GSCALE_B - 3 - changes the graphic to BLUE scale. GSCALE_RG - 4 - changes the graphic to YELLOW scale. GSCALE_RB - 5 - changes the graphic to PURPLE scale. GSCALE_GB - 6 - changes the graphic to CYAN scale. GSCALE_OFF - -1 - no change, graphic stays as it is, so filter is not applied.


Notes

The exact formula is:

c = 0.3 * oldpixel_r + 0.59 * oldpixel_g + 0.11 * oldpixel_b

Method 0:

for every pixel:
    newpixel_rgb = (c,c,c)

Method 1:

for every pixel:
    newpixel_rgb = (c,0,0)

Method 2:

for every pixel:
    newpixel_rgb = (0,c,0)

Method 3:

for every pixel:
    newpixel_rgb = (0,0,c)

Method 4:

for every pixel:
    newpixel_rgb = (c,c,0)

Method 5:

for every pixel:
    newpixel_rgb = (c,0,c)

Method 6:

for every pixel:
    newpixel_rgb = (0,c,c)

Other methodnumbers:

for every pixel:
    newpixel_rgb = oldpixel_rgb

Note that [[rgbscale]](0,map,1,1,1) = [[grayscale]](0,map,0) for a valid graphic (0,map).

Example

/* Example converted from bennupack, fenix test section, 2 Medium\fenix test\Fenix Test3\Test_GRAYSCALE.prg */

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_map";
IMPORT "mod_effects";
IMPORT "mod_proc";
IMPORT "mod_grproc";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_screen";

GLOBAL

int fpg;
int png;

PROCESS main();

BEGIN

  scale_mode=scale_normal2x;
  set_mode(320,200,mode_16bits);

  fpg=load_fpg("FPG2.FPG");
  png=load_png("Triangulo_16.png");

  say("Grayscale test...");
  say("Press ESC to quit...");

  put_screen(fpg,1);

  ball(110,50,"mode 0: GSCALE_RGB",GSCALE_RGB);
  ball(160,50,"mode 1: GSCALE_R",GSCALE_R);
  ball(210,50,"mode 2: GSCALE_G",GSCALE_G);
  ball(160,100,"mode 3: GSCALE_B",GSCALE_B);
  ball(110,150,"mode 4: GSCALE_RG",GSCALE_RG);
  ball(160,150,"mode 5: GSCALE_RB",GSCALE_RB);
  ball(210,150,"mode 6: GSCALE_GB",GSCALE_GB);
  ball(260,150,"mode -1: GSCALE_OFF",GSCALE_OFF);

  REPEAT
    FRAME;
  UNTIL (key(_esc))

  let_me_alone();

END

PROCESS ball(int x,int y,string txt,int blur);

BEGIN

  say(txt);
  graph=map_clone(0,png);
  grayscale(fpg,graph,blur);

  LOOP
    FRAME;
  END
END

Is_playing_song()

Definition

INT is_playing_song ( )

Checks to see if Bennu is playing a song file, started with [play_song]().

Returns

INT : Whether Bennu is playing a song at the moment of calling.


[true] - Bennu is playing a song. [false] - Bennu is not playing a song.


Example

program music_example;
global
    my_song;
    playing;
    paused;
    faded_in;
    v;
begin
    set_mode(640,480,16);

    my_song=load_song("beat.ogg");

    write(0,320,30,4,"Use the keyboard to control the music playback.");
    write(0,320,50,4,"Key [ENTER] starts / stops the song.");
    write(0,320,60,4,"Key [SPACE] pauses / resumes the song.");
    write(0,320,70,4,"Key [0] through key [9] changes the song volume.");
    write(0,320,80,4,"Key [F] fades the song in or out.");

    write(0,320,120,5,"Playing: ");
    write_int(0,320,120,3,&playing);

    write(0,320,140,5,"Paused: ");
    write_int(0,320,140,3,&paused);

    write(0,320,160,5,"Faded in: ");
    write_int(0,320,160,3,&faded_in);

    write(0,320,180,5,"Volume: ");
    write_int(0,320,180,3,&v);

    v=128;
    faded_in=true;

    repeat
        if(key(_enter))
            if(is_playing_song())
                stop_song();
                playing=false;
            else
                play_song(my_song,1);
                playing=true;
            end
            while(key(_enter))frame;end
        end

        if(key(_space))
            if(paused)
                paused=false;
                resume_song();
            else
                paused=true;
                pause_song();
            end
            while(key(_space))frame;end
        end

        if(key(_f))
            if(faded_in)
                faded_in=false;
                fade_music_off(100);
            else
                faded_in=true;
                fade_music_in(my_song,1,100);
            end
            while(key(_f))frame;end
        end

        if(key(_0))v=0;end
        if(key(_1))v=14;end
        if(key(_2))v=28;end
        if(key(_3))v=43;end
        if(key(_4))v=57;end
        if(key(_5))v=71;end
        if(key(_6))v=85;end
        if(key(_7))v=100;end
        if(key(_8))v=114;end
        if(key(_9))v=128;end

        set_song_volume(v);

    frame;
    until(key(_esc))

    exit();
end

Used in example: [key](), [set_mode](), [load_song](), [write_int](), [pause_song](), [play_song](), [stop_song](), [resume_song](), [fade_music_in](), [fade_music_off](), [set_song_volume]().


Is_playing_wav()

Definition

INT is_playing_wav ( INT )

Checks to see if Bennu is playing a wave file on the indicated [Sound_channel], started with [play_wav]().

Parameters

INT channel: The [Sound_channel]

Returns

INT : Whether Bennu is playing a song at the moment of calling.


[true] - Bennu is playing a song. [false] - Bennu is not playing a song.


Example

Used in example:


Isinf()

Syntax

INT isinf ( <FLOAT number> )

Description

Checks if a given value is an infinity. It does not check for Not-A-Numbers. Use the [Isnan]() function for that.

Parameters


FLOAT number - The value to check.


Returns


INT FALSE - The value is a not an infinity. INT TRUE - The value is a positive or negative infinity.


See also

Wikipedia page about the mathematical subject infinity.


Isnan()

Syntax

INT isnan ( <FLOAT number> )

Description

Checks if a given value is a number. It does not check for infinties. Use the [Isinf]() function for that.

Parameters


FLOAT number - The value to check.


Returns


INT FALSE - The value is a number. INT TRUE - The value is NOT a number.



Itoa()

Definition

STRING itoa ( <INT value> )

Returns a [string] containing a certain [int] value.

Parameters


INT value - The value the returned string will contain.


Returns

STRING : The string containing the specified value, including sign.


Join()

Syntax

STRING join ( <STRING separator> , <POINTER array> , <INT array_size> )

Description

Joins an array of strings, given a separator. Returns the resulting string. The function is the opposite of [Split](). It is usefull for generating comma seperated value lists, i.e. for use in spreadsheets or text based file formats.

The function concatinates individual strings from an array, and adds a separator between them, the first piece will be copied from array[0], the second from array[1], and so forth, until either there are no more pieces left or max_number pieces are copied from the array.

Parameters


STRING separator - The regular expression used as separator, i.e. comma's, spaces, semi columns, etc. POINTER array - Pointer to the string array where the strings are stored that are to be joined. INT array_size - The length of the array.


Returns

STRING : The resulting (concatinated) string.

Example

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_regex";

GLOBAL

   string separator=","; // the separator character
   string csv_list[9];   // array with 10 strings

PROCESS main();

BEGIN

   // fill the array with words, that will become an comma seperated list
   // this is could for instance be data for a some spreadsheet file
   csv_list[0]="A";
   csv_list[1]="300";
   csv_list[2]="100";
   csv_list[3]="B";
   csv_list[4]="255";
   csv_list[5]="30";
   csv_list[6]="C";
   csv_list[7]="1000";
   csv_list[8]="10";
   csv_list[9]="<END_DATA>";

   // print the joined string
   say("");
   say(join(separator,&csv_list, 10));
   say("");

END

This program will print as result:

A,300,100,B,255,30,C,1000,10,<END_DATA>

Used in example: [say]() See also: [split]()


Joy_axes() (MISSING)

Joy_buttons() (MISSING)

Joy_getaxis()

Syntax

INT joy_getaxis ( [ <INT joy>], <INT axis> )

Description

Returns the selected joystick state for the given axis.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with joy_select().

Also called [joy_getposition](). The previous name [get_joy_position]() is deprecated.

Parameters


[INT JoyID] - The [JoyID]. INT axis - The [axis].


Returns

INT : state for the given axis.


Joy_getball()

Syntax

INT joy_getball ( [ <INT JoyID> ] , <POINTER dx> , <POINTER dy>)

Description

Returns the state of the specfied ball on the current selected joystick.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with [joy_select]().

Parameters


[INT JoyID] - The [JoyID]. POINTER dx - A pointer to the variable X of the ball. POINTER dy - A pointer to the variable Y of the ball.


Returns

INT : The state of the specfied ball on the current selected joystick.

Example


Joy_getbutton()

Syntax

INT joy_getbutton ( [ <INT joy>], <INT button> )

Description

Returns the selected joystick state for the given button.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with joy_select().

The previous name [get_joy_button]() is deprecated.

Parameters


[INT JoyID] - The [JoyID]. INT button - The [button].


Returns

INT : state for the given button.


Joy_gethat()

Syntax

INT joy_gethat ( [ <INT JoyID> ] , <INT hat> )

Description

Returns the current position of the digital POV hat of the controller pad selected.

The return values are:


Constant - Value - Description JOY_HAT_CENTERED - 0 - The hat is centered. JOY_HAT_UP - 1 - The hat is moved up. JOY_HAT_RIGHT - 2 - The hat is moved right. JOY_HAT_DOWN - 4 - The hat is moved down. JOY_HAT_LEFT - 8 - The hat is moved left. JOY_HAT_RIGHTUP - 3 - The hat is moved right and up. JOY_HAT_RIGHTDOWN - 6 - The hat is moved right and down. JOY_HAT_LEFTUP - 9 - The hat is moved left and up. JOY_HAT_LEFTDOWN - 12 - The hat is moved left and down.


You may notice that some are combinations of others. For example JOY_HAT_RIGHTUP == (JOY_HAT_RIGHT | JOY_HAT_UP ). This is because the returned value has [bit flags] indicating four directions: up, down, left, right. These can be combined to make diagonal directions.

A value of -1 is returned when there is no hat or [joystick] detected.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with [joy_select]().

Parameters


[INT JoyID] - The [JoyID]. INT hat - The number of the hat, starting at 0


Returns

INT : The position of the POV hat.

Example


Joy_name()

Syntax

STRING joy_name ( <INT JoyID> )

Description

Returns the name of the specified [joystick]. This is a string describing the specified joystick, mostly used for the brand and model of the joystick.

Parameters


INT JoyID - The [JoyID].


Returns

STRING : The name of the [joystick].


Joy_numaxes()

Syntax

INT joy_numaxes ( [ <INT JoyID> ] )

Description

Returns the number of [axes] on the specified [joystick]. If no joystick is specified, the number of axes on the currently [selected joystick] will be returned.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with [joy_select]().

Also called [joy_axes]().

Parameters


[INT JoyID] - The [JoyID].


Returns

INT : The number of [axes].


Joy_numballs()

Syntax

INT joy_numballs ( [ <INT JoyID> ] )

Description

Returns the number of [balls] on the specified [joystick]. If no joystick is specified, the number of balls on the currently [selected joystick] will be returned.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with joy_select().

Parameters


[INT JoyID] - The [JoyID].


Returns

INT : The number of [balls].


Joy_number()

Syntax

INT joy_number ( )

Description

Returns the number of joysticks present in the system.

Also called [joy_numjoysticks](). The previous name [number_joy]() is deprecated.

Returns

INT : The number of joysticks present in the system.


Joy_numbuttons()

Syntax

INT joy_numbuttons ( [ <INT JoyID> ] )

Description

Returns the number of [buttons] on the specified [joystick]. If no joystick is specified, the number of buttons on the currently [selected joystick] will be returned.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with joy_select().

Also called [joy_buttons]().

Parameters


[INT JoyID] - The [JoyID].


Returns

INT : The number of [buttons].


Joy_numhats()

Syntax

INT joy_numhats ( [ <INT JoyID> ] )

Description

Returns the number of [hats] on the specified [joystick]. If no joystick is specified, the number of hats on the currently [selected joystick] will be returned.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with joy_select().

Parameters


[INT JoyID] - The [JoyID].


Returns

INT : The number of [hats].


Joy_numjoysticks() (MISSING)

Joy_select()

Syntax

INT joy_select ( <INT JoyID> )

Description

Select the joystick with id equals to JoyID. The old name [select_joy]() is deprecated.

Parameters


INT JoyID - The [JoyID].


Returns

INT : The ID of the selected joystick number.


Key()

Definition

INT key( <INT scancode> )

Checks if a certain key is being pressed.

Parameters


INT scancode - The [scancode] of the key to be checked.


Returns

INT : [true]: Whether the key is being pressed.

Notes

Take a look at the [scancodes] for a complete list.

Example

Program input_test;
Begin

    While( !key(_esc) )

        delete_text(ALL_TEXT);

        if( key(_left) && !key(_right) )  
            write(0,160,120,4, "LEFT");
        end;

        if( key(_right) && !key(_left) ) 
            write(0,160,120,4, "RIGHT"); 
        end;

        frame;

    End;

    exit();

End

Used in example: [delete_text](), [write](), [ALL_TEXT]

This will output the words LEFT or RIGHT according to the keys you press, or it will quit the program once ESCAPE is pressed.


Ksort()

Definition

INT ksort ( <VARSPACE array> , <VARSPACE sort-variable> , [<INT datacount>] )

Sorts a certain [array] according to a sort-variable within the elements and by sorting a certain number of elements. By default the whole array is sorted.

If the array elements contain only one variable each or the first one is the sort-variable, [sort]() can be used. For more advanced sorting, look at [quicksort]().

Parameters


VARSPACE array - The [array] to be sorted. VARSPACE sort-variable - The variable within each element to be used for the sorting. [INT datacount] - Number of elements to sort.


Returns

INT: Successrate


[true] - Sorting succeeded. [false] - Sorting failed, probably the type of sort-variable isn't supported.


Example

Program sorting;

Type _player
    String name;
    int score;
End

Const
    maxplayers = 5;
Global
    _player player[maxplayers-1];
Begin

    // Insert some values
    player[0].name = "That one bad looking dude";
    player[1].name = "Ah pretty lame guy";
    player[2].name = "Some cool dude";
    player[3].name = "OMG ZOMG guy";
    player[4].name = "This person is ok";

    player[0].score = 70;
    player[1].score = 30;
    player[2].score = 80;
    player[3].score = 90;
    player[4].score = 50;

    // Show array
    say("-------------------- unsorted");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

/* Sort by name ( quicksort() can't be used to sort Strings,
   as a String in Fenix is a pointer to the actual String,
   so it would sort the pointer addresses */

    // sort()
    sort(player); // sorts by name because name is the first variable in each element

    // Show array
    say("-------------------- name - sort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

    // ksort()
    ksort(player,player[0].name,maxplayers);

    // Show array
    say("-------------------- name - ksort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

/* Sort by score (sort() cannot be used here, because score is not the first variable) */

    // ksort()
    ksort(player,player[0].score,maxplayers);

    // Show array
    say("-------------------- score - ksort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

    // quicksort()
    quicksort(&player[0],sizeof(_player),maxplayers,sizeof(String),sizeof(int),0);

    // Show array
    say("-------------------- score - quicksort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

    // Wait until ESC is pressed
    Repeat
         frame;
    Until(key(_esc))

End

Used in example: [say](), [ksort](), [type], [pointer]


Lcase()

Definition

STRING lcase ( <STRING str> )

Returns a [string] identical to a certain string, with the exception that all uppercase characters are replaced by their lowercase counterparts.

Parameters


STRING str - The string in "normal"-form.


Returns

STRING : The string in "lowercase"-form.


Len()

Definition

INT len ( <STRING str> )

Returns the length, the number of characters, of a certain [string].

Also called [Strlen]().

Parameters


STRING str - The string of which the length will be returned.


Returns

INT : The length of the specified string.


Let_me_alone()

Definition

INT let_me_alone ( )

Kills all [processes] except the calling one.

To kill only one process, use [signal]().

Returns

INT : [true]

Example

Const
    screen_width = 320;
    screen_height = 200;
    screen_depth = 8;
End

/**
 * Description
 *   Generates an error. Puts the error in the console and stdout.txt and shows it onscreen
 *   for certain time. Immediately kills all other processes and quits the program after a
 *   certain time.
 *
 * Parameters
 *   String message   - The error message.
 *   int delay        - The time to display the error onscreen and after which the program will quit.
 *                      In 1/100seconds.
 *
 * Returns
 *   0 - Success.
 */
Process error(String message,int delay)
Begin

    // Put the error message in the console and in stdout.txt
    say("[ERROR] " + message);

    // Show the error message onscreen, the size adjust for the screen width
    set_text_color(rgb(255,0,0));
    graph = write_in_map(0,message,4);
    size = 100*(screen_width-10)/graphic_info(0,graph,G_WIDTH);
    x = screen_width/2;
    y = screen_height/2;

    // Kill all other processes
    let_me_alone();

    // Wait the specified time
    timer[0] = 0;
    Repeat
        frame;
    Until(timer[0]>delay)

    // Unload the used graph
    unload_map(0,graph);

    return 0;

End

Process Main();
Begin

    // Set the screen mode
    set_mode(screen_width,screen_height,screen_depth);

    // Generate an error
    error("ERROR, QUITTING IN 2 SECONDS",200);

    Repeat
        frame;
    Until(key(_esc))

End

Ln()

[Up to Log.dll functions]


Definition

FLOAT ln ( <FLOAT n> )

Returns the natural logarithm of number n (logarithm with base ε (Euler)).

Parameters


FLOAT n - The number that will be used for the logarithm.


Returns

FLOAT : The natural logarithm of n.

Example

Import "log.dll";

Global
    float logarithm=0.0;
End

Process main()
Begin
    write_float(0,160,100,4,&logarithm);

    While(not(key(_ESC)))
    If (key(_1)) logarithm=ln(13.37); End 

        Frame;
    End
End

Used in example: [import], [write_float](), [ln]()


Load()

Definition

INT load ( <STRING filename> , <VARSPACE data> )

Loads the data read from the specified file into the specified variable.

Parameters


STRING filename - The name of the file to be loaded. VARSPACE data - The variable (of any [datatype]) in which the data read from the file will be loaded.


Returns

INT : The number of bytes read from the file.

Notes

To check whether a file exists before it is loaded, [file_exists]() can be used.

Example

Program test;
Global
    struct My_struct
        Level_number;
        string Map_name;
    End
Begin
    If (file_exists("myfile.sav")) 
        Load("myfile.sav",My_struct);            // Content from myfile.sav is loaded into My_struct
        Write(0,10,10,0,My_struct.level_number); // A variable from the loaded struct is shown on screen
        Write(0,10,20,0,My_struct.map_name);     // Another variable loaded is shown on screen
    Else
        Write(0,10,10,0,"File couldn't be loaded, it doesn't exist.");
    End

    While (!key(_esc))
        Frame;
    End
End

Used in example: [file_exists](), [load](), [key]()


Load_song()

Definition

INT load_song ( <STRING filename>, [ <POINTER id>] )

Loads a song for later use with [play_song]().

There are multiple [filetypes] you can load using this [function]. Included are:

  • OGG Vorbis (.ogg). Good quality for [songs] and doesn't take too much space (it's similar to *.mp3).
  • MIDI (.mid). Takes very low space, but it's limited to samples of the soundcard.
  • Modules (.xm, .it, .s3m, .mod). Like MIDI, but Modules also contain the samples themselves.

Parameters


STRING filename - The music file to be loaded, including a possible path. POINTER id - Optional parameter, for loading a song in the background.


Returns

INT : [SongID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The songID of the newly created sound.


the following applies for versions prior rc282:

INT : [SongID]


-1 - Could not load music file (errormessage in console). >=0 - The SongID.


Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_song("archivo_gordo.ogg", &idsong);
      while(idsong==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idsong==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

Example

Program example;
Private
    int song;
Begin
    song = load_song("my_song.ogg");
    play_song(song,0);
    Repeat
        frame;
    Until(key(_ESC))
OnExit
    unload_song(song);
End

Used in example: [play_song](), [key]()


Load_wav()

Definition

INT load_wav ( <STRING filename>, [ <POINTER id>] )

Loads a [sound effect] in the WAV format for later use with [play_wav]().

Parameters


STRING filename - The WAV file to be loaded, including a possible path. POINTER id - Optional parameter, for loading a wav in the background.


Returns

INT : [WaveID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The waveID of the newly created sound.


the following applies for versions prior rc282:

INT : [WaveID]


-1 - Error: sound inactive; opening file 0 - Could not load wave file. >0 - The [WaveID].


Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_wav("archivo_gordo.wav", &idwav);
      while(idwav==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idwav==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

Example

Program
Private
    int wave;
Begin
    wave = load_wav("my_wav.wav");
    play_wav(wave,0);
    Loop
        frame;
    End
End

Used in example: [play_wav]()


Log()

[Up to Log.dll functions]


Definition

FLOAT log ( <FLOAT n> , [<FLOAT b>] )

Returns a logarithm of number n with base b. If b is not specified, the number 10 will be used as base.

Parameters


FLOAT n - The number that will be used for the logarithm. FLOAT base - The base that will be used for the logarithm.


Returns

FLOAT : The logarithm of n.

Example

Import "log.dll";

Global
    float logarithm=0.0;
End

Process main()
Begin
    write_float(0,160,100,4,&logarithm);

    While(not(key(_esc)))
        If (key(_1)) logarithm=log(1000,9); End 
        If (key(_2)) logarithm=log(1000); End

        Frame;
    End
End

Used in example: [import], [write_float](), [log]()


Log2()

[Up to Log.dll functions]


Definition

FLOAT log2 ( <FLOAT n> )

Returns a logarithm of number n with base 2.

Parameters


FLOAT n - The number that will be used for the logarithm.


Returns

FLOAT : The logarithm of n with base 2.

Example

Import "log.dll";

Global
    float logarithm=0.0;
End

Process main()
Begin
    write_float(0,160,100,4,&logarithm);

    While(not(key(_esc)))
        If (key(_1)) logarithm=log2(1024); End 

        Frame;
    End
End

Used in example: [import], [write_float](), [log2]()


Lpad()

Definition

STRING lpad( <STRING str> , <INT length> )

Returns the string str, padding (adding spaces to) the front of the string if needed to make str of length length. The original string will remain unchanged.

If length is smaller or equal to the length of str, the returned string is str.

Parameters


STRING str - The string to pad (add spaces to). INT length - The minimal length of the returned string.


Returns

STRING: padded string

Example

import "mod_string"
import "mod_say"

Process Main()
Private
    string ABC = "ABC";
    string _ABC;
    string ABC__;
Begin

    ABC = lpad(ABC,2);
    _ABC = lpad(ABC,4);
    ABC__ = rpad(ABC,5);

    say('ABC = "' + ABC + '"');
    say('_ABC = "' + _ABC + '"');
    say('ABC__ = "' + ABC__ + '"');

End

Used in example: [say](), [rpad]()

Result:

ABC = "ABC"
_ABC = " ABC"
ABC__ = "ABC  "

Map_block_copy()

Definition

INT map_block_copy ( <INT fileID> , <INT destinationGraphID> , <INT destinationX> , <INT destinationY> , <INT originGraphID> , <INT x> , <INT y> , <INT width> , <INT height>, <INT blitflags> )

Draws ([blits]) a rectangular block from one [graphic] onto another graphic.

If the entire graphic is to be blitted, [map_put]() or [map_xput]() can be used.

Parameters


INT fileID - The [fileID] that holds the destination and origin graphics. INT destinationGraphID - The [graphID] to draw on. INT destinationX - Where on the destination graph's x-axis to put the block. INT destinationY - Where on the destination graph's y-axis to put the block. INT originGraphID - The [graphID] to draw with. INT x - The x-coordinate of the upperleft corner of the origin block. INT y - The y-coordinate of the upperleft corner of the origin block. INT width - The width of the block in pixels. INT height - The height of the block in pixels. INT blitflags - What [blit flags] to draw the graphic with.


Returns

INT : [true]

Notes

[Blit flags] can be used to give the drawing (blitting) a special effect.

Errors


Invalid origin graph - The origin graph is invalid. Invalid destination graph - The destination graph is invalid. Unsupported color depth - The origin graphic's color depth is greater than the destination graph's.



Map_buffer()

Definition

POINTER map_buffer ( <INT fileID> , <INT graphID> )

Get access to the memory buffer of the map. This function is usefull in combination with [Memset](). This way you can manipulate the actual bytes of the map.

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to get information from.


Returns

POINTER : Pointer to the memory contents of the map.

Example

In this example I'm going to demonstrate how you can manipulate the pixel buffer of the map. I load the same map twice (each with their own ID), and one of them is butchered by messing with it's pixel buffer. By assiging that map to a [Pointer] with map_buffer(), we can use [Memset]() to change the bytes in the memory area that the map occupies.

IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_key";
IMPORT "mod_map";
IMPORT "mod_video";
IMPORT "mod_wm";
IMPORT "mod_draw";
IMPORT "mod_screen";
IMPORT "mod_mem";
IMPORT "mod_text";

GLOBAL

   int map_id;    // id code of the map to load
   int map_id2;

   pointer p_map; // pointer to the map_buffer

PROCESS main();

BEGIN

   set_mode(320,200,32);

   write(0,10,10,3,"map_buffer example, press 'ESC' to quit.");

   write(0,10,30,3,"press '1' to show the modified map.");
   write(0,10,40,3,"press '2' to show the orginial map.");

   // load two maps, this map can be found in bennupack: 2 Medium\IA\PATH.FIND\3COCHE.MAP
   // it is a the "car" graphic of the pathfind tutorial for TYCO. Both maps are the same,
   // but one of them we're going to modify with map_buffer().
   map_id=load_map("3COCHE.MAP");
   map_id2=load_map("3COCHE.MAP"); // same map, but this one is left intact

   graph=map_id2; // original map
   x=100; 
   y=100;

   // get the memory adress of the "raw" pixel buffer of the map.
   p_map=map_buffer(0,map_id);

   // now that we've got acccess to the pixel buffer, we can change individual bytes.
   // with memset we can modify memory contents of individual bytes. 
   // in this case, we change the first 1000 bytes into the color #100.
   memset(p_map,100,1000); 

   // no, we're offsetting 200 adresses from the start of the memory block, and change another
   // 1000 bytes into a different color.
   memset(p_map+200,150,1000); 

   LOOP
      IF (key(_esc))
         BREAK;
      END

      IF (key(_1))     // show the "butchered" map
         FRAME(100);
         graph=map_id;
         say("showing map modified with map_buffer()");
      END

      IF (key(_2))    // show the original map
         FRAME(100);
         graph=map_id2;
         say("showing original map");
      END

      FRAME;
   END
END

Used in example: [Load_map](), [Memset](), [Say]()

Notes

In the [Memset]() function, indiviual bytes are used. The amount of bytes to store the color of one pixel depends on it's colordepth. In 8 bit mode, you need only one byte per pixel, in rgb mode 3 bytes and in rgba mode 4 bytes per pixel. So that is something you should be aware of. This is a similair caveat as with the [Alloc]() function, because you're dealing with raw memory contents here.


Map_clear()

Definition

INT map_clear ( <INT fileID> , <INT graphID> , <WORD color> )

Clears a certain graph to a certain color.

Parameters


INT fileID - The [file] that holds the graphic. INT graphID - The [graphic] to clear. WORD color - The [color] used to clear.


Returns

INT : [true]

Notes

Instead of using map_clear() to clear the screen [background], [clear_screen]() is recommended as it is a little bit faster.

Errors


Unsupported color depth - The specified graph has a not supported color depth.


Example

Program a_map_is_born;
Private
    int map;
Begin

    // Create a new graph of size 100x100 and color depth of 8bit
    map = new_map(100,100,8);

    // Clear the map red
    map_clear(0,map,rgb(255,0,0));

    // Put it in the center of the screen
    put(0,map,160,100);

    Loop
        frame;
    End

End

Used in example: [new_map](), [put]()

This will result in something like:\ http://wwwhome.cs.utwente.nl/~bergfi/fenix/wiki/new_map.PNG


Map_clone()

Definition

INT map_clone ( <INT fileID> , <INT graphID> )

Clones a certain [graphic] and puts it in the [system file].

Parameters


INT fileID - The [fileID] holding the graphic. INT graphID - The [graphID] of the graphic to be cloned.


Returns

INT : [GraphID]


0 - Invalid graphic specified; >0 - The graphID of the clone graphic.


Errors


Unsupported color depth - The specified graph has a not supported color depth. (Console) Insufficient memory - There is insufficient memory available. This error doesn't occur often. (Console)



Map_del() (MISSING)

Map_exists()

Syntax

INT map_exists ( <INT fileID> , <INT graphID> )

Description

Checks if a [graphic] exists in the specified [File] with the specified [graphID].

Parameters


INT fileID - The [fileID] that holds the graphic (or not). INT graphID - The [graphID].


Returns

INT : Whether the [graphic] exists


[false] does not exist. [true] exists.



Map_get_pixel()

Definition

INT map_get_pixel ( <INT fileID> , <INT graphID> , <INT x> , <INT y> )

Returns the [color] on the specified [graphic] of the specified [pixel].

Parameters


INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] to get the pixel from. INT x - The X-coordinate of the [pixel] the color is wanted. INT y - The Y-coordinate of the [pixel] the color is wanted.


Returns

INT : The color


-1 - Error: invalid map; invalid; invalid pixel; invalid color depth of map. Note: in 32bit graphs this can be a color too. !-1 - The color.



Map_info()

Definition

INT map_info ( <INT fileID> , <INT graphID> , <INT infotype> )

Gets some information about the [graph] specified. This function is also known as [Graphic_info]() and [Map_info_get]().

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to get information from. INT infotype - What [type of information] you want.


Returns

INT : Returns the information you want.\ If the specified graph was invalid it returns 0.\ If the specified infotype was not recognized it returns 1.

Example

See [Graphic_info]() for example.


Map_info_get()

Definition

INT map_info_get ( <INT fileID> , <INT graphID> , <INT infotype> )

Gets some information about the [graph] specified. This function is also known as [Graphic_info]() and [Map_info]().

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to get information from. INT infotype - What [type of information] you want.


Returns

INT : Returns the information you want.\ If the specified graph was invalid it returns 0.\ If the specified infotype was not recognized it returns 1.

Example

See [Graphic_info]() for example.


Map_info_set()

Definition

INT map_info_set ( <INT fileID> , <INT graphID> , <INT info_type> , <INT value> )

Changes the x or y coordinate of the center pixel (controlpoint 0). This function is also known as [Graphic_set]().

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to get information from. INT info_type - What [type of information] you want to change, see note. INT value - The new x or y coordinate of the center pixel.


Returns

INT : Returns the information you want.\ If the specified graph was invalid it returns 0.\ If the specified infotype was not recognized it returns 1.

Example

IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_key";
IMPORT "mod_map";
IMPORT "mod_video";
IMPORT "mod_wm";
IMPORT "mod_draw";
IMPORT "mod_screen";

GLOBAL

   int map_id;

   int status;

PROCESS main();

BEGIN

   set_mode(320,200,32);

   map_id=load_map("3COCHE.MAP");

   // print the original data.
   say("width of the map: "+graphic_info(0,map_id,G_WIDTH));
   say("height of the map: "+graphic_info(0,map_id,G_HEIGHT));
   say("g_x_center of the map: "+graphic_info(0,map_id,G_X_CENTER));
   say("g_y_center of the map: "+graphic_info(0,map_id,G_Y_CENTER));

   // change the x and y coordinates of the center pixel and display it.
   status=map_info_set(0,map_id,G_X_CENTER,20);
   status=map_info_set(0,map_id,G_Y_CENTER,10);
   say("center pixel changed:");
   say("g_x_center of the map: "+graphic_info(0,map_id,G_X_CENTER));
   say("g_y_center of the map: "+graphic_info(0,map_id,G_Y_CENTER));

   say("status: "+status);

   graph=map_id;
   x=100; 
   y=100;

   LOOP
      IF (key(_esc))
         BREAK;
      END
      FRAME;
   END
END

Notes

As infotype, only two options are valid:


G_X_CENTER - Change the x coordinate of the center pixel. G_Y_CENTER - Change the y coordinate of the center pixel.



Map_load()

Definition

INT map_load ( <STRING filename>, [ <POINTER id>] )

Creates a new [graphic], using the specified [MAP] file as contents and puts it in the [system file] of the created graphic. The [color depth] of the created graphic will be the same as the loaded MAP file.

The previous name [load_map]() is deprecated.

Parameters


STRING filename - The name of the [MAP]. POINTER id - Optional parameter, for loading a map in the background.


Returns

INT : [graphID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The graphID of the newly created graphic.


the following applies for versions prior rc282:

INT : [graphID]


0 - There was an error loading the file. >0 - The graphID of the newly created graphic.


Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_map("archivo_gordo.map", &idmap);
      while(idmap==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idmap==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

Map_name()

Definition

STRING map_name ( <INT fileID> , <INT graphID> )

Retrieves the name of an in-game [graphic].

Parameters


INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] of the graphic.


Returns

STRING : Name of the graphic


Map_new()

Definition

INT map_new ( <INT width> , <INT height> , <INT depth>, [ <INT flags> ] )

Creates a new [graphic], sets the color of all pixels to 0 (transparent) and puts it in the [system file].

The previous name [new_map]() is deprecated.

Parameters


INT width - The width of the to be created graph in [pixels]. INT height - The height of the to be created graph in pixels. INT depth - The [color depth] [INT flags] - can be: [B_CLEAR] (bitmap clear) or 0 (no clear new bitmap)


Returns

INT : [GraphID]


0 - There was an error. >0 - The graphID of the newly created graphic.


Errors


Unsupported color depth - The specified color depth is not supported. (Console) Insufficient memory - There is insufficient memory available. This error doesn't occur often. (Console)


Example

import "mod_map"
import "mod_screen"
import "mod_key"

Process Main()
Private
    int map;
Begin

    // Create a new graph of size 100x100 and color depth of 8bit
    map = map_new(100,100,8);

    // Clear the map red
    map_clear(0,map,rgb(255,0,0));

    // Put it in the center of the screen
    put(0,map,160,100);

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [map_new](), [map_clear](), [key]()

This will result in something like:\


Map_put()

Syntax

INT map_put ( <INT fileID> , <INT destinationGraphID> , <INT originGraphID> , <INT x> , <INT y> )

Description

Draws ([blits] onto another graph.

If more advanced parameters are needed, [map_xput]() can be used. If a graph from one [file] needs to be drawn onto another graph in a different file, or a separate width and height scaling is needed, [map_xputnp]() can be used.

Parameters


INT fileID - The [fileID] that holds the graphics. INT destinationGraphID - The [graphID] to draw on. INT originGraphID - The [graphID] to draw with. INT x - Where on the destination graphic's x-axis to put the graph. INT y - Where on the destination graphic's y-axis to put the graph.


Returns

INT : [true]

Notes

The x and y parameters denote where to draw the graph, that is, where the center of the to be drawn graph will be.

Errors


Invalid origin graph - The origin graph is invalid. Invalid destination graph - The destination graph is invalid. Unsupported color depth - The origin graph's color depth is greater than the destination graph's.


Example

import "mod_video"
import "mod_map"
import "mod_wm"

Process Main()
Private
    int destgraph;
    int origgraph1;
    int origgraph2;
Begin

    // Set the mode to 16bit and some resolution
    set_mode(320,200,16);

    // Makes the destination graphic a red square
    destgraph=new_map(100,100,16);
    map_clear(0,destgraph,rgb(255,0,0));

    // Makes the first origin graphic a green square
    origgraph1=new_map(100,100,16);
    map_clear(0,origgraph1,rgb(0,255,0));

    // Makes the second origin graphic a blue square
    origgraph2=new_map(100,100,16);
    map_clear(0,origgraph2,rgb(0,0,255));

    // Draws the blue and green squares at a random position on the red square
    map_put(0,destgraph,origgraph1,rand(0,100),rand(0,100));
    map_put(0,destgraph,origgraph2,rand(0,100),rand(0,100));

    // Shows the final graph
    put(0,destgraph,160,100);

    Repeat
        frame;
    Until(exit_status)

End

Used in example: [set_mode](), [new_map](), [map_put](), [key]

This will result in something like:\


Map_put_pixel()

Definition

INT map_put_pixel ( <INT fileID> , <INT graphID> , <INT x> , <INT y> , <INT color> )

Draws a single colored [pixel] on a [graph].

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to draw on. INT x - Where on the graph's x-axis to put the pixel. INT y - Where on the graph's y-axis to put the pixel. INT color - What [color] to draw.


Returns

INT : [true]

Errors


Invalid map - Map doesn't exist. Unsupported color depth - Destination graph is of an unsupported colordepth.


Example

import "mod_video"
import "mod_map"
import "mod_screen"
import "mod_wm"
import "mod_draw"

Process Main()
Private
    int map;
    int i;
Begin

    // Set the mode to 16bit and some res
    set_mode(320,200,16);

    // Create a blue-ish square map
    map = new_map(100,100,16);
    map_clear(0,map,rgb(50,100,150));

    // Puts 100 yellow-ish pixels in random places in the graphic
    for(i=0; i<100; i++)
        map_put_pixel(0,map,rand(0,100),rand(0,100),rgb(255,255,55));
    end

    // Puts the map in the center of the screen
    put(0,map,160,100);

    Repeat
        frame;
    Until(exit_status)

End

Used in example: [set_mode](), [new_map](), [map_put_pixel](), [rand]()


Map_save()

Definition

INT map_save ( <INT fileID> , <INT graphID> , <STRING filename> )

Saves the specified [graphic] as filename with the format [MAP].

The previous name [save_map]() is deprecated.

Parameters


INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] of the graphic to unload. STRING filename - The name of the [MAP] file to be saved, including a possible path.


Returns

INT : Successrate


[false] - An error: Invalid graphic; could not open file. [true] - Graphic saved.



Map_set_name()

Definition

INT map_set_name ( <INT fileID> , <INT graphID> , <STRING name>)

Sets the name of a [graphic] in an [FPG]. Useful in combination with [map_name]() to retrieve names of files and [save_fpg]() to save any changed values.

Parameters


INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] of the graphic. STRING name - The new name of the graphic specified.


Returns

INT : 0


Map_unload()

Definition

INT map_unload ( <INT fileID> , <INT graphID> )

Frees the memory used by the specified [graphic]. The associated ([fileID]) combination is no longer valid afterwards.

Also called [map_del](). The previous name [unload_map] is deprecated.

Parameters


INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] of the graphic to unload.


Returns

INT : Successrate


[false] - Invalid graphic. [true] - Graphic unloaded.



Map_xput()

Definition

INT map_xput ( <INT fileID> , <INT destinationGraphID> , <INT originGraphID> , <INT x> , <INT y> , <INT angle> , <INT size> , <INT blitflags> )

Draws ([blits] onto another graphic.

If the advanced parameters aren't needed, [map_put]() can be used. If a graphic from one [file] needs to be drawn onto another graphic in a different file, or a separate width and height scaling is needed, [map_xputnp]() can be used.

Parameters


INT fileID - The [fileID] that holds the graphics. INT destinationGraphID - The [graphID] to draw on. INT originGraphID - The [graphID] to draw with. INT x - Where on the destination graphic's x-axis to put the graphic. INT y - Where on the destination graphic's y-axis to put the graphic. INT angle - What [angle] to draw the graphic at. INT size - What [size] to draw the graphic at. INT blitflags - What [blit flags] to draw the graphic with.


Returns

INT : [true]

Notes

The x and y parameters denote where to draw the graphic, that is, where the center of the to be drawn graphic will be. Blit flags can be used to give the drawing (blitting) a special effect.

When angle is 0 and size is 100, the speed is greater, because the graph doesn't need rotating or scaling.

Errors


Unsupported color depth - The origin graphic's color depth is greater than the destination graphic's.


Example

import "mod_video"
import "mod_map"
import "mod_wm"

Process Main()
Private
    int destgraph;
    int origgraph;
Begin

    // Set the mode to 16bit and some resolution
    set_mode(320,200,16);

    // Makes the destination graphic a red square
    destgraph=new_map(100,100,16);
    map_clear(0,destgraph,rgb(255,0,0));

    // Makes the origin graphic a blue square
    origgraph=new_map(100,100,16);
    map_clear(0,origgraph,rgb(0,0,255));

    // Draws the blue square on the center of the red square transparently,
    // at a random angle and a random size
    map_xput(0,destgraph,origgraph,50,50,rand(-180000,180000),rand(50,150),4);
    map_xput(0,destgraph,origgraph,50,50,rand(-180000,180000),rand(50,150),4);

    // Shows the final graph
    put(0,destgraph,160,100);

    Repeat
        frame;
    Until(exit_status)

End

Used in example: [set_mode](), [new_map](), [map_xput](), [key]

This will result in something like:


Map_xputnp()

Definition

INT map_xputnp ( <INT destinationFileID> , <INT destinationGraphID> , <INT originFileID> , <INT originGraphID> , <INT x> , <INT y> , <INT angle> , <INT scale_x> , <INT scale_y> , <INT blitflags> )

Draws ([blits] onto another graphic.

If the advanced parameters aren't needed, [map_put]() can be used.

Parameters


INT destinationFileID - The [fileID] that holds the destination graphic. INT destinationGraphID - The [graphID] to draw on. INT originFileID - The [fileID] that holds the origin graphic. INT originGraphID - The [graphID] to draw with. INT x - Where on the destination graph's x-axis to put the graphic. INT y - Where on the destination graph's y-axis to put the graphic. INT angle - What [angle] to draw the graphic at. INT scale_x - What [size]) INT scale_y - What [size]). INT blitflags - What [blit flags] to draw the graphic with.


Returns

INT : [true]

Notes

The x and y parameters denote where to draw the graphic, that is, where the center of the to be drawn [graphic] will be. [Blit flags] can be used to give the drawing (blitting) a special effect.

When angle is 0 and size is 100, the speed is greater, because the graphic doesn't need rotating or scaling.

Errors


Unsupported color depth - The origin graphic's color depth is greater than the destination graph's.


Example

import "mod_video"
import "mod_map"
import "mod_wm"

Process Main()
Global
    int destgraph;
    int origgraph;
Begin

    // Set the mode to 16bit and some resolution
    set_mode(320,200,16);

    // Makes the destination graphic a red square
    destgraph=new_map(100,100,16);
    map_clear(0,destgraph,rgb(255,0,0));

    // Makes the origin graphic a blue square
    origgraph=new_map(100,100,16);
    map_clear(0,origgraph,rgb(0,0,255));

    // Draws the blue square on the center of the red square transparently,
    // at a random angle and a random size
    map_xputnp(0,destgraph,0,origgraph,50,50,rand(-180000,180000),rand(50,150),rand(50,150),4);
    map_xputnp(0,destgraph,0,origgraph,50,50,rand(-180000,180000),rand(50,150),rand(50,150),4);

    // Shows the final graph
    put(0,destgraph,160,100);

    Repeat
         frame;
    Until(exit_status)

End

Used in example: [set_mode](), [new_map](), [map_xputnp](), [exit_status], [blit flags]

This will result in something like:


Mem_alloc() (MISSING)

Mem_available() (MISSING)

Mem_calloc() (MISSING)

Mem_cmp() (MISSING)

Mem_copy() (MISSING)

Mem_free() (MISSING)

Mem_move() (MISSING)

Mem_realloc() (MISSING)

Mem_set() (MISSING)

Mem_seti() (MISSING)

Mem_setw() (MISSING)

Mem_total() (MISSING)

Memcmp()

Definition

INT memcmp ( <VOID POINTER ptr1> , <VOID POINTER ptr2> , <INT number> )

Compares the first number bytes of the block of memory pointed by ptr1 to the first number bytes pointed by ptr2, returning zero if they all match or a value different from zero representing which is greater if they do not.

Also called [mem_cmp]().

Parameters


VOID POINTER ptr1 - Pointer to a block of memory VOID POINTER ptr2 - Pointer to a block of memory. INT number - The number of bytes to be checked.


Returns

INT : Difference


0 - The blocks of memory are identical. >0 - The first differing byte in both memory blocks has a greater value in ptr1. <0 - The first differing byte in both memory blocks has a greater value in ptr2.


A byte ranges from 0 to 255, meaning 189 is a greater value than 105.

Example

Program example;
Const
    elements = 10;
End
Private
    byte pointer pbyte1;
    byte pointer pbyte2;
    int result;
End
Begin

    // Allocate memory
    pbyte1 = alloc(elements);
    pbyte2 = alloc(elements);

    // Make the blocks the same and compare
    memset(pbyte1,3,elements);
    memset(pbyte2,3,elements);
    result = memcmp(pbyte1,pbyte2,elements); // You can also compare the first 5 bytes,
                                             // or the first elements/2 bytes, it
                                             // depends on what you want.
    say("Memcmp 1: " + result);

    // Make the first block have a greater value and compare
    pbyte1[0] = 4;
    result = memcmp(pbyte1,pbyte2,elements);
    say("Memcmp 2: " + result);

    // Make the blocks the same and compare
    pbyte2[0] = 4;
    result = memcmp(pbyte1,pbyte2,elements);
    say("Memcmp 3: " + result);

    // Make the first block have a greater value and compare
    pbyte2[1] = 5;
    result = memcmp(pbyte1,pbyte2,elements);
    say("Memcmp 4: " + result);

    Repeat
        frame;
    Until(key(_esc))

    // Free the used memory
    free(pbyte1);
    free(pbyte2);

End

Used in example: [alloc](), [memset](), [say](), [pointer]


Memcopy()

Syntax

INT memcopy ( <VOID POINTER destination> , <VOID POINTER origin> , <INT size> )

Description

Copies a certain number of [bytes] from one point in [memory] to another.

Difference between [memmove]() and [memcopy]() is that the first one can be used if the destination section and origin section overlap. With [memcopy](), this can go wrong, though some systems make [memcopy]() safe too.

Also called [mem_copy]().

Parameters


VOID POINTER destination - Pointer to the first byte of the destination. VOID POINTER origin - Pointer to the first byte of the origin. INT size - The size of the to be copied memory in bytes.


Returns

INT : [true]

Example

import "mod_mem"
import "mod_say"

Const
    elements = 5;
End

Process Main()
Private
    byte bytearray[elements-1];
    byte* pbyte;
    int i;
End
Begin

    // Allocate memory
    pbyte = alloc(elements);

    // Set numbers
    for(i=0; i<elements; i++)
        bytearray[i] = i;
    end

    // Copy bytes to bytearray
    memcopy(pbyte,&bytearray[0],elements);

    // Show numbers
    for(i=0; i<elements; i++)
        say("byte["+i+"] = " + pbyte[i]);
    end

OnExit

    // Free the used memory
    free(pbyte);

End

Used in example: [alloc](), [memcopy](), [free], [pointer]


Memmove()

Definition

INT memmove ( <VOID POINTER destination> , <VOID POINTER origin> , <INT size> )

Copies a certain number of [bytes] from one point in [memory] to another.

Difference between [memmove]() and [memcopy]() is that the first one can be used if the destination section and origin section overlap. With [memcopy](), this can go wrong, though some systems make [memcopy]() safe too.

Also called [mem_move]().

Parameters


VOID POINTER destination - Pointer to the first byte of the destination. VOID POINTER origin - Pointer to the first byte of the origin. INT size - The size of the to be copied memory in bytes.


Returns

INT : [true]

Example

import "mod_mem"
import "mod_say"

Const
    elements = 5;
End

Process Main()
Private
    byte bytearray[elements-1];
    byte* pbyte;
    int i;
End
Begin

    // Allocate memory
    pbyte = alloc(elements);

    // Set numbers
    for(i=0; i<elements; i++)
        bytearray[i] = i;
    end

    // Copy bytes to bytearray
    memmove(pbyte,&bytearray[0],elements);

    // Show numbers
    for(i=0; i<elements; i++)
        say("byte["+i+"] = " + pbyte[i]);
    end

OnExit

    // Free the used memory
    free(pbyte);

End

Used in example: [alloc](), [memmove](), [free], [pointer]


Memory_free()

Syntax

INT memory_free ( )

Description

Returns the free memory total in bytes.

Also called [mem_available]().

Returns

INT : Free memory total in bytes.

Example

import "mod_mem"
import "mod_say"

Process Main()
Begin

    say("Total memory: " + memory_total());
    say("Free memory:  " + memory_free() );

End

Used in example: [say](), [memory_total](), [memory_free]()


Memory_total()

Definition

INT memory_total ( )

Returns the memory total in bytes.

Also called [mem_total]().

Returns

INT : Memory total in bytes.

Example

import "mod_mem"
import "mod_say"

Process Main()
Begin

    say("Total memory: " + memory_total());
    say("Free memory:  " + memory_free() );

End

Used in example: [say](), [memory_total](), [memory_free]()


Memset()

Syntax

INT memset ( <VOID POINTER data> , <BYTE value> , <INT bytes> )

Description

Sets all bytes in the specified memory block to the specified value.

Also called [mem_set]().

Parameters


VOID POINTER data - Pointer to the block of bytes in memory BYTE value - Value to set all bytes to. INT bytes - Number of bytes to change the value of.


Returns

INT : [true]

Example

See [alloc]().

Also useful in conjunction with [map_buffer]() with 8bit [maps]. (Example can be found in the map_buffer article.)


Memseti()

Syntax

INT memseti ( <VOID POINTER data> , <INT value> , <INT ints> )

Description

Sets all [ints] in the specified memory block to the specified value.

Also called [mem_seti]().

Parameters


VOID POINTER data - Pointer to the block of ints in memory. INT value - Value to set all ints to. INT ints - Number of ints to change the value of.


Returns

INT : [true]

Example

See [alloc]().

Also useful in conjunction with [map_buffer]() with 32bit [maps]. (Example needed.)


Memsetw()

Syntax

INT memsetw ( <VOID POINTER data> , <WORD value> , <INT words> )

Description

Sets all words in the specified memory block to the specified value.

Also called [mem_setw]().

Parameters


VOID POINTER data - Pointer to the block of words in memory. WORD value - Value to set all words to. INT words - Number of words to change the value of.


Returns

INT : [true]

Example

See [alloc]().

Also useful in conjunction with [map_buffer]() with 16bit [maps]. (Example needed.)


Minimize()

Definition

INT minimize ( )

Iconifies/minimizes the window.

Returns

INT : success


0 - If minimizing/iconification is not support or was refused by the window manager. !0 - Success.


Example

import "mod_key"
import "mod_wm"

Process Main()
Begin

    Repeat
        if(key(_M))
            while(key(_M)) frame; end
            minimize();
        end
        frame;
    Until(key(_ESC)||exit_status)

End

Used in example: [key](), [minimize](), [exit_status]


Mode_is_ok()

Definition

INT mode_is_ok ( <INT width> , <INT height> , <INT depth>, <INT flags> )

Returns 0 if the requested mode is not supported under any bit depth,or returns the bits-per-pixel of the closest available mode with the given width, height and requested flags.

Parameters


INT width - Width of the screen in [pixels]. INT height - Height of the screen in [pixels]. INT depth - [Color depth]. INT flags - Mode of rendering. See [render flags].


Returns

INT : Whether the specified mode can be used.


0 - The specified mode cannot be used. >0 - The bits-per-pixel of the closest available mode for the given width, height and flags.


Example

import "mod_video"
import "mod_key"
import "mod_wm"

Process Main()
Begin
    if (is_mode_ok(640,400,16,0))
     set_mode(640,400,16);
    else
     set_mode(640,480,16);
    end
    Repeat
        frame;
    Until(key(_ESC)||exit_status)
End

Used in example: [is_mode_ok](), [key]


Move_draw()

Definition

INT move_draw ( <INT DrawID> , <INT x> , <INT y> )

Moves a certain [drawing] on the screen. Only drawings drawn with a certain z value can be moved like this, as other ones are drawn on a [graphic] and thus cannot be moved.

Parameters


INT DrawID - [DrawID] to be moved. INT x - The new x coordinate of the drawing. INT y - The new y coordinate of the drawing.


Returns

INT : [true]


Move_scroll()

Definition

INT Move_scroll ( <INT scrollnumber>)

The move_scroll function is a slighty more advanced function. It allow the scroll's internal coordinates x0, y0, x1 and y1 of the [scroll structure] to be updated in a forcefull way. This gives great flexibility when multiple [scroll windows] are used.

For instance, in a situation where multiple scroll windows are active on screen, and one scroll is controlled by the main player, the other scrolls can be updated manually. However, the function can also be usefull when there's only one scroll active. In that case you can have any process take control over the scroll.

Also called [scroll_move]().

Parameters


INT scrollnumber - The ID for the scroll window to be moved


Returns

INT : [true]

Example

IMPORT "mod_video";
IMPORT "mod_map";
IMPORT "mod_scroll";
IMPORT "mod_screen";
IMPORT "mod_key";
IMPORT "mod_proc";

GLOBAL

int graphics;
int counter;

PRIVATE

PROCESS main();

BEGIN
    set_fps(100, 0);
    graphics=load_fpg("help.fpg");
    start_scroll(0, graphics, 103, 102, 0, 15);

    scroll.camera=id; // assign the "main" process instance (this one) to the scroll's camera.
    priority=100;

    FROM counter=-2000 TO 2000 step 100;
        movable_process(counter);
    END

    say("Use the right and left cursors to move");

    graph=101;
    ctype=c_scroll;

    LOOP
        if (key(_right))
            x+=2;
            flags=0;
        END
        if (key(_left))
            x-=2;
            flags=1;
        END

        move_scroll(0); // Updates the scroll structure[], in this case affect scroll 0.

        FRAME;
    END
END

PROCESS movable_process(x_scroll);

PRIVATE

BEGIN
    ctype=c_scroll;
    z=100;
    graph=104;
    LOOP
        x=x_scroll-scroll.x0; 
        FRAME;
    END
END

Using Scrolling

For each [process] that you want to be part of a [scroll window], you must set the [local variable] to value [C_SCROLL]. It should also be noted that the local variable [c_number] is used for selecting in which scroll a process should be displayed. Additionally, you must set the camera property of the [scroll structure] to the [processID] of the process you wish to be followed.


Move_text()

Definition

INT move_text ( <INT TextID> , <INT x> , <INT y>, <INT z>)

Moves an existing [text] to another place on the screen.

Parameters


INT TextID - [Identifier of the text] you want to move. This identifier should have been appointed to a text earlier on. INT x - The new horizontal coordinate (of the control point) of your text. INT y - The new vertical coordinate (of the control point) of your text. INT z - The new depthplane (of the control point) of your text. (introduced in version r282)


Returns

INT : TRUE

Notes

The "z" argument is a newer feature, so it is not anvailible in all versions.

Errors

None.

Example

Program test;
Global
    My_text;
Begin
    My_text=write(0,320/2,200/2,4,"Press space to move this.");
    Loop
        If (key(_space))
            Move_text(My_text,rand(0,319),rand(0,199));
        End
        Frame;
    End
End

Used in example: [write](), [rand]()

This will result in something like:\

Example 2

import "mod_text";
import "mod_mouse";
import "mod_key";
import "mod_video";
import "mod_rand";
import "mod_map";

private
    txt[10];
    counter;
    tz;
begin
    set_mode(640,480,32);

    txt[0]=write_int(0,10,10,10,0,&counter);
    txt[1]=write_int(0,10,20,-5,0,&tz);
    txt[2]=write(0,10,10,0,0,"hello world");

    set_text_color(txt[1], rgb(255,0,0));

    while(!key(_ESC))

        counter++;

        move_text(txt[2], mouse.x, mouse.y, tz );

        set_text_color(txt[0], rand(0101010h, 0ffffffh));

        if ( key( _DOWN ) ) tz--; end
        if ( key( _UP ) ) tz++; end

        frame;
    end
end

Used in example: [write](), [write_int](), [rand](), [set_text_color]()


Move_window()

Definition

INT move_window ( <INT x> , <INT y> )

Moves the [Bennu] window so that the top left of the window is on the specified (x,y).

Also called [Set window pos]().

Parameters


INT x - The new X coordinate of the top left of the window. INT y - The new Y coordinate of the top left of the window.


Returns

INT : [true]


Near_angle()

Definition

INT near_angle ( <INT angle> , <INT final angle> , <INT increment> )

Returns an [angle] closer to another angle, with the indicated increment. It is used for aiming the original angle and it gradually changes into the final angle. The increment controls the rate in wich the final angle is added or subtracted from the orginal angle. The returned angle will be ranging from 0 to 360000 (0-360º).

Parameters


INT angle - The original angle. INT final angle - The new angle. INT increment - The addition or subtraction rate between the two angles.


Returns

INT : An angle nearer the final angle.

Notes

The [angle] value returned by this function is in thousandths of degrees, as most angles within [Bennu] are.

Example

/* Modified example converted from bennupack, fenix test section, 2 Medium\fenix test\Fenix Test3\Test_NEAR_ANGLE.prg */

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
//IMPORT "mod_math";
IMPORT "mod_mathi";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_screen";
IMPORT "mod_mouse";
IMPORT "mod_proc";
IMPORT "mod_grproc";

GLOBAL

   int fpg;
   int ang;
   //int increment=5000;
   int increment=10000;
   //int increment=25000;
   //int increment=50000;

PROCESS main();

BEGIN

  full_screen=false;
  fpg=load_fpg("Fpg.fpg");

  say("Test near_angle...");
  say("Press ESC to quit, and use mouse to move triangle.");

  put_screen(fpg,2);

  // set the mouse cursor 
  mouse.graph=200;
  mouse.x=0;
  mouse.y=0;

  graph=101;

  REPEAT

    // Returns the angle between two certain points. The returned angle will be ranging from 0 to 360000 (0-360º). 
    ang=fget_angle(x,y,mouse.x,mouse.y);

    // int near_angle (int <angle>, int <final angle>, int <increment>)
    angle=near_angle(angle,ang,increment);

    say("angle: "+angle);
    say("ang: "+ang);
    say("increment: "+increment);   

    advance(5);
    FRAME;
  UNTIL(key(_esc))

END

Used in example: [say](), [fget_angle](), [Advance], [graph], [angle]


Pal_clone()

Syntax

INT pal_clone ( <INT paletteID> )

Description

This function is creates a copy of palette loaded with [Pal_load](). It can be used for the functions [Pal_get]() and [Pal_map_assign]().

Parameters


INT paletteID - The handle of the color palette loaded with [Pal_load]().


Returns

INT : Error.


0 - Error: could not open file; corrupt or truncated file; file doesn't contain palette information. 1 - The identifier of the [palette].


Example

/* original bennupack example FROM: \2 Medium\fenix test\palettes\rbear8-2.prg (from bomberlink) */

/* this program demonstrates the use of the functions: pal_load(), pal_clone(), pal_get(),       */
/* pal_map_assign(), pal_set() and pal_refresh().                                                */

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_text";

GLOBAL

   // palette identifiers
   int pal_orange;
   int pal_green;
   int pal_normal;

   int status1;
   int status2;

   // identifier of the fpg archive
   int fpg_id;

   // arrays for the data of the two color palettes.
   byte pal_orange_data[255]; 
   byte pal_green_data[255];  

   int map_count;

PROCESS main();

BEGIN

    set_fps(10,0);
    set_mode(320,200,16);  // we use a 16 bit color mode

    // load two color palettes and duplicate one
    pal_green=pal_load("rbear8-green.pal");
    pal_orange=pal_load("rbear8-orange.pal");

    // pal_clone (int pal_id);
    pal_normal=pal_clone(pal_orange); // duplicate palette, i.e. make a copy of it.

    // load the fpg file
    fpg_id=fpg_load("rbear8.fpg");

    write_int(0,10,10,0,&fps);
    write(0,10,20,0,"F1/F2 - change palette");

    x = 160;
    y = 120;

    // pal_get (int pal_id, int start_color, int num_colors, pointer pal_data);
    pal_get(pal_green,7,7,&pal_green_data);    // get colors 7 - 13 and store them in the array
    pal_get(pal_orange,7,7,&pal_orange_data);        

    FROM map_count=1 TO 102; // there are 102 frames in the animation

        // pal_map_assign (int fileid, int graph, int pal_id);
        pal_map_assign(fpg_id,map_count,pal_normal); // assign the "normal (original source)" color 
                                                     // palette that we duplicated earlier.
    END

    WHILE (NOT key(_ESC))

        FROM graph=1 TO 13;

            FRAME;

            IF (key(_F1))
                say("switched to green palette");

                // pal_set (int pal_id, int start_color, int num_colors, pointer pal_data);
                status1=pal_set(pal_normal,7,7,&pal_green_data); // change colors 7 - 13 in the "normal" 
                                                                 // palette, by using the values from the
                                                                 // "green" color palette.

                say("pal_set_status: "+status1);                                                                 

                // pal_refresh (int pal_id);
                status2=pal_refresh(pal_normal); // apply the modified color palette to the graphics.
                                                 // this function is required to make the change visible.  

                say("pal_refresh_status: "+status2);                                                   

                // conclusion: the difference between pal_map_assign() and pal_set() is that pal_map_assign()
                // works immediately, and that pal_set() requires the palette to be refreshed to make the 
                // change visible.                
            END

            IF (key(_F2))
                say("switched to orange palette");
                pal_set(pal_normal,7,7,&pal_orange_data);  // colors 7 - 13
                pal_refresh(pal_normal);
            END

            IF (key(_ESC)) 
                BREAK; 
            END
        END
    END

END

Used in example: [Pal_load](), [pal_get](), [Pal_map_assign](), [Pal_refresh](), [Set_fps](), [Write]()


Pal_del() (MISSING)

Pal_get()

Syntax

INT pal_get ( [<INT paletteID>] , <INT first_color> , <INT num_colors> , <POINTER palette_data>)

Description

This function is used in conjuction with [Pal_set]() to load palette data that was loaded with [Pal_load]() into an array, for later use with [Pal_set](). This [palette] can also be loaded from [MAP]'s, [FNT]'s and other image formats, provided that they are 8 bit images.

Also called [colors_get](). The previous name [get_colors]() is deprecated.

Parameters


INT paletteID - The handle of the color palette loaded with [Pal_load](). This paramter is optional. INT first_color - The first color number of the palette. This doesn't necessarily have be the first color. INT num_colors - The number of colors you want to replace, wich counts from the first_color to the num_colors. See notes. POINTER palette_data - Pointer ([Offset]) to an array where the color values will be stored.


Note

The maximum number of colors cannot be bigger the 255. The num_colors starts counting from first_color, so if the first_color is 7, and num_colors is 7, the color value's 7-13 are changed. So logically, the value num_colors can only be 255 when first_color is 0. This range gives you all the colors. To be safe, the formula for the number of colors to modified is: num_colors-first_color.

I.e. num_colors: 55 - first_color: 4 = 51 colors are changed, the range from color index 4 up to color index 55.

Returns

INT : Error.


0 - Error: could not open file; corrupt or truncated file; file doesn't contain palette information. 1 - No error: [palette] was set with success.


Example

/* original bennupack example FROM: \2 Medium\fenix test\palettes\rbear8-2.prg (from bomberlink) */

/* this program demonstrates the use of the functions: pal_load(), pal_clone(), pal_get(),       */
/* pal_map_assign(), pal_set() and pal_refresh().                                                */

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_text";

GLOBAL

   // palette identifiers
   int pal_orange;
   int pal_green;
   int pal_normal;

   int status1;
   int status2;

   // identifier of the fpg archive
   int fpg_id;

   // arrays for the data of the two color palettes.
   byte pal_orange_data[255]; 
   byte pal_green_data[255];  

   int map_count;

PROCESS main();

BEGIN

    set_fps(10,0);
    set_mode(320,200,16);  // we use a 16 bit color mode

    // load two color palettes and duplicate one
    pal_green=pal_load("rbear8-green.pal");
    pal_orange=pal_load("rbear8-orange.pal");

    // pal_clone (int pal_id);
    pal_normal=pal_clone(pal_orange); // duplicate palette, i.e. make a copy of it.

    // load the fpg file
    fpg_id=fpg_load("rbear8.fpg");

    write_int(0,10,10,0,&fps);
    write(0,10,20,0,"F1/F2 - change palette");

    x = 160;
    y = 120;

    // pal_get (int pal_id, int start_color, int num_colors, pointer pal_data);
    pal_get(pal_green,7,7,&pal_green_data);    // get colors 7 - 13 and store them in the array
    pal_get(pal_orange,7,7,&pal_orange_data);        

    FROM map_count=1 TO 102; // there are 102 frames in the animation

        // pal_map_assign (int fileid, int graph, int pal_id);
        pal_map_assign(fpg_id,map_count,pal_normal); // assign the "normal (original source)" color 
                                                     // palette that we duplicated earlier.
    END

    WHILE (NOT key(_ESC))

        FROM graph=1 TO 13;

            FRAME;

            IF (key(_F1))
                say("switched to green palette");

                // pal_set (int pal_id, int start_color, int num_colors, pointer pal_data);
                status1=pal_set(pal_normal,7,7,&pal_green_data); // change colors 7 - 13 in the "normal" 
                                                                 // palette, by using the values from the
                                                                 // "green" color palette.

                say("pal_set_status: "+status1);                                                                 

                // pal_refresh (int pal_id);
                status2=pal_refresh(pal_normal); // apply the modified color palette to the graphics.
                                                 // this function is required to make the change visible.  

                say("pal_refresh_status: "+status2);                                                   

                // conclusion: the difference between pal_map_assign() and pal_set() is that pal_map_assign()
                // works immediately, and that pal_set() requires the palette to be refreshed to make the 
                // change visible.                
            END

            IF (key(_F2))
                say("switched to orange palette");
                pal_set(pal_normal,7,7,&pal_orange_data);  // colors 7 - 13
                pal_refresh(pal_normal);
            END

            IF (key(_ESC)) 
                BREAK; 
            END
        END
    END

END

Used in example: [Pal_load](), [pal_clone](), [Pal_map_assign](), [Pal_refresh](), [Set_fps](), [Write]()


Pal_load()

Syntax

INT pal_load ( <STRING filename>, [ <POINTER id>] )

Description

Loads a color palette from a file.

The current [palette] is switched to the loaded one. Note that one can load a palette from an 8bit [FPG] or [MAP] file (the remaining graphic data will not be loaded) or a [PAL] file.

The previous name [load_pal]() is deprecated.

Parameters


STRING filename - The filename of the file that you wish to load the [palette] from (including extension and possible path). POINTER id - Optional parameter, for loading a palette in the background.


Returns

INT : [graphID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The graphID of the newly created palette.


the following applies for versions prior rc282:

INT : Error.


-1 - Error: could not open file; corrupt or truncated file; file doesn't contain palette information. 0 - Error: could not obtain filename; some [FPL] error. 1 - No error: [palette] was loaded with success.


Example

Program example;
Begin

    load_pal("example.pal");

    Loop
        frame;
    End

End

Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_pal("archivo_gordo.pal", &idpal);
      while(idpal==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idpal==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

Pal_map_assign()

Syntax

INT pal_map_assign ( <INT fileID> , <INT graphID>, <INT paletteID> )

Description

Changes the color palette of an 8 bit (256 color) graphic, with the palette that is loaded with [Pal_load](). This [palette] can also be loaded from [MAP]'s, [FNT]'s and other image formats, provided that they are 8 bit images. Unlike [Pal_set](), the change is immediately visible.

Parameters


INT fileID - The fileID of the graphic(s), i.e. 0 for the systemfile, or the id code of an [FPG] archive. INT graphID - The graphic (or mapcode) to modify. INT paletteID - The handle of the color palette loaded with [Pal_load]().


Returns

INT : Error.


0 - Error: could not open file; corrupt or truncated file; file doesn't contain palette information. 1 - No error: [palette] was loaded with success.


Example

/* Original example from bennupack: 2 Medium\fenix test\palettes\rbear8_1.prg (from bomberlink) */

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_text";

GLOBAL
   int pal_orange;  // palette 1
   int pal_green;   // palette 2

   int map_count;

   int fpg_id;

PROCESS main();

BEGIN

    set_fps(10,0);
    set_mode(320,200,16);

    // load the fpg archive
    fpg_id=fpg_load("rbear8.fpg");

    // load the two palettes
    pal_orange=pal_load("rbear8-orange.pal");
    pal_green=pal_load("rbear8-green.pal");

    write_int(0,10,10,0,&fps);
    write(0,10,20,0,"F1/F2 - change palette");

    x=160;
    y=120;

    WHILE (NOT key(_ESC))

        FROM graph=1 TO 3;

          FRAME;

           IF (key(_F1))
              FROM map_count=1 TO 102;
                 say("changing colors: "+map_count);
                 pal_map_assign(fpg_id,map_count,pal_green);  // apply palette 1
              END
           END

           IF (key(_F2))
              FROM map_count=1 TO 102;
                 say("changing colors: "+map_count);
                 pal_map_assign(fpg_id,map_count,pal_orange); // apply palette 2
              END
           END

           IF (key(_ESC)) 
              BREAK; 
           END
        END
    END

END

Used in example: [Pal_load](), [Say](), [Set_mode](), [Write_int]()


Pal_map_getid()

Syntax

INT pal_map_getid ( <INT fileID> , <INT graphID> )

Description

This function returns the identification code of the palette of a specific graphic.

Parameters


INT fileID - The handle of the file. INT graphID - The handle of the graph.


Returns

INT : Error/status.


0 - Error: could not open file; corrupt or truncated file; file doesn't contain palette information. id - The identifier of the [palette].


Example

/* original bennupack example FROM: \2 Medium\fenix test\palettes\rbear8-5.prg (from bomberlink) */

/* this program demonstrates the use of the functions: pal_load(), pal_map_get_id()              */
/* pal_map_assign(), pal_set() and pal_refresh().                                                */

/* In this example pal_get() is not used but the table is filled with data by forehand.          */

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_text";

GLOBAL

   int pal_normal; // identifier of the palette

   int fpg_id;     // identifier of the fpg file

   // the arrays with data (pre-filled)   
   byte orange_palette_data[21] =
                                80,0,0,
                               110,0,0,
                               140,0,0,
                               170,0,0,
                               190,0,0,
                               220,0,0,
                               250,0,0;
   byte green_palette_data[21] =
                               0, 80,0,
                               0,110,0,
                               0,140,0,
                               0,170,0,
                               0,190,0,
                               0,220,0,
                               0,250,0;

   int count;

PROCESS main();   

BEGIN

    set_fps(10,0);
    set_mode(320,200,16);

    // load the fpg
    fpg_id=fpg_load("rbear8.fpg");

    write_int(0,10,10,0,&fps);
    write(0,10,20,0,"F1/F2 - change palette");

    x=160;
    y=120;

    pal_normal=pal_map_getid(fpg_id,1); // file,graph   
    say("pal_normal: "+pal_normal);

    WHILE (NOT key(_ESC))

        FROM graph=1 TO 13;

            FRAME;

            IF (key(_F1))
                pal_set(pal_normal,7,7,&green_palette_data);    // colors 7 - 13
                pal_refresh(pal_normal);
            END

            IF (key(_F2))
                pal_set(pal_normal,7,7,&orange_palette_data);  // colors 7 - 13
                pal_refresh(pal_normal);
            END

            IF (key(_ESC)) 
               BREAK; 
            END
        END
    END

END

Used in example: , [Pal_set](), [Pal_map_assign](), [Pal_refresh](), [Set_fps](), [Write]()

See also

[Pal_set]()


Pal_map_remove()

Syntax

INT pal_map_remove ( <INT fileID> , <INT graphID> )

Description

Removes the color palette that assigned with [Pal_map_assign](). It is basically an undo function for color palette changes.

Parameters


INT fileID - The fileID of the graphic(s), i.e. 0 for the systemfile, or the id code of an [FPG] archive. INT graphID - The graphic (or mapcode).


Returns

INT : Status/Error.


0 - Error: could not open file; corrupt or truncated file; file doesn't contain palette information. 1 - No error: [palette] was reverted with success.


Example

/* Original example from bennupack: 2 Medium\fenix test\palettes\rbear8_1.prg (from bomberlink) */

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_text";

GLOBAL
   int pal_orange;  // palette 1
   int pal_green;   // palette 2

   int map_count;

   int fpg_id;

   int status;

PROCESS main();

BEGIN

    set_fps(10,0);
    set_mode(320,200,16);  // we use a 16 bit colormode

    // load the fpg archive
    fpg_id=fpg_load("rbear8.fpg");

    // load the two palettes
    pal_orange=pal_load("rbear8-orange.pal");
    pal_green=pal_load("rbear8-green.pal");

    write_int(0,10,10,0,&fps);
    write(0,10,20,0,"F1/F2 - change palette");
    write(0,10,30,0,"F3 - to undo palette changes");

    x=160;
    y=120;

    WHILE (NOT key(_ESC))

        FROM graph=1 TO 3; // cycle through 3 graphics

          FRAME;

           IF (key(_F1))
              FROM map_count=1 TO 102; // there are 102 frames in the animation.
                 say("changing colors: "+map_count);
                 pal_map_assign(fpg_id,map_count,pal_green);  // apply palette 1
              END
           END

           IF (key(_F2))
              FROM map_count=1 TO 102;
                 say("changing colors: "+map_count);
                 pal_map_assign(fpg_id,map_count,pal_orange); // apply palette 2
              END
           END

           IF (key(_F3))
              FROM map_count=1 TO 102;
                 say("changing colors: "+map_count);
                 status=pal_map_remove(fpg_id,map_count); 
                 say("status: "+status);
              END
           END

           IF (key(_ESC)) 
              BREAK; 
           END
        END
    END

END

Used in example: [Say](), [Pal_load](), [Pal_map_assign](), [Key](), [Write_int]()


Pal_new()

Syntax

INT pal_new ()

Description

This function creates a new palette in memory and returns the handle, for later use by other [palette] functions such as [Pal_save](), [Pal_set], etc. When you're done, you can free the memory with [Pal_unload]().

The previous name [new_pal()] is deprecated.

Returns

INT : Status.


id - The identification code of the memory area for the newly created palette.



Pal_refresh()

Syntax

INT pal_refresh ( [<INT paletteID>] )

Description

Refreshes the color palette after a call of [Pal_set](), to the make color change visible.

Parameters


INT paletteID - The handle of the color palette loaded with [Pal_load](). The parameter is optional.


Returns

INT : Status.


1 - The status.


Example

/* original bennupack example FROM: \2 Medium\fenix test\palettes\rbear8-2.prg (from bomberlink) */

/* this program demonstrates the use of the functions: pal_load(), pal_clone(), pal_get(),       */
/* pal_map_assign(), pal_set() and pal_refresh().                                                */

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_text";

GLOBAL

   // palette identifiers
   int pal_orange;
   int pal_green;
   int pal_normal;

   int status1;
   int status2;

   // identifier of the fpg archive
   int fpg_id;

   // arrays for the data of the two color palettes.
   byte pal_orange_data[255]; 
   byte pal_green_data[255];  

   int map_count;

PROCESS main();

BEGIN

    set_fps(10,0);
    set_mode(320,200,16);  // we use a 16 bit color mode

    // load two color palettes and duplicate one
    pal_green=pal_load("rbear8-green.pal");
    pal_orange=pal_load("rbear8-orange.pal");

    // pal_clone (int pal_id);
    pal_normal=pal_clone(pal_orange); // duplicate palette, i.e. make a copy of it.

    // load the fpg file
    fpg_id=fpg_load("rbear8.fpg");

    write_int(0,10,10,0,&fps);
    write(0,10,20,0,"F1/F2 - change palette");

    x = 160;
    y = 120;

    // pal_get (int pal_id, int start_color, int num_colors, pointer pal_data);
    pal_get(pal_green,7,7,&pal_green_data);    // get colors 7 - 13 and store them in the array
    pal_get(pal_orange,7,7,&pal_orange_data);        

    FROM map_count=1 TO 102; // there are 102 frames in the animation

        // pal_map_assign (int fileid, int graph, int pal_id);
        pal_map_assign(fpg_id,map_count,pal_normal); // assign the "normal (original source)" color 
                                                     // palette that we duplicated earlier.
    END

    WHILE (NOT key(_ESC))

        FROM graph=1 TO 13;

            FRAME;

            IF (key(_F1))
                say("switched to green palette");

                // pal_set (int pal_id, int start_color, int num_colors, pointer pal_data);
                status1=pal_set(pal_normal,7,7,&pal_green_data); // change colors 7 - 13 in the "normal" 
                                                                 // palette, by using the values from the
                                                                 // "green" color palette.

                say("pal_set_status: "+status1);                                                                 

                // pal_refresh (int pal_id);
                status2=pal_refresh(pal_normal); // apply the modified color palette to the graphics.
                                                 // this function is required to make the change visible.  

                say("pal_refresh_status: "+status2);                                                   

                // conclusion: the difference between pal_map_assign() and pal_set() is that pal_map_assign()
                // works immediately, and that pal_set() requires the palette to be refreshed to make the 
                // change visible.                
            END

            IF (key(_F2))
                say("switched to orange palette");
                pal_set(pal_normal,7,7,&pal_orange_data);  // colors 7 - 13
                pal_refresh(pal_normal);
            END

            IF (key(_ESC)) 
                BREAK; 
            END
        END
    END

END

Used in example: [Pal_load](), [pal_get](), [Pal_map_assign](), [Pal_clone](), [Set_fps](), [Write]()


Pal_save()

Syntax

INT pal_save ( <STRING filename>, [<INT paletteID>] )

Description

This function saves a [palette] to a file on disk in the [PAL] format. When the second parameter is omitted, the system palette is saved, otherwise the palette data indicate with the paletteID. Concluding from this, is that it's possible to load multiple palettes in bennu and assign an unique identifier to them and save them to a file later.

The previous name [save_pal]() is deprecated.

Parameters


STRING filename - The filename of the new palette file. INT paletteID - The handle of the [palette](). This parameter is optional.


Returns

INT : Status.


id - The file handle.



Pal_set()

Syntax

INT pal_set ( [<INT paletteID>] , <INT first_color> , <INT num_colors> , <POINTER palette_data>)

Description

Changes the color palette of an 8 bit (256 color) graphic, with the palette that is loaded with [Pal_load](). This [palette] can also be loaded from [MAP]'s, [FNT]'s and other image formats, provided that they are 8 bit images. Unlike [Pal_map_assign](), the change is not immediately visible, and the function [Pal_refresh]() has to be called afterwards to make the change visible. The difference however, is that it not replaces the whole palette, but allows a specified number of colors to be changed, so it's a bit more flexible.

Also called [colors_set](). The previous name [set_colors]() is deprecated.

Parameters


INT paletteID - The handle of the color palette loaded with [Pal_load](). This paramter is optional. INT first_color - The first color number of the palette. This doesn't necessarily have be the first color. INT num_colors - The number of colors you want to replace, wich counts from the first_color to the num_colors. See notes. POINTER palette_data - Pointer ([Offset]().


Note

The maximum number of colors cannot be bigger the 255. The num_colors starts counting from first_color, so if the first_color is 7, and num_colors is 7, the color value's 7-13 are changed. So logically, the value num_colors can only be 255 when first_color is 0. This range gives you all the colors. To be safe, the formula for the number of colors to modified is: num_colors-first_color.

I.e. num_colors: 55 - first_color: 4 = 51 colors are changed, the range from color index 4 up to color index 55.

Returns

INT : Error.


0 - Error: could not open file; corrupt or truncated file; file doesn't contain palette information. 1 - No error: [palette] was set with success.


Example

/* original bennupack example FROM: \2 Medium\fenix test\palettes\rbear8-2.prg (from bomberlink) */

/* this program demonstrates the use of the functions: pal_load(), pal_clone(), pal_get(),       */
/* pal_map_assign(), pal_set() and pal_refresh().                                                */

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_text";

GLOBAL

   // palette identifiers
   int pal_orange;
   int pal_green;
   int pal_normal;

   int status1;
   int status2;

   // identifier of the fpg archive
   int fpg_id;

   // arrays for the data of the two color palettes.
   byte pal_orange_data[255]; 
   byte pal_green_data[255];  

   int map_count;

PROCESS main();

BEGIN

    set_fps(10,0);
    set_mode(320,200,16);  // we use a 16 bit color mode

    // load two color palettes and duplicate one
    pal_green=pal_load("rbear8-green.pal");
    pal_orange=pal_load("rbear8-orange.pal");

    // pal_clone (int pal_id);
    pal_normal=pal_clone(pal_orange); // duplicate palette, i.e. make a copy of it.

    // load the fpg file
    fpg_id=fpg_load("rbear8.fpg");

    write_int(0,10,10,0,&fps);
    write(0,10,20,0,"F1/F2 - change palette");

    x = 160;
    y = 120;

    // pal_get (int pal_id, int start_color, int num_colors, pointer pal_data);
    pal_get(pal_green,7,7,&pal_green_data);    // get colors 7 - 13 and store them in the array
    pal_get(pal_orange,7,7,&pal_orange_data);        

    FROM map_count=1 TO 102; // there are 102 frames in the animation

        // pal_map_assign (int fileid, int graph, int pal_id);
        pal_map_assign(fpg_id,map_count,pal_normal); // assign the "normal (original source)" color 
                                                     // palette that we duplicated earlier.
    END

    WHILE (NOT key(_ESC))

        FROM graph=1 TO 13;

            FRAME;

            IF (key(_F1))
                say("switched to green palette");

                // pal_set (int pal_id, int start_color, int num_colors, pointer pal_data);
                status1=pal_set(pal_normal,7,7,&pal_green_data); // change colors 7 - 13 in the "normal" 
                                                                 // palette, by using the values from the
                                                                 // "green" color palette.

                say("pal_set_status: "+status1);                                                                 

                // pal_refresh (int pal_id);
                status2=pal_refresh(pal_normal); // apply the modified color palette to the graphics.
                                                 // this function is required to make the change visible.  

                say("pal_refresh_status: "+status2);                                                   

                // conclusion: the difference between pal_map_assign() and pal_set() is that pal_map_assign()
                // works immediately, and that pal_set() requires the palette to be refreshed to make the 
                // change visible.                
            END

            IF (key(_F2))
                say("switched to orange palette");
                pal_set(pal_normal,7,7,&pal_orange_data);  // colors 7 - 13
                pal_refresh(pal_normal);
            END

            IF (key(_ESC)) 
                BREAK; 
            END
        END
    END

END

Used in example: [Pal_load](), [pal_clone](), [Pal_map_assign](), [Pal_refresh](), [Set_fps](), [Write]()


Pal_unload()

Syntax

INT pal_unload ( <INT paletteID> )

Description

This function unloads the palette, thus freeing the memory it ouccupies.

Also called [pal_del](). The previous name [unload_pal]() is deprecated.

Parameters


INT paletteID - The handle of the [palette]().


Returns

INT : Status.


1 - Operation completed.



Palette_convert()

Syntax

INT palette_convert ( <INT fileID> , <INT graphID> , <POINTER palette_data> )

Description

This function changes the colormap of an image, but does not change the color index values it self. That is, that the individual pixels will keep their color indexes, but the r,g,b values in the palette are modified. This function requires an [Array] of maximum 255 bytes (or integers), to store the palette values. The array is accessed with the [Offset] operator.

The previous name [Convert_palette]() is deprecated.

Parameters


INT fileID - The handle of the file containing the graphics. INT graphID - The handle of the graphic. POINTER palette_data - Pointer to the [Array] operator.


Returns

INT : Status.


1 - Success.


Example

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_screen";
IMPORT "mod_text";

GLOBAL

  int map_id;
  int clonemap_id;

  int palette_table[255];
  int color;

  int status;

PROCESS main();  

BEGIN

  set_mode(320,240,16);

  map_id=load_map("MAP.MAP");

  clonemap_id=map_clone(0,map_id); // create a copy of the map

  write(0,80,30,4,"Original image:");
  write(0,240,30,4,"Converted image (clone):");
  write(0,160,140,4,"Spacebar: Change the palette of the clone...");
  write(0,160,190,4,"Press ESC to quit...");

  // palette color 0 (the transparant color) will be not changed, that's why the 
  // count starts at 1. 
  // values that go beyond 255 will be cut off by the MOD (%). So, 256, becomes 0, 
  // 257 becomes 2 etc. The fist 16 colors will stay untouched.
  FROM color=1 TO 255; 
     palette_table[color]=(color+16) MOD 255; 
     say("palette_table["+color+"]");
  END

  xput(0,map_id,80,70,0,25,0,0);

  x=240; 
  y=70; 
  graph=clonemap_id; 
  size=25;

  REPEAT

     IF (key(_space)) 
        // let's do the conversion
        status=palette_convert(0,clonemap_id,&palette_table); 
        say("status: "+status);
     END

     FRAME;
  UNTIL(key(_esc))

END

Used in example: [Say](), [Write](), [Xput]()


Palette_roll()

Syntax

INT palette_roll ( <INT start_color> , <INT end_color> , <INT increment> )

Description

Cycles the colors in the [palette] by rotating them. This function shifts colors between the range specified by the start color and the end color, at a given increment. This can be used to create a very old school waterfall animation effect. This technique is called color cycling. It is a very memory efficient way of doing these kinds of animations, since only one bitmap is used and the effect is achieved by cycling through a specific range of colors. Here's a nice (web based) example of this technique in action.

To use this function, you have to create graphics that use a range of consecutive colors of the original palette, in a perpetual cycle (i.e., colors ranging from 0 to 15, painting something with the colors 0, 1, 2, 3, ... , 14, 15, 0, 1, 2, ...).

Also, make sure that these colors are not used by other graphics that are going to appear on the screen at the same time, if you do not want to apply these effects on them, or they'll look funny.

One important thing, this function only works in 8 bit mode.

The previous name [roll_palette]() is deprecated.

Parameters


INT start_color - The start color of the range (0-255). INT end_colors - The last color of the range (0-255). INT increment - The cycle speed (-1, 0, 1, etc).


Notes

An increment of 0 is pointless, because that will stop the cycle. The higher the number, the faster the cycle goes. Negative values will cycle in the opposite direction.

Returns

INT : Status.


1 - Success.


Example

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_screen";
IMPORT "mod_text";

GLOBAL
   int map;
   int fnt;

   byte color_increment=1;
   byte initial_color;
   byte num_colors=10;

PROCESS main();

BEGIN

   set_fps(50,0);
   set_mode(640,480,8);     // for palette_roll to work is the 8 bit mode required!

   map=load_map("MAP.MAP");

   put_screen(0,map);

   write(0,10,10,3,"Rolling Palette demo, +/-: change number of colors, 0, 1, 2: change increment, Press ESC to quit...");

   REPEAT

      // changes the amount of colors      
      IF (key(_plus) AND num_colors<255)
         FRAME;
         num_colors+=1;
      END

      IF (key(_minus) AND num_colors>1)
         FRAME;
         num_colors-=1;
      END

      // change the speed 
      IF (key(_0))
         FRAME;
         color_increment=0;
      END

      IF (key(_1))
         FRAME;
         color_increment=1;
      END

      IF (key(_2))
         FRAME;
         color_increment=-1;
      END

      // roll the palette
      palette_roll(initial_color,num_colors,color_increment);      
      say("initial color: "+initial_color+" num color: "+num_colors+" increment: "+color_increment);

      FRAME;
   UNTIL(key(_esc))

END

Used in example: [Say](), [Write]()


Path_find()

Syntax

'''INT ''' path_find ( <INT fileID> , <INT graphID> , <INT start_x> , <INT start_y> , <INT dest_x> , <INT dest_y> , <INT options>)

Description

The pathfinding function is based on the A* algorithm with a heuristic value. It uses a logic map with a maze, a start position and an end position. The logic map is an 8 bit image (with palette), preferably with only 2 colors, black and white, wich indicates the walls and the paths.

Here's the bennu source code: mod_path.c, wikipedia page about pathfinding.

Parameters


INT fileID - The fpg archive wich contains the map, may be 0 when the systemfile is used. INT graphID - The bitmap (either mapcode from fpg or loaded with [Map_load]() into the systemfile) with the maze, see notes*. INT start_x - The x coordniate of the start position. INT start_y - The y coordniate of the start position. INT dest_x - The x coordinate of the destination position. INT dest_y - The y coordinate of the destination position. INT options - The kind of pathfinding, [PF_NODIAG]


Returns

INT : Status.


0 - The path has not been found yet. 1 - The path has been found.


Example

Look at this tutorial: .

Notes

  • This function requires the use of 8 bit indexed (256 color) bitmaps for the path map, because of the logic behind it's design. The philosophy behind this is similair to a hardness (logic) map. It is perfectly possible to combine 8 bit images in 16 or 32 bit colormodes, provided that all 8 bit maps share the same colorpalette.

Path_getxy()

Syntax

'''INT ''' path_getxy ( <POINTER x>, <POINTER y> )

Description

This function gets a node and returns a 1 when there's still a point left, or a 0 when there are no more points. This function requires a two dimensional [Array] to work on. The arguments should accessed with the [Offset] operator. The function is typically used inside a loop. The pathfinding in bennu is based on the A* algorithm. It uses a logic map with a maze, a start position and an end position.

Here's the bennu source code: mod_path.c, wikipedia page about pathfinding.

Parameters


POINTER x - Offset of the array with the x values. POINTER y - Offset of the array with the y values.


Returns

INT : Status.


0 - There are no more coordinate points (nodes) in the list. 1 - There are still coordinate points (nodes) in the list.


Example

Look at this tutorial: .


Path_wall()

Syntax

'''INT ''' path_wall ( <INT wall_color> )

Description

This function changes the wall color. Normally, [Path_find]() only uses two colors, i.e. black and white. By using this function before making a call to Path_find, Path_find will use the color indiated by this function instead. The color may not be a zero, bcause that is usually black. ''For more information, see the [http://bennugd.svn.sourceforge.net/viewvc/bennugd/modules/mod\_path/mod\_path.c?revision=277&view=markup bennu mod_path.c sourcecode]. ''

Parameters


INT Color - The palette color.


Returns

INT : - The color value.


Pause_song()

Definition

INT pause_song ( )

Pauses the currently playing song.

Notes

The song pauses immediately, but can be resumed later by calling [resume_song](). For a nicer effect, you may want to fade the music out before pausing. See [fade_music_off]().

Returns

INT : Error.


-1 - Error: sound inactive. 0 - No error.


Example

program music_example;
global
    my_song;
    playing;
    paused;
    faded_in;
    v;
begin
    set_mode(640,480,16);

    my_song=load_song("beat.ogg");

    write(0,320,30,4,"Use the keyboard to control the music playback.");
    write(0,320,50,4,"Key [ENTER] starts / stops the song.");
    write(0,320,60,4,"Key [SPACE] pauses / resumes the song.");
    write(0,320,70,4,"Key [0] through key [9] changes the song volume.");
    write(0,320,80,4,"Key [F] fades the song in or out.");

    write(0,320,120,5,"Playing: ");
    write_int(0,320,120,3,&playing);

    write(0,320,140,5,"Paused: ");
    write_int(0,320,140,3,&paused);

    write(0,320,160,5,"Faded in: ");
    write_int(0,320,160,3,&faded_in);

    write(0,320,180,5,"Volume: ");
    write_int(0,320,180,3,&v);

    v=128;
    faded_in=true;

    repeat
        if(key(_enter))
            if(is_playing_song())
                stop_song();
                playing=false;
            else
                play_song(my_song,1);
                playing=true;
            end
            while(key(_enter))frame;end
        end

        if(key(_space))
            if(paused)
                paused=false;
                resume_song();
            else
                paused=true;
                pause_song();
            end
            while(key(_space))frame;end
        end

        if(key(_f))
            if(faded_in)
                faded_in=false;
                fade_music_off(100);
            else
                faded_in=true;
                fade_music_in(my_song,1,100);
            end
            while(key(_f))frame;end
        end

        if(key(_0))v=0;end
        if(key(_1))v=14;end
        if(key(_2))v=28;end
        if(key(_3))v=43;end
        if(key(_4))v=57;end
        if(key(_5))v=71;end
        if(key(_6))v=85;end
        if(key(_7))v=100;end
        if(key(_8))v=114;end
        if(key(_9))v=128;end

        set_song_volume(v);

    frame;
    until(key(_esc))

    exit();
end

Used in example: [key](), [set_mode](), [load_song](), [write_int](), [pause_song](), [play_song](), [stop_song](), [resume_song](), [fade_music_in](), [fade_music_off](), [set_song_volume]().


Pause_wav()

Definition

INT pause_wav (INT < channel > )

Pauses the currently playing wave channel.

Notes

The sound channel pauses immediately, but can be resumed later by calling [resume_wav](). For a nicer effect, you may want to fade the music out before pausing. See [set_channel_volume]().

Parameters


INT channel - The WAV [sound channel].


Returns

INT : Error.


-1 - Error: sound channel inactive. 0 - No error.


Example

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_proc";
IMPORT "mod_key";
IMPORT "mod_sound";

GLOBAL
   int wav;
   int channel;

PROCESS main();  
BEGIN

  wav=load_wav("wav.wav");

  say("Test pause_wav...");
  say("ENTER = Pause Sound...");
  say("Press ESC to quit...");

  channel=play_wav(wav,-1);

  REPEAT

    IF(key(_enter))
      pause_wav(channel);
      FRAME(2500);
      resume_wav(channel);
    END

    FRAME;
  UNTIL(key(_esc))
END

Used in example: [key](), [resume_wav](), [play_wav]().


Pcx_load()

Definition

INT pcx_load ( <STRING filename>, [ <POINTER id>] )

Creates a new [graphic], using the specified pcx file as contents and puts it in the [system file]. Returns the [graphID] of the created graphic. The [color depth] of the created graphic will be the same as the loaded pcx file.

The previous name [load_pcx]() is deprecated.

Parameters


STRING filename - The name of the pcx file to be loaded, including a possible [path]. POINTER id - Optional parameter, for loading a map in the background.


Returns

INT : [graphID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The graphID of the newly created graphic.


the following applies for versions prior rc282:

INT : [graphID]


0 - There was an error loading the file. >0 - The graphID of the newly created graphic.


Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_pcx("archivo_gordo.pcx", &idpcx);
      while(idpcx==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idpcx==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

Play_song()

Definition

INT play_song ( <INT songID> , <INT repeats> )

Plays a song.

Parameters


INT songID - [SongID](). INT repeats - Number of times to repeat the song. Use -1 for an infinite loop.


Returns

INT : Error.


-1 - Error: sound inactive; mixer error; invalid [songID]. 0 - No error.


Errors


Sound inactive - The sound is inactive. Invalid songID - The [songID] was invalid. Other - Some Mixer error.


Example

Program example;
Private
    int song;
Begin
    song = load_song("my_song.ogg");
    play_song(song,0);
    Loop
        frame;
    End
End

Used in example: [load_song]()


Play_wav()

Definition

INT play_wav ( <INT waveID> , <INT repeats> , [<INT channel>] )

Plays a [sound effect] previously loaded with [load_wav]().

Parameters


INT waveID - The [WaveID] of the sound effect to be played. INT repeats - Number of times to repeat the sound effect. Use -1 for an infinite loop. [INT channel] - The [sound channel] is to be played on (-1 for any, default).


Returns

INT : The [sound channel] the [sound effect] is now playing on.


-1 - Error: sound inactive; invalid [waveID] >=0 - The [sound channel] is now playing on.


Example

Program
Private
    int wave;
Begin
    wave = load_wav("my_wav.wav");
    play_wav(wave,0);
    Loop
        frame;
    End
End

Used in example: [load_wav]()


Png_load()

Definition

INT png_load ( <STRING filename>, [ <POINTER id>] )

Creates a new [graphic], using the specified [PNG] file as contents and puts it in the [system file] of the created graphic. The [color depth] of the created graphic will be the same as the loaded PNG file.

The previous name [load_png]() is deprecated.

Parameters


STRING filename - The name of the [PNG]. POINTER id - Optional parameter, for loading a map in the background.


Returns

INT : [graphID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The graphID of the newly created graphic.


the following applies for versions prior rc282:

INT : [graphID]


0 - There was an error loading the file. >0 - The graphID of the newly created graphic.


Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_png("archivo_gordo.png", &idpng);
      while(idpng==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idpng==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

Example

Checkout the [PNG_LoadDirectory] tutorial.


Png_save()

Definition

INT png_save ( <INT fileID> , <INT graphID> , <STRING filename> )

Saves the specified [graphic] as filename with the format [PNG].

The previous name [save_png]() is deprecated.

Parameters


INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] of the graphic to save. STRING filename - The name of the [PNG].


Returns

INT : Successrate


[false] - Error. [true] - Success.


Example

//here's a cool thing to save a screenshot
import "mod_map"
import "mod_screen"
import "mod_key"

Global
    int takingscreenshot;
End

Process Main()
Begin

    Loop

        If (key(_F12)) 
            If (takingscreenshot==0)
                takingscreenshot=1;
                graph=screen_get(); // grabs the screen and sets it as the program graphic
                png_save(0,graph,"shot"+rand(0,9999)+".png"); // saves the graphic as a png with a
                                                              // random number in the filename to
                                                              // prevent overwriting 
                map_unload(0,graph);  //frees the graphic
            Else
                takingscreenshot=0;
            End
            While(key(_F12)) Frame; End
       End

        frame;
    End
End

Used in example: [key](), [screen_get](), [png_save](), [map_unload]()


Point_get()

Definition

INT get_point ( <INT fileID> , <INT graphID> , <INT controlpointID> , <INT POINTER x>, <INT POINTER y>)

Allows you to obtain a control point of a particular [graph].

Any graph can contain up to 1000 control points (from 0 to 999). Control point 0 is the center of the graphic. This [function] allows you to know the location of any control point belonging to any graph.

To set a control point, use [set_point]() or, for only the center of a graph, [set_center]().

The previous name [get_point]() is deprecated.

Parameters


INT fileID - Number of the FPG library. INT graphID - Number of the graph inside the library which you want to use. INT controlpointID - Number of the control point. INT POINTER x - Pointer to where the X-coordinate of the control point will be written. INT POINTER y - Pointer to where the Y-coordinate of the control point will be written.


Returns

INT : Successrate


[false] - One of the following: specified graph is invalid, specified control point is invalid, specified control point is undefined. [true] - The control point was defined or the center was used.


Example

Program cpoint;
Private
    int map;
    int cx,cy;
Begin

    // Create a red graph
    map = new_map(100,100,8);
    map_clear(0,map,rgb(255,0,0));

    // Set the center to a random point
    set_center(0,map,rand(-10,110),rand(-10,110));

    // Get the center
    get_point(0,map,0,&cx,&cy);

    // Show the center
    say("Center-X: " + cx);
    say("Center-Y: " + cy);

    // Assign the map to the graph variable
    graph = map;

    // Set the location of this process to the center of the screen
    x = 160;
    y = 100;

    Loop
        frame;
    End

End

Used in example: [new_map](), [map_clear](), [set_center](), [pointer]

Notice that setting the center influences the position of the graph:


Point_set()

Definition

INT point_set ( <INT fileID> , <INT graphID> , <INT controlpointID> , <INT x>, <INT y>)

Allows you to set a control point of a particular [graphic].

Any graph can contain up to 1000 control points (from 0 to 999). Control point 0 is the center of the graphic. This [function] allows you to set the location of any control point belonging to any graph. The coordinates are relative to the upper left corner of the graphic.

To obtain the coordinates of a control point, use [point_get]().

The previous name [set_point]() is deprecated.

Parameters


INT fileID - [FileID] containing the graphic. INT graphID - [GraphID] of which to set a control point. INT controlpointID - Number of the control point. INT x - The new X-coordinate of the control point. INT y - The new Y-coordinate of the control point.


Returns

INT : Successrate


-1 - One of the following: specified graph is invalid, specified control point is invalid. 1 - The control point was set successfully.


Example

import "mod_map"
import "mod_say"
import "mod_wm"
import "mod_key"
import "mod_grproc"

Process Main()
Private
    int map;
    int cx,cy;
Begin

    // Create a red graph
    map = new_map(100,100,8);
    map_clear(0,map,rgb(255,0,0));

    // Set the center to a random point
    point_set(0,map,0,rand(-10,110),rand(-10,110));

    // Get the center
    point_get(0,map,0,&cx,&cy);

    // Show the center
    say("Center-X: " + cx);
    say("Center-Y: " + cy);

    // Assign the map to the graph variable
    graph = map;

    // Set the location of this process to the center of the screen
    x = 160;
    y = 100;

    Repeat
        frame;
    Until(exit_status||key(_ESC))

End

Used in example: [new_map](), [map_clear](), [point_set](), [point_get](), [pointer]

Notice that setting the center influences the position of the graph:


Pow()

Definition

FLOAT pow ( <FLOAT base> , <FLOAT power> )

Returns base to the power of power (base\^power).

Parameters


FLOAT base - The base. FLOAT power - The power.


Returns

FLOAT : base to the power of power (base\^power).

Example

Program powerful;
Global
    float value1;
    int   value2;
Begin

    write_float(0,0, 0,0,&value1);
    write_int  (0,0,10,0,&value2);

    value1 = pow(2.3,4.6);
    value2 = pow(2  ,3  );

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [write_float](), [write_int](), [key]()


Put()

Definition

INT put ( <INT fileID> , <INT graphID> , <INT x> , <INT y> )

Draws ([blits] onto the [background].

For more advanced blitting, see:

  • [xput]()
  • [map_put]()
  • [map_xput]()
  • [map_xputnp]()

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to draw with. INT x - Where on the background's x-axis to put the graph. INT y - Where on the background's y-axis to put the graph.


Returns

INT : [true]

Notes

The x and y parameters denote where to draw the graph, that is, where the center of the to be drawn graph will be.

Errors


Unsupported color depth - The origin graph's color depth is greater than the destination graph's.


Example

import "mod_map"
import "mod_screen"
import "mod_key"

Process Main()
Private
    int map;
Begin

    // Create a new graph of size 100x100 and color depth of 8bit
    map = map_new(100,100,8);

    // Clear the map red
    map_clear(0,map,rgb(255,0,0));

    // Put it in the center of the screen
    put(0,map,160,100);

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [map_new](), [map_clear](), [key]()

This will result in something like:\


Quicksort()

Definition

INT quicksort ( <VOID POINTER array> , <INT elementsize> , <INT elements> , <INT dataoffset> , <BYTE datasize> , <BYTE datatype> )

Sorts an [array] by the Quicksort ordering algorithm.

This function is very handy for user defined [types] for elements in which a sort-[variable] is present. For simple arrays or arrays in which the first variable is the sort-variable, [sort]() can be used. For arrays in which the sort-variable is a String, [ksort]() can be used.

Parameters


VOID POINTER array - [Pointer] to be sorted. INT elementsize - The size of an element in the array in bytes. INT elements - The number of elements in the array. INT dataoffset - The number of [bytes] in each element is relative to the start of that element. BYTE datasize - The size of the sort-variable in bytes. BYTE datatype - The datatype of the sort-variable. (0:[integer])


Returns

INT: [true]

Example

Program sorting;

Type _player
    String name;
    int score;
End

Const
    maxplayers = 5;
Global
    _player player[maxplayers-1];
Begin

    // Insert some values
    player[0].name = "That one bad looking dude";
    player[1].name = "Ah pretty lame guy";
    player[2].name = "Some cool dude";
    player[3].name = "OMG ZOMG guy";
    player[4].name = "This person is ok";

    player[0].score = 70;
    player[1].score = 30;
    player[2].score = 80;
    player[3].score = 90;
    player[4].score = 50;

    // Show array
    say("-------------------- unsorted");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

/* Sort by name ( quicksort() can't be used to sort Strings,
   as a String in Fenix is a pointer to the actual String,
   so it would sort the pointer addresses */

    // sort()
    sort(player); // sorts by name because name is the first variable in each element

    // Show array
    say("-------------------- name - sort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

    // ksort()
    ksort(player,player[0].name,maxplayers);

    // Show array
    say("-------------------- name - ksort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

/* Sort by score (sort() cannot be used here, because score is not the first variable) */

    // ksort()
    ksort(player,player[0].score,maxplayers);

    // Show array
    say("-------------------- score - ksort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

    // quicksort()
    quicksort(&player[0],sizeof(_player),maxplayers,sizeof(String),sizeof(int),0);

    // Show array
    say("-------------------- score - quicksort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

    // Wait until ESC is pressed
    Repeat
         frame;
    Until(key(_esc))

End

Used in example: [say](), [ksort](), [type], [pointer]


Rand()

Definition

INT rand ( <INT lowerlimit> , <INT upperlimit> )

Returns a random number, ranging from a certain lower limit to a certain upper limit. The limits are within the range.

Make sure the difference between lowerlimit and upperlimit does not exceed 32767 (2\^15-1). If that is needed, the function rand2() below can be used.

Parameters


INT lowerlimit - The lower limit for the random value. INT upperlimit - The upper limit for the random value.


Returns

INT : A random value: lowerlimit <= result <= upperlimit

Notes

To synchronize rand() on different computers, the function [rand_seed]() can be used.

Rand() is not a very good function on itself. To counter this, the following rand2() can be used:

#define RAND_MAX 32767
#define DRAND_RANGE (1.0/((RAND_MAX + 1)*(RAND_MAX + 1)))
#define irand(x) ((unsigned int) ((x) * drand ()))
Function float drand ()
Private
    float f;
Begin
    Repeat
       f = (rand (0,RAND_MAX) * (RAND_MAX + 1.0)
          + rand (0,RAND_MAX)) * DRAND_RANGE;
    Until (f < 1); /* Round off */
    return f;
End
Function int rand2(int lowerlimit, int upperlimit)
Begin
    return (lowerlimit+irand(upperlimit-lowerlimit+1));
End

To understand this code, one can read its source.


Rand_seed()

Definition

INT rand_seed ( <INT seed> )

Seeds the random generator, used in [rand]().

This is useful for synchronizing the random generator on multiple machines, as when the same seed is used, calls to [rand]() with the same limits will return values in the same order on all the machines.

To reset the seeding to its original state, meaning the state before any call to [rand]() or [rand_seed](), set seed to 1.

Parameters


INT seed - The seed for the random generator used in [rand](); 1 to reset.


Returns

INT : [true]

Example

import "mod_rand"
import "mod_say"
import "mod_time"

Process Main()
Begin
    say("First number: " + (rand(0,1000)%100));
    rand_seed(time());
    say("Random number: " + (rand(0,1000)%100));
    rand_seed(1);
    say("Again the first number: " + (rand(0,1000)%100));
End

Used in example: [say](), [rand_seed]()


Realloc()

Syntax

VOID POINTER realloc ( <VOID POINTER data> , <INT size> )

Description

Resizes the given block of memory.

It allocates a new block of memory, copying the old data. If the new size is smaller than the old size, the last part of the data is lost. If the new size of the block of memory requires movement of the block, the old memory block is freed.

Also called [mem_realloc]().

Parameters


VOID POINTER data - Pointer to the block of memory to be resized. INT size - The new size of the block of memory in bytes.


Returns

VOID POINTER : Pointer to (the first element of) the newly allocated memory block.


[NULL] - There was are an error allocating the memory, like insufficient memory available. ![NULL] - Pointer to (the first element of) the newly allocated memory block.


Example

import "mod_mem"
import "mod_say"

Process Main()
Private
    byte pointer pbyte;
    byte pointer pbyte2;
    int elements = 10;
    int newelements = 15;
    int i;
Begin

    // Allocate memory
    pbyte = alloc(elements);

    // Set them to 13
    memset(pbyte,13,elements);

    // Relocate it to a larger, newly made memory block
    pbyte2 = realloc(pbyte,newelements);

    // Set the added part's elements to 16 (newelements > elements)
    memset(pbyte+elements,16,newelements-elements);

    // Show numbers
    for(i=0; i<newelements; i++)
        say("byte2["+i+"] = " + pbyte2[i]);
    end

OnExit

    // Free the used memory
    free(pbyte2);

End

Example 2

// Alloc, calloc and realloc tutorial, by handsource-dyko.

// This sample program demonstrates how create integer array's with alloc, and calloc, 
// and how to resize them with realloc. 

// Some general remarks with manual memory managment, ALWAYS free data after use, and test if an
// allocation was successfull with IF (p_test_array2==NULL). When one of these memory allocation
// functions returns a NULL, the allocation was NOT sucessfull, and any kind of unpredicatable things
// can happen. With manual memory managment, you'll have to really know what you're doing, as the slightest
// mistake can cause crashes and unpredicatable behaviour, wich is one of the dangers with using pointers.

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_mem";

 /*
    alloc(int size);
    returns: void pointer
    purpose: create a block of memory, of a certain size, the returned pointer indicates the start adress of this block.
*/

/*
    calloc(int size,type);
    returns: void pointer
    purpose: create a block of memory, of a certain size, the returned pointer indicates the start adress of this block.
             is used for creating arrays.
*/

/*

   realloc (void pointer data, int size);
   returns: void pointer
   purpose: resizes the given block of memory, it allocates a new block of memory, copying the old data. 
            if the new size is smaller than the old size, the last part of the data is lost. 
            if the new size of the block of memory requires movement of the block, the old memory block is freed. 

*/

GLOBAL

int pointer p_first_array;  // 10 elments, created with alloc()
int pointer p_third_array;  // 10 elments, created with calloc()
int pointer p_second_array; // resized copy of p_first_array, 15 elements, created with realloc()
int pointer p_fourth_array; // resized copy of p_second_array, 15 elements, created with realloc()

int test[9];                // simple array with 10 elements
int pointer p_test_array;   // will be used for storing the pointer to test[0]
int pointer p_test_array2;  // will be the resized array, created with realloc, is now 15 elements

int elements=10;            // initial array size
int new_elements=15;        // new array size

int count;                  // general purpose loop counter

PROCESS main();

BEGIN

    // standard array
    say("");
    say("");
    // print the array
    FOR (count=0; count<elements; count+=1)
        say("test["+count+"]="+test[count]);
    END

    say("");
    say("");
    say("the size of the array 'test' is "+sizeof(test)+" bytes");  
    say("");
    say("");

    // Allocate memory (10 integers), this way we create an array of integers from (0-9, so 10 elements)
    // The alloc() function works with bytes. It is always good practice to use the sizeof() operator, because
    // you'd have to know exactly how many bytes make up a particulair data. An integer is 4 bytes in bennu,
    // so for an array of 10 elements, you need to allocate 40 bytes. If you do "alloc(elements)",like in the
    // wiki, you only get 10 bytes! so that is totally too small for you array! always use this syntax:
    // 
    // alloc(sizeof(<data_type>)), or for arrays: alloc(elements*sizeof(<data_type>)). Note that <data_type> can 
    // also be a user-defined type.

    p_first_array=alloc(elements*sizeof(int));
    //p_first_array=calloc(elements,sizeof(int));

    // check if the allocation succeeded
    IF (p_first_array==NULL)
       // allocation failed
       say("allocation failed!! p_first_array="+p_first_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_first_array ,0,elements);

       say("");
       say("");
       // print the array
       FOR (count=0; count<elements; count+=1)
           say("p_first_array["+count+"]="+p_first_array[count]);
       END

       say("");
       say("");
       say("the size of the array is "+(elements*sizeof(int))+" bytes");  
       say("");
       say("");
    END

    // Now let's use calloc to create the same array, but calloc is a bit smarter. It's more suited to array's and
    // it even initializes all the data to 0 for you, so that you can omit the memset() function. In this case I 
    // kept memseti() in there, but you can omit it when using calloc(). But with alloc() you need to use it!

    // Note the small difference between alloc() and calloc().

    //p_second_array=alloc(elements*sizeof(int));
    p_second_array=calloc(elements,sizeof(int));

    // check if the allocation succeeded
    IF (p_second_array==NULL)
       // allocation failed
       say("allocation failed!! p_second_array="+p_second_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_second_array ,0,elements);

       say("");
       say("");
       // print the array
       FOR (count=0; count<elements; count+=1)
           say("p_second_array["+count+"]="+p_second_array[count]);
       END

       say("");
       say("");
       say("the size of the array is "+(elements*sizeof(int))+" bytes");
       say("");
       say("");
    END   

    // Let's resize p_first_array to a bigger size (15). This is where realloc() is used for. Also, just as with
    // alloc(), it is important to remember that it works with bytes! So we use this (new_elements*sizeof(int)) again.
    p_third_array=realloc(p_first_array,(new_elements*sizeof(int)));

    // check if the allocation succeeded
    IF (p_third_array==NULL)
       // allocation failed
       say("allocation failed!! p_third_array="+p_third_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_third_array ,0,new_elements);

       say("");
       say("");
       // print the array
       FOR (count=0; count<new_elements; count+=1)
           say("p_third_array["+count+"]="+p_third_array[count]);
       END

       say("");
       say("");
       say("the size of the array is "+(new_elements*sizeof(int))+" bytes");  
       say("");
       say("");
    END

    // Let's resize p_second_array to a bigger size (15).
    p_fourth_array=realloc(p_second_array,(new_elements*sizeof(int)));

    // check if the allocation succeeded
    IF (p_fourth_array==NULL)
       // allocation failed
       say("allocation failed!! p_fourth_array="+p_fourth_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_fourth_array ,0,new_elements);

       say("");
       say("");

       // print the array

       FOR (count=0; count<new_elements; count+=1)
           say("p_fourth_array["+count+"]="+p_fourth_array[count]);
       END

       say("");
       say("the size of the array is "+(new_elements*sizeof(int))+" bytes");  
       say("");
       say("");
    END

    // Let's try to resize an standard array (the array test[9]) to 15 
    p_test_array=test[0];   // <-- p_test_array is a pointer, we store the ADRESS of the first element (wich is 0) in it.
                            // test[0] is actually a pointer itself, it represents the start adress of the array.
                            // The whole concept of array indexing is actuallty a concealed form of pointer artihmatic,
                            // consult any good C book about the details of this. 
    p_test_array2=realloc(p_test_array,(new_elements*sizeof(int)));

    // check if the allocation succeeded
    IF (p_test_array2==NULL)
       // allocation failed
       say("allocation failed!! p_test_array2="+p_test_array2);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_test_array2 ,0,new_elements);

       say("");
       say("");

       // print the array

       FOR (count=0; count<new_elements; count+=1)
           say("p_test_array2["+count+"]="+p_test_array2[count]);
       END

       say("");
       say("the size of the array is "+(new_elements*sizeof(int))+" bytes");  
       say("");
       say("");
    END

ONEXIT

   // Free the used memory
   say("freeing old memory........");
   say("p_first_array...");
   free(p_first_array);
   say("ok");
   say("p_second_array...");
   free(p_second_array);
   say("ok"); 
   say("p_third_array...");
   free(p_third_array);
   say("ok");
   say("p_fourth_array...");
   free(p_fourth_array);
   say("ok");  
   say("p_test_array...");
   free(p_test_array);
   say("ok"); 
   say("p_test_array2...");
   free(p_test_array2);
   say("ok");

END

Used in example: [alloc](), [memset](), [say](), [pointer]


Regex()

Syntax

INT regex ( <STRING pattern> , <STRING string> )

Description

Match a regular expresion to the given string. Regular expressions are very powerfull, and allow to do complex pattern searches in texts. You can read about the wealth of posibilities here. Please note that regular expresion synthax is quite cryptic and difficult in general. Some things can be achieved in easier way with string functions like [Find](), [Substr](). It is unknown to wich extend bennu supports certain expressions.

Matches are stored into the predefined global array [Regex_reg].

Parameters


STRING pattern - The desired search pattern. STRING string - The string to search in.


Returns

INT : status/match position


>0 - The character position where the match has been found. -1 - There is no match found.


Example

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_regex";

GLOBAL

   string sourcetext="It's raining cat's and dogs";
   string searchtext="cat"; // the search pattern

   int status;

PROCESS main();

BEGIN

   // print the joined string
   say("");

   // looking for the position of the word "cat"
   status=regex(searchtext,sourcetext);

   say("match found at: "+status);
   say("");

   // the last character of a line. 
   status=regex("$","99 bottles of beer on the wall.");

   say(status+" is the last character position in 99 bottles of beer on the wall.");
   say("");
END

This program will print as result:

match found at: 13

31 is the last character position in 99 bottles of beer on the wall.

Used in example: [say]() See also: regular expresion examples


Regex_replace()

Syntax

STRING regex_replace ( <STRING pattern> , <STRING string> , <STRING replacement> )

Description

Match a regular expresion to the given string. For each match, substitute it with the given replacement. \0 - \9 escape sequences are accepted in the replacement. Regular expressions are very powerfull, and allow to do complex pattern searches in texts. You can read about the wealth of posibilities here.

Matches are stored into the predefined global array [Regex_reg].

Parameters


STRING pattern - The desired search pattern (i.e. the word or pattern that should change). STRING string - The string with the replacement pattern. STRING replacement - The replacement string (this is the source string), see example


Returns

STRING : the resulting replacement string.

Example

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_regex";

GLOBAL

   string sourcetext="It's raining cat's and dogs."; // the orginal sentence
   string searchtext="cat";                          // the search string
   string replacetext="bird";                        // the replacement string

   string replace_result;

   int result;

PROCESS main();

BEGIN

   // first, look for "cat".
   result=regex(searchtext,sourcetext);
   say("");
   say(searchtext+" found at position: "+result);

   say("");
   say("orginal text: "+sourcetext);

   // replace "cat" with "bird".
   replace_result=regex_replace(searchtext,replacetext,sourcetext);
   say("");
   say("replace_result: "+replace_result);

END

This program will print as result:

cat found at position: 13

orginal text: It's raining cat's and dogs.

replace_result: It's raining bird's and dogs

In this example one word was replaced, but it's possible to do more advanced matching patterns, similair to what most text editors do.

Used in example: [regex]() See also: regular expresion examples


Region_define()

Definition

INT region_define ( <INT regionID> , <INT x> , <INT y> , <INT width> , <INT height> )

Defines the boundaries of a [region].

There are 32 regions, range 0..31. Region 0 is always the whole screen and cannot be changed. Defining regions can be useful for the function [out_region](), the [local variable] and using them with [scrolls].

Also called [define_region]().

Parameters


INT regionID - The [regionID] of the region to define. INT x - The x coordinate of the top left corner of the region. INT y - The y coordinate of the top left corner of the region. INT width - The width of the region. INT height - The height of the region.


Returns

INT : The [regionID] specified.


Region_out()

Definition

INT out_region ( <INT processID> , <INT regionID> )

Checks if the specified [process] is completely outside of the specified [region].

The check is not pixel perfect, but uses the [bounding box] of the process.

Also called [out_region]().

Parameters


INT processID - The [processID] of the process to check. INT regionID - The [regionID] of the region to check with.


Returns

INT : [true]: whether the process is completely outside the region.


[true] - The process is completely outside the region. [false] - The process is (partly) inside the region or invalid region or process specified.



Reserve_channels()

Definition

INT reserve_channels ( <INT num_channels> )

This functions reserves the indicated number of [sound channels] from the default sound mixing setup. This is usefull if you want to create groups of sound channels, so that you can devide them for different tasks. When you indicate a 0, all reservations are removed. The channels are reserved starting from channel 0 to num_channels -1. Normally SDL_mixer starts without any channels reserved.

Parameters


INT num_channels - The number of channels to reserve.


Returns

INT : Status.


>0 - The number of reserved channels. -1 - Error: sound inactive.



Resume_song()

Definition

INT resume_song ( )

Resumes a song, after it has been paused with the function [pause_song]().

Returns

INT : Error.


-1 - Error: sound inactive. 0 - No error.


Notes

The song will instantly start playing again with this function. For a nicer effect, you may want to fade the music in as you resume it. See [fade_music_in]().

Example

program music_example;
global
    my_song;
    playing;
    paused;
    faded_in;
    v;
begin
    set_mode(640,480,16);

    my_song=load_song("beat.ogg");

    write(0,320,30,4,"Use the keyboard to control the music playback.");
    write(0,320,50,4,"Key [ENTER] starts / stops the song.");
    write(0,320,60,4,"Key [SPACE] pauses / resumes the song.");
    write(0,320,70,4,"Key [0] through key [9] changes the song volume.");
    write(0,320,80,4,"Key [F] fades the song in or out.");

    write(0,320,120,5,"Playing: ");
    write_int(0,320,120,3,&playing);

    write(0,320,140,5,"Paused: ");
    write_int(0,320,140,3,&paused);

    write(0,320,160,5,"Faded in: ");
    write_int(0,320,160,3,&faded_in);

    write(0,320,180,5,"Volume: ");
    write_int(0,320,180,3,&v);

    v=128;
    faded_in=true;

    repeat
        if(key(_enter))
            if(is_playing_song())
                stop_song();
                playing=false;
            else
                play_song(my_song,1);
                playing=true;
            end
            while(key(_enter))frame;end
        end

        if(key(_space))
            if(paused)
                paused=false;
                resume_song();
            else
                paused=true;
                pause_song();
            end
            while(key(_space))frame;end
        end

        if(key(_f))
            if(faded_in)
                faded_in=false;
                fade_music_off(100);
            else
                faded_in=true;
                fade_music_in(my_song,1,100);
            end
            while(key(_f))frame;end
        end

        if(key(_0))v=0;end
        if(key(_1))v=14;end
        if(key(_2))v=28;end
        if(key(_3))v=43;end
        if(key(_4))v=57;end
        if(key(_5))v=71;end
        if(key(_6))v=85;end
        if(key(_7))v=100;end
        if(key(_8))v=114;end
        if(key(_9))v=128;end

        set_song_volume(v);

    frame;
    until(key(_esc))

    exit();
end

Used in example: [key](), [set_mode](), [load_song](), [write_int](), [pause_song](), [play_song](), [stop_song](), [resume_song](), [fade_music_in](), [fade_music_off](), [set_song_volume]().


Resume_wav()

Definition

INT resume_wav (INT < channel > )

Resumes the currently paused wave channel, that was paused by [Pause_wav]().

Parameters


INT channel - The WAV [sound channel].


Returns

INT : Error.


-1 - Error: sound inactive. 0 - No error.


Example

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_proc";
IMPORT "mod_key";
IMPORT "mod_sound";

GLOBAL
   int wav;
   int channel;

PROCESS main();  
BEGIN

  wav=load_wav("wav.wav");

  say("Test pause_wav...");
  say("ENTER = Pause Sound...");
  say("Press ESC to quit...");

  channel=play_wav(wav,-1);

  REPEAT

    IF(key(_enter))
      pause_wav(channel);
      FRAME(2500);
      resume_wav(channel);
    END

    FRAME;
  UNTIL(key(_esc))
END

Used in example: [key](), [pause_wav](), [play_wav]().


Reverse_stereo()

Definition

INT reverse_stero ( <INT channel> , <INT flip>)

This function swaps the stereo of the indicated [sound channel].

Parameters


INT channels - The channel of wich it's stereo is to be reversed. INT flip - The flip, (0 = normal , 1 = reverse).


Returns

INT : Status.


0 - Ok. -1 - There is an error.



Rgb()

Syntax

DWORD rgb ( <BYTE red> , <BYTE green> , <BYTE blue> , [<INT depth>] )

Description

Finds the single [color] in the current color mode closest to the combined red, green, and blue values specified. In 32bit mode, the alpha is set to 255.

Equal to [[rgba]](''red'',''green'',''blue'',255)

Parameters


BYTE red - Level of red in the desired color from 0 to 255. BYTE green - Level of green in the desired color from 0 to 255. BYTE blue - Level of blue in the desired color from 0 to 255. INT depth - Depth (optional paramter that may be omitted, only in 16 and 32 bit mode). When this parameter is used, the function returns the correct color code for the indicated depth.


Returns

DWORD : Returns the best matched color code.

Notes

Different color depths have different color codes, this is why rgb() is useful: it returns the appropriate code, based on the current color depth. When in 8bit mode, this code is 0..255 and when in 16bit mode 0..65535. In 32bit mode the code is 0xRRGGBBAA, two letters meaning one byte.

Using this function in different color depths can be tricky. This is because rgb() will return a different color code under different color depths. For example, when at 8bit, we do:

my_color = rgb(100,100,100);

my_color will most likely have the value 6 at this time. Suppose we change the color depth to 16bit now, using [set_mode](). Now, my_color holds a totally different color than before, as 6 is nowhere near rgb(100,100,100) in 16bit mode. To counter this effect, my_color needs to be reinitialized:

my_color = rgb(100,100,100);

The same code, but rgb() now returns the proper code, as it always returns the code belonging to the current color depth. my_color will now be about 25388.

Example

import "mod_map"
import "mod_text"
import "mod_key"
import "mod_wm"

Process Main()
Private
    byte red=0;
    byte green=255;
    byte blue=0;
Begin

    set_text_color(rgb(red,green,blue)); // rgb finds the color closest to pure green and
                                         // passes it to set_text_color

    write(0,1,1,0,"Green text for everybody!"); //this text will be green

    Repeat
        frame;
    Until(key(_ESC)||exit_status)

End

Used in example: [set_text_color](), [rgb](), [key]


Rgb_get()

Syntax

INT rgb_get ( <INT pixel_color > , <POINTER red> , <POINTER green> , <POINTER blue> , [<INT depth>] )

Description

Get access to the memory sections of the color components, these can be accessed with the [Offset] operator.

The previous [get_rgb]() is deprecated.

Parameters


INT pixel_color - The color value of a pixel . POINTER red - Pointer to the level of red in the desired color from 0 to 255. POINTER green - Pointer to the level of green in the desired color from 0 to 255. POINTER blue - Pointer to the level of blue in the desired color from 0 to 255. INT depth - Depth (optional paramter that may be omitted, only in 16 and 32 bit mode). When this parameter is used, the function returns the correct color code for the indicated depth.


Returns

1 : This function always returns a 1.

Notes

The color value's have to be obtained with the [Offset] operator, and the pixel color value can be obtained with [Map_get_pixel]().

Example

IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_key";
IMPORT "mod_map";
IMPORT "mod_video";
IMPORT "mod_wm";
IMPORT "mod_draw";
IMPORT "mod_screen";
IMPORT "mod_mem";
IMPORT "mod_text";

GLOBAL

   int map_id;    // id code of the map to load

   int status;    // status for debugging

   // color components
   int my_r;      
   int my_g;
   int my_b; 

PROCESS main();

BEGIN

   set_mode(320,200,32);

   // load the map
   map_id=load_map("3COCHE.MAP");

   // first, we're going to check the r,g,b values of 5 pixels, with the optional
   // depth parameter.
   status=get_rgb(map_get_pixel(0,map_id,0,0), &my_r, &my_g, &my_b ,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b);  
   say("status: "+status);

   status=get_rgb(map_get_pixel(0,map_id,4,0), &my_r, &my_g, &my_b ,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b);  
   say("status: "+status);

   status=get_rgb(map_get_pixel(0,map_id,50,1), &my_r, &my_g, &my_b ,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b);  
   say("status: "+status);

   status=get_rgb(map_get_pixel(0,map_id,13,24), &my_r, &my_g, &my_b, 32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b);  
   say("status: "+status);

   status=get_rgb(map_get_pixel(0,map_id,84,40), &my_r, &my_g, &my_b, 32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b);  
   say("status: "+status);

   // second, we use the simpler way, that is valid for a bit maps
   say("");
   say("8 bit color codes");
   say(map_get_pixel(0,map_id,0,0));
   say(map_get_pixel(0,map_id,4,0));
   say(map_get_pixel(0,map_id,50,1));
   say(map_get_pixel(0,map_id,13,24));
   say(map_get_pixel(0,map_id,84,40));

   LOOP
      IF (key(_esc))
         BREAK;
      END

      FRAME;
   END
END

See also

The articles about the functions, [Rgb]() and [Rgba]() for more information, since this function is related to some extend.


Rgba()

Syntax

DWORD rgba ( <BYTE red> , <BYTE green> , <BYTE blue>, <BYTE alpha> , [<INT depth>] )

Description

Finds the single [color] in the current color mode closest to the combined red, green, blue and alpha values specified. This function is useful in 32 bpp modes.

Parameters


BYTE red - Level of red in the desired color from 0 to 255. BYTE green - Level of green in the desired color from 0 to 255. BYTE blue - Level of blue in the desired color from 0 to 255. BYTE alpha - Level of alpha in the desired color from 0 to 255, 0 being completely transparent and 255 completely opaque. INT depth - Optional parameter, wich may be omitted. Only usefull in 16 and 32 bit modes, ensures that the function returns a colorcode that is valid for the specified mode.


Returns

DWORD : Returns the best matched color code.

Notes

Different color depths have different color codes, this is why rgba() is useful: it returns the appropriate code, based on the current color depth. When in 8bit mode, this code is 0..255 and when in 16bit mode 0..65535. In 32bit mode the code is 0xRRGGBBAA, two letters meaning one byte.

Using this function in different color depths can be tricky. This is because rgba() will return a different color code under different color depths. For example, when at 8bit, we do:

my_color = rgba(100,100,100,255);

my_color will most likely have the value 6 at this time. Suppose we change the color depth to 16bit now, using [set_mode](). Now, my_color holds a totally different color value than before, as 6 is nowhere near rgba(100,100,100,255) in 16bit mode. To counter this effect, my_color needs to be reinitialized:

my_color = rgba(100,100,100,255);

The same code, but rgba() now returns the proper code, as it always returns the code belonging to the current color depth. my_color will now be about 25388.

Example

import "mod_text"
import "mod_map"
import "mod_key"
import "mod_video"
import "mod_wm"

Const
    SCREEN_WIDTH  = 320;
    SCREEN_HEIGHT = 200;
    SCREEN_DEPTH  = 16;
End

Process Main()
Private
    int r=0;
    int g=255;
    int b=0;
    int a=0;
    int da=10;
Begin

    set_mode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_DEPTH);

    graph = map_new(100,100,SCREEN_DEPTH);
    map_clear(0,graph,rgba(r,g,b,a));

    x = y = 100;

    Repeat
        a += da;
        if(a<0)
            da = -da;
            a = 0;
        elseif(a>255)
            da = -da;
            a = 255;
        end
        map_clear(0,graph,rgba(r,g,b,a));
        frame;
    Until(key(_ESC)||exit_status)

End

Used in example: [set_mode](), [map_new](), [key](), [graph]


Rgba_get()

Syntax

DWORD rgba_get ( <INT pixel_color > , <POINTER red> , <POINTER green> , <POINTER blue> , <POINTER alpha> , [<INT depth>] )

Description

Get access to the memory sections of the color components, these can be accessed with the [Offset] operator.

The previous name [Get_rgba]() is deprecated.

Parameters


INT pixel_color - The color value of a pixel . POINTER red - Pointer to the level of red in the desired color from 0 to 255. POINTER green - Pointer to the level of green in the desired color from 0 to 255. POINTER blue - Pointer to the level of blue in the desired color from 0 to 255. POINTER alpha - Pointer to the alpha channel in the from 0 to 255. INT depth - Depth (optional paramter that may be omitted, only in 16 and 32 bit mode). When this parameter is used, the function returns the correct color code for the indicated depth.


Returns

1 : This function always returns a 1.

Notes

The color value's have to be obtained with the [Offset] operator, and the pixel color value can be obtained with [Map_get_pixel]().

Example

IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_key";
IMPORT "mod_map";
IMPORT "mod_video";
IMPORT "mod_wm";
IMPORT "mod_draw";
IMPORT "mod_screen";
IMPORT "mod_mem";
IMPORT "mod_text";

GLOBAL

   int map_id;    // id code of the map to load

   int status;    // status for debugging

   // color components
   int my_r;      
   int my_g;
   int my_b; 
   int my_a;

PROCESS main();

BEGIN

   set_mode(320,200,32);

   // load the map
   map_id=load_map("3COCHE.MAP");

   // first, we're going to check the r,g,b,a values of 5 pixels, with the optional
   // depth parameter.
   status=get_rgba(map_get_pixel(0,map_id,0,0), &my_r, &my_g, &my_b, &my_a,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b+" my_a: "+my_a);  
   say("status: "+status);

   status=get_rgba(map_get_pixel(0,map_id,4,0), &my_r, &my_g, &my_b, &my_a,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b+" my_a: "+my_a);  
   say("status: "+status);

   status=get_rgba(map_get_pixel(0,map_id,50,1), &my_r, &my_g, &my_b, &my_a,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b+" my_a: "+my_a);  
   say("status: "+status);

   status=get_rgba(map_get_pixel(0,map_id,13,24), &my_r, &my_g, &my_b, &my_a,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b+" my_a: "+my_a);  
   say("status: "+status);

   status=get_rgba(map_get_pixel(0,map_id,84,40), &my_r, &my_g, &my_b, &my_a,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b+" my_a: "+my_a);  
   say("status: "+status);

   // second, we use the simpler way, that is valid for a bit maps
   say("");
   say("8 bit color codes");
   say(map_get_pixel(0,map_id,0,0));
   say(map_get_pixel(0,map_id,4,0));
   say(map_get_pixel(0,map_id,50,1));
   say(map_get_pixel(0,map_id,13,24));
   say(map_get_pixel(0,map_id,84,40));

   LOOP
      IF (key(_esc))
         BREAK;
      END

      FRAME;
   END
END

See also

The articles about the functions, [Rgb]() and [Rgba]() for more information, since this function is related to some extend.


Rgbscale()

Definition

INT rgbscale ( <INT fileID> , <INT graphID> , <FLOAT r> , <FLOAT g> , <FLOAT b> )

This will convert the specified [graphic] by using the specified color as a reference. The converted graphic will have only the specified color and lighter/darker colors; see [notes] for the details.

Parameters


INT fileID - The [fileID] that holds the graphics. INT graphID - The [graphID] to convert. FLOAT r - The red component of the color to be used for reference. FLOAT g - The green component of the color to be used for reference. FLOAT b - The blue component of the color to be used for reference.


Returns

INT


-1 - Invalid graphic. 1 - Success.


Notes

The exact formula is:

for every pixel:
    c = 0.3 * oldpixel_r + 0.59 * oldpixel_g + 0.11 * oldpixel_b
    newpixel_r = r * c;
    newpixel_g = g * c;
    newpixel_b = b * c;

where r,g,b are the specified r,g,b.

Note that [[rgbscale]](0,map,1,1,1) = [[grayscale]](0,map,0), for a valid graphic (0,map).


Rm()

Definition

INT rm ( <STRING filename> )

Removes (deletes) the file specified with filename.

Parameters


STRING filename - The name of the file to be removed (deleted).


Returns

INT : Success


0 ([false]) - Removing the file with the specified name failed. !0 ([true]) - Removing the file with the specified name succeeded.



Rpad()

Definition

STRING rpad( <STRING str> , <INT length> )

Returns the string str, padding (adding spaces to) the back of the string if needed to make str of length length. The original string will remain unchanged.

If length is smaller or equal to the length of str, the returned string is str.

Parameters


STRING str - The string to pad (add spaces to). INT length - The minimal length of the returned string.


Returns

STRING: padded string

Example

import "mod_string"
import "mod_say"

Process Main()
Private
    string ABC = "ABC";
    string _ABC;
    string ABC__;
Begin

    ABC = lpad(ABC,2);
    _ABC = lpad(ABC,4);
    ABC__ = rpad(ABC,5);

    say('ABC = "' + ABC + '"');
    say('_ABC = "' + _ABC + '"');
    say('ABC__ = "' + ABC__ + '"');

End

Used in example: [say](), [rpad]()

Result:

ABC = "ABC"
_ABC = " ABC"
ABC__ = "ABC  "

Save()

Definition

INT save ( <STRING filename> , <VARSPACE data> )

Saves the data from the specified variable to the specified file.

Parameters


STRING filename - The name of the file that will be saved. VARSPACE data - The variable (of any [datatype]) that will be saved in a file.


Returns

INT : The number of bytes written to the file.

Notes

Attempting to use "?","*","<",">" or "|" in a filename will result in no file at all on Windows, while using ":" in a filename results in everything from the ":" and beyond being cut off from the file name and the resulting file will be of size 0.

Using the characters "/" or "\" in the filename (without directories that can be accessed that way) results in everything from this character and before being cut off from the filename. The file will be saved successfully nonetheless.

Example

Program test;
Global
    struct My_struct
        Level_number="99";
        string Map_name="Amazing map";
    End
Begin
        Save("myfile.sav",My_struct); // The content of My_struct is saved in myfile.sav
        Write(0,10,10,0,"Data saved!");

    While (!key(_ESC))
        Frame;
    End
End

Used in example: [save](), [key]()


Say()

Definition

INT say ( <STRING message> )

Prints message to stdout (console).

  • Similar to System.out.println(message) in Java.
  • Similar to printf("%s\n",message) in C

Parameters


STRING message - The message to print to stdout


Returns

INT - [true]

Example

import "mod_say"

Process Main()
Begin
    Say("Hello World!");
End

This will result in the output on console:

Hello World!

Say_fast()

Definition

INT say_fast ( <STRING message> )

Prints message to stdout (console). This function is the same as the [Say]() function, but with the difference that the debugging information isn't flushed (buffered) into the standard output. As you can see in the bennu source code mod_say.c, the difference is only 1 instruction, so it's slightly faster.

  • Similar to System.out.println(message) in Java.
  • Similar to printf("%s\n",message) in C

Parameters


STRING message - The message to print on to the console


Returns

INT - [true]

Example

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";

GLOBAL

int count;

PROCESS main();

BEGIN

   say("hello world.");
   say("");
   say("");
   FOR (count=0; count<5000; count+=1)
      say_fast("count: "+count);
   END
END

This will result in the output on console:

Hello World!

Screen_clear()

Definition

INT screen_clear ( )

Clears the [background] of the screen, making it completely black.

Also called [clear_screen]().

Returns

INT : [true]

Notes

This is the same as '''[[map_clear]]'''(0,[[BACKGROUND]]). When the background is cleared in either way, [Bennu] knows the background is empty and will take advantage of this knowledge.

Errors


Unsupported color depth - The specified graph has a not supported color depth.



Screen_get()

Definition

INT screen_get ( )

Creates a new [graphic] containing a copy of the lastly rendered frame.

The map will contain everything, including background, [processes] and [text](), the newly created graphic will be located in the [System file] of 0); the [graphID] will be returned. After the use of this graphic, it should be freed using [map_unload]().

Also called [get_screen]().

Returns

INT : [GraphID]


0 - Some error. >0 - The [GraphID] created.


Example

import "mod_key"
import "mod_screen"
import "mod_map"

Global
    int my_map;
End

Process Main()
Begin
    Repeat
        if(key(_F5))
            my_map = screen_get();
            png_save(0,my_map,"snapshot.PNG");
            map_unload(0,my_map);
            while(key(_F5)) frame; end
        end
        frame;
    Until(key(_ESC))
End

Used in example: [key](), [screen_get](), [png_save](), [map_unload]()


Screen_put()

Definition

INT screen_put ( <INT fileID> , <INT graphID> )

Clears and draws ([blits] onto the [background] in the center.

For more advanced blitting, see:

  • [put]()
  • [xput]()

Also called [put_screen]().

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to draw with.


Returns

INT


0 - Invalid map. 1 - Success.


Notes

The center of the specified graph influences its placement.

The following codes are equivalent:

screen_put(f,g);

screen_clear();
put(f,g,graphic_info(0,BACKGROUND,G_WIDTH)/2,graphic_info(0,BACKGROUND,G_HEIGHT)/2);

See [screen_clear]() and [map_info]().

Errors


Invalid map - The specified map is invalid. Unsupported color depth - The origin graph's color depth is greater than the destination graph's.



Set_Wav_Volume()

Syntax

INT set_wav_volume ( <INT waveID> , <INT volume> )

Description

Change the reproduction volume of the wav track.

With this function, it is possible to set the volume of the sound effects, etc.

Parameters


INT waveID - [waveID](). INT volume - New volume. (0..128)


Returns

(assumed) INT : Error.


-1 - Error: sound inactive. 0 - No error.


Notes

This function changes the reproduction volume of the wav track. The volume level can be set between 0 (silence) and 128 (original 100% volume of the track. The default volume is 128.

Example

global
    int my_wav;
    int v;
end

process main()
begin

    set_mode(640,480,16);

    my_wav = load_wav("beat.wav");

    write(0,320,30,4,"Use the keyboard to control the music playback.");
    write(0,320,50,4,"Key [ENTER] starts the wav.");
    write(0,320,60,4,"Key [0] through key [9] changes the song volume.");

    write(0,320,180,5,"Volume: ");
    write_int(0,320,180,3,&v);

    v = 128;

    repeat
        if(key(_ENTER))
            play_wav(my_wav,50);
            while(key(_ENTER))
                frame;
            end
        end

        if(key(_0)) v =   0; end
        if(key(_1)) v =  14; end
        if(key(_2)) v =  28; end
        if(key(_3)) v =  43; end
        if(key(_4)) v =  57; end
        if(key(_5)) v =  71; end
        if(key(_6)) v =  85; end
        if(key(_7)) v = 100; end
        if(key(_8)) v = 114; end
        if(key(_9)) v = 128; end

        set_wav_volume(v);

        frame;
    until(key(_ESC))

end

Used in example: [key](), [set_mode](), [write](), [play_wav]().

This example uses media: [beat.wav]


Set_channel_volume()

Definition

INT set_channel_volume ( <INT channel> , <INT volume> )

Change the reproduction volume of the wave [sound channel]. With this function, it is possible to set the channels to different volumes.

Parameters


INT channel - The [sound channel]. INT volume - New volume. (0..128).


Returns

INT : Error.


-1 - Error: sound inactive. 0 - No error.


Notes

This function changes the reproduction volume of the sound channel. The volume level can be set between 0 (silence) and 128 (original 100% volume of the track. The default volume is 128.


Set_distance()

Definition

INT set_distance ( <INT channel> , <INT distance> )

Set the "distance" of a [sound channel]. the distance specifies the location of the sound in relation to the listener. If you want also want to have control over the angle, see [Set_position]().

Parameters


INT channel - The [sound channel] to change the position of. INT distance - The distance (0-255).


Returns

INT : Status.


0 - Ok. -1 - Error: sound inactive.


Notes

Distance value's


0 - The sound is near (or at it's loudest). 255 - The sound is far away (very quite).



Set_fps()

Definition

INT set_fps ( <INT fps> , <INT skip> )

Sets the frames per second ([framerate]) your program aims to display. The more frames per second, the faster your program runs. Some computers might not be able to display the amount of frames you specified, and will show a lower fps. Therefore, it is important you choose a fps that is reasonable and can also be displayed by the somewhat slower computers. If you don't use this function then the default fps will be used (25 fps).

Parameters


INT fps - Frames per second to use. The default is 25. INT skip - Frames the program is allowed to skip to keep up with the specified framerate if it's running low on processor time. The default is 0.


Returns

INT : The FPS entered.

Notes

If you use Set_fps(0,0), then your program will run at the maximum speed your computer can possibly handle.

The current FPS can be read from the [global variable].

Errors

None.

Example

Program test;
Begin
    Set_fps(60,0);
    Loop
        Frame;
    End
End

Set_icon()

Definition

INT set_icon ( <INT fileID> , <INT graphID> )

Set the window icon to a certain graph.

The icon will only be updated after [set_mode]() is called, so call set_icon() before set_mode(). The map used for the icon must be 32x32 large, but it can have different depths. After set_icon() and set_mode() have been called, the map used for the icon can be freed from memory using [unload_map]().

Parameters


INT fileID - The fileID of the [file]. INT graphID - The graphID of the graph to be used as an icon.


Returns

INT : [true]

Example

import "mod_key"
import "mod_map"
import "mod_wm"
import "mod_video"

Const
    screen_width  = 320;
    screen_height = 200;
    screen_depth  =  16;
End

Process Main()
Private
    int map;
    int iconsize      =  32;
Begin

    set_mode(screen_width,screen_height,screen_depth);

    map = new_map(iconsize,iconsize,screen_depth);
    map_clear(0,map,rgb(0,255,255));

    set_title("<-- Look at the cyan block!");
    set_icon(0,map);

    unload_map(0,map);

    Repeat
        frame;
    Until(key(_ESC)||exit_status)

End

Used in example: [set_mode](), [new_map](), [rgb](), [set_icon](), [unload_map](), [exit_status]


Set_mode()

Syntax

INT set_mode ( <INT width> , <INT height> , [<INT depth>] , [<INT flags>] )

Description

Sets the screen resolution of your program, and optionally the colordepth of the screen and any [render flags] for extra options. If this command is not used, the default settings will take effect (320x240 at 32 bpp).

Some much used resolutions are: 320x240, 640x480, 800x600, 1024x768 and 1280x1024.

Parameters


INT width - Width of the screen in [pixels]. INT height - Height of the screen in [pixels]. INT [depth] - [Color depth]. INT [flags] - Mode of rendering. See [render flags].


Returns


INT : -1: error, setting the mode has failed INT : 0: sucess

INT : [true] (in versions prior rc282)

Notes

Any fpg files you load must have the same or a lower colordepth as you set for the screen.

Uncommon resolutions can also be used, for example 399x10, which will be the actual size of the window if you run in windowed mode. At full screen black edges might appear.

There is another method of calling set_mode(): with one parameter. In this parameter you must use the 4 right digits for the height and the rest fot the width. For example to set a 320x200 mode you can use set_mode(3200200). The maximum height that allow this method is 9999 pixels. This method is deprecated and its use is disadvised.

Example

import "mod_video"
import "mod_key"
import "mod_wm"

Process Main()
Begin
    set_mode(640,480,16);
    Repeat
        frame;
    Until(key(_ESC)||exit_status)

End

Used in example: [set_mode](), [key]


Set_music_position()

Definition

INT set_music_position ( <FLOAT position> )

Set the position of the currently playing music, loaded with [Load_song]() and played with [Play_song]() It only works with the formats supported by those functions. It does not apply to wave files.

Parameters


FLOAT position - Jumps to position seconds from the beginning of the song.


Returns

INT : Status.


position - The position in the music. -1 - Error: sound inactive.



Set_panning()

Definition

INT set_panning ( <INT channel> , <INT left> , <INT right> )

Sets the stereo panning of a [sound channel], i.e. set the volumes of the left and right speakers individually.

Parameters


INT channel - The [sound channel] to change the panning of. INT left - The volume of the left speaker (0-255). INT right - The volume of the right speaker (0-255).


Returns

INT : Status.


0 - Ok. -1 - Error: sound inactive.



Set_position()

Definition

INT set_position ( <INT channel> , <INT angle> , <INT distance> )

Sets the position of a [sound channel]. With this function you can "emulate" a simple 3d audio effect. If you only want to control the distance, you can use [Set_distance]().

Parameters


INT channel - The [sound channel] to change the position of. INT angle - The angle (0-360). INT distance - The distance (0-255).


Returns

INT : Status.


0 - Ok. -1 - Error: sound inactive.


Notes

Angle value's


0 degrees - Sound is directly in front. 90 degrees - Sound is directly to the right. 180 degrees - Sound is directly behind. 270 degrees - Sound is directly to the left.


Distance value's


0 - The sound is near (or at it's loudest). 255 - The sound is far away (very quite).



Set_song_volume()

Definition

INT set_song_volume ( <INT volume> )

Change the reproduction volume of the music track.

With this function, it is possible to set the background music to a different volume than the sound effects, etc.

Parameters


INT volume - New volume. (0..128).


Returns

INT : Error.


-1 - Error: sound inactive. 0 - No error.


Notes

This function changes the reproduction volume of the music track. The volume level can be set between 0 (silence) and 128 (original 100% volume of the track. The default volume is 128.

Example

program music_example;
global
    my_song;
    playing;
    paused;
    faded_in;
    v;
begin
    set_mode(640,480,16);

    my_song=load_song("beat.ogg");

    write(0,320,30,4,"Use the keyboard to control the music playback.");
    write(0,320,50,4,"Key [ENTER] starts / stops the song.");
    write(0,320,60,4,"Key [SPACE] pauses / resumes the song.");
    write(0,320,70,4,"Key [0] through key [9] changes the song volume.");
    write(0,320,80,4,"Key [F] fades the song in or out.");

    write(0,320,120,5,"Playing: ");
    write_int(0,320,120,3,&playing);

    write(0,320,140,5,"Paused: ");
    write_int(0,320,140,3,&paused);

    write(0,320,160,5,"Faded in: ");
    write_int(0,320,160,3,&faded_in);

    write(0,320,180,5,"Volume: ");
    write_int(0,320,180,3,&v);

    v=128;
    faded_in=true;

    repeat
        if(key(_enter))
            if(is_playing_song())
                stop_song();
                playing=false;
            else
                play_song(my_song,1);
                playing=true;
            end
            while(key(_enter))frame;end
        end

        if(key(_space))
            if(paused)
                paused=false;
                resume_song();
            else
                paused=true;
                pause_song();
            end
            while(key(_space))frame;end
        end

        if(key(_f))
            if(faded_in)
                faded_in=false;
                fade_music_off(100);
            else
                faded_in=true;
                fade_music_in(my_song,1,100);
            end
            while(key(_f))frame;end
        end

        if(key(_0))v=0;end
        if(key(_1))v=14;end
        if(key(_2))v=28;end
        if(key(_3))v=43;end
        if(key(_4))v=57;end
        if(key(_5))v=71;end
        if(key(_6))v=85;end
        if(key(_7))v=100;end
        if(key(_8))v=114;end
        if(key(_9))v=128;end

        set_song_volume(v);

    frame;
    until(key(_esc))

    exit();
end

Used in example: [key](), [set_mode](), [load_song](), [write_int](), [pause_song](), [play_song](), [stop_song](), [resume_song](), [fade_music_in](), [fade_music_off](), [set_song_volume]().


Set_text_color()

Definition

INT set_text_color ( [INT < textID>] , <WORD color> )

Sets the current text color (the color where texts will be written in). This only affects 1 bit (2 color) fonts, which can be loaded with [load_font]() or [load_bdf](). 8 bit and 16 bit fonts already contain color information themselves and thus aren't affected.

Parameters


INT textID - The identification code of the text (optional). WORD color - The [color] to use for text.


Returns

INT : [true] if successful and [false] if failed. (Needs confirmation.)

VOID: in version rc282 this function returns nothing.

Notes

Be warned that values returned by the [Rgb]() function differ with the video card. So, directly filling out color numbers as color parameter in 16 bit color mode without using [Rgb]() is a bad idea, as RGB returns the correct color code for every video card

The optional argument textID is fairly new. It is introduced in version rc282.

Errors

None.

Example

Program awesome;
Global
    byte red=0;
    byte green=255;
    byte blue=0;

Begin

    set_text_color(rgb(red,green,blue));
    write(0,1,1,0,"Mijn potlood is bruin"); //this text will be green as an Irishman's ejecta

    set_text_color(rgb(255,0,0));
    write(0,1,11,0,"Je moeder"); //this text will be red

    Loop

        frame;
    End
End

Used in example: [write]()

This results in something like this:\

Example 2

import "mod_text";
import "mod_mouse";
import "mod_key";
import "mod_video";
import "mod_rand";
import "mod_map";

private
    txt[10];
    counter;
    tz;
begin
    set_mode(640,480,32);

    txt[0]=write_int(0,10,10,10,0,&counter);
    txt[1]=write_int(0,10,20,-5,0,&tz);
    txt[2]=write(0,10,10,0,0,"hello world");

    set_text_color(txt[1], rgb(255,0,0));

    while(!key(_ESC))

        counter++;

        move_text(txt[2], mouse.x, mouse.y, tz );

        set_text_color(txt[0], rand(0101010h, 0ffffffh));

        if ( key( _DOWN ) ) tz--; end
        if ( key( _UP ) ) tz++; end

        frame;
    end
end

Used in example: [write](), [write_int](), [key](), [move_text]()


Set_title()

Definition

INT set_title ( <STRING title> )

Sets the title of the program's window.

The title will only be updated after [set_mode]() is called, so call set_title() before set_mode().

Parameters


STRING title - The new title for the program's window.


Returns

INT : [true]

Example

Program icon;
Private
    int map;
    int screen_width  = 320;
    int screen_height = 200;
    int screen_depth  =   8;
    int iconsize      =  32;
Begin

    map = new_map(iconsize,iconsize,screen_depth);
    map_clear(0,map,rgb(0,255,255));

    set_icon(0,map);
    set_title("<-- Look at the cyan block!");
    set_mode(screen_width,screen_height,screen_depth);

    unload_map(0,map);

    Repeat
        frame;
    Until(key(_esc))

End

Used in example: [new_map](), [map_clear](), [set_icon], [unload_map]()


Set_window_pos() (MISSING)

Signal()

Definition

INT signal ( <INT processID|processTypeID> , <INT signal> )

Allows a [process] or a range of processes/functions of certain [processType] to be controlled in a limited number of ways, by sending [signals].

Parameters


INT processID processTypeID - The [ProcessID] of the type of processes to send the signal to. INT signal - The [signal] that is to be sent to the target process(es).

Returns

INT :


[false]. [true].


Errors


Invalid signal - The specified [signal] is invalid.


Notes

To obtain the processType of a function, the operator [Type] can be used. For a process to send a signal to itself, the [local variable] [id] can be used. The parameter signal is passed by way of a set of [signals] which denote the signal to be sent. The parameter signal is one of the listed [signals]. To kill all processes at once, except the calling one, use [let_me_alone]().

To send a signal to all processes at once, except the calling one, use signal([[ALL_PROCESS]],signal).

To specify how a process reacts on an incoming signal, use [signal_action]().

A signal is carried out immediately, but this does not mean execution of processes is switched to the process, if you just woke it up. This can be achieved by using [[frame]](0); after the signal. A frame will cause Bennu to continue execution with the process having the lowest frame-percentage done and it will only continue execution with the current process after all other processes have had their turn. Moreover, using a frame-percentage of 0 will make sure there is nothing added to the done frame-percentage of the process, meaning it doesn't affect the framerate of the process.

Example

signal( get_id(type enemy) , s_kill ); // Kills a process of type enemy.
                                       // Becareful! If there is no enemy process alive, 
                                       // get_id() will return 0, which means signal()
                                       // will signal all processes.

signal( id , s_kill_tree );            // Kills the process that calls it, and all of its descendants

signal( Type player , s_freeze );      // Freezes all processes of type player so that they are
                                       //     still displayed, but do not execute any code.

signal(ALL_PROCESS,s_freeze);          // Freezes all processes except the one that called it.
                                       // Can be used to pause a game.

signal( someID , S_WAKEUP ); frame(0); // Wake up the process someID and let it execute once
                                       // (if not done this frame) before continuing.

Signal_action()

Definition

INT signal_action ( [<INT processID|processTypeID> , ] INT signal , INT action )

Sets the reaction of one or more [processes] when they receive a certain nonforceful-[signal]. Only existing processes are affected, processes created afterwards are not.

Parameters


INT processID processTypeID - A [ProcessID] or ALL_PROCESS. INT signal - The code of a nonforceful-[signal] for which a reaction is to be specified. INT action - The [reaction])

Returns

INT : [true]

Notes

The reaction to an incoming forced signal (S_KILL_FORCE, S_SLEEP_FORCE, etc) cannot be changed and is S_DFL by default.

Example

// The current process ignores the kill signal from now on
signal_action(S_KILL,S_IGN);

// All currently existing processes ignore the kill signal from now on
signal_action(ALL_PROCESS,S_KILL,S_IGN);

// All currently existing processes of type 'Player' ignore the freeze signal from now on
signal_action(type Player,S_FREEZE,S_IGN);

Sin()

Definition

FLOAT sin ( <FLOAT angle> )

Returns the sine of the specified [angle].

This [function] performs a sine calculation on a certain angle and returns a value between -1 and 1.

Parameters


FLOAT angle - [Angle], in thousandths of degrees. i.e. 75000 = 75º


Returns

FLOAT : The sine result of the specified [angle].

Notes

The [angle] value used in this function should be in thousandths of degrees, as most angles within [Bennu] are.

To read about all aspects of trigonometry, you can click on Wikipedia's Trigonometric function page.

Example

Const
    screen_width  = 320;
    screen_height = 200;
    screen_border = 15;
End

Global
    float value;
End

Process Main()
Begin

    // Modes
    set_title("Sine Graph");
    set_mode(screen_width,screen_height);

    // X axis
    for(x=1;x<=8;x++)
        write( 0,
               screen_border+x*(screen_width-screen_border)/8+3,
               screen_height-1,
               8,
               itoa(x*360/8 )+"^" );
    end
    draw_line(1,screen_height-screen_border,screen_width,screen_height-screen_border);

    // Y axis
    write(0,screen_border-1,20,5,"1");
    write(0,screen_border-1,screen_height/2,5,"0");
    write(0,screen_border-1,screen_height-20,5,"-1");
    draw_line(screen_border,1,screen_border,screen_height-1);

    // Draw tangent
    for(angle=0;angle<360;angle++)
        value=sin(angle*1000)*(screen_height/2-20);
        put_pixel( screen_border+angle*(screen_width-screen_border)/360,
                   screen_height/2-value,
                   rgb(255,255,255) );
        // screen_height/2-value because the screen's origin (0,0) is topleft instead of downleft.
    end

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [set_title](), [set_mode](), [draw_line](), [put_pixel]()

This will result in something like:\


Sort()

Syntax

INT sort ( <VARSPACE array> , [<INT datacount>] )

Description

Sorts an [array] by sorting a certain number of elements, by using the first variable in each element. By default the whole array is sorted.

If the elements contain multiple variables, [ksort]() can be used to select the variable to be used for sorting. For more advanced sorting, look at [quicksort]().

Parameters


VARSPACE array - The [array] to be sorted. [INT datacount] - Number of elements to sort.


Returns

INT: Successrate


[true] - Sorting succeeded. [false] - Sorting failed. Look in the output for the error.


Example

import "mod_sort";
import "mod_key";
import "mod_say";

Type _player
    String name;
    int score;
End

Const
    maxplayers = 5;
End;

Process main()
Private
    _player player[maxplayers-1];
    int i=0;
Begin
    // Insert some values
    player[0].name = "That one bad looking dude";
    player[1].name = "Ah pretty lame guy";
    player[2].name = "Some cool dude";
    player[3].name = "OMG ZOMG guy";
    player[4].name = "This person is ok";

    player[0].score = 70;
    player[1].score = 30;
    player[2].score = 80;
    player[3].score = 90;
    player[4].score = 50;

    // Show array
    say("-------------------- unsorted");
    for(i=0; i<maxplayers; i++)
        say(player[i].name + " - " + player[i].score);
    end

/* Sort by name ( quicksort() can't be used to sort Strings,
   as a String in Bennu is a pointer to the actual String,
   so it would sort the pointer addresses */

    // sort()
    sort(player); // sorts by name because name is the first variable in each element

    // Show array
    say("-------------------- name - sort()");
    for(i=0; i<maxplayers; i++)
        say(player[i].name + " - " + player[i].score);
    end

    // ksort()
    ksort(player,player[0].name,maxplayers);

    // Show array
    say("-------------------- name - ksort()");
    for(i=0; i<maxplayers; i++)
        say(player[i].name + " - " + player[i].score);
    end

/* Sort by score (sort() cannot be used here, because score is not the first variable) */

    // ksort()
    ksort(player,player[0].score,maxplayers);

    // Show array
    say("-------------------- score - ksort()");
    for(i=0; i<maxplayers; i++)
        say(player[i].name + " - " + player[i].score);
    end

    // quicksort()
    quicksort(&player[0],sizeof(_player),maxplayers,sizeof(String),sizeof(int),0);

    // Show array
    say("-------------------- score - quicksort()");
    for(i=0; i<maxplayers; i++)
        say(player[i].name + " - " + player[i].score);
    end
End

Used in example: [say](), [ksort](), [type], [pointer]


Sound_close()

Definition

VOID sound_init ( )

Manually Closes the audio system. This is normally not needed, but may be necessary on some systems with SDL mixer issues. It is used in combination with [Sound_init](). (verification needed)

Parameters

This function has no parameters.

Returns

VOID : This function does not return anything.

See also

[Sound_init]()


Sound_init()

Definition

INT sound_init ( )

Manually Initializes the audio system. This is normally not needed, but may be necessary on some systems with SDL mixer issues. (verification needed)

Parameters

This function has no parameters.

Returns

INT : Status/error.


0 - The audio device is opened. -1 - There's an error, failed to initialize the audio system.


See also

[Sound_close]()


Split()

Syntax

INT split ( <STRING delimiter> , <STRING str> , <STRING POINTER array> , <INT max_number> )

Description

Splits a [string] in several strings using a [regular expression] as delimiter.

The first piece will go to array[0], the second to array[1], and so forth, until either there are no more pieces left or max_number pieces are returned into the array. The number of pieces returned this way is returned by the function.

Parameters


STRING delimiter - The regular expression used as delimiter to split. STRING str - The input string to split into multiple string. STRING POINTER array - Pointer to the string array where the pieces will be returned to. INT max_number - The maximum number of strings to return.


Returns

INT : The number of pieces returned into the array.

Example

import "mod_say"
import "mod_regex"

Process Main()
Private
    string str = "A,B,C,D,E";
    string a[9];
    int n;
    int i;
Begin

    // Split
    n = split(",",str,&a,10);

    // Display result
    say("Number of pieces: " + n);
    for(i=0; i<n; i++)
        say("[" + i + "] = " + a[i]);
    end

End

Used in example: [split]()


Sqrt()

Definition

FLOAT sqrt ( <FLOAT value> )

Returns the square root of a certain value.

Parameters


FLOAT value - The value of which the square root will be returned.


Returns

FLOAT : The square root of value.


Start_scroll()

Definition

INT Start_scroll ( <INT scrollnumber> , <INT fileID> , <INT graphID> , <INT backgroundgraphID> , <INT regionnumber> , <INT lockindicator> , [ <INT destination fileID >, <INT destination graphID > ] )

This creates a [scroll window] in which it will perform a view against a background [graphic]. That is, by using a graphic bigger than the display window, a part of this graphic can be shown and shifted in any direction. After this function, the use of the struct [scroll] makes sense.

The parameters destination fileID and destination graphID are optional and may be omitted.

Also called [scroll_start]().

Parameters


INT scrollnumber - The ID for the new scroll window, so it can be referenced to later INT fileID - The [fileID] containing the scroll graphics INT graphID - The [graphID] of the main graphic to be scrolled INT backgroundgraphID - The graphID of the graphic for the background of the scroll window INT regionnumber - The [region] in which to put the scroll window INT lockindicator - A [bit flag] defining whether each of the two scroll planes is horizontally/vertically cyclical INT destination flileID - The [fileID] containing the destination graphics used in the scroll window, i.e. the systemfile. (optional) INT destination graphID - The [graphID] of the destination graphic where the scroll window will be drawn on. (optional)


Returns

INT : [true]

Notes

The locking indicator can be combinations of the following flags:


1 - The foreground will be displayed horizontally cyclical 2 - The foreground will be displayed vertically cyclical 4 - The background will be displayed horizontally cyclical 8 - The background will be displayed vertically cyclical


Combine them using the [bitwise OR] operator.

Using Scrolling

For each [process] that you want to be part of a [scroll window], you must set the [local variable] to value [C_SCROLL]. It should also be noted that the local variable [c_number] is used for selecting in which scroll a process should be displayed. Additionally, you must set the camera property of the [scroll structure] to the [processID] of the process you wish to be followed.

Example (scroll drawn on map)

In this example, a scroll is drawn on a map, so the advanced version with the parameters destination fileID and destination graphID are used.

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_proc";
IMPORT "mod_grproc";
IMPORT "mod_map";
IMPORT "mod_text";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_screen";
IMPORT "mod_draw";
IMPORT "mod_scroll";

GLOBAL

   int graphics_lib;

   int object1_id;

   int scroll_window;  
   int scroll_blit_graph;

PROCESS int main(); 

PRIVATE

BEGIN

    set_mode(640,480,8);
    set_fps(50,0);

    // load the fpg file with the graphics
    graphics_lib=load_fpg("graf2.fpg");

    // create a map to blit the scroll window on
    scroll_blit_graph=new_map(640,480,8);

    // display the "scroll_blit_graph".
    blit_graph();

    // (standard version)
    // int start_scroll (int scrollnumber, 
    //                   int file, 
    //                   int graph, 
    //                   int backgroundgraph, 
    //                   int regionnumber, 
    //                   int lockindicator); 

    // (advanced, extended version)
    // int start_scroll (int scrollnumber, 
    //                   int file, 
    //                   int graph, 
    //                   int backgroundgraph, 
    //                   int regionnumber, 
    //                   int lockindicator, 
    //                   int destination file, 
    //                   int destination graph); 

    // create an extended scroll, drawn on the "scroll_blit_graph".
    scroll_window=start_scroll(0,graphics_lib,1,0,0,3,0,scroll_blit_graph); 

    say("scroll_window status: "+scroll_window);

    // create the two objct processes.
    object1_id=object1(graphics_lib); 

    // write instructions  
    write(0 ,20,30,ALIGN_CENTER_LEFT,"Scroll extended (with destination map) test demo, instructions"); 

    write(0 ,20,40,ALIGN_CENTER_LEFT,"F3 and F4: decrease/increase size of destination map"); 
    write(0 ,20,50,ALIGN_CENTER_LEFT,"F5 and F6: decrease/increase angle of destination map"); 
    write(0 ,20,60,ALIGN_CENTER_LEFT,"F7 and F8: decrease/increase x of destination map"); 
    write(0 ,20,70,ALIGN_CENTER_LEFT,"F9 and F10: decrease/increase y of destination map"); 

    WHILE (NOT key(_esc))

        FRAME;
    END

    // stop scroll window.
    stop_scroll(0);

    // kill all processes, execpt the "main" process.
    let_me_alone();
END

PROCESS int object1 (int file);

PRIVATE

BEGIN

    graph=3;

    ctype=c_scroll;
    cnumber=c_0; // make this process visible in window 0

    scroll[0].camera=id;

    x=100;  
    y=100;

    LOOP

        // move main object
        IF (key(_up) AND y >0) 
           y-=5; 
        END
        IF (key(_down) AND y <800) 
           y+=5; 
        END
        IF (key(_left) AND x >0)  
           x-=5; 
        END
        IF (key(_right) AND x <2000) 
           x+=5; 
        END

        FRAME;
    END
END

// Process for handling the "destination graph" feature, i.e. the map on wich
// the mode7 windows are drawn.
PROCESS int blit_graph();

PRIVATE

BEGIN

   x=320;
   y=240;

   ctype=c_screen;

   file=0;
   graph=scroll_blit_graph; // set the graph to the map created in memory.

   LOOP

      // the controls for the "fancy stuff".
      IF (key(_f3) AND size >20)
         size-=10;
      END

      IF (key(_f4) AND size <1000)
         size+=10;
      END

      IF (key(_f5) AND angle >0)
         angle-=100;
      END

      IF (key(_f6) AND angle <360000)
         angle+=100;
      END

      IF (key(_f7) AND x >0)
         x-=10;
      END

      IF (key(_f8) AND x <1000)
         x+=10;
      END

      IF (key(_f9) AND y >0)
         y-=10;
      END

      IF (key(_f10) AND y <1000)
         y+=10;
      END

      FRAME;
   END
END

Stop_scroll()

Definition

INT Stop_scroll ( <INT scrollnumber>)

This functions stops an active [scroll window]. There can be up to 10 (0-9) [scroll windows] active. When the scroll is stopped, all the processes in it will no longer be displayed. This function is usefull for switching the game's state from active gameplay to a loading screen state or similair situations. Another use is, when there are multiple scroll [regions] active, and the game changes from split screen to single screen. This way you can have individual control over the display of the scroll.

Also called [scroll_stop]().

Parameters


INT scrollnumber - The ID for the scroll window to be stopped


Returns

INT : [true]

Example

IMPORT "mod_video";
IMPORT "mod_map";
IMPORT "mod_scroll";
IMPORT "mod_screen";
IMPORT "mod_key";
IMPORT "mod_proc";

GLOBAL

int graphics;

PROCESS main();

BEGIN

    graphics=load_fpg("help.fpg");

    say("Press [ENTER] to activate the scroll window.");
    say("Press [SPACE] to stop the scroll.");

    LOOP
        IF (scan_code==_space)

            stop_scroll(0); // The scroll is stopped.

        END
        IF (scan_code==_enter)
            start_scroll(0, 0, 103, 102, 0, 15);
        END

        FRAME;
    END
END

Using Scrolling

For each [process] that you want to be part of a [scroll window], you must set the [local variable] to value [C_SCROLL]. It should also be noted that the local variable [c_number] is used for selecting in which scroll a process should be displayed. Additionally, you must set the camera property of the [scroll structure] to the [processID] of the process you wish to be followed.


Stop_song()

Definition

INT stop_song ( )

Stops a song loaded with [load_song]() and played with [play_song]().

Parameters

This function has no parameters.

Returns

INT : Status


0 - The song is stopped.



Stop_wav()

Definition

INT stop_wav ( INT )

Stops a the playback of sound of the indicated wave [sound channel].

Parameters

' INT' channel: the [sound channel].

Returns

INT : Status


-1 - There is an error.



Strcasecmp()

Definition

INT strcasecmp( <STRING str1> , <STRING str2> )

Compares two strings case-insensitive and returns the result.

Parameters


STRING str1 - The first string. STRING str2 - The second string, to compare with the first string.


Returns

INT: difference


0 - The strings are equal. >0 - The ASCII value of the first differing characters is higher for str1. <0 - The ASCII value of the first differing characters is higher for str2.


Notes

If the strings differ, the ASCII difference between the first differing characters of the strings is actually returned. Let i be the index of the differing characters, then what is returned: ''str1''[''i'']-''str2''[''i''].

Example

import "mod_string"
import "mod_say"

Const
    AB = "AB";
    ABC = "ABC";
    CD = "CD";
    CD2 = "CD";
End

Process Main()
Begin

    say("strcasecmp(AB,ABC) = " + strcasecmp(AB,ABC));
    say("strcasecmp(AB,CD) = " + strcasecmp(AB,CD));
    say("strcasecmp(CD,AB) = " + strcasecmp(CD,AB));
    say("strcasecmp(CD,CD2) = " + strcasecmp(CD,CD2));

End

Used in example: [say](), [strcasecmp]()

Result:

strcasecmp(AB,ABC) = -67
strcasecmp(AB,CD) = -2
strcasecmp(CD,AB) = 2
strcasecmp(CD,CD2) = 0

Strlen() (MISSING)

Strrev()

Definition

STRING strrev ( <STRING str> )

Returns a reversed version of a certain [string], meaning the characters are in reversed order.

Parameters


STRING str - The non reversed string.


Returns

STRING : The reversed string.


Substr()

Syntax

INT substr ( <STRING str> , <INT startposition> , [<INT characters>] )

Description

Returns a subsection of a certain string.

Parameters


STRING str - The string of which a subsection will be returned. INT startposition - The position of the first character to be in the subsection. [INT characters] - The number of characters the subsection will hold. Negative values are special; see [Notes].


Returns

STRING : The subsection.

Notes

If the number of characters is a negative value, the following applies: the start of the subsection will be startposition; the end of the subsection will be the length of the string minus the absolute value of characters.

Example

Private                             
    String str = "This is my string.";
Begin

    // No specified number of characters
    say( substr(str,2)     + "<" ); // "is is my string."
    say( substr(str,-7)    + "<" ); // "string."

    // Specified number of characters
    say( substr(str,5,2)   + "<" ); // "is"

    // Number of characters greater than length of string
    say( substr(str,2,50)  + "<" ); // "is my string."
    say( substr(str,-7,50) + "<" ); // "string."

    // Negative number of characters
    say( substr(str,5,-5)  + "<" ); // "is my st"

    // Special case
    say( substr(str,0,0)   + "<" ); // "", but pre 0.92: "This is my string."

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [say]()


Tan()

Definition

FLOAT tan ( <FLOAT angle> )

Returns the tangent of a certain [angle].

This [function] performs a tangent calculation on a certain angle and returns a value.

Parameters


FLOAT angle - [Angle], in thousandths of degrees. i.e. 75000 = 75º


Returns

FLOAT : The tangent result of the specified [angle].

Notes

The [angle] value used in this function should be in thousandths of degrees, as most angles within [Bennu] are.

To read about all aspects of trigonometry, you can visit Wikipedia's Trigonometric function page.

Example

Const
    screen_width  = 320;
    screen_height = 200;
    screen_border = 15;
End

Global
    float value;
End

Process Main()
Begin

    // Modes
    set_title("Tangent Graph");
    set_mode(screen_width,screen_height);

    // X axis
    for(x=1;x<=8;x++)
        write( 0,
               screen_border+x*(screen_width-screen_border)/8+3,
               screen_height-1,
               8,
               itoa(x*360/8 )+"^" );
    end
    draw_line(1,screen_height-screen_border,screen_width,screen_height-screen_border);

    // Y axis
    write(0,screen_border-1,20,5,"1");
    write(0,screen_border-1,screen_height/2,5,"0");
    write(0,screen_border-1,screen_height-20,5,"-1");
    draw_line(screen_border,1,screen_border,screen_height-1);

    // Draw tangent
    for(angle=0;angle<360;angle++)
        value=tan(angle*1000)*(screen_height/2-20);
        put_pixel( screen_border+angle*(screen_width-screen_border)/360,
                   screen_height/2-value,
                   rgb(255,255,255) );
        // screen_height/2-value because the screen's origin (0,0) is topleft instead of downleft.
    end

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [set_title](), [set_mode](), [draw_line](), [put_pixel]()

This will result in something like:\


Text_height()

Definition

INT text_height ( <INT fontID> , <STRING text> )

Calculates the height in pixels of the specified text in the specified [font].

Parameters


INT FontID - [FontID] of the font for which the height of the text will be the calculated. STRING text - The text of which the height will be calculated.


Returns

INT : The height in pixels of the text in the font.


0 - Invalid or no text; invalid font. >0 - The height in pixels of the text in the font.


See also

  • [text_width]()

Text_width()

Definition

INT text_width ( <INT fontID> , <STRING text> )

Calculates the width in pixels of the specified text in the specified [font].

Parameters


INT FontID - [FontID] of the font for which the width of the text will be the calculated. STRING text - The text of which the width will be calculated.


Returns

INT : The width in pixels of the text in the font.


0 - Invalid or no text; invalid font. >0 - The width in pixels of the text in the font.


See also

  • [text_height]()

Time()

Syntax

INT time ( )

Description

Returns the current time, in seconds from January 1st, 1970.

This function is mostly useful for the [function] [ftime](), to display time and date in a particular format. It is also useful in [rand_seed](), to have 'more randomness'.

Returns

INT : The current time, in seconds from January 1st, 1970.

Example

import "mod_time"
import "mod_timer"
import "mod_text"
import "mod_key"

Process Main();
Private
    String timestring; // The string holding the formatted time
Begin

    write_string(0,0,0,0,&timestring); // Display the timestring
    timer = 100; // Make it so it updates the timestring immediately

    Repeat
        if(timer>100) // Update the timestring every 1 second
            timer = 0;
            timestring = ftime("%d-%m-%Y %H:%M:%S",time());
        end
        frame;
    Until(key(_esc))

End

Used in example: [write_string](), [ftime](), [timer]


Trim()

Definition

STRING trim ( <STRING str> )

Returns a copy of str without leading or ending whitespace (spaces, tabs, linefeeds, carriage returns).

Parameters


STRING str - The string to trim.


Returns

STRING: trimmed string

Example

import "mod_string"
import "mod_say"

Const
    _ABC_ = " ABC ";
End

Process Main()
Private
    string ABC;
Begin

    ABC = trim(_ABC_);
    say('_ABC_ = "' + _ABC_ + '"');
    say('ABC = "' + ABC + '"');

End

Used in example: [say]()

Result:

_ABC_ = " ABC "
ABC = "ABC"

Ucase()

Definition

STRING ucase ( <STRING str> )

Returns a [string] identical to a certain string, with the exception that all lowercase characters are replaced by their uppercase counterparts.

Parameters


STRING str - The string in "normal"-form.


Returns

STRING : The string in "uppercase"-form.


Unload_song()

Definition

INT unload_song ( <INT SongID> )

Frees the memory occupied by the song file, previously loaded with [load_song]().

Parameters


INT SongID - The [SongID] of the song to unload.


Returns

INT : Error.


-1 - Error: sound inactive; invalid [songID]. 0 - No error.


Notes

Instead of an INT a POINTER may also be used in the SongID argument.


Unload_wav()

Definition

INT unload_wav ( <INT WaveID> )

Frees the memory occupied by the wave file, previously loaded with [load_wav]().

Parameters


INT WaveID - The [WaveID] of the sound to unload.


Returns

INT : Error.


-1 - Error: sound inactive; invalid [waveID]. 0 - No error.


Notes

Instead of an INT a POINTER may also be used in the WaveID argument.


Write()

Definition

INT write ( <INT fontID> , <INT x> , <INT y> , [<INT z>] , <INT alignment> , <STRING text>)

Puts a dynamic text with a certain font on certain coordinates on the screen with a certain [alignment].

Parameters


INT fontID - The [FontID] of the font to be used for the text. INT x - The X coordinate of the text. INT y - The Y coordinate of the text. INT z - The depthplane of the text (optional, introduced in version rc282). INT alignment - The type of [alignment]. STRING text - The text to be used.


Returns

INT : [TextID]


-1 - Error. The text could not be obtained or was empty. >=0 - The [TextID] of the text.


Notes

There is a limit of 511 texts to simultaneously exist on the screen. The program will crash with an error when this number is reached.

The text depth can be changed by adjusting the global variable [text_z].

To write variables to the screen, rather use [write_int](), [write_string](), [write_float]() or [write_var]() than this command.

To write text on a map you can use the command [write_in_map]().

If you write texts with a font and you change any symbol of this font after, all written texts will be updated using the new changed symbols.

Example

Program texts;
Const
    maxtexts = 10;
Private
    int textid[maxtexts-1];
    string str;
    float flt;
Begin

    // Set FPS
    set_fps(60,0);

    // Write some texts
    textid[0] = write(0,0,0,0,"FPS:");
    textid[1] = write_int(0,30,0,0,&fps);
    textid[2] = write_string(0,160,95,1,&str);
    textid[3] = write_float(0,160,105,0,&flt);

    // Update the texts until ESC is pressed
    Repeat
        // Notice the texts get updated as the values of str and flt changes.
        // The same goes for the value of fps.
        str = "This program is running for " + timer/100 + " seconds.";
        flt = (float)timer/100;
        frame;
    Until(key(_esc));

    // Delete the texts
    for(x=0; x<maxtexts; x++)
        if(textid[x]!=0)
            delete_text(textid[x]);
        end
    end

End

Used in example: [set_fps](), [write_int](), [write_string](), [write_float](), [delete_text], [fps]

This will result in something like:\


Write_float()

Definition

INT write_float ( <INT fontID> , <INT x> , <INT y> , [<INT z>] , <INT alignment> , <FLOAT POINTER var> )

Writes a [floating point variable] to the screen, which will be automatically updated when the value of the variable changes. The floating point variable will remain on the screen until deleted with [delete_text]().

Parameters


INT fontID - The [FontID] of the font to be used for the text. INT x - The X coordinate of the text. INT y - The Y coordinate of the text. INT z - The depthplane of the text (optional, introduced in version rc282). INT alignment - The type of [alignment]. FLOAT POINTER var - A [pointer].


Returns

INT : [TextID]


-1 - Error. >=0 - The [TextID] of the text.


Notes

There is a limit of 511 texts to simultaneously exist on the screen. The program will crash with an error when this number is reached.

The text depth can be changed by adjusting the global variable [text_z].

Instead of [write_float](), [write_var]() can be used for the same purpose, which is a more general function that allows you to write variables of any type to the screen.

Errors


Too many texts onscreen - There are too many texts on the screen.


Example

Program test;
Private
    float my_float=3.14159265;
Begin

    write_float(0,320/2,200/2,4,&my_float);

    Repeat
        Frame;
    Until(key(_ESC))

End

This will result in something like:\


Write_in_map()

Definition

INT write_in_map ( <INT fontID> , <STRING text> , <INT alignment> )

Creates a new [graphic] in memory with the given text on it (without borders around the text) and puts it in the [system file].

Parameters


INT fontID - The [FontID] of the font to be used for the text. STRING text - The text to be used. INT alignment - The type of [alignment].


Returns

INT : [GraphID]


0 - Error. The text could not be obtained or was empty. !0 - The [GraphID].


Notes

This function creates a [graphic] containing the specified [font] and [height] determined by the physical size of the text; the graphic's size will fit the text exactly to the pixel. The graphic will be stored in memory with [FileID] 0 (using the [system file]), and can be obtained at any time by calling its [GraphID]. The graphic can also be unloaded from memory by using [unload_map]().

The centre of the graph ([control point] 0) is given according to the given [alignment]. This gives added functionality of being able to place the graph like texts, yet also using [flags], rotation, [collision](), etc.

Processes can adopt the graphic containing the text, or it can be displayed with some [maps functions], creating a very handy function.

Errors


Invalid font - The specified font does not exist or is invalid.


Example

Program example;
Begin
    Set_text_color(rgb(222,195,140));
    graph=write_in_map(0,"Game programming is awesome!",4);
    repeat
        x=mouse.x;
        y=mouse.y;
    frame;
    until(key(_esc))
End

Used in example: [set_text_color](), [rgb], [y]

This will result in something like:\


Write_int()

Definition

INT write_int ( <INT fontID> , <INT x> , <INT y> , [<INT z>] , <INT alignment> , <INT POINTER var> )

Writes an [integer] to the screen, which will be automatically updated when the value of the integer changes. The integer will remain on the screen until deleted with [delete_text]().

Parameters


INT fontID - The [FontID] of the font to be used for the text. INT x - The X coordinate of the text. INT y - The Y coordinate of the text. INT z - The depthplane of the text (optional, introduced in version rc282). INT alignment - The type of [alignment]. INT POINTER var - A [pointer].


Returns

INT : [TextID]


-1 - Error. >=0 - The [TextID] of the text.


Notes

There is a limit of 511 texts to simultaneously exist on the screen. The program will crash with an error when this number is reached.

The text depth can be changed by adjusting the global variable [text_z].

Instead of [write_int](), [write_var]() can be used for the same purpose, which is a more general function that allows you to write variables of any type to the screen.

Errors


Too many texts onscreen - There are too many texts on the screen.


Example

Program test;
Private
    my_integer=0;
Begin

    write_int(0,320/2,200/2,4,my_integer);

    Repeat
        my_integer=rand(1,1000);
        frame;
    Until(key(_ESC))

End

Used in example: [rand]()

This will result in something like:\


Write_string()

Syntax

INT write_string ( <INT fontID> , <INT x> , <INT y> , <INT alignment> , <STRING POINTER var> )

Description

Writes a [string] to the screen, which will be automatically updated when the value of the string changes. The string will remain on the screen until deleted with [delete_text]().

Parameters


INT fontID - The [FontID] of the font to be used for the text. INT x - The X coordinate of the text. INT y - The Y coordinate of the text. INT alignment - The type of [alignment]. STRING POINTER var - A [pointer].


Returns

INT : [TextID]


-1 - Error. The text could not be obtained or was empty. >=0 - The [TextID] of the text.


Notes

There is a limit of 511 texts to simultaneously exist on the screen. The program will crash with an error when this number is reached.

The text depth can be changed by adjusting the global variable [text_z].

Instead of [write_string](), [write_var]() can be used for the same purpose, which is a more general function that allows you to write variables of any type to the screen.

Errors


Too many texts onscreen - There are too many texts on the screen.


Example

import "mod_text"
import "mod_key"

Global
    string my_string="Bennu Game Development";
End
Process Main()
Begin

    write_string(0,320/2,200/2,4,&my_string);

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [write_string](), [key]()

This will result in something like:\


Write_var()

Syntax

INT write_var ( <INT fontID> , <INT x> , <INT y> , [<INT z>] , <INT alignment> , <VARSPACE var> )

Description

Writes a variable of any kind to the screen, which will be automatically updated when the value of the variable changes. The variable will remain on the screen until deleted with [delete_text]().

Parameters


INT fontID - The [FontID] of the font to be used for the text. INT x - The X coordinate of the text. INT y - The Y coordinate of the text. INT z - The depthplane of the text (optional, introduced in version rc282). INT alignment - The type of [alignment]. VARSPACE var - The name of [any variable].


Returns

INT : [TextID]


-1 - Error. >=0 - The [TextID] of the text.


Notes

Please note that for the [varspace] var parameter no pointer should be filled out, while [write_int]() do require a pointer.

There is a limit of 511 texts to simultaneously exist on the screen. The program will crash with an error when this number is reached.

The text depth can be changed by adjusting the global variable [text_z].

Instead of [write_var](), [write_int]() could be used to write an [int] to the screen, [write_string]() for a [string]() for a [float].

Errors


Too many texts onscreen - There are too many texts on the screen.


Example

import "mod_text"
import "mod_key"

Global
    my_integer=0;
    string my_string="Bennu Game Development";
End

Process Main()
Begin

    write_var(0,0,0,0,my_string);
    write_var(0,320/2,200/2,4,my_integer);

    Repeat
        my_integer=rand(1,1000);
        frame;
    Until(key(_ESC))

End

Used in example: [write_var](), [rand]()

This will result in something like:\


Xput()

Definition

INT xput ( <INT fileID> , <INT GraphID> , <INT x> , <INT y> , <INT angle> , <INT size> , <INT blitflags> , <INT region> )

Draws ([blits] onto the [background].

If the advanced parameters aren't needed, [put]() can be used.

Parameters


INT fileID - The [fileID] that holds the graphics. INT graphID - The [graphID] to draw with. INT x - Where on the background graphic's x-axis to put the graphic. INT y - Where on the background graphic's y-axis to put the graphic. INT angle - What [angle] to draw the graphic at. INT size - What [size] to draw the graphic at. INT blitflags - What [blit flags] to draw the graphic with. INT regionID - The [regionID] in which the graphic is only allowed to be drawn.


Returns

INT : [true]

Notes

The x and y parameters denote where to draw the graphic, that is, where the center of the to be drawn graphic will be. Blit flags can be used to give the drawing (blitting) a special effect.

When angle is 0 and size is 100, the speed is greater, because the graph doesn't need rotating or scaling.

Errors


Unsupported color depth - The graphic's color depth is greater than the background graphic's.




List of Constants

ALIGN_BOTTOM (MISSING)

ALIGN_BOTTOM_LEFT (MISSING)

ALIGN_BOTTOM_RIGHT (MISSING)

ALIGN_CENTER (MISSING)

ALIGN_CENTER_LEFT (MISSING)

ALIGN_CENTER_RIGHT (MISSING)

ALIGN_TOP (MISSING)

ALIGN_TOP_LEFT (MISSING)

ALIGN_TOP_RIGHT (MISSING)

ALL_SOUND (MISSING)

ALL_TEXT (MISSING)

BACKGROUND

Description

The background is a [graphic], in the [system file] of 0) with a [graphID] equal to [BACKGROUND].

Examples in use:

  • [[map_clear]](0,[[BACKGROUND]]);, to clear the background to black (same as [screen_clear]).
  • [[drawing_map]](0,[[BACKGROUND]]);, to set drawing to the background.

BLUR_3X3 (MISSING)

BLUR_5X5 (MISSING)

BLUR_5X5_MAP (MISSING)

BLUR_NORMAL (MISSING)

B_ABLEND (MISSING)

B_ALPHA (MISSING)

B_CLEAR (MISSING)

B_HMIRROR (MISSING)

B_NOCOLORKEY (MISSING)

B_SBLEND (MISSING)

B_TRANSLUCENT (MISSING)

B_VMIRROR (MISSING)

CHARSET_CP850 (MISSING)

CHARSET_ISO8859 (MISSING)

COMPLETE_DUMP (MISSING)

COMPLETE_RESTORE (MISSING)

CRYPT_3DES (MISSING)

CRYPT_DES (MISSING)

CRYPT_NONE (MISSING)

C_0 (MISSING)

C_1 (MISSING)

C_2 (MISSING)

C_3 (MISSING)

C_4 (MISSING)

C_5 (MISSING)

C_6 (MISSING)

C_7 (MISSING)

C_8 (MISSING)

C_9 (MISSING)

C_SCREEN (MISSING)

C_SCROLL (MISSING)

DOUBLE_BUFFER (MISSING)

FALSE (MISSING)

GSCALE_B (MISSING)

GSCALE_G (MISSING)

GSCALE_GB (MISSING)

GSCALE_OFF (MISSING)

GSCALE_R (MISSING)

GSCALE_RB (MISSING)

GSCALE_RG (MISSING)

GSCALE_RGB (MISSING)

G_ANIMATION_SPEED (MISSING)

G_ANIMATION_STEP (MISSING)

G_ANIMATION_STEPS (MISSING)

G_CENTER_X (MISSING)

G_CENTER_Y (MISSING)

G_DEPTH (MISSING)

G_FRAMES (MISSING)

G_HEIGHT (MISSING)

G_PITCH (MISSING)

G_WIDTH (MISSING)

G_X_CENTER (MISSING)

G_Y_CENTER (MISSING)

HW_SURFACE (MISSING)

JOY_HAT_CENTERED (MISSING)

JOY_HAT_DOWN (MISSING)

JOY_HAT_LEFT (MISSING)

JOY_HAT_LEFTDOWN (MISSING)

JOY_HAT_LEFTUP (MISSING)

JOY_HAT_RIGHT (MISSING)

JOY_HAT_RIGHTDOWN (MISSING)

JOY_HAT_RIGHTUP (MISSING)

JOY_HAT_UP (MISSING)

MAX_BYTE

Definition

CHAR MAX_BYTE = 255

The maximum integer value reachable with a [byte] ([unsigned]).

See also [MIN_BYTE].


MAX_CHAR

Definition

CHAR MAX_CHAR = 255

The maximum integer value reachable with a [char] ([byte]).

See also [MIN_CHAR].


MAX_DWORD

Definition

DWORD MAX_DWORD = 4294967295

The maximum integer value reachable with a [dword] ([unsigned]).

See also [MIN_DWORD].


MAX_INT

Definition

INT MAX_INT = 2147483647

The maximum integer value reachable with an [int].

See also [MIN_INT].


MAX_SBYTE

Definition

CHAR MAX_SBYTE = 127

The maximum integer value reachable with a [signed] [byte].

See also [MIN_SBYTE].


MAX_SHORT

Definition

SHORT MAX_SHORT = 32767

The maximum integer value reachable with a [short] ([signed]).

See also [MIN_SHORT].


MAX_WORD

Definition

WORD MAX_WORD = 65535

The maximum integer value reachable with a [word] ([unsigned]).

See also [MIN_WORD].


MIN_BYTE

Definition

CHAR MIN_BYTE = 0

The minimum integer value reachable with a [byte] ([unsigned]).

See also [MAX_BYTE].


MIN_CHAR

Definition

CHAR MIN_CHAR = 0

The minimum integer value reachable with a [char] ([byte]).

See also [MAX_CHAR].


MIN_DWORD

Definition

DWORD MIN_DWORD = 0

The minimum integer value reachable with a [dword] ([unsigned]).

See also [MAX_DWORD].


MIN_INT

Definition

INT MIN_INT = -2147483648

The minimum integer value reachable with an [int].

See also [MAX_INT].


MIN_SBYTE

Definition

CHAR MIN_SBYTE = -128

The minimum integer value reachable with a [signed byte].

See also [MAX_SBYTE].


MIN_SHORT

Definition

SHORT MIN_SHORT = -32768

The minimum integer value reachable with a [short] ([signed]).

See also [MAX_SHORT].


MIN_WORD

Definition

WORD MIN_WORD = 0

The minimum integer value reachable with a [word] ([unsigned]).

See also [MAX_WORD].


MODE_16BITS (MISSING)

MODE_16BPP (MISSING)

MODE_2XSCALE (MISSING)

MODE_8BITS (MISSING)

MODE_8BPP (MISSING)

MODE_DOUBLEBUFFER (MISSING)

MODE_FRAMELESS (MISSING)

MODE_FULLSCREEN (MISSING)

MODE_HARDWARE (MISSING)

MODE_MODAL (MISSING)

MODE_MONO (MISSING)

MODE_STEREO (MISSING)

MODE_WAITVSYNC (MISSING)

MODE_WINDOW (MISSING)

NFB_FIXEDWIDTH (MISSING)

NFB_VARIABLEWIDTH (MISSING)

NO_RESTORE (MISSING)

NULL

Description

NULL is a pointer, pointing to nothing. In programming it points to 0x00000000, or just plain 0.

The following check is the same as checking if a pointer variable is NULL:

if(my_pointer)
end

In which my_pointer is a pointer variable.


Constant - Value - Description NULL - 0 - 0x00000000, pointing to nothing.



OS_BEOS (MISSING)

OS_BSD (MISSING)

OS_DC (MISSING)

OS_GP2X (MISSING)

OS_GP32 (MISSING)

OS_LINUX (MISSING)

OS_MACOS (MISSING)

OS_WII (MISSING)

OS_WIN32 (MISSING)

PARTIAL_DUMP (MISSING)

PARTIAL_RESTORE (MISSING)

PF_NODIAG (MISSING)

PF_REVERSE (MISSING)

PI

Definition

INT PI == 180000

The equivalent to the mathematical pi (3.14159265...), in thousandths of a degree. It can be used to define angles, like assigning one to the local variable [angle], or passing one to the function [xadvance]().

Example

angle = PI/2; // 90000 (90 degrees)
xadvance(-PI/4,10); // -45000 (-45 degrees)

SCREEN (MISSING)

STATUS_DEAD (MISSING)

STATUS_FROZEN (MISSING)

STATUS_KILLED (MISSING)

STATUS_RUNNING (MISSING)

STATUS_SLEEPING (MISSING)

STATUS_WAITING (MISSING)

S_DFL (MISSING)

S_FREEZE (MISSING)

S_FREEZE_FORCE (MISSING)

S_FREEZE_TREE (MISSING)

S_FREEZE_TREE_FORCE (MISSING)

S_IGN (MISSING)

S_KILL (MISSING)

S_KILL_FORCE (MISSING)

S_KILL_TREE (MISSING)

S_KILL_TREE_FORCE (MISSING)

S_SLEEP (MISSING)

S_SLEEP_FORCE (MISSING)

S_SLEEP_TREE (MISSING)

S_SLEEP_TREE_FORCE (MISSING)

S_WAKEUP (MISSING)

S_WAKEUP_FORCE (MISSING)

S_WAKEUP_TREE (MISSING)

S_WAKEUP_TREE_FORCE (MISSING)

TRUE (MISSING)

_0 (MISSING)

_1 (MISSING)

_2 (MISSING)

_3 (MISSING)

_4 (MISSING)

_5 (MISSING)

_6 (MISSING)

_7 (MISSING)

_8 (MISSING)

_9 (MISSING)

_A (MISSING)

_ALT (MISSING)

_APOSTROPHE (MISSING)

_ASTERISK (MISSING)

_B (MISSING)

_BACKSLASH (MISSING)

_BACKSPACE (MISSING)

_C (MISSING)

_CAPS_LOCK (MISSING)

_COMMA (MISSING)

_CONTROL (MISSING)

_C_ASTERISK (MISSING)

_C_BACKSLASH (MISSING)

_C_CENTER (MISSING)

_C_DEL (MISSING)

_C_DOWN (MISSING)

_C_END (MISSING)

_C_ENTER (MISSING)

_C_HOME (MISSING)

_C_INS (MISSING)

_C_LEFT (MISSING)

_C_MINUS (MISSING)

_C_PGDN (MISSING)

_C_PGUP (MISSING)

_C_PLUS (MISSING)

_C_RIGHT (MISSING)

_C_UP (MISSING)

_D (MISSING)

_DEL (MISSING)

_DOWN (MISSING)

_E (MISSING)

_END (MISSING)

_ENTER (MISSING)

_EQUALS (MISSING)

_ESC (MISSING)

_F (MISSING)

_F1 (MISSING)

_F10 (MISSING)

_F11 (MISSING)

_F12 (MISSING)

_F2 (MISSING)

_F3 (MISSING)

_F4 (MISSING)

_F5 (MISSING)

_F6 (MISSING)

_F7 (MISSING)

_F8 (MISSING)

_F9 (MISSING)

_G (MISSING)

_GREATER (MISSING)

_H (MISSING)

_HOME (MISSING)

_I (MISSING)

_INS (MISSING)

_J (MISSING)

_K (MISSING)

_L (MISSING)

_LEFT (MISSING)

_LESS (MISSING)

_L_ALT (MISSING)

_L_BRACHET (MISSING)

_L_CONTROL (MISSING)

_L_SHIFT (MISSING)

_L_WINDOWS (MISSING)

_M (MISSING)

_MENU (MISSING)

_MINUS (MISSING)

_N (MISSING)

_NUM_LOCK (MISSING)

_O (MISSING)

_P (MISSING)

_PGDN (MISSING)

_PGUP (MISSING)

_PLUS (MISSING)

_POINT (MISSING)

_PRN_SCR (MISSING)

_P_NOWAIT (MISSING)

_P_WAIT (MISSING)

_Q (MISSING)

_R (MISSING)

_RIGHT (MISSING)

_R_ALT (MISSING)

_R_BRACHET (MISSING)

_R_CONTROL (MISSING)

_R_SHIFT (MISSING)

_R_WINDOWS (MISSING)

_S (MISSING)

_SCROLL_LOCK (MISSING)

_SEMICOLON (MISSING)

_SLASH (MISSING)

_SPACE (MISSING)

_T (MISSING)

_TAB (MISSING)

_U (MISSING)

_UP (MISSING)

_V (MISSING)

_W (MISSING)

_WAVE (MISSING)

_X (MISSING)

_Y (MISSING)

_Z (MISSING)


List of Globals

Argc

[Up to Global Variables] [Up to Internal]


Definition

INT argc

Argc is a [global variable], holding the number of arguments passed when calling [BGDI], including the bytecode file. The arguments can be found in the global variable [argv].


Argv

[Up to Global Variables] [Up to Internal]


Definition

STRING[32] argv

Argv is a [global variable], holding the arguments with which [BGDI] was called, including the bytecode file.


argv[0] - The bytecode file (possibly without extension). argv[1] - First argument. argv[2] - Second argument. argv[n] - nth argument.


If an argument was not given, the corresponding string will be "" (empty string). The number of arguments passed can be found with [argc]. This means that argv[argc-1] is the last argument.

Example

import "mod_say"

Process Main()
Private
    int i;
Begin

    say("Bytecode file: " + argv[0]);

    i = 1;
    while(i<argc)
        say("Argument " + i + ": " + argv[i]);
        i++;
    end

End

Running this on Windows XP:

> bgdi argv mies noot "mies noot" "'mies noot'" "\"mies noot\"" 'mies noot'
Bytecode file: argv
Number of arguments: 8
Argument 1: mies
Argument 2: noot
Argument 3: mies noot
Argument 4: 'mies noot'
Argument 5: "mies noot"
Argument 6: 'mies
Argument 7: noot'

Running this on Linux:

$ bgdi argv mies noot "mies noot" "'mies noot'" "\"mies noot\"" 'mies noot'
Bytecode file: argv
Number of arguments: 7
Argument 1: mies
Argument 2: noot
Argument 3: mies noot
Argument 4: 'mies noot'
Argument 5: "mies noot"
Argument 6: mies noot

Here you can see some interesting things:


text produces an argument word for each word (words are separated by spaces) "text" produces the argument text "'text'" produces the argument 'text'. "\"text\"" produces the argument "text" 'text' doesn't combine multiple words into one argument on Windows, but it does on Linux.


The passing of arguments is totally unrelated to [Bennu] and is OS dependent. Usually the doubleqoutes (" ") work, but as you can see, the single quotes (' ') don't always work to combine multiple words into one argument.


Ascii

[Up to Global Variables]


Definition

INT ascii

Ascii is defined in the module [mod_key] and, in contrast to [scan_code], it contains the last character typed on the keyboard instead of the last key. That means “A” and “a” will have the same [scan_code], but different ascii value.

Example

import "mod_text"
import "mod_key"
import "mod_video"

process main()
begin
    set_mode(640,320);

    write( 0, 60, 10, 0, "Use lower and upper case characters to see the difference");
    write( 0, 60, 20, 0, "between ascii and scan_code.    (ESC to exit)  ");

    write( 0, 60, 40, 0, "ascii: ");
    write_var( 0, 110, 40, 0, ascii);

    write( 0, 26, 50, 0, "scan_code: ");
    write_var( 0, 110, 50, 0, scan_code);

    while ( !key(_esc))
        frame;
    end
end   

Cdinfo (MISSING)

Dump_type

[Up to Global Variables]


Definition

INT dump_type = PARTIAL_DUMP

Dump_type is a [global variable], holding the current [dump_mode]. The mode can be changed by assigning a different mode to the variable. Default is [PARTIAL_DUMP].

See also [restore_type].


Exit_status

[Up to Global Variables]


Definition

INT exit_status

exit_status is a [predefined] [global variable], holding whether or not Bennu received a QUIT event this frame. A QUIT event is generated for example by pressing the X button of the window.


Value - Description [false] - There is no QUIT event. [true] - There is a QUIT event.



Fading

[Up to Global Variables]


Definition

INT fading = false

Fading is a [global variable], holding whether the screen is currently fading. This can be caused by the functions [fade]() or [fade_off](). Its value will be [true] if there is fading going on and [false] if not.

Example

Program faders;
Private
    int text_id;
Begin

    // Write something
    text_id = write(0,160,100,4,"Look at this fading text!");

    // Fade screen on and off
    fade_off_and_on();

    // Wait for ESC key
    Repeat
        frame;
    Until(key(_ESC))

    // Kill all other processes and clear up text
    let_me_alone();
    delete_text(text_id);

End

Process fade_off_and_on()
Begin
    Loop
        fade(0,0,0,4); // Fade to black
        while(fading) frame; end // Wait for the fading to finish
        fade(100,100,100,4); // Fade to normal
        while(fading) frame; end // Wait for the fading to finish
    End
End

Used in example: [write](), [let_me_alone](), [delete_text]()


Focus_status

[Up to Global Variables]


Definition

INT focus_status

focus_status is a [predefined] [global variable], holding whether or not the Bennu window has input focus.


Value - Description [false] - The Bennu window does not have input focus. [true] - The Bennu window has input focus.



Fps

[Up to Global Variables]


Definition

INT fps

The [global variable] holds the current frames per second on which [Bennu] is running. This means how many times a frame is executed every second and how many times the screen is updated every second.

If a different FPS is needed, the target FPS can be altered by use of [set_fps]().

If a more accurate FPS is needed, use [frame_time] to calculate it.

If you need to view the FPS in-game, please use the code (in a loop): write_int(0,0,0,0,&fps);


Frame_time

[Up to Global Variables]


Definition

FLOAT frame_time

Frame_time is a [global variable], holding the time passed the last frame. In other words: the difference in time between the start of the last frame and the current frame.

Doing a bit of physics, we see that:

: FPS = 1 / frame_time

Be advised that frame_time is in milliseconds accurate, so it can be 0 at times, so one might prevent such a case from happening:

: FPS = 1 / ( frame_time + (frame_time==0)*0.0001 );

This gives a sort of FPS which is accurate every frame.

Example

Display how long the program has been running, by use of frame_time:

Program timers;
Private
    int ft; // Help variable
    int i;  // how long the program has been running in 1/100s
    float f; // how long the program has been running in 1/100s
Begin

    set_mode(320,400,8);
    write_int   (0,0,300,0,&timer);
    write_int   (0,0,310,0,&i);
    write_float (0,0,320,0,&f);

    Repeat

        // Calculate how long the program has been running in 1/100s without a float
        ft %= 10; // keep the milliseconds from last time
        ft += frame_time*1000; // add the last passed time to it in milliseconds
        i += ft/10; // add it to the integer without the milliseconds

        // Calculate how long the program has been running in 1/100s with a float
        f+=frame_time*100;

        frame;
    Until(key(_ESC))

End

Used in example: [set_mode](), [write_int](), [write_float](), [timer]

Let a [process] wait for a certain time by calling this function:

Function int wait(float seconds)
Begin
    While( (seconds-=frame_time) > 0 ) frame; End
    return -seconds;
End

This can be done with a timer too, as is displayed [here].


Full_screen

[Up to Global Variables]


INT full_screen = false

Description

full_screen is a predefined [global variable]. It defines whether Bennu (libvideo to be more precise) will be rendered in windowed (default) or fullscreen mode.

The value of full_screen can be changed. [false] for windowed mode and [true] for fullscreen mode. For the change to have effect, [set_mode]() needs to be called afterwards.

See also

  • [graph_mode]
  • [scale_mode]

Graph_mode

[Up to Global Variables]


Definition

INT graph_mode

Graph_mode is a [global variable], holding the current [graph mode]. The mode can be changed by assigning a different mode to the variable. Default is 0 and after a call to [set_mode]() it reflects the set graph mode.

See also

  • [sound_mode]
  • [scale_mode]
  • [full_screen]

Mouse

[Up to Global Variables]


Definition

Struct Mouse

Mouse is a [global variable] [struct], containing information about the current state of the mouse. Also graphical settings can be configured to display a [graphic] following the mouse in a certain way.

Members


Member name - Description INT x - The [X]-coordinate of the mouse. INT y - The [Y]-coordinate of the mouse. INT graph - The [graphID] of the mouse. INT file - The [fileID] of the mouse is located. INT z - The [Z]-coordinate of the mouse. INT angle - The [angle] of the mouse process. INT size - The [size] of the mouse process. INT flags - The [render flags] of the mouse process. INT region - The [region] of the mouse process. INT left - [true]: whether the left mouse button is pressed. INT middle - [true]: whether the middle mouse button is pressed. INT right - [true]: whether the right mouse button is pressed. INT wheelup - [true]: whether the mouse wheel is scrolled upwards. INT wheeldown - [true]: whether the mouse wheel is scrolled downwards.


Example

import "mod_map"
import "mod_mouse"
import "mod_wm"

Process Main()
Private
    int dmap;
    int rmap;
    int gmap;
    int bmap;
    int ymap;
    int cmap;
    int mmap;
    int wmap;
Begin

    // Create a dark graph
    dmap = new_map(100,100,8);
    map_clear(0,dmap,rgb(50,50,50));

    // Create a red graph
    rmap = new_map(100,100,8);
    map_clear(0,rmap,rgb(255,0,0));

    // Create a green graph
    gmap = new_map(100,100,8);
    map_clear(0,gmap,rgb(0,255,0));

    // Create a blue graph
    bmap = new_map(100,100,8);
    map_clear(0,bmap,rgb(0,0,255));

    // Create a yellow graph
    ymap = new_map(100,100,8);
    map_clear(0,ymap,rgb(255,255,0));

    // Create a cyan graph
    cmap = new_map(100,100,8);
    map_clear(0,cmap,rgb(0,255,255));

    // Create a magenta graph
    mmap = new_map(100,100,8);
    map_clear(0,mmap,rgb(255,0,255));

    // Create a white graph
    wmap = new_map(100,100,8);
    map_clear(0,wmap,rgb(255,255,255));

    Repeat
        if(mouse.left) // +Red
            if(mouse.right) // +Green
                if(mouse.middle) // +Blue
                    mouse.graph = wmap;
                else
                    mouse.graph = ymap;
                end
            else
                if(mouse.middle) // +Blue
                    mouse.graph = mmap;
                else
                    mouse.graph = rmap;
                end
            end
        elseif(mouse.right) // +Green
            if(mouse.middle) // +Blue
                mouse.graph = cmap;
            else
                mouse.graph = gmap;
            end
        elseif(mouse.middle) // +Blue
            mouse.graph = bmap;
        else // Dark
            mouse.graph = dmap;
        end
        frame;
    Until(exit_status)

End

Used in example: [Mouse], [new_map](), [graph]

Shows some use of maps and the mouse.


Mouse_status

[Up to Global Variables]


Definition

INT mouse_status

mouse_status is a [predefined] [global variable], holding whether or not the mouse cursor is inside the Bennu window.


Value - Description [false] - The mouse cursor is outside the Bennu window. [true] - The mouse cursor is inside the Bennu window.



Os_id

[Up to Global Variables]


Definition

INT os_id

os_id is a [predefined] [global variable], holding the [OS code] of the operating system [Bennu] is currently running on while executing. Default is -1.


Regex_reg

[Up to Global Variables]


Definition

STRING[15] regex_reg

Regex_reg is a [global variable], holding 16 strings. It holds matches when the functions [Regex]() and [Regex_replace]() are used.

Examples

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_regex";

GLOBAL

   string sourcetext="It's raining cat's and dogs";
   string searchtext="cat"; // the search pattern

   int status;

PROCESS main();

BEGIN

   // print the joined string
   say("");

   // looking for the position of the word "cat"
   status=regex(searchtext,sourcetext);

   say("match found at: "+status);
   say("");

   // the last character of a line. 
   status=regex("$","99 bottles of beer on the wall.");

   say(status+" is the last character position in 99 bottles of beer on the wall.");
   say("");

   say("regex_reg[0]="+regex_reg[0]);
   say("regex_reg[1]="+regex_reg[1]);
   say("regex_reg[2]="+regex_reg[2]);
   say("regex_reg[3]="+regex_reg[3]);

   say("regex_reg[4]="+regex_reg[4]);
   say("regex_reg[5]="+regex_reg[5]);
   say("regex_reg[6]="+regex_reg[6]);
   say("regex_reg[7]="+regex_reg[7]);

   say("regex_reg[8]="+regex_reg[8]);
   say("regex_reg[9]="+regex_reg[9]);
   say("regex_reg[10]="+regex_reg[10]);
   say("regex_reg[11]="+regex_reg[11]);

   say("regex_reg[12]="+regex_reg[12]);
   say("regex_reg[13]="+regex_reg[13]);
   say("regex_reg[14]="+regex_reg[14]);
   say("regex_reg[16]="+regex_reg[15]);
END

Restore_type

[Up to Global Variables]


Definition

INT restore_type = PARTIAL_RESTORE

Restore_type is a [global variable], holding the current [restore_mode]. The mode can be changed by assigning a different mode to the variable. Default is [PARTIAL_RESTORE].

See also [dump_type].


Scale_mode

[Up to Global Variables]


INT scale_mode = SCALE_NONE

Description

Scale_mode is a [global variable], holding the current or to be [scale mode]. The mode can be changed by assigning a different mode to the variable and then calling [set_mode](). Default is [SCALE_NONE].

See also

  • [sound_mode]
  • [graph_mode]

Scale_resolution

[Up to Global Variables]


INT scale_resolution = WWWWHHHH

Where WWWW is the Width and HHHH the Height. [Resolution_modes] can be used.

Description

Scale_resolution is a [global variable] used to resize the screen without changing the real resolution. That means the game still uses the resolution indicated by [set_mode]() but it's displayed on the screen at the one assigned to scale_resolution. Unlike [scale_mode] can work with 32bits but doesn't use any filter.

Scale_resolution takes effect after [set_mode]() only and cannot be used togheter with [scale_mode]. Assigning NULL will cancel the use of scale_resolution.

Example

//This example is a modification of an example taken from Oscar's Manual
Import "mod_video";
Import "mod_text";
Import "mod_key";
Import "mod_map";
Import "mod_proc";
Import "mod_draw";

Process Main()
begin
  set_mode(800,600,32);
  write(0,100,80,0,"SCALE_RESOLUTION's value:");
  write_var(0,300,80,0,scale_resolution);
  proceso();
  repeat
    if(key(_a)) scale_resolution=03200240;end
    if(key(_s)) scale_resolution=06400480;end
    if(key(_d)) scale_resolution=08000600;end
    if(key(_f)) scale_resolution=10240768;end
    if(key(_c)) scale_resolution=NULL;end
    set_mode(800,600,32);
    frame;
  until(key(_esc))
  let_me_alone();
end

Process proceso()
begin
  x=180;y=150;
  graph=map_new(60,60,32);
  drawing_map(0,graph);
  drawing_color(rgb(255,255,0));
  draw_fcircle(25,25,25);
  loop
    frame;
  end
end

Used in example: [set_mode](), [write](), [map_new](), [drawing_map](), [drawing_color](), [draw_fcircle]().

See also

[scale_resolution_orientation], [scale_resolution_aspectratio].


Scale_resolution_aspectratio

[Up to Global Variables]


INT scale_resolution_aspectratio = [Scale_resolution_aspectratio_modes].

Description

Scale_resolution_aspectratio is a global variable used to choose between stretching a screen resized by [scale_resolution] to fill the screen or keeping his aspect ratio.

Example

Import "mod_video";
Import "mod_text";
Import "mod_key";
Import "mod_map";
Import "mod_proc";
Import "mod_screen";

Process Main()
begin
  set_mode(800,600,32);
  write(0,20,20,0,"SCALE_RESOLUTION:");
  write_var(0,160,20,0,scale_resolution);
  write(0,20,30,0,"( Press R) ");
  write(0,20,50,0,"SCALE_RESOLUTION_ORIENTATION:");
  write_var(0,255,50,0,scale_resolution_orientation);
  write(0,20,60,0,"( Press 0, 1, 2 or  ) ");
  write(0,20,90,0,"SCALE_RESOLUTION_ASPECTRATIO:");
  write_var(0,255,90,0,scale_resolution_aspectratio);
  write(0,20,100,0,"( Press A ) ");
  Screen_put(0,png_load("mz800x600.png"));
  repeat
    //Activates/deactivates scale_resolution. 
    if(key(_r))
      while(key(_r)) frame; end   //Wait until the key is released
      if (scale_resolution==0);    //If scale_resolution is not active...
        scale_resolution=08000480; //...then resize the screen 
      else                         //If scale_resolution is already working...
        scale_resolution=NULL;     //...then stop it.
      end
    end 

    //This rotates the screen. Only works when SCALE_RESOLUTION is being used. 
    if(key(_0)) scale_resolution_orientation=SRO_NORMAL;end
    if(key(_1)) scale_resolution_orientation=SRO_LEFT;end
    if(key(_2)) scale_resolution_orientation=SRO_DOWN;end
    if(key(_3)) scale_resolution_orientation=SRO_RIGHT;end

    //This activates/deactivates the ASPECT RATIO. Only works when SCALE_RESOLUTION is being used. 
    if(key(_a))
      while(key(_a)) frame; end
      if (scale_resolution_aspectratio==0);
        scale_resolution_aspectratio=SRA_PRESERVE;
      else
        scale_resolution_aspectratio=SRA_STRETCH;
      end
    end 

    set_mode(800,600,32);
    frame;
  until(key(_esc))
  let_me_alone();
end

Used in example: [write](), [write_var](), [Screen_put]()

File used in example: Mz800x600.png by MZ.

See also

[scale_resolution], [scale_resolution_orientation]


Scale_resolution_orientation

[Up to Global Variables]


INT scale_resolution_orientation = [Scale_resolution_orientation_modes].

Description

Scale_resolution_orientation is a global variable used to rotate a screen resized by [scale_resolution] without changing the real orientation.

Example

Import "mod_video";
Import "mod_text";
Import "mod_key";
Import "mod_map";
Import "mod_proc";
Import "mod_screen";

Process Main()
begin
  set_mode(800,600,32);
  write(0,20,20,0,"SCALE_RESOLUTION:");
  write_var(0,160,20,0,scale_resolution);
  write(0,20,30,0,"( Press R) ");
  write(0,20,50,0,"SCALE_RESOLUTION_ORIENTATION:");
  write_var(0,255,50,0,scale_resolution_orientation);
  write(0,20,60,0,"( Press 0, 1, 2 or  ) ");
  write(0,20,90,0,"SCALE_RESOLUTION_ASPECTRATIO:");
  write_var(0,255,90,0,scale_resolution_aspectratio);
  write(0,20,100,0,"( Press A ) ");
  Screen_put(0,png_load("mz800x600.png"));
  repeat
    //Activates/deactivates scale_resolution. 
    if(key(_r))
      while(key(_r)) frame; end   //Wait until the key is released
      if (scale_resolution==0);    //If scale_resolution is not active...
        scale_resolution=08000480; //...then resize the screen 
      else                         //If scale_resolution is already working...
        scale_resolution=NULL;     //...then stop it.
      end
    end 

    //This rotates the screen. Only works when SCALE_RESOLUTION is being used. 
    if(key(_0)) scale_resolution_orientation=SRO_NORMAL;end
    if(key(_1)) scale_resolution_orientation=SRO_LEFT;end
    if(key(_2)) scale_resolution_orientation=SRO_DOWN;end
    if(key(_3)) scale_resolution_orientation=SRO_RIGHT;end

    //This activates/deactivates the ASPECT RATIO. Only works when SCALE_RESOLUTION is being used. 
    if(key(_a))
      while(key(_a)) frame; end
      if (scale_resolution_aspectratio==0);
        scale_resolution_aspectratio=SRA_PRESERVE;
      else
        scale_resolution_aspectratio=SRA_STRETCH;
      end
    end 

    set_mode(800,600,32);
    frame;
  until(key(_esc))
  let_me_alone();
end

Used in example: [write](), [write_var](), [Screen_put]()

File used in example: Mz800x600.png by MZ.

See also

[scale_resolution], [scale_resolution_aspectratio]


Scan_code

[Up to Global Variables]


Definition

INT scan_code

Scan_code is defined in the module [mod_key] and, in contrast to [ascii], it contains the last key pressed, not the last character. That means “A” and “a” will have the same scan_code, but different [ascii] value.

Notes

Take a look at the [scancodes] for a complete list.

Example

import "mod_text"
import "mod_key"
import "mod_video"

process main()
begin
    set_mode(640,320);

    write( 0, 60, 10, 0, "Use lower and upper case characters to see the difference");
    write( 0, 60, 20, 0, "between ascii and scan_code.    (ESC to exit)  ");

    write( 0, 60, 40, 0, "ascii: ");
    write_var( 0, 110, 40, 0, ascii);

    write( 0, 26, 50, 0, "scan_code: ");
    write_var( 0, 110, 50, 0, scan_code);

    while ( !key(_esc))
        frame;
    end
end   

Scroll

Definition

STRUCT[9] Scroll

Scroll is a global variable struct array, containing information about the current state of the ten available scrolls (0..9). It is used to influence the settings of a scroll window, initiated by start_scroll().

Members of the scroll struct

Member name Description
INT x0 The X-coordinate of the foreground graphic.*
INT y0 The Y-coordinate of the foreground graphic.*
INT x1 The X-coordinate of the the background graphic.*
INT y1 The Y-coordinate of the the background graphic.*
INT z The Z-coordinate of the scroll window (default: 512).**
INT camera The processID of the process to be followed (default: 0).***
INT ratio The ratio in percent the foreground will move related to the background (default: 200).***,****
INT speed The maximum speed of the foreground, 0 for no limit (default: 0).***
INT region1 The region in which the scroll won't move, -1 for none (default: -1).***
INT region2 The region in which the maximum speed is ignored, -1 for none (default: -1).***
INT flags1 The bit flags for the foreground graphic.
INT flags2 The bit flags for the background graphic.
INT follow The scrollID of the scroll window to follow, -1 means none (default: -1).
INT[6] reserved Seven reserved integers.
* These fields become read only when the scroll window is in automatic mode (see notes).
** Processes on the scroll use this z value (see notes).
*** These fields only make sense when the scroll window is in automatic mode (see notes).
**** The ratio is in percent: 200 means the background moves twice as slow.

Notes

There are two main methods of controlling a scroll window. One is the manual way, thus changing the values of the x0,y0,x1 and y1 manually. This mode is used when the camera field is not set (is 0). When it is set with a processID, the scroll window is in automatic mode and will follow that process' coordinates and will try to keep it centered. This can be influenced by other members of the scroll struct.

The foreground is the plane to be controlled and the background moves relative to the foreground. If you want to move the background manually, you first need to set the scroll ratio to 0.

Processes in a scroll take over the z value of that scroll's z. Between processes on the same scroll the local variable z of that process does have the expected effect.


Shift_status

[Up to Global Variables]


Definition

INT shift_status

Shift_status is defined in the module [mod_key] and indicates whether a modifier key is being pressed. If more than a modifier key is pressed at the same time shift_status will return the sum.

List


Key - Value Right Control - 20 * Left Control - 36 Right Alt - 72 * Left Alt - 136 NUM LOCK - 256 CAPS LOCK - 512 Right Shift - 1025 Left Shift - 1026


* At the time of the writing of this article, right alt and right control didn't return anything. It is unknown whether it is a bug or just deprecated.


Sound_channels

[Up to Global Variables]


Definition

INT sound_channels = 8

Sound_channels is a [global variable], holding the number of sound channels, which is set when sound is used for the first time, meaning altering the value of this variable will have no effect after sound has been initialized. This number can range from 1 to 32 and the default is 8.

See also

  • [sound_mode]
  • [sound_freq]

Sound_freq

[Up to Global Variables]


Definition

INT sound_freq = 22050

Sound_freq is a [global variable], holding the set sound frequency, which is set when sound is used for the first time, meaning altering the value of this variable will have no effect after sound has been initialized. The higher the frequency, the higher the quality is. Accepted frequencies are:

  • 44100: high quality (recommended)
  • 22050: medium quality (default)
  • 11025: low quality (not recommended)

See also

  • [sound_mode]
  • [sound_channels]

Sound_mode

[Up to Global Variables]


Definition

INT sound_mode = MODE_STEREO

Sound_mode is a [global variable], holding the set [sound mode], which is set when sound is used for the first time, meaning altering the value of this variable will have no effect after sound has been initialized. The mode can be changed by assigning a different mode to the variable. Default is [MODE_STEREO].

See also

  • [graph_mode]
  • [sound_freq]
  • [sound_channels]

Text_flags

[Up to Global Variables]


Definition

INT text_flags = 0

Text_flags is a [global variable]. When a [dynamic text] is created ([write] value will equal the value of text_flags at the moment of creation. The default value is 0.

See also

  • [text_z]
  • [TextID]

Text_z

[Up to Global Variables]


Definition

INT text_z = -256

Text_z is a [global variable]. When a [dynamic text](), etc), its [z] value will equal the value of text_z at the moment of creation. The default value is -256.

See also

  • [z]
  • [text_flags]
  • [TextID]

Timer

[Up to Global Variables]


Definition

INT[9] timer

Timer is a [global variable], holding ten integers. Each [frame] a certain value is added to all of them. This value is the difference in time between the start of the last frame and the current frame, in 1/100 seconds.

So when all the timers are never altered, their values will be 1234 when the program has been running for about 12.34 seconds.

Examples

Display how long the program has been running

import "mod_timers"
import "mod_key"
import "mod_text"

Process Main()
Begin

    write_int(0,0,100,0,&timer[0]);

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [write_int](), [key]

This can be done more accurately with the use of [frame_time], which is in milliseconds.

Let a [process] wait for a certain time by calling this function

Function int wait(int t)
Begin
    t += timer[0];
    While(timer[0]<t) frame; End
    return t-timer[0];
End

This can be done without a timer too, as is displayed [here].


Window_status

[Up to Global Variables]


Definition

INT window_status

window_status is a [predefined] [global variable], holding whether or not the Bennu window is visible. For example the window is not visible when it is minimized.


Value - Description [false] - The Bennu window is not visible. [true] - The Bennu window is visible.




List of Locals

angle

[Up to Local Variables]


Definition

INT angle = 0

Angle is a predefined [local variable] which holds the angle (measured in 1/1000 of a degree) at which the [graphic] (assigned by the local variable [graph]) will be drawn. It also influences the result of the [function]().

An angle of 0 means to the right, 90000 means up, 180000 means left and 270000 and -90000 mean down.

Example

To make the graphic of a process spin:

import "mod_grproc"
import "mod_map"
import "mod_wm" // for exit_status
import "mod_key" // for key()

Process Main()
Begin
    graph = map_new(100,100,8);  //Create a cyan square and assign it to 'graph'
    map_clear(0,graph,rgb(0,255,255));
    x = 160;     //Position the graphic's center
    y = 100;     //in the center of the screen
    Repeat
        angle += 1000;    //increase the angle of graphic by 1000 each frame. 1000 = 1 degree.
        frame;
    Until(key(_ESC) || exit_status)
OnExit
    map_unload(0,graph);
End

Used in example: [map_new](), [map_clear](), [map_unload](), [exit_status], [x]

This process will spin the cyan square by 1 degree each frame.


bigbro

[Up to Local Variables]


Definition

INT bigbro

Bigbro is a predefined [local variable]. Bigbro holds the [ProcessID] of the [process] that was immediately called before by the [father] of the current [process]. There are several other local variables which refer to the ProcessID of a related process:

  • [Father]
  • [Son]
  • [Smallbro]

c_number

[Up to Local Variables]


Definition

The cnumber is variable that is used when there's more then one [scroll] window active, i.e. in a splitscreen configuration with two or more scroll or mode7 windows.

The cnumber indicates in wich window(s) the process is visible. It is only necessary for processes that are intended to visible in a scroll or mode7 window. The default value is 0, wich means that the process is visible in all scroll or mode7 windows. Up to 10 scroll or mode7 windows can be defined, wich are numbered from 0 to 9, wich are enumerated by the predefined constants [C_0], [C_2], [C_5], [C_8].

The cnumbers can be added, and the sum of these indicate the visibility. If there, are for instance 4 scroll windows active, (numbered 0, 1, 2, and 3) and a specific process should only be visible in windows 0 and 2, then you should use:

cnumber = C_0 + C2; // this is 1+4

It is possible to change the value of the cnumber in runtime, wich can be handy in certain situations.

Look for more information about scrolls and mode7 in the articles of the [Start_scroll]() and [Start_mode7]() functions.


ctype

[Up to Local Variables]


Definition

Coordinatetype modes are used to set the type of coordinatesytem to be used, by assigning them to the [local variable]. Different coordinatesystems have different ways of interpreting the coordinates of a process. There's another local variable which influences the interpretation of a process' coordinate, which is [Resolution].

How to change in which individual [scroll] or [Mode7]-view the process is visible, see [C_number] and [its constants].

List


Constant - Value - Relative to C_SCREEN - 0 - The [ screen]'s top left corner, coordinate (0,0). C_SCROLL - 1 - The foreground graphic of the [scroll] in which the process is shown. C_M7 - 2 - The main graphic of the [Mode7]-view.



father

[Up to Local Variables]


Definition

INT father

Father is a predefined [local variable]. Father holds the [ProcessID] of the [process] that called the current [process]. There are several other local variables which refer to the ProcessID of a related process:

  • [Son]
  • [Bigbro]
  • [Smallbro]

Example

Program example;
Begin
    first_process();
    Loop
        frame;
    End
End

Process first_process()  // Declaration of the first process
Begin
    second_process();  // Call the second process
    Loop
        frame; // This loop makes "first_process()" a process rather than a function
    End
End

Process second_process()  //declaration of another process
Begin
    x = father.x; // These two lines use the father variable to move this process
    y = father.y; // to the position of first_process, as the father variable here
                  // holds the ProcessID of "first_process()"
    Loop
        frame;  
    End
End

Used in example: [process], [function]


file

: This is about the [filetype]. Did you mean the local variable [file] or the function [file]()?


[Up to Filetypes]


Description

A file is a container for [graphics], identified by a non-negative [integer] (0 or higher). It holds all information about the contained graphics ([pixels], [width], [depth], name, etc). Each of these graphics have a unique identifier inside the file (positive [int]).

A file can be created for example by loading an [FPG] (Fichero Para Gráficos, meaning "file for graphics") into it, by using [fpg_load](), which creates a new file with the graphics from the loaded FPG and returns a unique identifier. Another option is to create a new, empty one by using [fpg_new](). Don't let the name fpg_new() fool you: fpg_new() has nothing to do with the filetype FPG. This is because the FPG format is only for files and not for internal use. There are more ways to load graphics into a file.

A file can be used by using the [local variable] or by using the identifier in the various [functions] with a file parameter.

Don't forget to unload it with [fpg_unload]() after use.

Example

import "mod_map"
import "mod_grproc"
import "mod_key"
import "mod_wm"

Global
    int file_id;
    int file_id2;
End

Process Main()
Begin

    // Load FPG
    file_id = load_fpg("example.fpg");
    file_id2 = load_fpg("example2.fpg");

    // Set locals for display of graph
    file = file_id;
    graph = 1;
    x = y = 50;

    // assign Ship to use example2.fpg
    Ship(300,100,5,file_id2,1); // undefined in this sample

    Repeat
        frame;
    Until(key(_ESC)||exit_status)

End

Used in example: [load_fpg](), [key], [file]. [process]

Media in example: [example.fpg]

Note: nothing will be seen unless you have an [FPG] "example.fpg" with a [graphic] with ID 1.


flags

[Up to Local Variables]


Definition

INT flags = 0

Flags is a predefined [local variable] which is used to manipulate how the [graphic] of a [process], assigned to its local variable [graph], is displayed.

To alter the effect, change the value of this local variable by assigning it [blit flags]. Like most [bit flags], constants can be added together to combine effects. A horizontally mirrored translucent graphic would need flags B_TRANSLUCENT (4) and B_HMIRROR (1), so flags = B_TRANSLUCENT|B_HMIRROR (5) will do the trick.

Example

To make the graphic of a process spin:

Program mirror
Begin
    mirror_graphic();
    Loop
        frame;
    End
End
Process mirror_graphic()
Begin
    graph = new_map(50,50,8);
    map_clear(0,graph,rgb(0,255,255));
    x = 100;     //Position the graphic 100 pixels
    y = 100;     //from the top and left of the screen
    Loop
        if (key(_l))
            flags = B_HMIRROR; //if you press the L key, your graphic is horizontally mirrored
        else
            flags = 0;
        end       
        frame;
    End
End

The process will mirror its graphic when the key L is held down.


graph

[Up to Local Variables]


Definition

INT graph = 0

Graph is a predefined local variable which holds the [GraphID] of the process. A [graphic] can be assigned to the process by assigning the [GraphID] of that graphic to graph. Assign 0 to the local variable graph to have the process display no graph. Keep in mind that this doesn't free the memory used by the graphic; to free it, use [unload_map]().

Example

Process cyan_graphic()
Begin
    graph = new_map(100,100,8);   // create a new 100x100x8 map.
    map_clear(0,graph,rgb(0,255,255));   // clear it cyan-colored
    x = 100;     //Position the graphic 100 pixels
    y = 100;     //from the top and left of the screen
    Repeat
        frame;
    Until(key(_ESC))
End

Used in example: [new_map](), [map_clear], [x]


height

[Up to Local Variables]


Definition

The predefined local variable height is used in [Mode7] windows, and it is assigned to each process. It is therefore only relevant in the coordinate system of mode7 ([Ctype]). It is used to define the height of the process graphics in relation to the semi-3d field. This is not to be confused with the local variable [Z], as that is used to control the depth of the graphical layers.

The height is normally a positive number, because the height of the bottom is 0, and all the processes are placed above it. When the height variable is not defined, it is 0 by default. The graphic base is placed at the indicated height, with the exception when [controlpoint] number 0 is changed (the default is overruled by the [Center_set]() function). In that case, the controlpoint will be placed at that height.


priority

[Up to Local Variables]


Definition

INT priority = 0

priority is a predefined [local variable], holding the priority of the [process]; default is 0.

Using this priority, the order of process-execution can be influenced, because processes with a higher priority are executed before processes with a lower priority.

Example

import "mod_say"
import "mod_proc"
import "mod_timers"

Process A()
Begin
    priority = 0; // Default
    Loop
        say("[" + timer[0] + "] " + "A");
        frame(100000000); // This is very high because Bennu runs without limiter here
    End
End

Process main()
Private
    int f=0;
Begin
    priority = 1; // Set to higher priority than A
    A();
    Repeat
        f++;
        say("[" + timer[0] + "] " + "Main");
        frame(100000000); // This is very high because Bennu runs without limiter here
    Until(f==5)
OnExit
    let_me_alone();
End

Used in example: [say](), [let_me_alone], [priority]

Possible output:

[0] A
[0] Main
[26] Main
[26] A
[50] Main
[50] A
[74] Main
[74] A
[98] Main
[98] A

It can be seen here that regardless of priority, A is first executed, because A is called by Main. As soon as A reaches its [frame] statement, Main continues until its frame statement and this concludes the first frame. The second frame it is shown that the priority has effect: Main is executed before A.


region

[Up to Local Variables]


Definition

Local variable

INT region = 0

Region is a predefined [local variable]. Region holds the [RegionID] of the [region]' [graphic] should only be displayed in. By default this is region 0, the whole screen.

The graphic of the process is only displayed in its region, even if the x and y coordinates are outside of the region, the part inside the region will still be displayed.

Concept

A region is a rectangular field inside the screen. It can be defined with [define_region]() and can be useful for displaying graphics in only certain parts of the screen and for the function [region_out](). There are 32 regions (0..31) and region 0 is the whole screen.


reserved

[Up to Local Variables]


Definition

Struct Reserved

Reserved is a [local variable] [struct], containing information that is reserved for [Bennu]'s internals. However, sometimes you may wish to use certain members of it. Using in the sense of reading only, do not under any circumstances alter their values, unless you know what you are doing.

If it's not documented what these members do, their use is reasonably limited. If you want to know what these members do, your programming goals are of a level, where you can also look in the [sourcecode]. This is because most of these members would require a lengthy explanation about what they do and why.

Members


Member name - Description INT ID_scan - Internal use only (formerly [got]). INT process_type - The [ProcessTypeID] of the process. INT type_scan - Internal use only (formerly [got] from within the process). INT status - The status of the process, containing a [status code]. INT changed - Internal use only. INT xgraph_flags - Internal use only ([blit flags]). INT saved_status - Internal use only (for [signals]). INT prev_z - Previous [z] value. INT distance1 - Not used. INT distance2 - Not used. INT frame_percent - Internal use only. INT box_x0 - The x-coordinate of the topleft corner of the process' [graphic] (process.x-graphic.width/2). INT box_y0 - The y-coordinate of the topleft corner of the process' graphic (process.y-graphic.height/2). INT box_x1 - The x-coordinate of the bottomright corner of the process' graphic (process.x+graphic.width/2). INT box_y1 - The y-coordinate of the bottomright corner of the process' graphic (process.y+graphic.height/2).



resolution

[Up to Local Variables]


Definition

Local variable

INT resolution = 0

[Resolution] is used to alter the precision of the position of [processes] on screen; the level of precision is defined by the value of resolution.

This simulating of fractions in positions is useful for calculations or animations in need of a high precision in order to work properly. It causes the coordinates of all processes to be interpreted as being multiplied by the value of the local variable resolution, associated with that process. So when a process' [graphic] is displayed, it will appear as if the process' [x] and [y] values were divided by the value of resolution. A resolution of 0 is interpreted as if it were 1.

The default value of [resolution] is 0, so set it to 1 if the correct value is needed.

Screen Resolution

The resolution of a screen is the dimensions of the screen in pixels. [Bennu]'s default screen resolution is 320×200 pixels. This can be altered by use of [set_mode]().

Example

import "mod_grproc"
import "mod_time"
import "mod_key"
import "mod_video"
import "mod_map"
import "mod_draw"
import "mod_proc"
import "mod_wm"

Process Main()
Begin

    // Set screen resolution to 320x200 with a color depth of 8bit
    set_mode(320,200,8);

    // Set the FPS to 60
    set_fps(60,0);

    // Set resolution for this process (try changing it to see the effect)
    resolution = 100;

    // Create a 200x200 cyan circle and assign its graphID to the local variable graph
    graph = map_new(200,200,8);
    drawing_map(0,graph);
    drawing_color(rgb(0,255,255));
    draw_fcircle(100,100,99);

    // Set size
    size = 10;

    // Set the coordinates at screen position (160,180).
    x = 160 * resolution;
    y = 180 * resolution;

    // Move around in circles while leaving a trail behind
    Repeat
        trail(x,y,graph,(int)(0.2*size),get_timer()+1000); // create a mini reflection of this process,
                                                // lasting one second
        advance(3*resolution); // advance (3 * resolution) units (= 3 pixels)
        angle+=2000; // turn 2 degrees left
        frame;
    Until(key(_ESC)||exit_status)

OnExit

    let_me_alone();
    map_unload(0,graph);

End

Process trail(x,y,graph,size,endtime)
Begin

    // Get the resolution of the process calling this one
    resolution = father.resolution;

    // Remain existent until the specified endtime was reached
    Repeat
        frame;
    Until(get_timer()>=endtime)

End

Used in example: [set_mode](), [set_fps](), [drawing_map](), [drawing_color](), [draw_fcircle](), [get_timer](), [let_me_alone](), [map_unload](), [resolution], [size], [angle]

Here are a few screenshots with different resolutions to display the effect it can have.

The effect is clearly visible, so when you are moving processes with graphics around the screen, you might want to consider using a resolution of at least 10 in those processes.


size

[Up to Local Variables]


Definition

INT size = 100

Size is a predefined [local variable] that can be used to stretch or compress a graphic, equally along the horizontal axis and vertical axis. It is defined as a percentage of the original graphic size. The graphics's center will remain at the drawing coordinates when the graphic is drawn.

This variable only has effect for the appearance of a [process] when its local variables [size_x] and [size_y] are both 100. When either is not equal to 100, [size] doesn't affect the appearance of the graphic.

Example

To make the [graphic] of a [process] continually stretch:

Process Main()
Begin
    graph = new_map(50,50,8); // Create a new graphic
    x = 100;                  // Position the graphic 100 pixels
    y = 100;                  // from the top and left of the screen
    Loop
        size += 1;            // Increase the height and width of the graphic by 1 percent each frame.
        frame;
    End
OnExit
    unload_map(0,graph);
End

Used in example: [new_map], [y], [unload_map]()

See also

  • [size_x]
  • [size_y]

size_x

[Up to Local Variables]


Definition

INT size_x = 100

Size_x is a predefined [local variable] that can be used to stretch or compress a graphic along its horizontal axis. It is defined as a percentage of the original graphic size. The graphics's center will remain at the drawing coordinates when the graphic is drawn.

When either [size_x] of a [process] are unequal to [code]100[/code], that process' [size] has no effect.

Example

To make the [graphic] of a [process] continually stretch horizontally:

Process Main()
Begin
    graph = new_map(50,50,8); // Create a new graphic
    x = 100;                  // Position the graphic 100 pixels
    y = 100;                  // from the top and left of the screen
    Loop
        size_x += 1;          // Increase the width of the graphic by 1 percent each frame.
        frame;
    End
OnExit
    unload_map(0,graph);
End

Used in example: [new_map](), [[x], [y], [unload_map]()

See also

  • [size]
  • [size_y]

size_y

[Up to Local Variables]


Definition

INT size_y = 100

Size_y is a predefined [local variable] that can be used to stretch or compress a graphic along its vertical axis. It is defined as a percentage of the original graphic size. The graphics's center will remain at the drawing coordinates when the graphic is drawn.

When either [size_x] of a [process] are unequal to [code]100[/code], that process' [size] has no effect.

Example

To make the [graphic] of a [process] continually stretch vertically:

Process Main()
Begin
    graph = new_map(50,50,8); // Create a new graphic
    x = 100;                  // Position the graphic 100 pixels
    y = 100;                  // from the top and left of the screen
    Loop
        size_y += 1;          // Increase the height of the graphic by 1 pixel each frame.
        frame;
    End
OnExit
    unload_map(0,graph);
End

Used in example: [new_map](), [[x], [y], [unload_map]()

See also

  • [size]
  • [size_x]

smallbro

[Up to Local Variables]


Definition

INT smallbro

Smallbro is a predefined [local variable]. Smallbro holds the [ProcessID] of the [process] that was immediately called after by the [father] of the current [process]. There are several other local variables which refer to the ProcessID of a related process:

  • [Father]
  • [Son]
  • [Bigbro]

son

[Up to Local Variables]


Definition

INT son

Son is a predefined [local variable]. Son holds the [ProcessID] of the [process] that was last called by the current [process]. There are several other local variables which refer to the ProcessID of a related process:

  • [Father]
  • [Bigbro]
  • [Smallbro]

x

: This is about the [local variable]. Did you mean the scan code [_X]?


[Up to Local Variables]


Definition

INT x = 0

X is a predefined [local variable] that defines the vertical position of the process graph in the screen.

See also

  • [y]
  • [z]

xgraph

[Up to Local Variables]


Definition

The predefined local variable xgraph is assigned to each process. It is the so called "extended" graphic, and it allows graphics to be displayed that are controlled by the nearest process [Angle]. When the xgraph is defined, the normal variable [Graph] is ignored, and the graphic used for display is determined by the angle.

So when the angle changes, a different graphic is selected from a table (defined as an [Array]). The standard value of xgraph is 0, so normally it isn't used unless it is explicitly specified. Xgraps are usefull in combination with [Mode7], to create graphics with perspectives. This mechanism is similair to how Wolfenstein3D, Doom and Duke Nukem 3D render their sprites. So it's not true 3d, but just a bunch of sprites wich perspective depends on the viewing angle.

How to use it

First, you'll have to make sprites for all intended perspective's. To more angle's you wish, the more perspectives you'll need.

Second, you must place the graphics in order of their angle, in clockwise fashion.

Third, you'll have to make a table with the graphic codes.

GLOBAL

perspective_table[]=4,10,11,12,13; // the length doesn't matter, but the more perspectives you wish, 
                                   // the more graphics you need to have.

Fourth, you'll have to assing the table offset to the xgraph.

xgraph=&perspective_table; // xgraph get's the offset adress of the array.

The [Offset] operator is get's the adress of the data, this is related to pointers.

Remarks

When xgraph is defined, it has to be set to 0 in order to deactivate it.

When a graphic code in the table has a negative number, this graphic will be mirrored horizontally.


y

: This is about the [local variable]. Did you mean the scan code [_Y]?


[Up to Local Variables]


Definition

INT y = 0

Y is a predefined [local variable] that defines the horizontal position of the process graph in the screen.

See also

  • [x]
  • [z]

z

: This is about the [local variable]. Did you mean the scan code [_Z]?


[Up to Local Variables]


Definition

INT z = 0

Z is a predefined [local variable] that defines the depth position of the process [graph] in the [screen]. This variable affects what process [graph] will be drawn before other one. A process with higher z will be drawn beneath a process with a lower z.

See also

  • [x]
  • [y]


Functions

[Up to Index]

[Function Categories]


List of all documented functions regarding [Bennu]: native, [DLL] or otherwise.


category=functions notnamespace = Template redirects = include

mode=userformat ordermethod = titlewithoutnamespace

columns = 5 listseparators = ,\n* [%TITLE%](),, resultsfooter = \n%PAGES% functions replaceintitle = /\\? /,_



Crypt

crypt_decrypt() (MISSING)

crypt_del() (MISSING)

crypt_encrypt() (MISSING)

crypt_new() (MISSING)


Debug

say()

Definition

INT say ( <STRING message> )

Prints message to stdout (console).

  • Similar to System.out.println(message) in Java.
  • Similar to printf("%s\n",message) in C

Parameters


STRING message - The message to print to stdout


Returns

INT - [true]

Example

import "mod_say"

Process Main()
Begin
    Say("Hello World!");
End

This will result in the output on console:

Hello World!

say_fast()

Definition

INT say_fast ( <STRING message> )

Prints message to stdout (console). This function is the same as the [Say]() function, but with the difference that the debugging information isn't flushed (buffered) into the standard output. As you can see in the bennu source code mod_say.c, the difference is only 1 instruction, so it's slightly faster.

  • Similar to System.out.println(message) in Java.
  • Similar to printf("%s\n",message) in C

Parameters


STRING message - The message to print on to the console


Returns

INT - [true]

Example

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";

GLOBAL

int count;

PROCESS main();

BEGIN

   say("hello world.");
   say("");
   say("");
   FOR (count=0; count<5000; count+=1)
      say_fast("count: "+count);
   END
END

This will result in the output on console:

Hello World!


Drawing

delete_draw()

Definition

INT delete_draw ( <INT DrawID> )

Deletes a certain [drawing] from the screen.

Parameters


INT DrawID - [DrawID] to be deleted.


Returns

INT : [true]

Notes

Delete_draw\ deletes all drawings from the screen.


draw_box()

Definition

INT draw_box ( <INT x0> , <INT y0> , <INT x1> , <INT y1> )

Draws a filled rectangle with corners (x0,y0), (x0,y1), (x1,y0) and (x1,y1).

Parameters


INT x0 - The x coordinate of one corner of the filled rectangle. INT y0 - The y coordinate of one corner of the filled rectangle. INT x1 - The x coordinate of the diagonally opposite corner of the filled rectangle. INT y1 - The y coordinate of the diagonally opposite corner of the filled rectangle.


Returns

INT : [DrawID]


-1 - Error. 1 - If drawn after [drawing_map](). !-1&&!1 - The [DrawID] created.



draw_circle()

Definition

INT draw_circle ( <INT x> , <INT y> , <INT radius> )

Draws a non-filled circle with center (x0,y0) and radius radius.

Parameters


INT x - The x coordinate of one center of the non-filled circle. INT y - The y coordinate of one center of the non-filled circle. INT radius - The radius of the non-filled circle.


Returns

INT : [DrawID]


-1 - Error. 1 - If drawn after [drawing_map](). !-1&&!1 - The [DrawID] created.



draw_curve()

Definition

INT draw_curve ( <INT x0> , <INT y0> , <INT x1> , <INT y1> , <INT x2> , <INT y2> , <INT x3> , <INT y3> , <INT smoothness> )

Draws a curve starting at the point (x0,y0), ending at the point (x3,y3) and influenced by the points (x1,y1) and (x2,y2) with a certain level of smoothness.

Parameters


INT x0 - The x coordinate of the starting point of the curve. INT y0 - The y coordinate of the starting point of the curve. INT x1 - The x coordinate of the first influence point of the curve. INT y1 - The x coordinate of the first influence point of the curve. INT x2 - The x coordinate of the second influence point of the curve. INT y2 - The x coordinate of the second influence point of the curve. INT x3 - The x coordinate of the end point of the curve. INT y3 - The y coordinate of the end point of the curve. INT smoothness - The smoothness with which the line will be drawn from 1 to 15, 15 being the smoothest.


Returns

INT : [DrawID]


-1 - Error. 1 - If drawn after [drawing_map](). !-1&&!1 - The [DrawID] created.


Example

import "mod_draw"
import "mod_video"
import "mod_mouse"
import "mod_map"

GLOBAL
scr_width = 640, scr_height=480;
End;

Process main()
Begin
    /* Check that we can set the video mode before actually setting it */
    if(!mode_is_ok(scr_width, scr_height, 16, MODE_WINDOW))
        return -1;
    end;
    set_mode(scr_width, scr_height, 16, MODE_WINDOW);

    /* Draw three long bezier lines with different colors and smoothnesses */
    drawing_map(0, 0);
    drawing_color(rgb(255, 0, 0));
    draw_curve(0, scr_height/4, scr_width/4, 0, 3*scr_width/4, 2*scr_height/4,
               scr_width, scr_height/4, 1);
    drawing_color(rgb(0, 255, 0));
    draw_curve(0, 2*scr_height/4, scr_width/4, scr_height/4, 3*scr_width/4,
               3*scr_height/4, scr_width, 2*scr_height/4, 3);
    drawing_color(rgb(0, 0, 255));
    draw_curve(0, 3*scr_height/4, scr_width/4, 2*scr_height/4, 3*scr_width/4,
               4*scr_height/4, scr_width, 3*scr_height/4, 15);

    while(! mouse.left)
        FRAME;
    end;

    // Delete all the lines
    delete_draw(0);
End;

Used in example: [mode_is_ok](), [set_mode](), [drawing_map]() [drawing_color](), [draw_curve](), [delete_draw]()


draw_fcircle()

Definition

INT draw_fcircle ( <INT x> , <INT y> , <INT radius> )

Draws a filled circle with center (x0,y0) and radius radius.

Parameters


INT x - The x coordinate of one center of the filled circle. INT y - The y coordinate of one center of the filled circle. INT radius - The radius of the filled circle.


Returns

INT : [DrawID]


-1 - Error. 1 - If drawn after [drawing_map](). !-1&&!1 - The [DrawID] created.



draw_line()

Definition

INT draw_line( <INT x0> , <INT y0> , <INT x1> , <INT y1> )

Draws a line from point (x0,y0) to point (x1,y1).

Parameters


INT x0 - The x coordinate of one point of the line. INT y0 - The y coordinate of one point of the line. INT x1 - The x coordinate of the other point of the line. INT y1 - The y coordinate of the other point of the line.


Returns

INT : [DrawID]


-1 - Error. 1 - If drawn after [drawing_map](). !-1&&!1 - The [DrawID] created.



draw_rect()

Definition

INT draw_rect ( <INT x0> , <INT y0> , <INT x1> , <INT y1> )

Draws a non-filled rectangle with corners (x0,y0), (x0,y1), (x1,y0) and (x1,y1).

Parameters


INT x0 - The x coordinate of one corner of the non-filled rectangle. INT y0 - The y coordinate of one corner of the non-filled rectangle. INT x1 - The x coordinate of the diagonally opposite corner of the non-filled rectangle. INT y1 - The y coordinate of the diagonally opposite corner of the non-filled rectangle.


Returns

INT : [DrawID]


-1 - Error. 1 - If drawn after [drawing_map](). !-1&&!1 - The [DrawID] created.



drawing_alpha()

Definition

INT drawing_alpha ( <INT alpha> )

Tells [Bennu] to draw the coming [drawings] value

Note: there currently is a 'bug' that makes drawing objects (draw commands with no map as target) have their alpha value altered too. This is to be changed.

Parameters


INT alpha - The alpha value to be drawn with.


Returns

INT : [true]


drawing_color()

Definition

INT drawing_color ( <INT color> )

Tells [Bennu] to draw the coming [drawings] in a certain color.

Parameters


INT color - The color to be drawn in (see [rgb]()).


Returns

INT : [true]


drawing_map()

Definition

INT drawing_map ( <INT fileID> , <INT graphID> )

Tells [Bennu] to draw the coming [drawings] on a certain [graphic].

In order to draw with a certain z value again, [drawing_z]() can be used.

Parameters


INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] to draw on.


Returns

INT : [true]


drawing_stipple()

Definition

INT drawing_stipple ( <INT stipples> )

Tells [Bennu] which pixels to draw of the coming [drawings].

This is done by passing a 32bit value, each bit representing a pixel. Bit 0 represents the first pixels drawn, bit 1 represents the second, etc. When a 33rd pixel is to be drawn or not, bit 0 is checked and the cycle starts over. This means a value of 0xFFFFFFFF (=2^32-1) means normal operation, meaning all the pixels will be drawn.

Note that this works only for non-filled drawings. For [draw_curve](), the pattern is not always visible for the higher smoothness levels.

Parameters


INT stipples - Which pixels to draw, repetitive 32bits.

Returns

INT : [true]

Example

Program example;         
Private
//    int draw_id;
Begin

    // Draw in background
    drawing_map(0,background);

    // Set stipplemode to display every other pixel.
    // binary code 0101 0101 0101 0101 0101 0101 0101 0101
    // hex code 55555555h
    drawing_stipple(55555555h);

    // Draw two lines
    draw_line(10,10,190,10);
    draw_line(11,12,190,12);

    // Draw this funky pattern
    // binary code 0011 1100 0111 1100 1010 0001 1101 0011
    // hex code 3C7CA1D3h
    drawing_stipple(3C7CA1D3h);

    // Draw two lines
    draw_line(10,20,190,20);
    draw_line(11,22,190,22);

    // Draw a circle
    draw_circle(100,100,50);

    // Draw a rectangle
    draw_rect(50,50,150,150);

    // Draw some lines
    draw_line( 50, 50,100,150);
    draw_line(100,150,150, 50);
    draw_line( 50,150,100, 50);
    draw_line(100, 50,150,150);

    // Draw two curves: one with high smoothness (bit pattern not visible) and one with low smoothness
    draw_curve( 200,200,
                100,200,
                100,150,
                300,100,15);
    draw_curve( 200,200,
                100,200,
                100,150,
                300,100,1);

    // Draw a filled circle
    draw_fcircle(20,180,15);

    // Draw a filled rectangle
    draw_box(50,180,80,195);

    // Wait for key ESC
    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [drawing_map](), [draw_line](), [draw_circle](), [draw_rect](), [draw_curve](), [draw_fcircle](), [draw_box]()

This will result in something like:\


drawing_z()

Definition

INT drawing_z ( <INT z> )

Tells [Bennu] to draw the coming [drawings] on a certain z value.

In order to draw on a certain [graphic] again, [drawing_map]() can be used.

Parameters


INT z - The z value to be drawn on.


Returns

INT : [true]


move_draw()

Definition

INT move_draw ( <INT DrawID> , <INT x> , <INT y> )

Moves a certain [drawing] on the screen. Only drawings drawn with a certain z value can be moved like this, as other ones are drawn on a [graphic] and thus cannot be moved.

Parameters


INT DrawID - [DrawID] to be moved. INT x - The new x coordinate of the drawing. INT y - The new y coordinate of the drawing.


Returns

INT : [true]



Files

cd()

Definition

STRING cd ( [<STRING folder>] )

Sets the current path of execution if folder was specified and returns it.

Note that it is highly recommended to use [chdir]() for changing the current path of execution, as cd() will make [Bennu] crash when a folder is specified and the returned path of execution is used in the Bennu program. Just using cd() without a folder is not a problem.

Parameters


STRING folder - The folder to be entered from the current path of execution or a new path of execution.


Returns

STRING : The current path of execution.

Example

import "mod_dir"
import "mod_say"
import "mod_key"

Process Main()
Begin

    say(cd());
    say(chdir(".."));
    say(cd());

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [cd](), [say]()


chdir()

Definition

INT chdir ( <STRING directoryname> )

Sets the current path of execution.

Parameters


STRING directoryname - The name of the directory to be entered from the current path of execution or a new path of execution.


Returns

INT : Success


0 - Setting of current path of execution succeeded. !0 - Setting of current path of execution failed.


Example

import "mod_dir"
import "mod_say"
import "mod_key"

Process Main()
Begin

    say(CD());
    ChDir("..");
    say(CD());

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [cd](), [say]()


dirclose()

Definition

INT dirclose ( <INT handleId> )

Close a directory using a given handle id obtained with [diropen]().

Parameters


INT handleId - The handle id of a directory.


Returns

INT : The handle of the opened directory.


0 - There was an error. 1 - The directory was closed successfully.



diropen()

Definition

INT diropen ( <STRING folder> )

Open a directory for read it, returns handle id.

Parameters


STRING folder - The folder to open for read.


Returns

INT : The handle of the opened directory.


0 - There was an error. >0 - The handle of the opened directory.



dirread()

Definition

STRING dirread ( <INT handle> )

Given a path with wildcards ('*' or '?' characters), returns the first file that matches and, in every next call, all matching files found until no more files exists. It then returns NIL. Presumebly it's somewhat similair to [glob]. Also you can read multiple directories with different search criteria. This is usefull for filemanagers and dialogboxes, when you only want to list files of a specific type.

Parameters


INT handle - The id of the folder opened with [Diropen].


Returns

'''STRING ''' : The filename that matches with the wildcard search pattern.

Example

IMPORT "mod_dir";
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_key";

GLOBAL

int dir_id[9];

string dir_result[9];

string directory1="c:\windows\*.exe";
string directory2="c:\windows\*.dll";
string directory3="c:\windows\*.txt";

PROCESS main();

BEGIN

   dir_id[0]=diropen(directory1);
   dir_id[1]=diropen(directory2);
   dir_id[2]=diropen(directory3);

   /* print all exe files */
   say("");
   say("dirread test");
   say("");
   say("");
   say("the directory is: "+directory1);
   say("");
   say("reading directory.....");
   say("");  
   REPEAT

      IF (key(_esc))
         say("<aborted>");
         BREAK;
      END
      // read the dir
      dir_result[0]=dirread(dir_id[0]);     
      say(dir_result[0]);

   FRAME;
   UNTIL (dir_result[0]=="")

   /* print all dll files */
   say("");
   say("dirread test");
   say("");
   say("");
   say("the directory is: "+directory2);
   say("");
   say("reading directory.....");
   say("");
   REPEAT

      IF (key(_esc))
         say("<aborted>");
         BREAK;
      END
      // read the dir
      dir_result[1]=dirread(dir_id[1]);     
      say(dir_result[1]);

   FRAME;
   UNTIL (dir_result[1]=="")

   /* print all txt files */
   say("");
   say("dirread test");
   say("");
   say("");
   say("the directory is: "+directory3);
   say("");
   say("reading directory.....");
   say("");
   REPEAT

      IF (key(_esc))
         say("<aborted>");
         BREAK;
      END
      // read the dir
      dir_result[2]=dirread(dir_id[2]);     
      say(dir_result[2]);

   FRAME;
   UNTIL (dir_result[2]=="")

   say("closing the directory");
   dirclose(dir_id[0]);
   dirclose(dir_id[1]);
   dirclose(dir_id[2]);

END

Used in example: [say](), [Diropen]().


fremove()

Definition

INT fremove ( <STRING filename> )

Removes (deletes) files, from the bennu source code: files.c.

Parameters


STRING filename - The file to remove.


Returns

INT : [true]: the status result of the action.


[true] - The action was a success. [false] - The action failed.



mkdir()

Definition

INT mkdir ( <STRING directoryname> )

Creates a new directory in the current path of execution with a certain name.

Parameters


STRING directoryname - The name of the directory to be created.


Returns

INT : Success


0 ([false]) - Creating a new directory with the specified name failed. !0 ([true]) - Creating a new directory with the specified name succeeded.



rmdir()

Definition

INT rmdir ( <STRING directoryname> )

Removes (deletes) the directory in the current path of execution with a certain name.

Parameters


STRING directoryname - The name of the directory to be removed (deleted).


Returns

INT : Success


0 ([false]) - Removing the directory with the specified name failed. !0 ([true]) - Removing the directory with the specified name succeeded.




Fonts

bdf_load()

Definition

INT bdf_load ( <STRING filename>, [ <POINTER id>] )

Loads a BDF font file into memory as a [font].

The previous name [load_bdf]() is deprecated.

Parameters


STRING filename - The filename of the bdf file that you wish to load (including extension and possible path). POINTER id - Optional parameter, for loading a font in the background.


Returns

INT : [graphID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The graphID of the newly created font.


the following applies for versions prior rc282:

INT : [FontID]


-1 - Error: file does not exist. 0 - Filename could not be obtained from the specified string (doesn't happen usually). >0 - The FontID.


Errors


Format not recognized - The format of the specified file could not be recognized.


Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_bdf("archivo_gordo.bdf", &idbdf);
      while(idbdf==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idbdf==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

fnt_load()

Definition

INT fnt_load ( <STRING filename>, [ <POINTER id>] )

Loads a [FNT] file into memory as a [font]. A font is usually with the extension .fnt.

The previous name [load_fnt]() is deprecated.

Parameters


STRING filename - The filename of the [FNT] file that you wish to load (including extension and possible path). POINTER id - Optional parameter, for loading a font in the background.


Returns

INT : [graphID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The graphID of the newly created font.


the following applies for versions prior rc282:

INT : [FontID]


-1 - Error: file does not exist. 0 - Filename could not be obtained from the specified string (doesn't happen usually). >0 - The FontID.


Errors


Format not recognized - The format of the specified file could not be recognized.


Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_fnt("archivo_gordo.fnt", &idfnt);
      while(idfnt==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idfnt==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

fnt_new()

Definition

INT fnt_new ( <INT depth> )

Creates a new [font] with a certain color depth. There exists three variants of this function:

  • INT fnt_new ( <INT depth> )

  • INT fnt_new ( <INT charset> , <INT depth> )

  • INT fnt_new ( <INT file> , <INT graph>, <INT charset> , <INT width> , <INT height> , <INT first> , <INT last> , <INT flags> )

  • The first variant is a simple version wich uses the systemfont and the CP850 character set.

  • The second version allows the user to select a different characterset.

  • The third function allows custom fonts to made, from bitmaps in memory. It is similair to DIV gamestudio's font generator. In this variant, the depth cannot be set.

The previous name [new_fnt]() is deprecated.

Parameters


INT charset - The color characterset of the font, CHARSET_ISO8859 or CHARSET_CP850. INT depth - The color depth of the [glyphs] of the font. INT file - The [fileID] of the file wich contains the bitmaps with the letters. INT graph - The [graphID] of the bitmap wich contains the character set. INT width - The width of the [glyph]. INT height - The height of the [glyph]. INT first - The first character. INT last - The last character. INT flags - The kind of [glyph] width, NFB_VARIABLEWIDTH or NFB_FIXEDWIDTH.


Returns

INT : [FontID]


-1 - Error: could not create [font]. >=0 - The FontID.


Errors


Insufficient memory - There is insufficient memory available. This error doesn't occur often. Too many fonts - There are too many fonts loaded (255).


Example

IMPORT "mod_video";
IMPORT "mod_wm";
IMPORT "mod_text";
IMPORT "mod_map";
IMPORT "mod_key";

GLOBAL
   int a;
   int b;
   int c;

   int graph_id;

   int font_id1;
   int font_id2;

PROCESS main();    

BEGIN

    set_mode(640,480);

    graph_id=png_load("font.png");

    // new font, variable width
    font_id1=fnt_new(0,graph_id,CHARSET_ISO8859,16,16,0,255,NFB_VARIABLEWIDTH);

    write_int(font_id1,0,0,0,&a);
    write_int(font_id1,0,20,0,&b);
    write_int(font_id1,0,40,0,&c);
    write(font_id1,0,60,0,"hello world!");

    // new font, fixed width
    font_id2=fnt_new(0,graph_id,CHARSET_ISO8859,16,16,0,255,NFB_FIXEDWIDTH); 

    write_int(font_id2,0,100,0,&a);
    write_int(font_id2,0,120,0,&b);
    write_int(font_id2,0,140,0,&c);
    write(font_id2,0,160,0,"hello world!");

    // write texts in standard system font
    write_int(0,320,0,0,&a);
    write_int(0,320,20,0,&b);
    write_int(0,320,40,0,&c);
    write(0,320,60,0,"hello world!");

    WHILE (NOT key(_ESC) AND NOT exit_status)

        a++;
        b--;
        c*=2;

        IF (c==0) 
           c=1; 
        END

        FRAME;
    END
END

Used in example: [Png_load](), [Write]()

Notes

If only one argument is used, the CP850 character set is used. The charactermap is a bitmap, with the characters arranged in a grid. See this post


fnt_save()

Definition

INT fnt_save ( <INT fontID> , <STRING filename> )

Saves a [font] as a file. A font is usually with the extension ".fnt".

If the specified filename contains no extension, ".fnt" is added to it.

The previous name [save_fnt]() is deprecated.

Parameters


INT fontID - The [fontID] to be saved. STRING filename - The name of the font file to be saved, including a possible path.


Returns

INT : Successrate


[false]. [true] - Font successfully saved.


Errors


Invalid fontID - The specified [fontID] was invalid. Unable to create file - The file could not be created. Font corrupt - The font trying to be saved is corrupt. Insufficient memory - There is insufficient memory available. This error doesn't occur often.



fnt_unload()

Definition

INT fnt_unload ( <INT fontID> )

Unloads the specified [font] from memory.

The previous name [unload_fnt]() is deprecated.

Parameters


INT fontID - The [fontID] to unload.


Returns

INT : [false]


glyph_get()

Definition

INT get_glyph ( <INT fontID> , <INT glyphID> )

Creates a new [graphic] containing the specified [glyph].

The previous name [get_glyph]() is deprecated.

Parameters


INT fontID - The [fontID] of the font the glyph is wanted. INT glyphID - The [glyphID] of the glyph in the specified font.


Returns

INT : [GraphID]


0 - Invalid font; Invalid glyph; could not create graphic; >0 - The graphID of the graphic containing the glyph.


See also

  • [set_glyph]()

glyph_set()

Definition

INT glyph_set ( <INT fontID> , <INT glyphID> , <INT fileID> , <INT graphID> )

Sets the specified [glyph] of the specified [font]. The new glyph will be a copy of the specified [graphic] and thus it may be freed after the call.

The previous name [set_glyph]() is deprecated.

Parameters


INT fontID - The [fontID] of the font the glyph is to be set. INT glyphID - The [glyphID] of the glyph in the specified font. INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] to be copied.


Returns

INT : [false]

See also

  • [glyph_get]()


Fpg

fpg_add()

fpg_exists()

Definition

INT fpg_exists ( <INT FileID> )

Checks if an FPG exists with the specified [FileID].

Parameters


INT FileID - The [FileID] to check for existence.


Returns

INT : Whether the [File] exists


[false] does not exist. [true] exists.



fpg_load()

Definition

INT fpg_load ( <STRING filename>, [<INT POINTER> complete>] )

Loads a graphics library into your program.

This function loads the whole contents of an [FPG] graphics library into your project, enabling the contained [graphics] to be used in your program as [process]' graphs, screen backgrounds ([put_screen]()) or other graphics.

The previous name [load_fpg]() is deprecated.

Parameters


STRING filename - The filename of the FPG that you wish to load (including extension and possible path). [INT POINTER complete] - If this argument is specified the [FPG] on completion.


Returns

INT : [graphID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The [FileID] assigned to the archive.


the following applies for versions prior rc282:

INT : [FileID]


-1 - The specified archive could not be loaded. >=0 - The [FileID] assigned to the archive.


Errors


Archive not found - The specified archive could not be found.


Notes

Using an FPG file to contain all or some of the graphics used in a Bennu program is convenient, but isn't always the best way to load graphics. Other methods of loading graphics into your program include [load_map]() and [load_png]() which load individual graphic files. Graphics loaded individually will be given [FileID] 0 and a [GraphID] starting at 1000. This is because mod_map reserves room for the first FPG loaded (FPG files can contain 999 different graphics max.), sometimes referred to as the [system file] or [environment file].

The first FPG file loaded using mod_map returns and uses the [FileID] 0, which is reserved by mod_map for use as the [system file]. All extra FPG files loaded will have a different FileID, progressing from 1 upwards.

An FPG file holds all its contained graphs in memory simultaneously. Having a lot of large graphs being read from a single FPG file at once has been known to cause a slowdown.

Once an FPG file is no longer necessary to be held in the memory, its memory space can be released by using the function [unload_fpg](). It is not necessary to unload files at the termination of a program, as Bennu always releases all used memory at the end of program execution.

Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

     load_fpg("archivo_gordo.fpg", &idFpg);
      while(idFpg==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idFpg==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

      file=idFpg;

      graph = 7;

Example

Program example;
Global
    int my_fpg;
Begin
    my_fpg=load_fpg("test.fpg");   //Loads the FPG file into memory
    put_screen(my_fpg,1);          //Puts graphic with code 1 onto screen
    Repeat
        frame;
    Until(key(_esc))
    unload_fpg(my_fpg);
End

Used in example: [put_screen](), [unload_fpg]()


fpg_new()

Definition

INT fpg_new ( )

Creates and initializes a new [file].

To add [graphics] to the created file, use the returned [fileID] in the function [fpg_add](). The file can be saved with [fpg_save](). To free a file, use [fpg_unload]().

The previous name [new_fpg]() is deprecated.

Returns

INT : [fileID]


-1 - Too many files or insufficient memory. >=0 - The fileID of the new file.


Errors


Insufficient memory - There is insufficient memory available. This error doesn't occur often.



fpg_save()

Definition

INT fpg_save( <INT fileID> , <STRING filename> )

Saves a certain [file] to disk.

The previous name [save_fpg]() is deprecated.

Parameters


INT fileID - The [fileID] to save. STRING filename - The name of the [file].


Returns

INT : Success


[false]. [true] - Success.


Errors


Insufficient memory - There is insufficient memory available. This error doesn't occur often. Empty library - The specified [file]. Unsupported color depth - A [graphic] has an unsupported color depth. Differing color depths - An [FPG] of different color depths.



fpg_unload()

Definition

INT fpg_unload ( <INT fileID> )

Unloads a certain [file] from memory.

Also called [fpg_del](). The previous name [unload_fpg]() is deprecated.

Parameters


INT fileID - The [fileID] to unload.


Returns

INT : [true]



Graphical effects

blur()

Definition

INT blur ( <INT fileID> , <INT graphID> , <BYTE mode> )

This will make the specified [graphic] blurry by using a specified mode. It manipulates the graphic directly.

Only 16bit graphics are supported on 16bit video mode.

Parameters


INT fileID - The [fileID] that holds the graphics. INT graphID - The [graphID] to convert. BYTE mode - The blur mode that is applied to the [graphic]).


Returns

INT


0 - Invalid graphic or non 16bit graphic used. 1 - Success.


[Blur modes]


Constant - Value - Description BLUR_NORMAL - 0 - single pixel: considers pixels located to the left and above of each pixel. BLUR_3X3 - 1 - 3x3: considers all 8 adjacent pixels. BLUR_5X5 - 2 - 5x5: considers the 24 pixels that surrounds each pixel. BLUR_5X5_MAP - 3 - 5x5 with additional map: Just as the previous one but using a temporary map.


Examples


filter()

Definition

INT filter ( <INT fileID> , <INT graphID> , <POINTER filter_table> )

This function allows the colors of a graphic to be filtered with a nummerical range, defined as an [array].

Parameters


INT fileID - The [fileID] that holds the graphics. INT graphID - The [graphID]. POINTER fileter_table - Pointer to a table [array]).


Returns

INT


0 - Invalid graphic or non 16bit graphic used. 1 - Success.


Example

/* Example converted from bennupack, fenix test section, 2 Medium\fenix test\Fenix Test3\Test_FILTER.prg */

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_map";
IMPORT "mod_effects";
IMPORT "mod_proc";
IMPORT "mod_grproc";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_screen";

GLOBAL
int fpg;
int png;
int filter[]=8,20,3,4,5,6,7,8,9,70;
//int filter[]=448,20,3,4,5,6,7,8,9,70,255,344,255,1,0,0;
//int filter[]=5,30,20,40,60,80,100,1,1,2,3;

PROCESS main();

BEGIN

  scale_mode=scale_normal2x; 
  set_mode(320,200,mode_16bits);

  fpg=load_fpg("FPG2.FPG");
  png=load_png("PNG-1.PNG");

  say("Filter test...");
  say("Press ESC to quit...");

  put_screen(fpg,1);

  bola(100,100,"Normal",0);
  bola(200,100,"Filtered",1);

  REPEAT
     FRAME;
  UNTIL (key(_esc))

  let_me_alone();
END

PROCESS bola(int x,int y,string txt,int use_filter);

BEGIN
  say(txt);
  size=200; 
  graph=map_clone(0,png);

  IF (use_filter==TRUE) 
     filter(0,graph,&filter); 
  END

  LOOP
    FRAME;
  END
END

grayscale()

Definition

INT grayscale ( <INT fileID> , <INT graphID> , <BYTE method> )

This function will convert the specified [graphic] by using the specified method; see [notes] for the details.

Parameters


INT fileID - The [fileID] that holds the graphics. INT graphID - The [graphID] to convert. BYTE method - The method used (see [notes]).


Returns

INT


-1 - Invalid graphic. 1 - Success.


[Grayscale modes]


Constant - Value - Description GSCALE_RGB - 0 - changes the graphic to monochrome. GSCALE_R - 1 - changes the graphic to RED scale. GSCALE_G - 2 - changes the graphic to GREEN scale. GSCALE_B - 3 - changes the graphic to BLUE scale. GSCALE_RG - 4 - changes the graphic to YELLOW scale. GSCALE_RB - 5 - changes the graphic to PURPLE scale. GSCALE_GB - 6 - changes the graphic to CYAN scale. GSCALE_OFF - -1 - no change, graphic stays as it is, so filter is not applied.


Notes

The exact formula is:

c = 0.3 * oldpixel_r + 0.59 * oldpixel_g + 0.11 * oldpixel_b

Method 0:

for every pixel:
    newpixel_rgb = (c,c,c)

Method 1:

for every pixel:
    newpixel_rgb = (c,0,0)

Method 2:

for every pixel:
    newpixel_rgb = (0,c,0)

Method 3:

for every pixel:
    newpixel_rgb = (0,0,c)

Method 4:

for every pixel:
    newpixel_rgb = (c,c,0)

Method 5:

for every pixel:
    newpixel_rgb = (c,0,c)

Method 6:

for every pixel:
    newpixel_rgb = (0,c,c)

Other methodnumbers:

for every pixel:
    newpixel_rgb = oldpixel_rgb

Note that [[rgbscale]](0,map,1,1,1) = [[grayscale]](0,map,0) for a valid graphic (0,map).

Example

/* Example converted from bennupack, fenix test section, 2 Medium\fenix test\Fenix Test3\Test_GRAYSCALE.prg */

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_map";
IMPORT "mod_effects";
IMPORT "mod_proc";
IMPORT "mod_grproc";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_screen";

GLOBAL

int fpg;
int png;

PROCESS main();

BEGIN

  scale_mode=scale_normal2x;
  set_mode(320,200,mode_16bits);

  fpg=load_fpg("FPG2.FPG");
  png=load_png("Triangulo_16.png");

  say("Grayscale test...");
  say("Press ESC to quit...");

  put_screen(fpg,1);

  ball(110,50,"mode 0: GSCALE_RGB",GSCALE_RGB);
  ball(160,50,"mode 1: GSCALE_R",GSCALE_R);
  ball(210,50,"mode 2: GSCALE_G",GSCALE_G);
  ball(160,100,"mode 3: GSCALE_B",GSCALE_B);
  ball(110,150,"mode 4: GSCALE_RG",GSCALE_RG);
  ball(160,150,"mode 5: GSCALE_RB",GSCALE_RB);
  ball(210,150,"mode 6: GSCALE_GB",GSCALE_GB);
  ball(260,150,"mode -1: GSCALE_OFF",GSCALE_OFF);

  REPEAT
    FRAME;
  UNTIL (key(_esc))

  let_me_alone();

END

PROCESS ball(int x,int y,string txt,int blur);

BEGIN

  say(txt);
  graph=map_clone(0,png);
  grayscale(fpg,graph,blur);

  LOOP
    FRAME;
  END
END

rgbscale()

Definition

INT rgbscale ( <INT fileID> , <INT graphID> , <FLOAT r> , <FLOAT g> , <FLOAT b> )

This will convert the specified [graphic] by using the specified color as a reference. The converted graphic will have only the specified color and lighter/darker colors; see [notes] for the details.

Parameters


INT fileID - The [fileID] that holds the graphics. INT graphID - The [graphID] to convert. FLOAT r - The red component of the color to be used for reference. FLOAT g - The green component of the color to be used for reference. FLOAT b - The blue component of the color to be used for reference.


Returns

INT


-1 - Invalid graphic. 1 - Success.


Notes

The exact formula is:

for every pixel:
    c = 0.3 * oldpixel_r + 0.59 * oldpixel_g + 0.11 * oldpixel_b
    newpixel_r = r * c;
    newpixel_g = g * c;
    newpixel_b = b * c;

where r,g,b are the specified r,g,b.

Note that [[rgbscale]](0,map,1,1,1) = [[grayscale]](0,map,0), for a valid graphic (0,map).



Joystick

joy_getaxis()

Syntax

INT joy_getaxis ( [ <INT joy>], <INT axis> )

Description

Returns the selected joystick state for the given axis.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with joy_select().

Also called [joy_getposition](). The previous name [get_joy_position]() is deprecated.

Parameters


[INT JoyID] - The [JoyID]. INT axis - The [axis].


Returns

INT : state for the given axis.


joy_getball()

Syntax

INT joy_getball ( [ <INT JoyID> ] , <POINTER dx> , <POINTER dy>)

Description

Returns the state of the specfied ball on the current selected joystick.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with [joy_select]().

Parameters


[INT JoyID] - The [JoyID]. POINTER dx - A pointer to the variable X of the ball. POINTER dy - A pointer to the variable Y of the ball.


Returns

INT : The state of the specfied ball on the current selected joystick.

Example


joy_getbutton()

Syntax

INT joy_getbutton ( [ <INT joy>], <INT button> )

Description

Returns the selected joystick state for the given button.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with joy_select().

The previous name [get_joy_button]() is deprecated.

Parameters


[INT JoyID] - The [JoyID]. INT button - The [button].


Returns

INT : state for the given button.


joy_gethat()

Syntax

INT joy_gethat ( [ <INT JoyID> ] , <INT hat> )

Description

Returns the current position of the digital POV hat of the controller pad selected.

The return values are:


Constant - Value - Description JOY_HAT_CENTERED - 0 - The hat is centered. JOY_HAT_UP - 1 - The hat is moved up. JOY_HAT_RIGHT - 2 - The hat is moved right. JOY_HAT_DOWN - 4 - The hat is moved down. JOY_HAT_LEFT - 8 - The hat is moved left. JOY_HAT_RIGHTUP - 3 - The hat is moved right and up. JOY_HAT_RIGHTDOWN - 6 - The hat is moved right and down. JOY_HAT_LEFTUP - 9 - The hat is moved left and up. JOY_HAT_LEFTDOWN - 12 - The hat is moved left and down.


You may notice that some are combinations of others. For example JOY_HAT_RIGHTUP == (JOY_HAT_RIGHT | JOY_HAT_UP ). This is because the returned value has [bit flags] indicating four directions: up, down, left, right. These can be combined to make diagonal directions.

A value of -1 is returned when there is no hat or [joystick] detected.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with [joy_select]().

Parameters


[INT JoyID] - The [JoyID]. INT hat - The number of the hat, starting at 0


Returns

INT : The position of the POV hat.

Example


joy_name()

Syntax

STRING joy_name ( <INT JoyID> )

Description

Returns the name of the specified [joystick]. This is a string describing the specified joystick, mostly used for the brand and model of the joystick.

Parameters


INT JoyID - The [JoyID].


Returns

STRING : The name of the [joystick].


joy_numaxes()

Syntax

INT joy_numaxes ( [ <INT JoyID> ] )

Description

Returns the number of [axes] on the specified [joystick]. If no joystick is specified, the number of axes on the currently [selected joystick] will be returned.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with [joy_select]().

Also called [joy_axes]().

Parameters


[INT JoyID] - The [JoyID].


Returns

INT : The number of [axes].


joy_numballs()

Syntax

INT joy_numballs ( [ <INT JoyID> ] )

Description

Returns the number of [balls] on the specified [joystick]. If no joystick is specified, the number of balls on the currently [selected joystick] will be returned.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with joy_select().

Parameters


[INT JoyID] - The [JoyID].


Returns

INT : The number of [balls].


joy_number()

Syntax

INT joy_number ( )

Description

Returns the number of joysticks present in the system.

Also called [joy_numjoysticks](). The previous name [number_joy]() is deprecated.

Returns

INT : The number of joysticks present in the system.


joy_numbuttons()

Syntax

INT joy_numbuttons ( [ <INT JoyID> ] )

Description

Returns the number of [buttons] on the specified [joystick]. If no joystick is specified, the number of buttons on the currently [selected joystick] will be returned.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with joy_select().

Also called [joy_buttons]().

Parameters


[INT JoyID] - The [JoyID].


Returns

INT : The number of [buttons].


joy_numhats()

Syntax

INT joy_numhats ( [ <INT JoyID> ] )

Description

Returns the number of [hats] on the specified [joystick]. If no joystick is specified, the number of hats on the currently [selected joystick] will be returned.

The JoyID is optional, if it is not present, the function uses the selected joystick. You can change the selected joystick with joy_select().

Parameters


[INT JoyID] - The [JoyID].


Returns

INT : The number of [hats].


joy_select()

Syntax

INT joy_select ( <INT JoyID> )

Description

Select the joystick with id equals to JoyID. The old name [select_joy]() is deprecated.

Parameters


INT JoyID - The [JoyID].


Returns

INT : The ID of the selected joystick number.



Maps

graphic_info()

Definition

INT graphic_info ( <INT fileID> , <INT graphID> , <INT infotype> )

Gets some information about the [graph] specified. This function is also known as [Map_info]() and [Map_info_get]().

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to get information from. INT infotype - What [type of information] you want.


Returns

INT : Returns the information you want.\ If the specified graph was invalid it returns 0.\ If the specified infotype was not recognized it returns 1.

Example

Program keuken;
Local
    gxc;
    gyc;

Begin

    set_mode(640,480,16);

    graph=new_map(rand(50,150),rand(50,150),16); //makes a randomly proportioned red rectangle
    map_clear(0,graph,rgb(255,0,0));
    x=320;
    y=240;

    gxc=graphic_info(0,graph,G_X_CENTER);
    gyc=graphic_info(0,graph,G_Y_CENTER);  //finds the graphic's center coordinates

    map_put_pixel(0,graph,gxc,gyc,rgb(255,255,255)); //puts a white pixel in the center of the graphic

    Loop

        frame;
    End
End

Used in example: [set_mode](), [new_map](), [map_put_pixel]()


graphic_set()

Definition

INT Graphic_set ( <INT fileID> , <INT graphID> , <INT info_type> , <INT value> )

Changes the x or y coordinate of the center pixel (controlpoint 0). This function is also known as [Map_info_set]().

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to get information from. INT info_type - What [type of information] you want to change, see note. INT value - The new x or y coordinate of the center pixel.


Returns

INT : Returns the information you want.\ If the specified graph was invalid it returns 0.\ If the specified infotype was not recognized it returns 1.

Notes

As infotype, only two options are valid:


G_X_CENTER - Change the x coordinate of the center pixel. G_Y_CENTER - Change the y coordinate of the center pixel.



map_block_copy()

Definition

INT map_block_copy ( <INT fileID> , <INT destinationGraphID> , <INT destinationX> , <INT destinationY> , <INT originGraphID> , <INT x> , <INT y> , <INT width> , <INT height>, <INT blitflags> )

Draws ([blits]) a rectangular block from one [graphic] onto another graphic.

If the entire graphic is to be blitted, [map_put]() or [map_xput]() can be used.

Parameters


INT fileID - The [fileID] that holds the destination and origin graphics. INT destinationGraphID - The [graphID] to draw on. INT destinationX - Where on the destination graph's x-axis to put the block. INT destinationY - Where on the destination graph's y-axis to put the block. INT originGraphID - The [graphID] to draw with. INT x - The x-coordinate of the upperleft corner of the origin block. INT y - The y-coordinate of the upperleft corner of the origin block. INT width - The width of the block in pixels. INT height - The height of the block in pixels. INT blitflags - What [blit flags] to draw the graphic with.


Returns

INT : [true]

Notes

[Blit flags] can be used to give the drawing (blitting) a special effect.

Errors


Invalid origin graph - The origin graph is invalid. Invalid destination graph - The destination graph is invalid. Unsupported color depth - The origin graphic's color depth is greater than the destination graph's.



map_buffer()

Definition

POINTER map_buffer ( <INT fileID> , <INT graphID> )

Get access to the memory buffer of the map. This function is usefull in combination with [Memset](). This way you can manipulate the actual bytes of the map.

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to get information from.


Returns

POINTER : Pointer to the memory contents of the map.

Example

In this example I'm going to demonstrate how you can manipulate the pixel buffer of the map. I load the same map twice (each with their own ID), and one of them is butchered by messing with it's pixel buffer. By assiging that map to a [Pointer] with map_buffer(), we can use [Memset]() to change the bytes in the memory area that the map occupies.

IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_key";
IMPORT "mod_map";
IMPORT "mod_video";
IMPORT "mod_wm";
IMPORT "mod_draw";
IMPORT "mod_screen";
IMPORT "mod_mem";
IMPORT "mod_text";

GLOBAL

   int map_id;    // id code of the map to load
   int map_id2;

   pointer p_map; // pointer to the map_buffer

PROCESS main();

BEGIN

   set_mode(320,200,32);

   write(0,10,10,3,"map_buffer example, press 'ESC' to quit.");

   write(0,10,30,3,"press '1' to show the modified map.");
   write(0,10,40,3,"press '2' to show the orginial map.");

   // load two maps, this map can be found in bennupack: 2 Medium\IA\PATH.FIND\3COCHE.MAP
   // it is a the "car" graphic of the pathfind tutorial for TYCO. Both maps are the same,
   // but one of them we're going to modify with map_buffer().
   map_id=load_map("3COCHE.MAP");
   map_id2=load_map("3COCHE.MAP"); // same map, but this one is left intact

   graph=map_id2; // original map
   x=100; 
   y=100;

   // get the memory adress of the "raw" pixel buffer of the map.
   p_map=map_buffer(0,map_id);

   // now that we've got acccess to the pixel buffer, we can change individual bytes.
   // with memset we can modify memory contents of individual bytes. 
   // in this case, we change the first 1000 bytes into the color #100.
   memset(p_map,100,1000); 

   // no, we're offsetting 200 adresses from the start of the memory block, and change another
   // 1000 bytes into a different color.
   memset(p_map+200,150,1000); 

   LOOP
      IF (key(_esc))
         BREAK;
      END

      IF (key(_1))     // show the "butchered" map
         FRAME(100);
         graph=map_id;
         say("showing map modified with map_buffer()");
      END

      IF (key(_2))    // show the original map
         FRAME(100);
         graph=map_id2;
         say("showing original map");
      END

      FRAME;
   END
END

Used in example: [Load_map](), [Memset](), [Say]()

Notes

In the [Memset]() function, indiviual bytes are used. The amount of bytes to store the color of one pixel depends on it's colordepth. In 8 bit mode, you need only one byte per pixel, in rgb mode 3 bytes and in rgba mode 4 bytes per pixel. So that is something you should be aware of. This is a similair caveat as with the [Alloc]() function, because you're dealing with raw memory contents here.


map_clear()

Definition

INT map_clear ( <INT fileID> , <INT graphID> , <WORD color> )

Clears a certain graph to a certain color.

Parameters


INT fileID - The [file] that holds the graphic. INT graphID - The [graphic] to clear. WORD color - The [color] used to clear.


Returns

INT : [true]

Notes

Instead of using map_clear() to clear the screen [background], [clear_screen]() is recommended as it is a little bit faster.

Errors


Unsupported color depth - The specified graph has a not supported color depth.


Example

Program a_map_is_born;
Private
    int map;
Begin

    // Create a new graph of size 100x100 and color depth of 8bit
    map = new_map(100,100,8);

    // Clear the map red
    map_clear(0,map,rgb(255,0,0));

    // Put it in the center of the screen
    put(0,map,160,100);

    Loop
        frame;
    End

End

Used in example: [new_map](), [put]()

This will result in something like:\ http://wwwhome.cs.utwente.nl/~bergfi/fenix/wiki/new_map.PNG


map_clone()

Definition

INT map_clone ( <INT fileID> , <INT graphID> )

Clones a certain [graphic] and puts it in the [system file].

Parameters


INT fileID - The [fileID] holding the graphic. INT graphID - The [graphID] of the graphic to be cloned.


Returns

INT : [GraphID]


0 - Invalid graphic specified; >0 - The graphID of the clone graphic.


Errors


Unsupported color depth - The specified graph has a not supported color depth. (Console) Insufficient memory - There is insufficient memory available. This error doesn't occur often. (Console)



map_exists()

Syntax

INT map_exists ( <INT fileID> , <INT graphID> )

Description

Checks if a [graphic] exists in the specified [File] with the specified [graphID].

Parameters


INT fileID - The [fileID] that holds the graphic (or not). INT graphID - The [graphID].


Returns

INT : Whether the [graphic] exists


[false] does not exist. [true] exists.



map_info()

Definition

INT map_info ( <INT fileID> , <INT graphID> , <INT infotype> )

Gets some information about the [graph] specified. This function is also known as [Graphic_info]() and [Map_info_get]().

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to get information from. INT infotype - What [type of information] you want.


Returns

INT : Returns the information you want.\ If the specified graph was invalid it returns 0.\ If the specified infotype was not recognized it returns 1.

Example

See [Graphic_info]() for example.


map_info_get()

Definition

INT map_info_get ( <INT fileID> , <INT graphID> , <INT infotype> )

Gets some information about the [graph] specified. This function is also known as [Graphic_info]() and [Map_info]().

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to get information from. INT infotype - What [type of information] you want.


Returns

INT : Returns the information you want.\ If the specified graph was invalid it returns 0.\ If the specified infotype was not recognized it returns 1.

Example

See [Graphic_info]() for example.


map_info_set()

Definition

INT map_info_set ( <INT fileID> , <INT graphID> , <INT info_type> , <INT value> )

Changes the x or y coordinate of the center pixel (controlpoint 0). This function is also known as [Graphic_set]().

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to get information from. INT info_type - What [type of information] you want to change, see note. INT value - The new x or y coordinate of the center pixel.


Returns

INT : Returns the information you want.\ If the specified graph was invalid it returns 0.\ If the specified infotype was not recognized it returns 1.

Example

IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_key";
IMPORT "mod_map";
IMPORT "mod_video";
IMPORT "mod_wm";
IMPORT "mod_draw";
IMPORT "mod_screen";

GLOBAL

   int map_id;

   int status;

PROCESS main();

BEGIN

   set_mode(320,200,32);

   map_id=load_map("3COCHE.MAP");

   // print the original data.
   say("width of the map: "+graphic_info(0,map_id,G_WIDTH));
   say("height of the map: "+graphic_info(0,map_id,G_HEIGHT));
   say("g_x_center of the map: "+graphic_info(0,map_id,G_X_CENTER));
   say("g_y_center of the map: "+graphic_info(0,map_id,G_Y_CENTER));

   // change the x and y coordinates of the center pixel and display it.
   status=map_info_set(0,map_id,G_X_CENTER,20);
   status=map_info_set(0,map_id,G_Y_CENTER,10);
   say("center pixel changed:");
   say("g_x_center of the map: "+graphic_info(0,map_id,G_X_CENTER));
   say("g_y_center of the map: "+graphic_info(0,map_id,G_Y_CENTER));

   say("status: "+status);

   graph=map_id;
   x=100; 
   y=100;

   LOOP
      IF (key(_esc))
         BREAK;
      END
      FRAME;
   END
END

Notes

As infotype, only two options are valid:


G_X_CENTER - Change the x coordinate of the center pixel. G_Y_CENTER - Change the y coordinate of the center pixel.



map_load()

Definition

INT map_load ( <STRING filename>, [ <POINTER id>] )

Creates a new [graphic], using the specified [MAP] file as contents and puts it in the [system file] of the created graphic. The [color depth] of the created graphic will be the same as the loaded MAP file.

The previous name [load_map]() is deprecated.

Parameters


STRING filename - The name of the [MAP]. POINTER id - Optional parameter, for loading a map in the background.


Returns

INT : [graphID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The graphID of the newly created graphic.


the following applies for versions prior rc282:

INT : [graphID]


0 - There was an error loading the file. >0 - The graphID of the newly created graphic.


Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_map("archivo_gordo.map", &idmap);
      while(idmap==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idmap==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

map_name()

Definition

STRING map_name ( <INT fileID> , <INT graphID> )

Retrieves the name of an in-game [graphic].

Parameters


INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] of the graphic.


Returns

STRING : Name of the graphic


map_new()

Definition

INT map_new ( <INT width> , <INT height> , <INT depth>, [ <INT flags> ] )

Creates a new [graphic], sets the color of all pixels to 0 (transparent) and puts it in the [system file].

The previous name [new_map]() is deprecated.

Parameters


INT width - The width of the to be created graph in [pixels]. INT height - The height of the to be created graph in pixels. INT depth - The [color depth] [INT flags] - can be: [B_CLEAR] (bitmap clear) or 0 (no clear new bitmap)


Returns

INT : [GraphID]


0 - There was an error. >0 - The graphID of the newly created graphic.


Errors


Unsupported color depth - The specified color depth is not supported. (Console) Insufficient memory - There is insufficient memory available. This error doesn't occur often. (Console)


Example

import "mod_map"
import "mod_screen"
import "mod_key"

Process Main()
Private
    int map;
Begin

    // Create a new graph of size 100x100 and color depth of 8bit
    map = map_new(100,100,8);

    // Clear the map red
    map_clear(0,map,rgb(255,0,0));

    // Put it in the center of the screen
    put(0,map,160,100);

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [map_new](), [map_clear](), [key]()

This will result in something like:\


map_put()

Syntax

INT map_put ( <INT fileID> , <INT destinationGraphID> , <INT originGraphID> , <INT x> , <INT y> )

Description

Draws ([blits] onto another graph.

If more advanced parameters are needed, [map_xput]() can be used. If a graph from one [file] needs to be drawn onto another graph in a different file, or a separate width and height scaling is needed, [map_xputnp]() can be used.

Parameters


INT fileID - The [fileID] that holds the graphics. INT destinationGraphID - The [graphID] to draw on. INT originGraphID - The [graphID] to draw with. INT x - Where on the destination graphic's x-axis to put the graph. INT y - Where on the destination graphic's y-axis to put the graph.


Returns

INT : [true]

Notes

The x and y parameters denote where to draw the graph, that is, where the center of the to be drawn graph will be.

Errors


Invalid origin graph - The origin graph is invalid. Invalid destination graph - The destination graph is invalid. Unsupported color depth - The origin graph's color depth is greater than the destination graph's.


Example

import "mod_video"
import "mod_map"
import "mod_wm"

Process Main()
Private
    int destgraph;
    int origgraph1;
    int origgraph2;
Begin

    // Set the mode to 16bit and some resolution
    set_mode(320,200,16);

    // Makes the destination graphic a red square
    destgraph=new_map(100,100,16);
    map_clear(0,destgraph,rgb(255,0,0));

    // Makes the first origin graphic a green square
    origgraph1=new_map(100,100,16);
    map_clear(0,origgraph1,rgb(0,255,0));

    // Makes the second origin graphic a blue square
    origgraph2=new_map(100,100,16);
    map_clear(0,origgraph2,rgb(0,0,255));

    // Draws the blue and green squares at a random position on the red square
    map_put(0,destgraph,origgraph1,rand(0,100),rand(0,100));
    map_put(0,destgraph,origgraph2,rand(0,100),rand(0,100));

    // Shows the final graph
    put(0,destgraph,160,100);

    Repeat
        frame;
    Until(exit_status)

End

Used in example: [set_mode](), [new_map](), [map_put](), [key]

This will result in something like:\


map_save()

Definition

INT map_save ( <INT fileID> , <INT graphID> , <STRING filename> )

Saves the specified [graphic] as filename with the format [MAP].

The previous name [save_map]() is deprecated.

Parameters


INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] of the graphic to unload. STRING filename - The name of the [MAP] file to be saved, including a possible path.


Returns

INT : Successrate


[false] - An error: Invalid graphic; could not open file. [true] - Graphic saved.



map_set_name()

Definition

INT map_set_name ( <INT fileID> , <INT graphID> , <STRING name>)

Sets the name of a [graphic] in an [FPG]. Useful in combination with [map_name]() to retrieve names of files and [save_fpg]() to save any changed values.

Parameters


INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] of the graphic. STRING name - The new name of the graphic specified.


Returns

INT : 0


map_unload()

Definition

INT map_unload ( <INT fileID> , <INT graphID> )

Frees the memory used by the specified [graphic]. The associated ([fileID]) combination is no longer valid afterwards.

Also called [map_del](). The previous name [unload_map] is deprecated.

Parameters


INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] of the graphic to unload.


Returns

INT : Successrate


[false] - Invalid graphic. [true] - Graphic unloaded.



map_xput()

Definition

INT map_xput ( <INT fileID> , <INT destinationGraphID> , <INT originGraphID> , <INT x> , <INT y> , <INT angle> , <INT size> , <INT blitflags> )

Draws ([blits] onto another graphic.

If the advanced parameters aren't needed, [map_put]() can be used. If a graphic from one [file] needs to be drawn onto another graphic in a different file, or a separate width and height scaling is needed, [map_xputnp]() can be used.

Parameters


INT fileID - The [fileID] that holds the graphics. INT destinationGraphID - The [graphID] to draw on. INT originGraphID - The [graphID] to draw with. INT x - Where on the destination graphic's x-axis to put the graphic. INT y - Where on the destination graphic's y-axis to put the graphic. INT angle - What [angle] to draw the graphic at. INT size - What [size] to draw the graphic at. INT blitflags - What [blit flags] to draw the graphic with.


Returns

INT : [true]

Notes

The x and y parameters denote where to draw the graphic, that is, where the center of the to be drawn graphic will be. Blit flags can be used to give the drawing (blitting) a special effect.

When angle is 0 and size is 100, the speed is greater, because the graph doesn't need rotating or scaling.

Errors


Unsupported color depth - The origin graphic's color depth is greater than the destination graphic's.


Example

import "mod_video"
import "mod_map"
import "mod_wm"

Process Main()
Private
    int destgraph;
    int origgraph;
Begin

    // Set the mode to 16bit and some resolution
    set_mode(320,200,16);

    // Makes the destination graphic a red square
    destgraph=new_map(100,100,16);
    map_clear(0,destgraph,rgb(255,0,0));

    // Makes the origin graphic a blue square
    origgraph=new_map(100,100,16);
    map_clear(0,origgraph,rgb(0,0,255));

    // Draws the blue square on the center of the red square transparently,
    // at a random angle and a random size
    map_xput(0,destgraph,origgraph,50,50,rand(-180000,180000),rand(50,150),4);
    map_xput(0,destgraph,origgraph,50,50,rand(-180000,180000),rand(50,150),4);

    // Shows the final graph
    put(0,destgraph,160,100);

    Repeat
        frame;
    Until(exit_status)

End

Used in example: [set_mode](), [new_map](), [map_xput](), [key]

This will result in something like:


map_xputnp()

Definition

INT map_xputnp ( <INT destinationFileID> , <INT destinationGraphID> , <INT originFileID> , <INT originGraphID> , <INT x> , <INT y> , <INT angle> , <INT scale_x> , <INT scale_y> , <INT blitflags> )

Draws ([blits] onto another graphic.

If the advanced parameters aren't needed, [map_put]() can be used.

Parameters


INT destinationFileID - The [fileID] that holds the destination graphic. INT destinationGraphID - The [graphID] to draw on. INT originFileID - The [fileID] that holds the origin graphic. INT originGraphID - The [graphID] to draw with. INT x - Where on the destination graph's x-axis to put the graphic. INT y - Where on the destination graph's y-axis to put the graphic. INT angle - What [angle] to draw the graphic at. INT scale_x - What [size]) INT scale_y - What [size]). INT blitflags - What [blit flags] to draw the graphic with.


Returns

INT : [true]

Notes

The x and y parameters denote where to draw the graphic, that is, where the center of the to be drawn [graphic] will be. [Blit flags] can be used to give the drawing (blitting) a special effect.

When angle is 0 and size is 100, the speed is greater, because the graphic doesn't need rotating or scaling.

Errors


Unsupported color depth - The origin graphic's color depth is greater than the destination graph's.


Example

import "mod_video"
import "mod_map"
import "mod_wm"

Process Main()
Global
    int destgraph;
    int origgraph;
Begin

    // Set the mode to 16bit and some resolution
    set_mode(320,200,16);

    // Makes the destination graphic a red square
    destgraph=new_map(100,100,16);
    map_clear(0,destgraph,rgb(255,0,0));

    // Makes the origin graphic a blue square
    origgraph=new_map(100,100,16);
    map_clear(0,origgraph,rgb(0,0,255));

    // Draws the blue square on the center of the red square transparently,
    // at a random angle and a random size
    map_xputnp(0,destgraph,0,origgraph,50,50,rand(-180000,180000),rand(50,150),rand(50,150),4);
    map_xputnp(0,destgraph,0,origgraph,50,50,rand(-180000,180000),rand(50,150),rand(50,150),4);

    // Shows the final graph
    put(0,destgraph,160,100);

    Repeat
         frame;
    Until(exit_status)

End

Used in example: [set_mode](), [new_map](), [map_xputnp](), [exit_status], [blit flags]

This will result in something like:


pcx_load()

Definition

INT pcx_load ( <STRING filename>, [ <POINTER id>] )

Creates a new [graphic], using the specified pcx file as contents and puts it in the [system file]. Returns the [graphID] of the created graphic. The [color depth] of the created graphic will be the same as the loaded pcx file.

The previous name [load_pcx]() is deprecated.

Parameters


STRING filename - The name of the pcx file to be loaded, including a possible [path]. POINTER id - Optional parameter, for loading a map in the background.


Returns

INT : [graphID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The graphID of the newly created graphic.


the following applies for versions prior rc282:

INT : [graphID]


0 - There was an error loading the file. >0 - The graphID of the newly created graphic.


Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_pcx("archivo_gordo.pcx", &idpcx);
      while(idpcx==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idpcx==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

png_load()

Definition

INT png_load ( <STRING filename>, [ <POINTER id>] )

Creates a new [graphic], using the specified [PNG] file as contents and puts it in the [system file] of the created graphic. The [color depth] of the created graphic will be the same as the loaded PNG file.

The previous name [load_png]() is deprecated.

Parameters


STRING filename - The name of the [PNG]. POINTER id - Optional parameter, for loading a map in the background.


Returns

INT : [graphID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The graphID of the newly created graphic.


the following applies for versions prior rc282:

INT : [graphID]


0 - There was an error loading the file. >0 - The graphID of the newly created graphic.


Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_png("archivo_gordo.png", &idpng);
      while(idpng==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idpng==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

Example

Checkout the [PNG_LoadDirectory] tutorial.


png_save()

Definition

INT png_save ( <INT fileID> , <INT graphID> , <STRING filename> )

Saves the specified [graphic] as filename with the format [PNG].

The previous name [save_png]() is deprecated.

Parameters


INT fileID - The [fileID] that holds the graphic. INT graphID - The [graphID] of the graphic to save. STRING filename - The name of the [PNG].


Returns

INT : Successrate


[false] - Error. [true] - Success.


Example

//here's a cool thing to save a screenshot
import "mod_map"
import "mod_screen"
import "mod_key"

Global
    int takingscreenshot;
End

Process Main()
Begin

    Loop

        If (key(_F12)) 
            If (takingscreenshot==0)
                takingscreenshot=1;
                graph=screen_get(); // grabs the screen and sets it as the program graphic
                png_save(0,graph,"shot"+rand(0,9999)+".png"); // saves the graphic as a png with a
                                                              // random number in the filename to
                                                              // prevent overwriting 
                map_unload(0,graph);  //frees the graphic
            Else
                takingscreenshot=0;
            End
            While(key(_F12)) Frame; End
       End

        frame;
    End
End

Used in example: [key](), [screen_get](), [png_save](), [map_unload]()


point_get()

Definition

INT get_point ( <INT fileID> , <INT graphID> , <INT controlpointID> , <INT POINTER x>, <INT POINTER y>)

Allows you to obtain a control point of a particular [graph].

Any graph can contain up to 1000 control points (from 0 to 999). Control point 0 is the center of the graphic. This [function] allows you to know the location of any control point belonging to any graph.

To set a control point, use [set_point]() or, for only the center of a graph, [set_center]().

The previous name [get_point]() is deprecated.

Parameters


INT fileID - Number of the FPG library. INT graphID - Number of the graph inside the library which you want to use. INT controlpointID - Number of the control point. INT POINTER x - Pointer to where the X-coordinate of the control point will be written. INT POINTER y - Pointer to where the Y-coordinate of the control point will be written.


Returns

INT : Successrate


[false] - One of the following: specified graph is invalid, specified control point is invalid, specified control point is undefined. [true] - The control point was defined or the center was used.


Example

Program cpoint;
Private
    int map;
    int cx,cy;
Begin

    // Create a red graph
    map = new_map(100,100,8);
    map_clear(0,map,rgb(255,0,0));

    // Set the center to a random point
    set_center(0,map,rand(-10,110),rand(-10,110));

    // Get the center
    get_point(0,map,0,&cx,&cy);

    // Show the center
    say("Center-X: " + cx);
    say("Center-Y: " + cy);

    // Assign the map to the graph variable
    graph = map;

    // Set the location of this process to the center of the screen
    x = 160;
    y = 100;

    Loop
        frame;
    End

End

Used in example: [new_map](), [map_clear](), [set_center](), [pointer]

Notice that setting the center influences the position of the graph:


point_set()

Definition

INT point_set ( <INT fileID> , <INT graphID> , <INT controlpointID> , <INT x>, <INT y>)

Allows you to set a control point of a particular [graphic].

Any graph can contain up to 1000 control points (from 0 to 999). Control point 0 is the center of the graphic. This [function] allows you to set the location of any control point belonging to any graph. The coordinates are relative to the upper left corner of the graphic.

To obtain the coordinates of a control point, use [point_get]().

The previous name [set_point]() is deprecated.

Parameters


INT fileID - [FileID] containing the graphic. INT graphID - [GraphID] of which to set a control point. INT controlpointID - Number of the control point. INT x - The new X-coordinate of the control point. INT y - The new Y-coordinate of the control point.


Returns

INT : Successrate


-1 - One of the following: specified graph is invalid, specified control point is invalid. 1 - The control point was set successfully.


Example

import "mod_map"
import "mod_say"
import "mod_wm"
import "mod_key"
import "mod_grproc"

Process Main()
Private
    int map;
    int cx,cy;
Begin

    // Create a red graph
    map = new_map(100,100,8);
    map_clear(0,map,rgb(255,0,0));

    // Set the center to a random point
    point_set(0,map,0,rand(-10,110),rand(-10,110));

    // Get the center
    point_get(0,map,0,&cx,&cy);

    // Show the center
    say("Center-X: " + cx);
    say("Center-Y: " + cy);

    // Assign the map to the graph variable
    graph = map;

    // Set the location of this process to the center of the screen
    x = 160;
    y = 100;

    Repeat
        frame;
    Until(exit_status||key(_ESC))

End

Used in example: [new_map](), [map_clear](), [point_set](), [point_get](), [pointer]

Notice that setting the center influences the position of the graph:


put_pixel()

Definition

INT put_pixel ( <INT x> , <INT y> , <INT color> )

Draws a single colored [pixel] on the [background]. Is equivalent to [map_put_pixel] ( 0, 0, x, y, color ).

Parameters


INT x - Where on the background's x-axis to put the pixel. INT y - Where on the background's y-axis to put the pixel. INT color - What [color] to draw.


Returns

INT : [true]

Example

import "mod_video"
import "mod_map"
import "mod_wm"
import "mod_draw"
import "mod_rand";

Process Main()
Private
    int i;
    int direction;
end
Begin

    // Set the mode to 16bit and some res
    set_mode(320,200,16);

    // Create a blue-ish square map
    graph = new_map(20,20,16);
    map_clear(0,graph,rgb(50,100,150));
    y=100;
    x=10;

    // Puts 100 yellow-ish pixels in random places in the background
    for(i=0; i<100; i++)
        put_pixel(rand(0,320),rand(0,200),rgb(255,255,55));
    end

    Repeat
        x=x+direction; 
        if (x>=310) direction=-3; end 
        if (x<=10) direction=3; end
        frame;
    Until(exit_status)

End

Used in example: [set_mode](), [new_map](), [rand]()



Math

abs()

Definition

FLOAT abs ( <FLOAT value> )

Returns the absolute value of value.

Parameters


FLOAT value - The value.


Returns

FLOAT : The absolute value of value.

Example

Global
    float value1;
    int value2;
End

Process Main()
Begin

    write_float(0,0, 0,0,&value1);
    write_int(0,0,10,0,&value2);

    value1 = abs(3);
    value2 = abs(-4);

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [write_float](), [write_int](), [key]()


acos()

Syntax

FLOAT acos ( <FLOAT value> )

Description

Returns the arccosine of a certain value.

This [function] performs an arccosine calculation on a certain value and returns an [angle] between and including 0 and 180000 (0-180º).

Parameters


FLOAT value - The value to be performed an arccosine calculation on.


Returns

FLOAT : The arccosine result of the specified value, an angle between and including 0 and 180000 (0-180º).

Notes

The [angle] value returned by this function is in thousandths of degrees, as most angles within [Bennu] are.

To read about all aspects of trigonometry, you can visit Wikipedia's Trigonometric function page.


asin()

Syntax

FLOAT asin ( <FLOAT value> )

Description

Returns the arcsine of a certain value.

This [function] performs an arcsine calculation on a certain value and returns an [angle] between and including -90000 and 90000 (-90-90º).

Parameters


FLOAT value - The value to be performed an arcsine calculation on.


Returns

FLOAT : The arcsine result of the specified value, an angle between and including -90000 and 90000 (-90-90º).

Notes

The [angle] value returned by this function is in thousandths of degrees, as most angles within [Bennu] are.

To read about all aspects of trigonometry, you can visit Wikipedia's Trigonometric function page.


atan()

Syntax

FLOAT atan ( <FLOAT value> )

Description

Returns the arctangent of a certain value.

This [function] performs an arctangent calculation on a certain value and returns an [angle] between but not including -90000 and 90000 (-90-90º).

Parameters


FLOAT value - The value to be performed an arctangent calculation on.


Returns

FLOAT : The arctangent result of the specified value, an angle between but not including -90000 and 90000 (-90-90º).

Notes

The [angle] value returned by this function is in thousandths of degrees, as most angles within [Bennu] are.

To read about all aspects of trigonometry, you can visit Wikipedia's Trigonometric function page.


atan2()

Syntax

FLOAT atan2 ( <FLOAT y> , <FLOAT x>)

Description

Returns the arctangent of a certain value. It is computed as the arc tangent of y/x. The signs of the arguments are used to perform the calculation.

This [function] performs an arctangent calculation on a certain value and returns an [angle] between but not including -180000 and 180000 (-180-180º).

Parameters


FLOAT y - The Y value to be performed an arctangent calculation on. FLOAT x - The X value to be performed an arctangent calculation on.


Returns

FLOAT : The arctangent result of the specified value, an angle between but not including -180000 and 180000 (-180-180º).

Notes

The [angle] value returned by this function is in thousandths of degrees, as most angles within [Bennu] are.

See also

[atan]()

To read about all aspects of trigonometry, you can visit Wikipedia's Trigonometric function page.

Wikipedia's Atan2 page.


cos()

Syntax

FLOAT cos ( <FLOAT angle> )

Description

Returns the cosine of the specified angle.

This [function] performs a cosine calculation on a certain angle and returns a value between -1 and 1.

Parameters


FLOAT angle - [Angle], in thousandths of degrees. i.e. 75000 = 75º


Returns

FLOAT : The cosine result of the specified [angle].

Notes

The [angle] value used in this function should be in thousandths of degrees, as most angles within [Bennu] are.

To read about all aspects of trigonometry, you can visit Wikipedia's Trigonometric function page.

Example

Const
    screen_width  = 320;
    screen_height = 200;
    screen_border = 15;
End

Global
    float value;
End

Process Main()
Begin

    // Modes
    set_title("Cosine Graph");
    set_mode(screen_width,screen_height);

    // X axis
    for(x=1;x<=8;x++)
        write( 0,
               screen_border+x*(screen_width-screen_border)/8+3,
               screen_height-1,
               8,
               itoa(x*360/8 )+"^" );
    end
    draw_line(1,screen_height-screen_border,screen_width,screen_height-screen_border);

    // Y axis
    write(0,screen_border-1,20,5,"1");
    write(0,screen_border-1,screen_height/2,5,"0");
    write(0,screen_border-1,screen_height-20,5,"-1");
    draw_line(screen_border,1,screen_border,screen_height-1);

    // Draw tangent
    for(angle=0;angle<360;angle++)
        value=cos(angle*1000)*(screen_height/2-20);
        put_pixel( screen_border+angle*(screen_width-screen_border)/360,
                   screen_height/2-value,
                   rgb(255,255,255) );
        // screen_height/2-value because the screen's origin (0,0) is topleft instead of downleft.
    end

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [set_title](), [set_mode](), [draw_line](), [put_pixel]()

This will result in something like:\


fget_angle()

Definition

INT fget_angle ( <INT pointA-X> , <INT pointA-Y> , <INT pointB-X> , <INT pointB-Y> )

Returns the [angle] between two certain points. The returned angle will be ranging from 0 to 360000 (0-360º).

Parameters


INT pointA-X - The X-coordinate of point A. INT pointA-Y - The Y-coordinate of point A. INT pointB-X - The X-coordinate of point B. INT pointB-Y - The Y-coordinate of point B.


Returns

INT : The angle between point A and point B.

Notes

The [angle] value returned by this function is in thousandths of degrees, as most angles within [Bennu] are.

Example

Const
    screen_width     = 320;
    screen_height    = 200;
    screen_depth     = 8;
    screen_fps       = 60;
    screen_frameskip = 0;
End

Global
    int distance;
    int tempID;
End

Process Main()
Begin

    // Set the screen mode
    set_mode(screen_width,screen_height,screen_depth);
    set_fps(screen_fps,screen_frameskip);

    // Change this to see what happens
    resolution = 100;

    // Create mouse graph, assign to mouse.graph
    mouse.graph = new_map(20,20,screen_depth);
    map_clear(0,mouse.graph,rgb(255,0,0));

    // Create arrow, assign to graph
    graph = new_map(30,30,screen_depth);
    drawing_map(0,graph);
    drawing_color(rgb(0,255,0));
    draw_line( 0,29,29,30/2);
    draw_line( 0, 0,30,30/2);

    // Set position
    x = screen_width /2 * resolution;
    y = screen_height/2 * resolution;

    // Display distance
    write(0,0,0,0,"Distance:");
    write_int(0,60,0,0,&distance);

    // Always point to the mouse
    Repeat
        // Get the angle and distance between this process' coordinates and those of the mouse.
        angle    = fget_angle(x,y,mouse.x*resolution,mouse.y*resolution);
        distance = fget_dist (x,y,mouse.x*resolution,mouse.y*resolution);
        frame;
    Until(key(_esc))

End

Used in example: [set_mode](), [new_map](), [drawing_map](), [drawing_color](), [draw_line](), [write_int](), [fget_angle](), [fget_dist](), [resolution], [graph], [angle]

This example could also be done with [get_angle](), but that would be more work.

It could look something like:\


fget_dist()

Definition

INT fget_dist ( <INT pointA-X> , <INT pointA-Y> , <INT pointB-X> , <INT pointB-Y> )

Returns the distance between two certain points.

Parameters


INT pointA-X - The X-coordinate of point A. INT pointA-Y - The Y-coordinate of point A. INT pointB-X - The X-coordinate of point B. INT pointB-Y - The Y-coordinate of point B.


Returns

INT : The distance between point A and point B.

Example

Program angling;
Const
    screen_width     = 320;
    screen_height    = 200;
    screen_depth     = 8;
    screen_fps       = 60;
    screen_frameskip = 0;
Global
    int distance;
    int tempID;
Begin

    // Set the screen mode
    set_mode(screen_width,screen_height,screen_depth);
    set_fps(screen_fps,screen_frameskip);

    // Change this to see what happens
    resolution = 100;

    // Create mouse graph, assign to mouse.graph
    mouse.graph = new_map(20,20,screen_depth);
    map_clear(0,mouse.graph,rgb(255,0,0));

    // Create arrow, assign to graph
    graph = new_map(30,30,screen_depth);
    drawing_map(0,graph);
    drawing_color(rgb(0,255,0));
    draw_line( 0,29,29,30/2);
    draw_line( 0, 0,30,30/2);

    // Set position
    x = screen_width /2 * resolution;
    y = screen_height/2 * resolution;

    // Display distance
    write(0,0,0,0,"Distance:");
    write_int(0,60,0,0,&distance);

    // Always point to the mouse
    Repeat
        // Get the angle and distance between this process' coordinates and those of the mouse.
        angle    = fget_angle(x,y,mouse.x*resolution,mouse.y*resolution);
        distance = fget_dist (x,y,mouse.x*resolution,mouse.y*resolution);
        frame;
    Until(key(_esc))

End

Used in example: [set_mode](), [new_map](), [drawing_map](), [drawing_color](), [draw_line](), [write_int](), [fget_angle](), [fget_dist](), [resolution], [graph], [angle]

This example could also be done with [get_dist](), but that would be more work. It also gives a much less accurate distance when the [resolution] is >1.

Resolution is 100:


{{Image image = get_angle.png caption = [get_angle]() }}



finite()

Syntax

INT Finite ( <FLOAT number> )

Description

Checks if a given value is a finite number. This function is the opposite of the [Isinf]() function. It does not check for Not-A-Numbers. Use the [Isnan]() function for that.

Parameters


FLOAT number - The value to check.


Returns


INT FALSE - The value is an infinity. INT TRUE - The value is a finite number.


See also

Wikipedia page about the mathematical subject infinity.


get_distx()

Definition

INT get_distx ( <INT angle> , <INT distance> )

Returns the horizontal distance in pixels of a specified displacement.

This is the same as [[cos]](''angle'')*''distance''.

Parameters


INT angle - [Angle], in thousandths of degrees (90° = 90000). INT distance - Length (in pixels) to measure.


Returns

INT : The horizontal distance, in pixels, of a specified displacement.

Notes

This function returns the width of an imaginary rectangle who's opposite corners are the specified distance apart, at the specified [angle] from each other.

Example

Global
    xdist;
    ydist;
    dist;
    ang;
    mydraw;
End

Process Main()
Begin

    set_mode(640,480,16);
    set_fps (50,0);
    graph = new_map(3,3,16);
    map_clear(0,graph,rgb(0,255,0));
    x = 320;
    y = 240;

    set_text_color(rgb(0,0,0));
    write    (0,60, 0,2,"X Diff: ");
    write_int(0,60, 0,0,&xdist);
    write    (0,60,10,2,"Y Diff: ");
    write_int(0,60,10,0,&ydist);
    write    (0,60,20,2,"Angle: ");
    write_int(0,60,20,0,&ang);
    write    (0,60,30,2,"Distance: ");
    write_int(0,60,30,0,&dist);

    write    (0,10,40,0,"Left/right rotates your angle, up/down changes your distance");

    put(0,graph,x,y);
    drawing_background();

    repeat
        if(key(_up))
            dist++;
        end

        if(key(_down))
            dist--;
        end

        if(key(_left))
            ang-=1000;
        end

        if(key(_right))
            ang+=1000;
        end

        xdist = get_distx(ang,dist);
        ydist = get_disty(ang,dist);

        x = 320 + xdist;
        y = 240 + ydist;

        frame;

    until(key(_esc))

    let_me_alone();
    exit();

End

Process drawing_background()
Begin
    graph = new_map(640,480,16);
    set_ceter   (0,graph,0,0);
    map_clear    (0,graph,rgb(64,0,0));
    drawing_map  (0,graph);
    drawing_color(rgb(0,0,0));
    loop
        map_clear(0,graph,rgb(255,255,255));
        mydraw = draw_line(320,240,father.x,father.y);
        frame;
        delete_draw(mydraw);
    end
OnExit
    unload_map(0,graph);
End

Used in example: [set_mode](), [set_fps](), [set_text_color](), [write](), [put](), [get_distx](), [get_disty](), [let_me_alone](), [set_center](), [map_clear](), [drawing_map](), [drawing_color](), [draw_line](), [delete_draw](), [unload_map]()


get_disty()

Definition

INT get_disty ( <INT angle> , <INT distance> )

Returns the vertical distance in pixels of a specified displacement.

This is the same as -[[sin]](''angle'')*''distance''.

Parameters


INT angle - [Angle], in thousandths of degrees (90° = 90000). INT distance - Length (in pixels) to measure.


Returns

INT : The vertical distance, in pixels, of a specified displacement.

Notes

This function returns the height of an imaginary rectangle who's opposite corners are the specified distance apart, at the specified [angle] from each other.

Example

Global
    xdist;
    ydist;
    dist;
    ang;
    mydraw;
End

Process Main()
Begin

    set_mode(640,480,16);
    set_fps (50,0);
    graph = new_map(3,3,16);
    map_clear(0,graph,rgb(0,255,0));
    x = 320;
    y = 240;

    set_text_color(rgb(0,0,0));
    write    (0,60, 0,2,"X Diff: ");
    write_int(0,60, 0,0,&xdist);
    write    (0,60,10,2,"Y Diff: ");
    write_int(0,60,10,0,&ydist);
    write    (0,60,20,2,"Angle: ");
    write_int(0,60,20,0,&ang);
    write    (0,60,30,2,"Distance: ");
    write_int(0,60,30,0,&dist);

    write    (0,10,40,0,"Left/right rotates your angle, up/down changes your distance");

    put(0,graph,x,y);
    drawing_background();

    repeat
        if(key(_up))
            dist++;
        end

        if(key(_down))
            dist--;
        end

        if(key(_left))
            ang-=1000;
        end

        if(key(_right))
            ang+=1000;
        end

        xdist = get_distx(ang,dist);
        ydist = get_disty(ang,dist);

        x = 320 + xdist;
        y = 240 + ydist;

        frame;

    until(key(_esc))

    let_me_alone();
    exit();

End

Process drawing_background()
Begin
    graph = new_map(640,480,16);
    set_ceter   (0,graph,0,0);
    map_clear    (0,graph,rgb(64,0,0));
    drawing_map  (0,graph);
    drawing_color(rgb(0,0,0));
    loop
        map_clear(0,graph,rgb(255,255,255));
        mydraw = draw_line(320,240,father.x,father.y);
        frame;
        delete_draw(mydraw);
    end
OnExit
    unload_map(0,graph);
End

Used in example: [set_mode](), [set_fps](), [set_text_color](), [write](), [put](), [get_distx](), [get_disty](), [let_me_alone](), [set_center](), [map_clear](), [drawing_map](), [drawing_color](), [draw_line](), [delete_draw](), [unload_map]()


isinf()

Syntax

INT isinf ( <FLOAT number> )

Description

Checks if a given value is an infinity. It does not check for Not-A-Numbers. Use the [Isnan]() function for that.

Parameters


FLOAT number - The value to check.


Returns


INT FALSE - The value is a not an infinity. INT TRUE - The value is a positive or negative infinity.


See also

Wikipedia page about the mathematical subject infinity.


isnan()

Syntax

INT isnan ( <FLOAT number> )

Description

Checks if a given value is a number. It does not check for infinties. Use the [Isinf]() function for that.

Parameters


FLOAT number - The value to check.


Returns


INT FALSE - The value is a number. INT TRUE - The value is NOT a number.



near_angle()

Definition

INT near_angle ( <INT angle> , <INT final angle> , <INT increment> )

Returns an [angle] closer to another angle, with the indicated increment. It is used for aiming the original angle and it gradually changes into the final angle. The increment controls the rate in wich the final angle is added or subtracted from the orginal angle. The returned angle will be ranging from 0 to 360000 (0-360º).

Parameters


INT angle - The original angle. INT final angle - The new angle. INT increment - The addition or subtraction rate between the two angles.


Returns

INT : An angle nearer the final angle.

Notes

The [angle] value returned by this function is in thousandths of degrees, as most angles within [Bennu] are.

Example

/* Modified example converted from bennupack, fenix test section, 2 Medium\fenix test\Fenix Test3\Test_NEAR_ANGLE.prg */

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
//IMPORT "mod_math";
IMPORT "mod_mathi";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_screen";
IMPORT "mod_mouse";
IMPORT "mod_proc";
IMPORT "mod_grproc";

GLOBAL

   int fpg;
   int ang;
   //int increment=5000;
   int increment=10000;
   //int increment=25000;
   //int increment=50000;

PROCESS main();

BEGIN

  full_screen=false;
  fpg=load_fpg("Fpg.fpg");

  say("Test near_angle...");
  say("Press ESC to quit, and use mouse to move triangle.");

  put_screen(fpg,2);

  // set the mouse cursor 
  mouse.graph=200;
  mouse.x=0;
  mouse.y=0;

  graph=101;

  REPEAT

    // Returns the angle between two certain points. The returned angle will be ranging from 0 to 360000 (0-360º). 
    ang=fget_angle(x,y,mouse.x,mouse.y);

    // int near_angle (int <angle>, int <final angle>, int <increment>)
    angle=near_angle(angle,ang,increment);

    say("angle: "+angle);
    say("ang: "+ang);
    say("increment: "+increment);   

    advance(5);
    FRAME;
  UNTIL(key(_esc))

END

Used in example: [say](), [fget_angle](), [Advance], [graph], [angle]


pow()

Definition

FLOAT pow ( <FLOAT base> , <FLOAT power> )

Returns base to the power of power (base\^power).

Parameters


FLOAT base - The base. FLOAT power - The power.


Returns

FLOAT : base to the power of power (base\^power).

Example

Program powerful;
Global
    float value1;
    int   value2;
Begin

    write_float(0,0, 0,0,&value1);
    write_int  (0,0,10,0,&value2);

    value1 = pow(2.3,4.6);
    value2 = pow(2  ,3  );

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [write_float](), [write_int](), [key]()


rand()

Definition

INT rand ( <INT lowerlimit> , <INT upperlimit> )

Returns a random number, ranging from a certain lower limit to a certain upper limit. The limits are within the range.

Make sure the difference between lowerlimit and upperlimit does not exceed 32767 (2\^15-1). If that is needed, the function rand2() below can be used.

Parameters


INT lowerlimit - The lower limit for the random value. INT upperlimit - The upper limit for the random value.


Returns

INT : A random value: lowerlimit <= result <= upperlimit

Notes

To synchronize rand() on different computers, the function [rand_seed]() can be used.

Rand() is not a very good function on itself. To counter this, the following rand2() can be used:

#define RAND_MAX 32767
#define DRAND_RANGE (1.0/((RAND_MAX + 1)*(RAND_MAX + 1)))
#define irand(x) ((unsigned int) ((x) * drand ()))
Function float drand ()
Private
    float f;
Begin
    Repeat
       f = (rand (0,RAND_MAX) * (RAND_MAX + 1.0)
          + rand (0,RAND_MAX)) * DRAND_RANGE;
    Until (f < 1); /* Round off */
    return f;
End
Function int rand2(int lowerlimit, int upperlimit)
Begin
    return (lowerlimit+irand(upperlimit-lowerlimit+1));
End

To understand this code, one can read its source.


rand_seed()

Definition

INT rand_seed ( <INT seed> )

Seeds the random generator, used in [rand]().

This is useful for synchronizing the random generator on multiple machines, as when the same seed is used, calls to [rand]() with the same limits will return values in the same order on all the machines.

To reset the seeding to its original state, meaning the state before any call to [rand]() or [rand_seed](), set seed to 1.

Parameters


INT seed - The seed for the random generator used in [rand](); 1 to reset.


Returns

INT : [true]

Example

import "mod_rand"
import "mod_say"
import "mod_time"

Process Main()
Begin
    say("First number: " + (rand(0,1000)%100));
    rand_seed(time());
    say("Random number: " + (rand(0,1000)%100));
    rand_seed(1);
    say("Again the first number: " + (rand(0,1000)%100));
End

Used in example: [say](), [rand_seed]()


sin()

Definition

FLOAT sin ( <FLOAT angle> )

Returns the sine of the specified [angle].

This [function] performs a sine calculation on a certain angle and returns a value between -1 and 1.

Parameters


FLOAT angle - [Angle], in thousandths of degrees. i.e. 75000 = 75º


Returns

FLOAT : The sine result of the specified [angle].

Notes

The [angle] value used in this function should be in thousandths of degrees, as most angles within [Bennu] are.

To read about all aspects of trigonometry, you can click on Wikipedia's Trigonometric function page.

Example

Const
    screen_width  = 320;
    screen_height = 200;
    screen_border = 15;
End

Global
    float value;
End

Process Main()
Begin

    // Modes
    set_title("Sine Graph");
    set_mode(screen_width,screen_height);

    // X axis
    for(x=1;x<=8;x++)
        write( 0,
               screen_border+x*(screen_width-screen_border)/8+3,
               screen_height-1,
               8,
               itoa(x*360/8 )+"^" );
    end
    draw_line(1,screen_height-screen_border,screen_width,screen_height-screen_border);

    // Y axis
    write(0,screen_border-1,20,5,"1");
    write(0,screen_border-1,screen_height/2,5,"0");
    write(0,screen_border-1,screen_height-20,5,"-1");
    draw_line(screen_border,1,screen_border,screen_height-1);

    // Draw tangent
    for(angle=0;angle<360;angle++)
        value=sin(angle*1000)*(screen_height/2-20);
        put_pixel( screen_border+angle*(screen_width-screen_border)/360,
                   screen_height/2-value,
                   rgb(255,255,255) );
        // screen_height/2-value because the screen's origin (0,0) is topleft instead of downleft.
    end

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [set_title](), [set_mode](), [draw_line](), [put_pixel]()

This will result in something like:\


sqrt()

Definition

FLOAT sqrt ( <FLOAT value> )

Returns the square root of a certain value.

Parameters


FLOAT value - The value of which the square root will be returned.


Returns

FLOAT : The square root of value.


tan()

Definition

FLOAT tan ( <FLOAT angle> )

Returns the tangent of a certain [angle].

This [function] performs a tangent calculation on a certain angle and returns a value.

Parameters


FLOAT angle - [Angle], in thousandths of degrees. i.e. 75000 = 75º


Returns

FLOAT : The tangent result of the specified [angle].

Notes

The [angle] value used in this function should be in thousandths of degrees, as most angles within [Bennu] are.

To read about all aspects of trigonometry, you can visit Wikipedia's Trigonometric function page.

Example

Const
    screen_width  = 320;
    screen_height = 200;
    screen_border = 15;
End

Global
    float value;
End

Process Main()
Begin

    // Modes
    set_title("Tangent Graph");
    set_mode(screen_width,screen_height);

    // X axis
    for(x=1;x<=8;x++)
        write( 0,
               screen_border+x*(screen_width-screen_border)/8+3,
               screen_height-1,
               8,
               itoa(x*360/8 )+"^" );
    end
    draw_line(1,screen_height-screen_border,screen_width,screen_height-screen_border);

    // Y axis
    write(0,screen_border-1,20,5,"1");
    write(0,screen_border-1,screen_height/2,5,"0");
    write(0,screen_border-1,screen_height-20,5,"-1");
    draw_line(screen_border,1,screen_border,screen_height-1);

    // Draw tangent
    for(angle=0;angle<360;angle++)
        value=tan(angle*1000)*(screen_height/2-20);
        put_pixel( screen_border+angle*(screen_width-screen_border)/360,
                   screen_height/2-value,
                   rgb(255,255,255) );
        // screen_height/2-value because the screen's origin (0,0) is topleft instead of downleft.
    end

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [set_title](), [set_mode](), [draw_line](), [put_pixel]()

This will result in something like:\



Memory

alloc()

Syntax

VOID POINTER alloc ( <INT size> )

Description

Allocates a [block of memory] of a certain size. Returns a pointer to the newly allocating memory block, or [NULL] on failure.

Also called [mem_alloc]().

Parameters


INT size - The size of the to be allocated memory in [bytes].


Returns

VOID POINTER : Pointer to the first element of the allocated memory block.


[NULL] - There was are an error allocating the memory, like insufficient memory available. ![NULL] - Pointer to the first element of the allocated memory block.


Example

import "mod_mem"
import "mod_say"

Process Main()
Private
    byte* pbyte;
    word* pword;
    int* pint;
    int elements = 10;
    int i;
Begin

    // Allocate memory
    pbyte = alloc(elements);
    pword = alloc(elements*sizeof(*pword)); // note the sizeof() here, this is possible!
    pint  = alloc(elements*sizeof(int));

    // Reset memory to 0's
    memset (pbyte,0,elements);
    memsetw(pword,0,elements); // same as  memset(pword,0,elements*sizeof(word));
                               // because value-parameter is 0.
    memseti(pint ,0,elements); // same as  memset(pint,0,elements*sizeof(int));
                               // because value-parameter is 0.

    // Write numbers to bytes and ints
    for(i=0; i<elements; i++)
        pbyte[i]  = 133; // pbyte[i] is the same as *(pbyte+i)
        *(pint+i) = 4555; // pint[i] is the same as *(pint+i)
    end

    // Write numbers to words
    memsetw(pword,345,elements);

    // Show numbers
    for(i=0; i<elements; i++)
        say("byte["+i+"] = " + *(pbyte+i));
        say("word["+i+"] = " + pword[i]);
        say("int ["+i+"] = " + pint[i]);
    end

OnExit

    // Free the used memory
    free(pbyte);
    free(pword);
    free(pint);

End

Example 2

The following three examples show the difference in size, when array's are created. Note the use of the [sizeof]() operator, to calculate the amount of bytes required for the data type. You can also allocate user defined types and even structs. Be carefull with strings though, as they show up as 4 bytes, but in the case of strings, you get a [pointer] (start adress) of the [string], wich is a 4 byte integer.


Example 1 - array of 10 (4 byte) integers Example 2 - array of 10 (1 byte) byte (could also be char) Example 3 - array of 10 (2 byte) short integers


// Some general remarks with manual memory managment, ALWAYS free data after use, and test if an
// allocation was successfull with IF (p_test_array2==NULL). When one of these memory allocation
// functions returns a NULL, the allocation was NOT sucessfull, and any kind of unpredicatable things
// can happen. With manual memory managment, you'll have to really know what you're doing, as the slightest
// mistake can cause crashes and unpredicatable behaviour, wich is one of the dangers with using pointers.

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_mem";

 /*
    alloc(int size);
    returns: void pointer
    purpose: create a block of memory, of a certain size, the returned pointer indicates the start adress of this block.
*/

GLOBAL

int pointer p_first_array;    // 10 elments, created with alloc(), 10 integers       (4 byte elements)
byte pointer p_second_array;  // 10 elments, created with alloc(), 10 bytes          (1 byte elements)
short pointer p_third_array;  // 10 elments, created with alloc(), 10 short integers (2 byte elements)

int elements=10;            // initial array size

int count;                  // general purpose loop counter

PROCESS main();

BEGIN

    // Allocate memory (10 integers), this way we create an array of integers from (0-9, so 10 elements)
    // The alloc() function works with bytes. It is always good practice to use the sizeof() operator, because
    // you'd have to know exactly how many bytes make up a particulair data. An integer is 4 bytes in bennu,
    // so for an array of 10 elements, you need to allocate 40 bytes. If you do "alloc(elements)",like in the
    // wiki, you only get 4 bytes! so that is totally too small for you array! always use this syntax:
    // 
    // alloc(sizeof(<data_type>)), or for arrays: alloc(elements*sizeof(<data_type>)). Note that <data_type> can 
    // also be a user-defined type.

    p_first_array=alloc(elements*sizeof(int));

    // check if the allocation succeeded
    IF (p_first_array==NULL)
       // allocation failed
       say("allocation failed!! p_first_array="+p_first_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_first_array ,0,elements);

       say("");
       say("");
       // print the array
       FOR (count=0; count<elements; count+=1)
           say("p_first_array["+count+"]="+p_first_array[count]);
       END

       say("");
       say("");
       say("the size of the array is "+(elements*sizeof(int))+" bytes");  
       say("");
       say("");
    END

    // now let's create an array of 10 bytes, the size of the array will be 10 * 1 byte =10 bytes
    p_second_array=alloc(elements*sizeof(byte));

    // check if the allocation succeeded
    IF (p_first_array==NULL)
       // allocation failed
       say("allocation failed!! p_second_array="+p_second_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_second_array ,0,elements);

       say("");
       say("");
       // print the array
       FOR (count=0; count<elements; count+=1)
           say("p_second_array["+count+"]="+p_second_array[count]);
       END

       say("");
       say("");
       say("the size of the array is "+(elements*sizeof(byte))+" bytes");  
       say("");
       say("");
    END

    // now let's create an array of 10 short integers, the size of the array will be 10 * 2 bytes =20 bytes
    p_third_array=alloc(elements*sizeof(short));

    // check if the allocation succeeded
    IF (p_first_array==NULL)
       // allocation failed
       say("allocation failed!! p_second_array="+p_third_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_third_array ,0,elements);

       say("");
       say("");
       // print the array
       FOR (count=0; count<elements; count+=1)
           say("p_third_array["+count+"]="+p_third_array[count]);
       END

       say("");
       say("");
       say("the size of the array is "+(elements*sizeof(short))+" bytes");  
       say("");
       say("");
    END    

ONEXIT

   // Free the used memory
   say("freeing old memory........");
   say("p_first_array...");
   free(p_first_array);
   say("ok");

   say("freeing old memory........");
   say("p_second_array...");
   free(p_second_array);
   say("ok");

   say("freeing old memory........");
   say("p_third_array...");
   free(p_third_array);
   say("ok");
END

Used in example: [alloc](), [memset](), [memseti](), [say](), [OnExit], [sizeof]


calloc()

Syntax

VOID POINTER calloc (<INT num> ,<INT size>)

Description

Allocates (creates) a [block of memory] of a certain size. Calloc is slightly different from alloc, as it is more natively suited for creating arrays. It also automatically initialises the data with zeros, so that the use of [memset]() or [memseti]() can be omitted. Returns a pointer to the newly allocating memory block, or [NULL] on failure.

Also called [mem_calloc]().

Parameters


INT num - The amount of elements to be created in [ints].


Returns

VOID POINTER : Pointer to the first element of the allocated memory block.


[NULL] - There was are an error allocating the memory, like insufficient memory available. ![NULL] - Pointer to the first element of the allocated memory block.


Example

// Some general remarks with manual memory managment, ALWAYS free data after use, and test if an
// allocation was successfull with IF (p_array==NULL). When one of these memory allocation
// functions returns a NULL, the allocation was NOT sucessfull, and any kind of unpredicatable things
// can happen. With manual memory managment, you'll have to really know what you're doing, as the slightest
// mistake can cause crashes and unpredicatable behaviour, wich is one of the dangers with using pointers.

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_mem";

/*
    calloc(int size,type);
    returns: void pointer
    purpose: create a block of memory, of a certain size, the returned pointer indicates the start adress of this block.
*/

GLOBAL

int pointer p_array;        // 10 elments, created with calloc()

int elements=10;            // initial array size

int count;                  // general purpose loop counter

PROCESS main();

BEGIN

    // Now let's use calloc to create an array, but calloc is a bit smarter then alloc. It's more suited to array's and
    // it even initializes all the data to 0 for you, so that you can omit the memset() function. In this case I 
    // kept memseti() in there, but you can omit it when using calloc(). But with alloc() you need to use it!

    // Note the small difference between alloc() and calloc().

    //p_array=alloc(elements*sizeof(int));
    p_array=calloc(elements,sizeof(int));   // 10 * 4 bytes (the size of an int)

    // check if the allocation succeeded
    IF (p_array==NULL)
       // allocation failed
       say("allocation failed!! p_array="+p_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       /*
       memseti(p_array ,0,elements); // not need for calloc();
       */

       say("");
       say("");
       // print the array
       FOR (count=0; count<elements; count+=1)
           say("p_array["+count+"]="+p_array[count]);
       END

       say("");
       say("");
       say("the size of the array is "+(elements*sizeof(int))+" bytes");
       say("");
       say("");
    END   

ONEXIT

   // Free the used memory
   say("freeing old memory........");

   say("p_array...");
   free(p_array);
   say("ok"); 

END

Used in example: [alloc](), [memset](), [memseti](), [say](), [OnExit], [sizeof]


free()

Definition

INT free ( <VOID POINTER data> )

Frees a block of memory.

The pointer used must be a pointer to a previously allocated block of memory, else the behavior of free() is undefined.

Also called [mem_free]().

Parameters


VOID POINTER data - Pointer to the block of memory to be freed.


Returns

INT : [true]

Example

Program example;
Private
    byte pointer pbyte;
    word pointer pword;
    int  pointer pint;
    int elements = 10;
    int i;
Begin

    // Allocate memory
    pbyte = alloc(elements);
    pword = alloc(elements*sizeof(word));
    pint  = alloc(elements*sizeof(int));

    // Reset memory to 0's
    memset (pbyte,0,elements);
    memsetw(pword,0,elements); // same as  memset(pword,0,elements*sizeof(word));
                               // because value-parameter is 0.
    memset (pint ,0,elements*sizeof(int)); // There isn't a "memseti()", so we need to
                                           // set the individual bytes to 0. To change
                                           // ints to nonzero values, memset() can't be
                                           // used easily

    // Write numbers to bytes and ints
    for(i=0; i<elements; i++)
        pbyte[i]  = 133; // pbyte[i] is the same as *(pbyte+i)
        *(pint+i) = 4555; // pint[i] is the same as *(pint+i)
    end

    // Write numbers to words
    memsetw(pword,345,elements);

    // Show numbers
    for(i=0; i<elements; i++)
        say("byte["+i+"] = " + *(pbyte+i));
        say("word["+i+"] = " + pword[i]);
        say("int ["+i+"] = " + pint[i]);
    end

    Repeat
        frame;
    Until(key(_esc))

    // Free the used memory
    free(pbyte);
    free(pword);
    free(pint);

End

Used in example: [alloc](), [memset](), [sizeof](), [free]


memcmp()

Definition

INT memcmp ( <VOID POINTER ptr1> , <VOID POINTER ptr2> , <INT number> )

Compares the first number bytes of the block of memory pointed by ptr1 to the first number bytes pointed by ptr2, returning zero if they all match or a value different from zero representing which is greater if they do not.

Also called [mem_cmp]().

Parameters


VOID POINTER ptr1 - Pointer to a block of memory VOID POINTER ptr2 - Pointer to a block of memory. INT number - The number of bytes to be checked.


Returns

INT : Difference


0 - The blocks of memory are identical. >0 - The first differing byte in both memory blocks has a greater value in ptr1. <0 - The first differing byte in both memory blocks has a greater value in ptr2.


A byte ranges from 0 to 255, meaning 189 is a greater value than 105.

Example

Program example;
Const
    elements = 10;
End
Private
    byte pointer pbyte1;
    byte pointer pbyte2;
    int result;
End
Begin

    // Allocate memory
    pbyte1 = alloc(elements);
    pbyte2 = alloc(elements);

    // Make the blocks the same and compare
    memset(pbyte1,3,elements);
    memset(pbyte2,3,elements);
    result = memcmp(pbyte1,pbyte2,elements); // You can also compare the first 5 bytes,
                                             // or the first elements/2 bytes, it
                                             // depends on what you want.
    say("Memcmp 1: " + result);

    // Make the first block have a greater value and compare
    pbyte1[0] = 4;
    result = memcmp(pbyte1,pbyte2,elements);
    say("Memcmp 2: " + result);

    // Make the blocks the same and compare
    pbyte2[0] = 4;
    result = memcmp(pbyte1,pbyte2,elements);
    say("Memcmp 3: " + result);

    // Make the first block have a greater value and compare
    pbyte2[1] = 5;
    result = memcmp(pbyte1,pbyte2,elements);
    say("Memcmp 4: " + result);

    Repeat
        frame;
    Until(key(_esc))

    // Free the used memory
    free(pbyte1);
    free(pbyte2);

End

Used in example: [alloc](), [memset](), [say](), [pointer]


memcopy()

Syntax

INT memcopy ( <VOID POINTER destination> , <VOID POINTER origin> , <INT size> )

Description

Copies a certain number of [bytes] from one point in [memory] to another.

Difference between [memmove]() and [memcopy]() is that the first one can be used if the destination section and origin section overlap. With [memcopy](), this can go wrong, though some systems make [memcopy]() safe too.

Also called [mem_copy]().

Parameters


VOID POINTER destination - Pointer to the first byte of the destination. VOID POINTER origin - Pointer to the first byte of the origin. INT size - The size of the to be copied memory in bytes.


Returns

INT : [true]

Example

import "mod_mem"
import "mod_say"

Const
    elements = 5;
End

Process Main()
Private
    byte bytearray[elements-1];
    byte* pbyte;
    int i;
End
Begin

    // Allocate memory
    pbyte = alloc(elements);

    // Set numbers
    for(i=0; i<elements; i++)
        bytearray[i] = i;
    end

    // Copy bytes to bytearray
    memcopy(pbyte,&bytearray[0],elements);

    // Show numbers
    for(i=0; i<elements; i++)
        say("byte["+i+"] = " + pbyte[i]);
    end

OnExit

    // Free the used memory
    free(pbyte);

End

Used in example: [alloc](), [memcopy](), [free], [pointer]


memmove()

Definition

INT memmove ( <VOID POINTER destination> , <VOID POINTER origin> , <INT size> )

Copies a certain number of [bytes] from one point in [memory] to another.

Difference between [memmove]() and [memcopy]() is that the first one can be used if the destination section and origin section overlap. With [memcopy](), this can go wrong, though some systems make [memcopy]() safe too.

Also called [mem_move]().

Parameters


VOID POINTER destination - Pointer to the first byte of the destination. VOID POINTER origin - Pointer to the first byte of the origin. INT size - The size of the to be copied memory in bytes.


Returns

INT : [true]

Example

import "mod_mem"
import "mod_say"

Const
    elements = 5;
End

Process Main()
Private
    byte bytearray[elements-1];
    byte* pbyte;
    int i;
End
Begin

    // Allocate memory
    pbyte = alloc(elements);

    // Set numbers
    for(i=0; i<elements; i++)
        bytearray[i] = i;
    end

    // Copy bytes to bytearray
    memmove(pbyte,&bytearray[0],elements);

    // Show numbers
    for(i=0; i<elements; i++)
        say("byte["+i+"] = " + pbyte[i]);
    end

OnExit

    // Free the used memory
    free(pbyte);

End

Used in example: [alloc](), [memmove](), [free], [pointer]


memory_free()

Syntax

INT memory_free ( )

Description

Returns the free memory total in bytes.

Also called [mem_available]().

Returns

INT : Free memory total in bytes.

Example

import "mod_mem"
import "mod_say"

Process Main()
Begin

    say("Total memory: " + memory_total());
    say("Free memory:  " + memory_free() );

End

Used in example: [say](), [memory_total](), [memory_free]()


memory_total()

Definition

INT memory_total ( )

Returns the memory total in bytes.

Also called [mem_total]().

Returns

INT : Memory total in bytes.

Example

import "mod_mem"
import "mod_say"

Process Main()
Begin

    say("Total memory: " + memory_total());
    say("Free memory:  " + memory_free() );

End

Used in example: [say](), [memory_total](), [memory_free]()


memset()

Syntax

INT memset ( <VOID POINTER data> , <BYTE value> , <INT bytes> )

Description

Sets all bytes in the specified memory block to the specified value.

Also called [mem_set]().

Parameters


VOID POINTER data - Pointer to the block of bytes in memory BYTE value - Value to set all bytes to. INT bytes - Number of bytes to change the value of.


Returns

INT : [true]

Example

See [alloc]().

Also useful in conjunction with [map_buffer]() with 8bit [maps]. (Example can be found in the map_buffer article.)


memseti()

Syntax

INT memseti ( <VOID POINTER data> , <INT value> , <INT ints> )

Description

Sets all [ints] in the specified memory block to the specified value.

Also called [mem_seti]().

Parameters


VOID POINTER data - Pointer to the block of ints in memory. INT value - Value to set all ints to. INT ints - Number of ints to change the value of.


Returns

INT : [true]

Example

See [alloc]().

Also useful in conjunction with [map_buffer]() with 32bit [maps]. (Example needed.)


memsetw()

Syntax

INT memsetw ( <VOID POINTER data> , <WORD value> , <INT words> )

Description

Sets all words in the specified memory block to the specified value.

Also called [mem_setw]().

Parameters


VOID POINTER data - Pointer to the block of words in memory. WORD value - Value to set all words to. INT words - Number of words to change the value of.


Returns

INT : [true]

Example

See [alloc]().

Also useful in conjunction with [map_buffer]() with 16bit [maps]. (Example needed.)


realloc()

Syntax

VOID POINTER realloc ( <VOID POINTER data> , <INT size> )

Description

Resizes the given block of memory.

It allocates a new block of memory, copying the old data. If the new size is smaller than the old size, the last part of the data is lost. If the new size of the block of memory requires movement of the block, the old memory block is freed.

Also called [mem_realloc]().

Parameters


VOID POINTER data - Pointer to the block of memory to be resized. INT size - The new size of the block of memory in bytes.


Returns

VOID POINTER : Pointer to (the first element of) the newly allocated memory block.


[NULL] - There was are an error allocating the memory, like insufficient memory available. ![NULL] - Pointer to (the first element of) the newly allocated memory block.


Example

import "mod_mem"
import "mod_say"

Process Main()
Private
    byte pointer pbyte;
    byte pointer pbyte2;
    int elements = 10;
    int newelements = 15;
    int i;
Begin

    // Allocate memory
    pbyte = alloc(elements);

    // Set them to 13
    memset(pbyte,13,elements);

    // Relocate it to a larger, newly made memory block
    pbyte2 = realloc(pbyte,newelements);

    // Set the added part's elements to 16 (newelements > elements)
    memset(pbyte+elements,16,newelements-elements);

    // Show numbers
    for(i=0; i<newelements; i++)
        say("byte2["+i+"] = " + pbyte2[i]);
    end

OnExit

    // Free the used memory
    free(pbyte2);

End

Example 2

// Alloc, calloc and realloc tutorial, by handsource-dyko.

// This sample program demonstrates how create integer array's with alloc, and calloc, 
// and how to resize them with realloc. 

// Some general remarks with manual memory managment, ALWAYS free data after use, and test if an
// allocation was successfull with IF (p_test_array2==NULL). When one of these memory allocation
// functions returns a NULL, the allocation was NOT sucessfull, and any kind of unpredicatable things
// can happen. With manual memory managment, you'll have to really know what you're doing, as the slightest
// mistake can cause crashes and unpredicatable behaviour, wich is one of the dangers with using pointers.

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_mem";

 /*
    alloc(int size);
    returns: void pointer
    purpose: create a block of memory, of a certain size, the returned pointer indicates the start adress of this block.
*/

/*
    calloc(int size,type);
    returns: void pointer
    purpose: create a block of memory, of a certain size, the returned pointer indicates the start adress of this block.
             is used for creating arrays.
*/

/*

   realloc (void pointer data, int size);
   returns: void pointer
   purpose: resizes the given block of memory, it allocates a new block of memory, copying the old data. 
            if the new size is smaller than the old size, the last part of the data is lost. 
            if the new size of the block of memory requires movement of the block, the old memory block is freed. 

*/

GLOBAL

int pointer p_first_array;  // 10 elments, created with alloc()
int pointer p_third_array;  // 10 elments, created with calloc()
int pointer p_second_array; // resized copy of p_first_array, 15 elements, created with realloc()
int pointer p_fourth_array; // resized copy of p_second_array, 15 elements, created with realloc()

int test[9];                // simple array with 10 elements
int pointer p_test_array;   // will be used for storing the pointer to test[0]
int pointer p_test_array2;  // will be the resized array, created with realloc, is now 15 elements

int elements=10;            // initial array size
int new_elements=15;        // new array size

int count;                  // general purpose loop counter

PROCESS main();

BEGIN

    // standard array
    say("");
    say("");
    // print the array
    FOR (count=0; count<elements; count+=1)
        say("test["+count+"]="+test[count]);
    END

    say("");
    say("");
    say("the size of the array 'test' is "+sizeof(test)+" bytes");  
    say("");
    say("");

    // Allocate memory (10 integers), this way we create an array of integers from (0-9, so 10 elements)
    // The alloc() function works with bytes. It is always good practice to use the sizeof() operator, because
    // you'd have to know exactly how many bytes make up a particulair data. An integer is 4 bytes in bennu,
    // so for an array of 10 elements, you need to allocate 40 bytes. If you do "alloc(elements)",like in the
    // wiki, you only get 10 bytes! so that is totally too small for you array! always use this syntax:
    // 
    // alloc(sizeof(<data_type>)), or for arrays: alloc(elements*sizeof(<data_type>)). Note that <data_type> can 
    // also be a user-defined type.

    p_first_array=alloc(elements*sizeof(int));
    //p_first_array=calloc(elements,sizeof(int));

    // check if the allocation succeeded
    IF (p_first_array==NULL)
       // allocation failed
       say("allocation failed!! p_first_array="+p_first_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_first_array ,0,elements);

       say("");
       say("");
       // print the array
       FOR (count=0; count<elements; count+=1)
           say("p_first_array["+count+"]="+p_first_array[count]);
       END

       say("");
       say("");
       say("the size of the array is "+(elements*sizeof(int))+" bytes");  
       say("");
       say("");
    END

    // Now let's use calloc to create the same array, but calloc is a bit smarter. It's more suited to array's and
    // it even initializes all the data to 0 for you, so that you can omit the memset() function. In this case I 
    // kept memseti() in there, but you can omit it when using calloc(). But with alloc() you need to use it!

    // Note the small difference between alloc() and calloc().

    //p_second_array=alloc(elements*sizeof(int));
    p_second_array=calloc(elements,sizeof(int));

    // check if the allocation succeeded
    IF (p_second_array==NULL)
       // allocation failed
       say("allocation failed!! p_second_array="+p_second_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_second_array ,0,elements);

       say("");
       say("");
       // print the array
       FOR (count=0; count<elements; count+=1)
           say("p_second_array["+count+"]="+p_second_array[count]);
       END

       say("");
       say("");
       say("the size of the array is "+(elements*sizeof(int))+" bytes");
       say("");
       say("");
    END   

    // Let's resize p_first_array to a bigger size (15). This is where realloc() is used for. Also, just as with
    // alloc(), it is important to remember that it works with bytes! So we use this (new_elements*sizeof(int)) again.
    p_third_array=realloc(p_first_array,(new_elements*sizeof(int)));

    // check if the allocation succeeded
    IF (p_third_array==NULL)
       // allocation failed
       say("allocation failed!! p_third_array="+p_third_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_third_array ,0,new_elements);

       say("");
       say("");
       // print the array
       FOR (count=0; count<new_elements; count+=1)
           say("p_third_array["+count+"]="+p_third_array[count]);
       END

       say("");
       say("");
       say("the size of the array is "+(new_elements*sizeof(int))+" bytes");  
       say("");
       say("");
    END

    // Let's resize p_second_array to a bigger size (15).
    p_fourth_array=realloc(p_second_array,(new_elements*sizeof(int)));

    // check if the allocation succeeded
    IF (p_fourth_array==NULL)
       // allocation failed
       say("allocation failed!! p_fourth_array="+p_fourth_array);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_fourth_array ,0,new_elements);

       say("");
       say("");

       // print the array

       FOR (count=0; count<new_elements; count+=1)
           say("p_fourth_array["+count+"]="+p_fourth_array[count]);
       END

       say("");
       say("the size of the array is "+(new_elements*sizeof(int))+" bytes");  
       say("");
       say("");
    END

    // Let's try to resize an standard array (the array test[9]) to 15 
    p_test_array=test[0];   // <-- p_test_array is a pointer, we store the ADRESS of the first element (wich is 0) in it.
                            // test[0] is actually a pointer itself, it represents the start adress of the array.
                            // The whole concept of array indexing is actuallty a concealed form of pointer artihmatic,
                            // consult any good C book about the details of this. 
    p_test_array2=realloc(p_test_array,(new_elements*sizeof(int)));

    // check if the allocation succeeded
    IF (p_test_array2==NULL)
       // allocation failed
       say("allocation failed!! p_test_array2="+p_test_array2);

    ELSE

       // allocation succeeded
       // set the value's to zero
       memseti(p_test_array2 ,0,new_elements);

       say("");
       say("");

       // print the array

       FOR (count=0; count<new_elements; count+=1)
           say("p_test_array2["+count+"]="+p_test_array2[count]);
       END

       say("");
       say("the size of the array is "+(new_elements*sizeof(int))+" bytes");  
       say("");
       say("");
    END

ONEXIT

   // Free the used memory
   say("freeing old memory........");
   say("p_first_array...");
   free(p_first_array);
   say("ok");
   say("p_second_array...");
   free(p_second_array);
   say("ok"); 
   say("p_third_array...");
   free(p_third_array);
   say("ok");
   say("p_fourth_array...");
   free(p_fourth_array);
   say("ok");  
   say("p_test_array...");
   free(p_test_array);
   say("ok"); 
   say("p_test_array2...");
   free(p_test_array2);
   say("ok");

END

Used in example: [alloc](), [memset](), [say](), [pointer]



Palettes

color_find()

Syntax

INT color_find ( <BYTE red> , <BYTE green> , <BYTE blue> )

Description

Match an RGB value to a particular palette index. This is usefull in 8 bit mode.

The previous name [find_color]() is deprecated.

Parameters


BYTE red - Level of red in the desired color from 0 to 255. BYTE green - Level of green in the desired color from 0 to 255. BYTE blue - Level of blue in the desired color from 0 to 255.


Returns

INT : Returns the palette inxed of the color that corresponds with the rgb combination.

Example

IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_key";
IMPORT "mod_map";
IMPORT "mod_video";
IMPORT "mod_wm";
IMPORT "mod_draw";
IMPORT "mod_screen";
IMPORT "mod_text";

GLOBAL

   int map_id;    // id code of the map to load

   int status;    // status for debugging

PROCESS main();

BEGIN

   set_mode(320,200,32);

   // load the map
   map_id=load_map("3COCHE.MAP");

   status=color_find(0,0,0);
   say("color: "+status);
   status=color_find(0,252,0);
   say("color: "+status);
   status=color_find(0,67,0);
   say("color: "+status);
   status=color_find(0,243,0);
   say("color: "+status);
   status=color_find(0,10,0);
   say("color: "+status);
   status=color_find(255,252,0);
   say("color: "+status);
   status=color_find(100,252,100);
   say("color: "+status);

END

fade()

Definition

INT fade ( <INT red> , <INT green> , <INT blue> , <INT speed> )

Fades the screen from the current setting to the specified setting (red,green,blue) at the specified speed.

Parameters


INT red - Amount of red shown from 0 to 200. 100 is normal. INT green - Amount of red shown from 0 to 200. 100 is normal. INT blue - Amount of red shown from 0 to 200. 100 is normal. INT speed - The speed of the fade from 1 to 64.


Returns

INT : [true]

Notes

Standard RGB combinations:


(R,G,B) - Description (0,0,0) - Black out. (100,100,100) - Normal. (200,200,200) - White out.


The number of frames the fading will take can be calculated like this:

: frames = roundup( 64 / speed ) : speed = roundup( 64 / frames )

So:


Speed - Description <0 - Takes 1 frame. 0 - Pointless. 1 - Takes 64 frames. 2 - Takes 32 frames. 3 - Takes 22 frames. >=64 - Takes 1 frame.


See also [fade_on]() and [fade_off]().


fade_off()

Definition

INT fade_off ( )

Fades the screen from the current setting to black out.

This call is equivalent to [[fade]](0,0,0,16).

Returns

INT : [true]


fade_on()

Definition

INT fade_on ( )

Fades the screen from the current setting to normal.

This call is equivalent to [[fade]](100,100,100,16).

Returns

INT : [true]


pal_clone()

Syntax

INT pal_clone ( <INT paletteID> )

Description

This function is creates a copy of palette loaded with [Pal_load](). It can be used for the functions [Pal_get]() and [Pal_map_assign]().

Parameters


INT paletteID - The handle of the color palette loaded with [Pal_load]().


Returns

INT : Error.


0 - Error: could not open file; corrupt or truncated file; file doesn't contain palette information. 1 - The identifier of the [palette].


Example

/* original bennupack example FROM: \2 Medium\fenix test\palettes\rbear8-2.prg (from bomberlink) */

/* this program demonstrates the use of the functions: pal_load(), pal_clone(), pal_get(),       */
/* pal_map_assign(), pal_set() and pal_refresh().                                                */

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_text";

GLOBAL

   // palette identifiers
   int pal_orange;
   int pal_green;
   int pal_normal;

   int status1;
   int status2;

   // identifier of the fpg archive
   int fpg_id;

   // arrays for the data of the two color palettes.
   byte pal_orange_data[255]; 
   byte pal_green_data[255];  

   int map_count;

PROCESS main();

BEGIN

    set_fps(10,0);
    set_mode(320,200,16);  // we use a 16 bit color mode

    // load two color palettes and duplicate one
    pal_green=pal_load("rbear8-green.pal");
    pal_orange=pal_load("rbear8-orange.pal");

    // pal_clone (int pal_id);
    pal_normal=pal_clone(pal_orange); // duplicate palette, i.e. make a copy of it.

    // load the fpg file
    fpg_id=fpg_load("rbear8.fpg");

    write_int(0,10,10,0,&fps);
    write(0,10,20,0,"F1/F2 - change palette");

    x = 160;
    y = 120;

    // pal_get (int pal_id, int start_color, int num_colors, pointer pal_data);
    pal_get(pal_green,7,7,&pal_green_data);    // get colors 7 - 13 and store them in the array
    pal_get(pal_orange,7,7,&pal_orange_data);        

    FROM map_count=1 TO 102; // there are 102 frames in the animation

        // pal_map_assign (int fileid, int graph, int pal_id);
        pal_map_assign(fpg_id,map_count,pal_normal); // assign the "normal (original source)" color 
                                                     // palette that we duplicated earlier.
    END

    WHILE (NOT key(_ESC))

        FROM graph=1 TO 13;

            FRAME;

            IF (key(_F1))
                say("switched to green palette");

                // pal_set (int pal_id, int start_color, int num_colors, pointer pal_data);
                status1=pal_set(pal_normal,7,7,&pal_green_data); // change colors 7 - 13 in the "normal" 
                                                                 // palette, by using the values from the
                                                                 // "green" color palette.

                say("pal_set_status: "+status1);                                                                 

                // pal_refresh (int pal_id);
                status2=pal_refresh(pal_normal); // apply the modified color palette to the graphics.
                                                 // this function is required to make the change visible.  

                say("pal_refresh_status: "+status2);                                                   

                // conclusion: the difference between pal_map_assign() and pal_set() is that pal_map_assign()
                // works immediately, and that pal_set() requires the palette to be refreshed to make the 
                // change visible.                
            END

            IF (key(_F2))
                say("switched to orange palette");
                pal_set(pal_normal,7,7,&pal_orange_data);  // colors 7 - 13
                pal_refresh(pal_normal);
            END

            IF (key(_ESC)) 
                BREAK; 
            END
        END
    END

END

Used in example: [Pal_load](), [pal_get](), [Pal_map_assign](), [Pal_refresh](), [Set_fps](), [Write]()


pal_get()

Syntax

INT pal_get ( [<INT paletteID>] , <INT first_color> , <INT num_colors> , <POINTER palette_data>)

Description

This function is used in conjuction with [Pal_set]() to load palette data that was loaded with [Pal_load]() into an array, for later use with [Pal_set](). This [palette] can also be loaded from [MAP]'s, [FNT]'s and other image formats, provided that they are 8 bit images.

Also called [colors_get](). The previous name [get_colors]() is deprecated.

Parameters


INT paletteID - The handle of the color palette loaded with [Pal_load](). This paramter is optional. INT first_color - The first color number of the palette. This doesn't necessarily have be the first color. INT num_colors - The number of colors you want to replace, wich counts from the first_color to the num_colors. See notes. POINTER palette_data - Pointer ([Offset]) to an array where the color values will be stored.


Note

The maximum number of colors cannot be bigger the 255. The num_colors starts counting from first_color, so if the first_color is 7, and num_colors is 7, the color value's 7-13 are changed. So logically, the value num_colors can only be 255 when first_color is 0. This range gives you all the colors. To be safe, the formula for the number of colors to modified is: num_colors-first_color.

I.e. num_colors: 55 - first_color: 4 = 51 colors are changed, the range from color index 4 up to color index 55.

Returns

INT : Error.


0 - Error: could not open file; corrupt or truncated file; file doesn't contain palette information. 1 - No error: [palette] was set with success.


Example

/* original bennupack example FROM: \2 Medium\fenix test\palettes\rbear8-2.prg (from bomberlink) */

/* this program demonstrates the use of the functions: pal_load(), pal_clone(), pal_get(),       */
/* pal_map_assign(), pal_set() and pal_refresh().                                                */

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_text";

GLOBAL

   // palette identifiers
   int pal_orange;
   int pal_green;
   int pal_normal;

   int status1;
   int status2;

   // identifier of the fpg archive
   int fpg_id;

   // arrays for the data of the two color palettes.
   byte pal_orange_data[255]; 
   byte pal_green_data[255];  

   int map_count;

PROCESS main();

BEGIN

    set_fps(10,0);
    set_mode(320,200,16);  // we use a 16 bit color mode

    // load two color palettes and duplicate one
    pal_green=pal_load("rbear8-green.pal");
    pal_orange=pal_load("rbear8-orange.pal");

    // pal_clone (int pal_id);
    pal_normal=pal_clone(pal_orange); // duplicate palette, i.e. make a copy of it.

    // load the fpg file
    fpg_id=fpg_load("rbear8.fpg");

    write_int(0,10,10,0,&fps);
    write(0,10,20,0,"F1/F2 - change palette");

    x = 160;
    y = 120;

    // pal_get (int pal_id, int start_color, int num_colors, pointer pal_data);
    pal_get(pal_green,7,7,&pal_green_data);    // get colors 7 - 13 and store them in the array
    pal_get(pal_orange,7,7,&pal_orange_data);        

    FROM map_count=1 TO 102; // there are 102 frames in the animation

        // pal_map_assign (int fileid, int graph, int pal_id);
        pal_map_assign(fpg_id,map_count,pal_normal); // assign the "normal (original source)" color 
                                                     // palette that we duplicated earlier.
    END

    WHILE (NOT key(_ESC))

        FROM graph=1 TO 13;

            FRAME;

            IF (key(_F1))
                say("switched to green palette");

                // pal_set (int pal_id, int start_color, int num_colors, pointer pal_data);
                status1=pal_set(pal_normal,7,7,&pal_green_data); // change colors 7 - 13 in the "normal" 
                                                                 // palette, by using the values from the
                                                                 // "green" color palette.

                say("pal_set_status: "+status1);                                                                 

                // pal_refresh (int pal_id);
                status2=pal_refresh(pal_normal); // apply the modified color palette to the graphics.
                                                 // this function is required to make the change visible.  

                say("pal_refresh_status: "+status2);                                                   

                // conclusion: the difference between pal_map_assign() and pal_set() is that pal_map_assign()
                // works immediately, and that pal_set() requires the palette to be refreshed to make the 
                // change visible.                
            END

            IF (key(_F2))
                say("switched to orange palette");
                pal_set(pal_normal,7,7,&pal_orange_data);  // colors 7 - 13
                pal_refresh(pal_normal);
            END

            IF (key(_ESC)) 
                BREAK; 
            END
        END
    END

END

Used in example: [Pal_load](), [pal_clone](), [Pal_map_assign](), [Pal_refresh](), [Set_fps](), [Write]()


pal_load()

Syntax

INT pal_load ( <STRING filename>, [ <POINTER id>] )

Description

Loads a color palette from a file.

The current [palette] is switched to the loaded one. Note that one can load a palette from an 8bit [FPG] or [MAP] file (the remaining graphic data will not be loaded) or a [PAL] file.

The previous name [load_pal]() is deprecated.

Parameters


STRING filename - The filename of the file that you wish to load the [palette] from (including extension and possible path). POINTER id - Optional parameter, for loading a palette in the background.


Returns

INT : [graphID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The graphID of the newly created palette.


the following applies for versions prior rc282:

INT : Error.


-1 - Error: could not open file; corrupt or truncated file; file doesn't contain palette information. 0 - Error: could not obtain filename; some [FPL] error. 1 - No error: [palette] was loaded with success.


Example

Program example;
Begin

    load_pal("example.pal");

    Loop
        frame;
    End

End

Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_pal("archivo_gordo.pal", &idpal);
      while(idpal==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idpal==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

pal_map_assign()

Syntax

INT pal_map_assign ( <INT fileID> , <INT graphID>, <INT paletteID> )

Description

Changes the color palette of an 8 bit (256 color) graphic, with the palette that is loaded with [Pal_load](). This [palette] can also be loaded from [MAP]'s, [FNT]'s and other image formats, provided that they are 8 bit images. Unlike [Pal_set](), the change is immediately visible.

Parameters


INT fileID - The fileID of the graphic(s), i.e. 0 for the systemfile, or the id code of an [FPG] archive. INT graphID - The graphic (or mapcode) to modify. INT paletteID - The handle of the color palette loaded with [Pal_load]().


Returns

INT : Error.


0 - Error: could not open file; corrupt or truncated file; file doesn't contain palette information. 1 - No error: [palette] was loaded with success.


Example

/* Original example from bennupack: 2 Medium\fenix test\palettes\rbear8_1.prg (from bomberlink) */

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_text";

GLOBAL
   int pal_orange;  // palette 1
   int pal_green;   // palette 2

   int map_count;

   int fpg_id;

PROCESS main();

BEGIN

    set_fps(10,0);
    set_mode(320,200,16);

    // load the fpg archive
    fpg_id=fpg_load("rbear8.fpg");

    // load the two palettes
    pal_orange=pal_load("rbear8-orange.pal");
    pal_green=pal_load("rbear8-green.pal");

    write_int(0,10,10,0,&fps);
    write(0,10,20,0,"F1/F2 - change palette");

    x=160;
    y=120;

    WHILE (NOT key(_ESC))

        FROM graph=1 TO 3;

          FRAME;

           IF (key(_F1))
              FROM map_count=1 TO 102;
                 say("changing colors: "+map_count);
                 pal_map_assign(fpg_id,map_count,pal_green);  // apply palette 1
              END
           END

           IF (key(_F2))
              FROM map_count=1 TO 102;
                 say("changing colors: "+map_count);
                 pal_map_assign(fpg_id,map_count,pal_orange); // apply palette 2
              END
           END

           IF (key(_ESC)) 
              BREAK; 
           END
        END
    END

END

Used in example: [Pal_load](), [Say](), [Set_mode](), [Write_int]()


pal_map_getid()

Syntax

INT pal_map_getid ( <INT fileID> , <INT graphID> )

Description

This function returns the identification code of the palette of a specific graphic.

Parameters


INT fileID - The handle of the file. INT graphID - The handle of the graph.


Returns

INT : Error/status.


0 - Error: could not open file; corrupt or truncated file; file doesn't contain palette information. id - The identifier of the [palette].


Example

/* original bennupack example FROM: \2 Medium\fenix test\palettes\rbear8-5.prg (from bomberlink) */

/* this program demonstrates the use of the functions: pal_load(), pal_map_get_id()              */
/* pal_map_assign(), pal_set() and pal_refresh().                                                */

/* In this example pal_get() is not used but the table is filled with data by forehand.          */

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_text";

GLOBAL

   int pal_normal; // identifier of the palette

   int fpg_id;     // identifier of the fpg file

   // the arrays with data (pre-filled)   
   byte orange_palette_data[21] =
                                80,0,0,
                               110,0,0,
                               140,0,0,
                               170,0,0,
                               190,0,0,
                               220,0,0,
                               250,0,0;
   byte green_palette_data[21] =
                               0, 80,0,
                               0,110,0,
                               0,140,0,
                               0,170,0,
                               0,190,0,
                               0,220,0,
                               0,250,0;

   int count;

PROCESS main();   

BEGIN

    set_fps(10,0);
    set_mode(320,200,16);

    // load the fpg
    fpg_id=fpg_load("rbear8.fpg");

    write_int(0,10,10,0,&fps);
    write(0,10,20,0,"F1/F2 - change palette");

    x=160;
    y=120;

    pal_normal=pal_map_getid(fpg_id,1); // file,graph   
    say("pal_normal: "+pal_normal);

    WHILE (NOT key(_ESC))

        FROM graph=1 TO 13;

            FRAME;

            IF (key(_F1))
                pal_set(pal_normal,7,7,&green_palette_data);    // colors 7 - 13
                pal_refresh(pal_normal);
            END

            IF (key(_F2))
                pal_set(pal_normal,7,7,&orange_palette_data);  // colors 7 - 13
                pal_refresh(pal_normal);
            END

            IF (key(_ESC)) 
               BREAK; 
            END
        END
    END

END

Used in example: , [Pal_set](), [Pal_map_assign](), [Pal_refresh](), [Set_fps](), [Write]()

See also

[Pal_set]()


pal_map_remove()

Syntax

INT pal_map_remove ( <INT fileID> , <INT graphID> )

Description

Removes the color palette that assigned with [Pal_map_assign](). It is basically an undo function for color palette changes.

Parameters


INT fileID - The fileID of the graphic(s), i.e. 0 for the systemfile, or the id code of an [FPG] archive. INT graphID - The graphic (or mapcode).


Returns

INT : Status/Error.


0 - Error: could not open file; corrupt or truncated file; file doesn't contain palette information. 1 - No error: [palette] was reverted with success.


Example

/* Original example from bennupack: 2 Medium\fenix test\palettes\rbear8_1.prg (from bomberlink) */

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_text";

GLOBAL
   int pal_orange;  // palette 1
   int pal_green;   // palette 2

   int map_count;

   int fpg_id;

   int status;

PROCESS main();

BEGIN

    set_fps(10,0);
    set_mode(320,200,16);  // we use a 16 bit colormode

    // load the fpg archive
    fpg_id=fpg_load("rbear8.fpg");

    // load the two palettes
    pal_orange=pal_load("rbear8-orange.pal");
    pal_green=pal_load("rbear8-green.pal");

    write_int(0,10,10,0,&fps);
    write(0,10,20,0,"F1/F2 - change palette");
    write(0,10,30,0,"F3 - to undo palette changes");

    x=160;
    y=120;

    WHILE (NOT key(_ESC))

        FROM graph=1 TO 3; // cycle through 3 graphics

          FRAME;

           IF (key(_F1))
              FROM map_count=1 TO 102; // there are 102 frames in the animation.
                 say("changing colors: "+map_count);
                 pal_map_assign(fpg_id,map_count,pal_green);  // apply palette 1
              END
           END

           IF (key(_F2))
              FROM map_count=1 TO 102;
                 say("changing colors: "+map_count);
                 pal_map_assign(fpg_id,map_count,pal_orange); // apply palette 2
              END
           END

           IF (key(_F3))
              FROM map_count=1 TO 102;
                 say("changing colors: "+map_count);
                 status=pal_map_remove(fpg_id,map_count); 
                 say("status: "+status);
              END
           END

           IF (key(_ESC)) 
              BREAK; 
           END
        END
    END

END

Used in example: [Say](), [Pal_load](), [Pal_map_assign](), [Key](), [Write_int]()


pal_new()

Syntax

INT pal_new ()

Description

This function creates a new palette in memory and returns the handle, for later use by other [palette] functions such as [Pal_save](), [Pal_set], etc. When you're done, you can free the memory with [Pal_unload]().

The previous name [new_pal()] is deprecated.

Returns

INT : Status.


id - The identification code of the memory area for the newly created palette.



pal_refresh()

Syntax

INT pal_refresh ( [<INT paletteID>] )

Description

Refreshes the color palette after a call of [Pal_set](), to the make color change visible.

Parameters


INT paletteID - The handle of the color palette loaded with [Pal_load](). The parameter is optional.


Returns

INT : Status.


1 - The status.


Example

/* original bennupack example FROM: \2 Medium\fenix test\palettes\rbear8-2.prg (from bomberlink) */

/* this program demonstrates the use of the functions: pal_load(), pal_clone(), pal_get(),       */
/* pal_map_assign(), pal_set() and pal_refresh().                                                */

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_text";

GLOBAL

   // palette identifiers
   int pal_orange;
   int pal_green;
   int pal_normal;

   int status1;
   int status2;

   // identifier of the fpg archive
   int fpg_id;

   // arrays for the data of the two color palettes.
   byte pal_orange_data[255]; 
   byte pal_green_data[255];  

   int map_count;

PROCESS main();

BEGIN

    set_fps(10,0);
    set_mode(320,200,16);  // we use a 16 bit color mode

    // load two color palettes and duplicate one
    pal_green=pal_load("rbear8-green.pal");
    pal_orange=pal_load("rbear8-orange.pal");

    // pal_clone (int pal_id);
    pal_normal=pal_clone(pal_orange); // duplicate palette, i.e. make a copy of it.

    // load the fpg file
    fpg_id=fpg_load("rbear8.fpg");

    write_int(0,10,10,0,&fps);
    write(0,10,20,0,"F1/F2 - change palette");

    x = 160;
    y = 120;

    // pal_get (int pal_id, int start_color, int num_colors, pointer pal_data);
    pal_get(pal_green,7,7,&pal_green_data);    // get colors 7 - 13 and store them in the array
    pal_get(pal_orange,7,7,&pal_orange_data);        

    FROM map_count=1 TO 102; // there are 102 frames in the animation

        // pal_map_assign (int fileid, int graph, int pal_id);
        pal_map_assign(fpg_id,map_count,pal_normal); // assign the "normal (original source)" color 
                                                     // palette that we duplicated earlier.
    END

    WHILE (NOT key(_ESC))

        FROM graph=1 TO 13;

            FRAME;

            IF (key(_F1))
                say("switched to green palette");

                // pal_set (int pal_id, int start_color, int num_colors, pointer pal_data);
                status1=pal_set(pal_normal,7,7,&pal_green_data); // change colors 7 - 13 in the "normal" 
                                                                 // palette, by using the values from the
                                                                 // "green" color palette.

                say("pal_set_status: "+status1);                                                                 

                // pal_refresh (int pal_id);
                status2=pal_refresh(pal_normal); // apply the modified color palette to the graphics.
                                                 // this function is required to make the change visible.  

                say("pal_refresh_status: "+status2);                                                   

                // conclusion: the difference between pal_map_assign() and pal_set() is that pal_map_assign()
                // works immediately, and that pal_set() requires the palette to be refreshed to make the 
                // change visible.                
            END

            IF (key(_F2))
                say("switched to orange palette");
                pal_set(pal_normal,7,7,&pal_orange_data);  // colors 7 - 13
                pal_refresh(pal_normal);
            END

            IF (key(_ESC)) 
                BREAK; 
            END
        END
    END

END

Used in example: [Pal_load](), [pal_get](), [Pal_map_assign](), [Pal_clone](), [Set_fps](), [Write]()


pal_save()

Syntax

INT pal_save ( <STRING filename>, [<INT paletteID>] )

Description

This function saves a [palette] to a file on disk in the [PAL] format. When the second parameter is omitted, the system palette is saved, otherwise the palette data indicate with the paletteID. Concluding from this, is that it's possible to load multiple palettes in bennu and assign an unique identifier to them and save them to a file later.

The previous name [save_pal]() is deprecated.

Parameters


STRING filename - The filename of the new palette file. INT paletteID - The handle of the [palette](). This parameter is optional.


Returns

INT : Status.


id - The file handle.



pal_set()

Syntax

INT pal_set ( [<INT paletteID>] , <INT first_color> , <INT num_colors> , <POINTER palette_data>)

Description

Changes the color palette of an 8 bit (256 color) graphic, with the palette that is loaded with [Pal_load](). This [palette] can also be loaded from [MAP]'s, [FNT]'s and other image formats, provided that they are 8 bit images. Unlike [Pal_map_assign](), the change is not immediately visible, and the function [Pal_refresh]() has to be called afterwards to make the change visible. The difference however, is that it not replaces the whole palette, but allows a specified number of colors to be changed, so it's a bit more flexible.

Also called [colors_set](). The previous name [set_colors]() is deprecated.

Parameters


INT paletteID - The handle of the color palette loaded with [Pal_load](). This paramter is optional. INT first_color - The first color number of the palette. This doesn't necessarily have be the first color. INT num_colors - The number of colors you want to replace, wich counts from the first_color to the num_colors. See notes. POINTER palette_data - Pointer ([Offset]().


Note

The maximum number of colors cannot be bigger the 255. The num_colors starts counting from first_color, so if the first_color is 7, and num_colors is 7, the color value's 7-13 are changed. So logically, the value num_colors can only be 255 when first_color is 0. This range gives you all the colors. To be safe, the formula for the number of colors to modified is: num_colors-first_color.

I.e. num_colors: 55 - first_color: 4 = 51 colors are changed, the range from color index 4 up to color index 55.

Returns

INT : Error.


0 - Error: could not open file; corrupt or truncated file; file doesn't contain palette information. 1 - No error: [palette] was set with success.


Example

/* original bennupack example FROM: \2 Medium\fenix test\palettes\rbear8-2.prg (from bomberlink) */

/* this program demonstrates the use of the functions: pal_load(), pal_clone(), pal_get(),       */
/* pal_map_assign(), pal_set() and pal_refresh().                                                */

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_text";

GLOBAL

   // palette identifiers
   int pal_orange;
   int pal_green;
   int pal_normal;

   int status1;
   int status2;

   // identifier of the fpg archive
   int fpg_id;

   // arrays for the data of the two color palettes.
   byte pal_orange_data[255]; 
   byte pal_green_data[255];  

   int map_count;

PROCESS main();

BEGIN

    set_fps(10,0);
    set_mode(320,200,16);  // we use a 16 bit color mode

    // load two color palettes and duplicate one
    pal_green=pal_load("rbear8-green.pal");
    pal_orange=pal_load("rbear8-orange.pal");

    // pal_clone (int pal_id);
    pal_normal=pal_clone(pal_orange); // duplicate palette, i.e. make a copy of it.

    // load the fpg file
    fpg_id=fpg_load("rbear8.fpg");

    write_int(0,10,10,0,&fps);
    write(0,10,20,0,"F1/F2 - change palette");

    x = 160;
    y = 120;

    // pal_get (int pal_id, int start_color, int num_colors, pointer pal_data);
    pal_get(pal_green,7,7,&pal_green_data);    // get colors 7 - 13 and store them in the array
    pal_get(pal_orange,7,7,&pal_orange_data);        

    FROM map_count=1 TO 102; // there are 102 frames in the animation

        // pal_map_assign (int fileid, int graph, int pal_id);
        pal_map_assign(fpg_id,map_count,pal_normal); // assign the "normal (original source)" color 
                                                     // palette that we duplicated earlier.
    END

    WHILE (NOT key(_ESC))

        FROM graph=1 TO 13;

            FRAME;

            IF (key(_F1))
                say("switched to green palette");

                // pal_set (int pal_id, int start_color, int num_colors, pointer pal_data);
                status1=pal_set(pal_normal,7,7,&pal_green_data); // change colors 7 - 13 in the "normal" 
                                                                 // palette, by using the values from the
                                                                 // "green" color palette.

                say("pal_set_status: "+status1);                                                                 

                // pal_refresh (int pal_id);
                status2=pal_refresh(pal_normal); // apply the modified color palette to the graphics.
                                                 // this function is required to make the change visible.  

                say("pal_refresh_status: "+status2);                                                   

                // conclusion: the difference between pal_map_assign() and pal_set() is that pal_map_assign()
                // works immediately, and that pal_set() requires the palette to be refreshed to make the 
                // change visible.                
            END

            IF (key(_F2))
                say("switched to orange palette");
                pal_set(pal_normal,7,7,&pal_orange_data);  // colors 7 - 13
                pal_refresh(pal_normal);
            END

            IF (key(_ESC)) 
                BREAK; 
            END
        END
    END

END

Used in example: [Pal_load](), [pal_clone](), [Pal_map_assign](), [Pal_refresh](), [Set_fps](), [Write]()


pal_unload()

Syntax

INT pal_unload ( <INT paletteID> )

Description

This function unloads the palette, thus freeing the memory it ouccupies.

Also called [pal_del](). The previous name [unload_pal]() is deprecated.

Parameters


INT paletteID - The handle of the [palette]().


Returns

INT : Status.


1 - Operation completed.



palette_convert()

Syntax

INT palette_convert ( <INT fileID> , <INT graphID> , <POINTER palette_data> )

Description

This function changes the colormap of an image, but does not change the color index values it self. That is, that the individual pixels will keep their color indexes, but the r,g,b values in the palette are modified. This function requires an [Array] of maximum 255 bytes (or integers), to store the palette values. The array is accessed with the [Offset] operator.

The previous name [Convert_palette]() is deprecated.

Parameters


INT fileID - The handle of the file containing the graphics. INT graphID - The handle of the graphic. POINTER palette_data - Pointer to the [Array] operator.


Returns

INT : Status.


1 - Success.


Example

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_screen";
IMPORT "mod_text";

GLOBAL

  int map_id;
  int clonemap_id;

  int palette_table[255];
  int color;

  int status;

PROCESS main();  

BEGIN

  set_mode(320,240,16);

  map_id=load_map("MAP.MAP");

  clonemap_id=map_clone(0,map_id); // create a copy of the map

  write(0,80,30,4,"Original image:");
  write(0,240,30,4,"Converted image (clone):");
  write(0,160,140,4,"Spacebar: Change the palette of the clone...");
  write(0,160,190,4,"Press ESC to quit...");

  // palette color 0 (the transparant color) will be not changed, that's why the 
  // count starts at 1. 
  // values that go beyond 255 will be cut off by the MOD (%). So, 256, becomes 0, 
  // 257 becomes 2 etc. The fist 16 colors will stay untouched.
  FROM color=1 TO 255; 
     palette_table[color]=(color+16) MOD 255; 
     say("palette_table["+color+"]");
  END

  xput(0,map_id,80,70,0,25,0,0);

  x=240; 
  y=70; 
  graph=clonemap_id; 
  size=25;

  REPEAT

     IF (key(_space)) 
        // let's do the conversion
        status=palette_convert(0,clonemap_id,&palette_table); 
        say("status: "+status);
     END

     FRAME;
  UNTIL(key(_esc))

END

Used in example: [Say](), [Write](), [Xput]()


palette_roll()

Syntax

INT palette_roll ( <INT start_color> , <INT end_color> , <INT increment> )

Description

Cycles the colors in the [palette] by rotating them. This function shifts colors between the range specified by the start color and the end color, at a given increment. This can be used to create a very old school waterfall animation effect. This technique is called color cycling. It is a very memory efficient way of doing these kinds of animations, since only one bitmap is used and the effect is achieved by cycling through a specific range of colors. Here's a nice (web based) example of this technique in action.

To use this function, you have to create graphics that use a range of consecutive colors of the original palette, in a perpetual cycle (i.e., colors ranging from 0 to 15, painting something with the colors 0, 1, 2, 3, ... , 14, 15, 0, 1, 2, ...).

Also, make sure that these colors are not used by other graphics that are going to appear on the screen at the same time, if you do not want to apply these effects on them, or they'll look funny.

One important thing, this function only works in 8 bit mode.

The previous name [roll_palette]() is deprecated.

Parameters


INT start_color - The start color of the range (0-255). INT end_colors - The last color of the range (0-255). INT increment - The cycle speed (-1, 0, 1, etc).


Notes

An increment of 0 is pointless, because that will stop the cycle. The higher the number, the faster the cycle goes. Negative values will cycle in the opposite direction.

Returns

INT : Status.


1 - Success.


Example

IMPORT "mod_debug";
IMPORT "mod_say";
IMPORT "mod_map";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_screen";
IMPORT "mod_text";

GLOBAL
   int map;
   int fnt;

   byte color_increment=1;
   byte initial_color;
   byte num_colors=10;

PROCESS main();

BEGIN

   set_fps(50,0);
   set_mode(640,480,8);     // for palette_roll to work is the 8 bit mode required!

   map=load_map("MAP.MAP");

   put_screen(0,map);

   write(0,10,10,3,"Rolling Palette demo, +/-: change number of colors, 0, 1, 2: change increment, Press ESC to quit...");

   REPEAT

      // changes the amount of colors      
      IF (key(_plus) AND num_colors<255)
         FRAME;
         num_colors+=1;
      END

      IF (key(_minus) AND num_colors>1)
         FRAME;
         num_colors-=1;
      END

      // change the speed 
      IF (key(_0))
         FRAME;
         color_increment=0;
      END

      IF (key(_1))
         FRAME;
         color_increment=1;
      END

      IF (key(_2))
         FRAME;
         color_increment=-1;
      END

      // roll the palette
      palette_roll(initial_color,num_colors,color_increment);      
      say("initial color: "+initial_color+" num color: "+num_colors+" increment: "+color_increment);

      FRAME;
   UNTIL(key(_esc))

END

Used in example: [Say](), [Write]()


rgb()

Syntax

DWORD rgb ( <BYTE red> , <BYTE green> , <BYTE blue> , [<INT depth>] )

Description

Finds the single [color] in the current color mode closest to the combined red, green, and blue values specified. In 32bit mode, the alpha is set to 255.

Equal to [[rgba]](''red'',''green'',''blue'',255)

Parameters


BYTE red - Level of red in the desired color from 0 to 255. BYTE green - Level of green in the desired color from 0 to 255. BYTE blue - Level of blue in the desired color from 0 to 255. INT depth - Depth (optional paramter that may be omitted, only in 16 and 32 bit mode). When this parameter is used, the function returns the correct color code for the indicated depth.


Returns

DWORD : Returns the best matched color code.

Notes

Different color depths have different color codes, this is why rgb() is useful: it returns the appropriate code, based on the current color depth. When in 8bit mode, this code is 0..255 and when in 16bit mode 0..65535. In 32bit mode the code is 0xRRGGBBAA, two letters meaning one byte.

Using this function in different color depths can be tricky. This is because rgb() will return a different color code under different color depths. For example, when at 8bit, we do:

my_color = rgb(100,100,100);

my_color will most likely have the value 6 at this time. Suppose we change the color depth to 16bit now, using [set_mode](). Now, my_color holds a totally different color than before, as 6 is nowhere near rgb(100,100,100) in 16bit mode. To counter this effect, my_color needs to be reinitialized:

my_color = rgb(100,100,100);

The same code, but rgb() now returns the proper code, as it always returns the code belonging to the current color depth. my_color will now be about 25388.

Example

import "mod_map"
import "mod_text"
import "mod_key"
import "mod_wm"

Process Main()
Private
    byte red=0;
    byte green=255;
    byte blue=0;
Begin

    set_text_color(rgb(red,green,blue)); // rgb finds the color closest to pure green and
                                         // passes it to set_text_color

    write(0,1,1,0,"Green text for everybody!"); //this text will be green

    Repeat
        frame;
    Until(key(_ESC)||exit_status)

End

Used in example: [set_text_color](), [rgb](), [key]


rgb_get()

Syntax

INT rgb_get ( <INT pixel_color > , <POINTER red> , <POINTER green> , <POINTER blue> , [<INT depth>] )

Description

Get access to the memory sections of the color components, these can be accessed with the [Offset] operator.

The previous [get_rgb]() is deprecated.

Parameters


INT pixel_color - The color value of a pixel . POINTER red - Pointer to the level of red in the desired color from 0 to 255. POINTER green - Pointer to the level of green in the desired color from 0 to 255. POINTER blue - Pointer to the level of blue in the desired color from 0 to 255. INT depth - Depth (optional paramter that may be omitted, only in 16 and 32 bit mode). When this parameter is used, the function returns the correct color code for the indicated depth.


Returns

1 : This function always returns a 1.

Notes

The color value's have to be obtained with the [Offset] operator, and the pixel color value can be obtained with [Map_get_pixel]().

Example

IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_key";
IMPORT "mod_map";
IMPORT "mod_video";
IMPORT "mod_wm";
IMPORT "mod_draw";
IMPORT "mod_screen";
IMPORT "mod_mem";
IMPORT "mod_text";

GLOBAL

   int map_id;    // id code of the map to load

   int status;    // status for debugging

   // color components
   int my_r;      
   int my_g;
   int my_b; 

PROCESS main();

BEGIN

   set_mode(320,200,32);

   // load the map
   map_id=load_map("3COCHE.MAP");

   // first, we're going to check the r,g,b values of 5 pixels, with the optional
   // depth parameter.
   status=get_rgb(map_get_pixel(0,map_id,0,0), &my_r, &my_g, &my_b ,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b);  
   say("status: "+status);

   status=get_rgb(map_get_pixel(0,map_id,4,0), &my_r, &my_g, &my_b ,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b);  
   say("status: "+status);

   status=get_rgb(map_get_pixel(0,map_id,50,1), &my_r, &my_g, &my_b ,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b);  
   say("status: "+status);

   status=get_rgb(map_get_pixel(0,map_id,13,24), &my_r, &my_g, &my_b, 32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b);  
   say("status: "+status);

   status=get_rgb(map_get_pixel(0,map_id,84,40), &my_r, &my_g, &my_b, 32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b);  
   say("status: "+status);

   // second, we use the simpler way, that is valid for a bit maps
   say("");
   say("8 bit color codes");
   say(map_get_pixel(0,map_id,0,0));
   say(map_get_pixel(0,map_id,4,0));
   say(map_get_pixel(0,map_id,50,1));
   say(map_get_pixel(0,map_id,13,24));
   say(map_get_pixel(0,map_id,84,40));

   LOOP
      IF (key(_esc))
         BREAK;
      END

      FRAME;
   END
END

See also

The articles about the functions, [Rgb]() and [Rgba]() for more information, since this function is related to some extend.


rgba()

Syntax

DWORD rgba ( <BYTE red> , <BYTE green> , <BYTE blue>, <BYTE alpha> , [<INT depth>] )

Description

Finds the single [color] in the current color mode closest to the combined red, green, blue and alpha values specified. This function is useful in 32 bpp modes.

Parameters


BYTE red - Level of red in the desired color from 0 to 255. BYTE green - Level of green in the desired color from 0 to 255. BYTE blue - Level of blue in the desired color from 0 to 255. BYTE alpha - Level of alpha in the desired color from 0 to 255, 0 being completely transparent and 255 completely opaque. INT depth - Optional parameter, wich may be omitted. Only usefull in 16 and 32 bit modes, ensures that the function returns a colorcode that is valid for the specified mode.


Returns

DWORD : Returns the best matched color code.

Notes

Different color depths have different color codes, this is why rgba() is useful: it returns the appropriate code, based on the current color depth. When in 8bit mode, this code is 0..255 and when in 16bit mode 0..65535. In 32bit mode the code is 0xRRGGBBAA, two letters meaning one byte.

Using this function in different color depths can be tricky. This is because rgba() will return a different color code under different color depths. For example, when at 8bit, we do:

my_color = rgba(100,100,100,255);

my_color will most likely have the value 6 at this time. Suppose we change the color depth to 16bit now, using [set_mode](). Now, my_color holds a totally different color value than before, as 6 is nowhere near rgba(100,100,100,255) in 16bit mode. To counter this effect, my_color needs to be reinitialized:

my_color = rgba(100,100,100,255);

The same code, but rgba() now returns the proper code, as it always returns the code belonging to the current color depth. my_color will now be about 25388.

Example

import "mod_text"
import "mod_map"
import "mod_key"
import "mod_video"
import "mod_wm"

Const
    SCREEN_WIDTH  = 320;
    SCREEN_HEIGHT = 200;
    SCREEN_DEPTH  = 16;
End

Process Main()
Private
    int r=0;
    int g=255;
    int b=0;
    int a=0;
    int da=10;
Begin

    set_mode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_DEPTH);

    graph = map_new(100,100,SCREEN_DEPTH);
    map_clear(0,graph,rgba(r,g,b,a));

    x = y = 100;

    Repeat
        a += da;
        if(a<0)
            da = -da;
            a = 0;
        elseif(a>255)
            da = -da;
            a = 255;
        end
        map_clear(0,graph,rgba(r,g,b,a));
        frame;
    Until(key(_ESC)||exit_status)

End

Used in example: [set_mode](), [map_new](), [key](), [graph]


rgba_get()

Syntax

DWORD rgba_get ( <INT pixel_color > , <POINTER red> , <POINTER green> , <POINTER blue> , <POINTER alpha> , [<INT depth>] )

Description

Get access to the memory sections of the color components, these can be accessed with the [Offset] operator.

The previous name [Get_rgba]() is deprecated.

Parameters


INT pixel_color - The color value of a pixel . POINTER red - Pointer to the level of red in the desired color from 0 to 255. POINTER green - Pointer to the level of green in the desired color from 0 to 255. POINTER blue - Pointer to the level of blue in the desired color from 0 to 255. POINTER alpha - Pointer to the alpha channel in the from 0 to 255. INT depth - Depth (optional paramter that may be omitted, only in 16 and 32 bit mode). When this parameter is used, the function returns the correct color code for the indicated depth.


Returns

1 : This function always returns a 1.

Notes

The color value's have to be obtained with the [Offset] operator, and the pixel color value can be obtained with [Map_get_pixel]().

Example

IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_key";
IMPORT "mod_map";
IMPORT "mod_video";
IMPORT "mod_wm";
IMPORT "mod_draw";
IMPORT "mod_screen";
IMPORT "mod_mem";
IMPORT "mod_text";

GLOBAL

   int map_id;    // id code of the map to load

   int status;    // status for debugging

   // color components
   int my_r;      
   int my_g;
   int my_b; 
   int my_a;

PROCESS main();

BEGIN

   set_mode(320,200,32);

   // load the map
   map_id=load_map("3COCHE.MAP");

   // first, we're going to check the r,g,b,a values of 5 pixels, with the optional
   // depth parameter.
   status=get_rgba(map_get_pixel(0,map_id,0,0), &my_r, &my_g, &my_b, &my_a,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b+" my_a: "+my_a);  
   say("status: "+status);

   status=get_rgba(map_get_pixel(0,map_id,4,0), &my_r, &my_g, &my_b, &my_a,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b+" my_a: "+my_a);  
   say("status: "+status);

   status=get_rgba(map_get_pixel(0,map_id,50,1), &my_r, &my_g, &my_b, &my_a,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b+" my_a: "+my_a);  
   say("status: "+status);

   status=get_rgba(map_get_pixel(0,map_id,13,24), &my_r, &my_g, &my_b, &my_a,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b+" my_a: "+my_a);  
   say("status: "+status);

   status=get_rgba(map_get_pixel(0,map_id,84,40), &my_r, &my_g, &my_b, &my_a,32);

   say("my_r: "+my_r+" my_g: "+my_g+" my_b: "+my_b+" my_a: "+my_a);  
   say("status: "+status);

   // second, we use the simpler way, that is valid for a bit maps
   say("");
   say("8 bit color codes");
   say(map_get_pixel(0,map_id,0,0));
   say(map_get_pixel(0,map_id,4,0));
   say(map_get_pixel(0,map_id,50,1));
   say(map_get_pixel(0,map_id,13,24));
   say(map_get_pixel(0,map_id,84,40));

   LOOP
      IF (key(_esc))
         BREAK;
      END

      FRAME;
   END
END

See also

The articles about the functions, [Rgb]() and [Rgba]() for more information, since this function is related to some extend.



Pathfind

path_find()

Syntax

'''INT ''' path_find ( <INT fileID> , <INT graphID> , <INT start_x> , <INT start_y> , <INT dest_x> , <INT dest_y> , <INT options>)

Description

The pathfinding function is based on the A* algorithm with a heuristic value. It uses a logic map with a maze, a start position and an end position. The logic map is an 8 bit image (with palette), preferably with only 2 colors, black and white, wich indicates the walls and the paths.

Here's the bennu source code: mod_path.c, wikipedia page about pathfinding.

Parameters


INT fileID - The fpg archive wich contains the map, may be 0 when the systemfile is used. INT graphID - The bitmap (either mapcode from fpg or loaded with [Map_load]() into the systemfile) with the maze, see notes*. INT start_x - The x coordniate of the start position. INT start_y - The y coordniate of the start position. INT dest_x - The x coordinate of the destination position. INT dest_y - The y coordinate of the destination position. INT options - The kind of pathfinding, [PF_NODIAG]


Returns

INT : Status.


0 - The path has not been found yet. 1 - The path has been found.


Example

Look at this tutorial: .

Notes

  • This function requires the use of 8 bit indexed (256 color) bitmaps for the path map, because of the logic behind it's design. The philosophy behind this is similair to a hardness (logic) map. It is perfectly possible to combine 8 bit images in 16 or 32 bit colormodes, provided that all 8 bit maps share the same colorpalette.

path_getxy()

Syntax

'''INT ''' path_getxy ( <POINTER x>, <POINTER y> )

Description

This function gets a node and returns a 1 when there's still a point left, or a 0 when there are no more points. This function requires a two dimensional [Array] to work on. The arguments should accessed with the [Offset] operator. The function is typically used inside a loop. The pathfinding in bennu is based on the A* algorithm. It uses a logic map with a maze, a start position and an end position.

Here's the bennu source code: mod_path.c, wikipedia page about pathfinding.

Parameters


POINTER x - Offset of the array with the x values. POINTER y - Offset of the array with the y values.


Returns

INT : Status.


0 - There are no more coordinate points (nodes) in the list. 1 - There are still coordinate points (nodes) in the list.


Example

Look at this tutorial: .


path_wall()

Syntax

'''INT ''' path_wall ( <INT wall_color> )

Description

This function changes the wall color. Normally, [Path_find]() only uses two colors, i.e. black and white. By using this function before making a call to Path_find, Path_find will use the color indiated by this function instead. The color may not be a zero, bcause that is usually black. ''For more information, see the [http://bennugd.svn.sourceforge.net/viewvc/bennugd/modules/mod\_path/mod\_path.c?revision=277&view=markup bennu mod_path.c sourcecode]. ''

Parameters


INT Color - The palette color.


Returns

INT : - The color value.



Process interaction

advance()

Definition

INT advance ( <INT distance> )

Moves the [calling] [process] forward by distance units in the direction of the process' [angle].

This function is influenced by the [local variables] and [resolution].

Parameters


INT distance - Distance to advance in units.


Returns


INT : Returns [true] if failed.

Example

import "mod_grproc"
import "mod_map"
import "mod_wm" // for exit_status
import "mod_key" // for key()
import "mod_proc"

Process Main()
Private
    int my_proc;
Begin

    proc(); //create a new process
    proc2(); //create a new process

    Repeat
        frame;
    Until(key(_ESC) || exit_status)

OnExit

    signal(my_proc,S_KILL);

End

Process proc()
Begin

    // Create a cyan square and assign it to 'graph'
    graph = map_new(100,100,8);
    map_clear(0,graph,rgb(0,255,255));

    // Set starting position
    x = 50;
    y = 50;

    // This loop makes this process advance 3 pixels every frame
    Loop
        advance(3); // advance 3 pixels
        frame;
    End

End

Process proc2()
Begin

    // Set resolution to 100
    resolution = 100;

    // Create a cyan square and assign it to 'graph'
    graph = map_new(100,100,8);
    map_clear(0,graph,rgb(0,255,255));

    // Set starting position
    x = 50*resolution;
    y = 150*resolution;

    // This loop makes this process advance 3/100 pixels every frame
    Loop
        advance(3); // advance 3/100 pixels
        frame;
    End

OnExit

    map_unload(0,graph);

End

Used in example: [key](), [map_new](), [rgb](), [map_unload](), [exit_status], [x], [resolution]


collision()

Definition

INT collision ( <INT processID|processTypeID> )

Checks if a [process] collided with the process calling Collision().

When a [processTypeID] is specified, there could be multiple fitting collisions. In this case, collision() returns a [processID] on each subsequent call, until it returns 0. This can be reset by use of the [frame]; statement, and in such case, frame(0); can be handy.

Parameters


INT processID processTypeID - The ProcessID of the process or the ProcessTypeID of the type of processes to be checked.

Returns

INT : The ID of the collided process.


0 - No collision >0 - The processID of the process colliding with the current process


Example

Process SpaceShip( int file , int graph , int x , int y , int angle , int maxspeed , int maxturnspeed )
Private
    int speed;
    int collisionID;
    string text;
Begin
    write_string(0,0,0,0,&text);
    Loop
        // Handle movement
        speed+=key(_up)*(speed<maxspeed)-key(_down)*(speed>-maxspeed);
        angle+=(key(_left)-key(_right))*maxturnspeed;
        advance(speed);
        // Handle collision
        if( (collisionID = collision(type main)))
            text = "collision with: " + collisionID;
        else
            text = "no collision";
        end
        frame;
    End
End

Process Main()
Private
    int map;
Begin

    // Create the graph for the ship
    map = new_map(20,20,8);
    map_clear(0,map,rgb(0,255,255));

    // Create the graph for the Main process
    graph = new_map(50,50,8);
    map_clear(0,graph,rgb(255,255,0));

    // Position the main process and create the ship
    x = y = z = 100;
    SpaceShip(0,map,100,100,0,20,5000);

    Repeat
        frame;
    Until(key(_ESC))

    let_me_alone();

End

Used in example: [write_string](), [key](), [new_map](), [advance](), [let_me_alone], [type]


collision_box()

Definition

INT collision_box ( <INT processID|processTypeID> )

Checks if a [process] collided with the process calling Collision_box().

When a [processTypeID] is specified, there could be multiple fitting collisions. In this case, collision_box() returns a [processID] on each subsequent call, until it returns 0. This can be reset by use of the [frame]; statement, and in such case, frame(0); can be handy.

The diference between collision_box and [collision] is that collision_box only checks the distance with the edges of the processes, on the other side collision() check pixel by pixel between these processes. Consequently, collision_box() is faster, but is more accurate collision().

Parameters


INT processID processTypeID - The ProcessID of the process or the ProcessTypeID of the type of processes to be checked.

Returns

INT : The ID of the collided process.


0 - No collision >0 - The processID of the process colliding with the current process


Example

Process SpaceShip( int file , int graph , int x , int y , int angle , int maxspeed , int maxturnspeed )
Private
    int speed;
    int collisionID;
    string text;
Begin
    write_string(0,0,0,0,&text);
    Loop
        // Handle movement
        speed+=key(_up)*(speed<maxspeed)-key(_down)*(speed>-maxspeed);
        angle+=(key(_left)-key(_right))*maxturnspeed;
        advance(speed);
        // Handle collision_box
        if( (collisionID = collision_box(type main)))
            text = "collision with: " + collisionID;
        else
            text = "no collision";
        end
        frame;
    End
End

Process Main()
Private
    int map;
Begin

    // Create the graph for the ship
    map = new_map(20,20,8);
    map_clear(0,map,rgb(0,255,255));

    // Create the graph for the Main process
    graph = new_map(50,50,8);
    map_clear(0,graph,rgb(255,255,0));

    // Position the main process and create the ship
    x = y = z = 100;
    SpaceShip(0,map,100,100,0,20,5000);

    Repeat
        frame;
    Until(key(_ESC))

    let_me_alone();

End

Used in example: [write_string](), [key](), [new_map](), [advance](), [let_me_alone], [type]


collision_circle()

Definition

INT collision_circle ( <INT processID|processTypeID> )

Checks if a [process] collided with the process calling Collision_circle().

When a [processTypeID] is specified, there could be multiple fitting collisions. In this case, collision_cirlce() returns a [processID] on each subsequent call, until it returns 0. This can be reset by use of the [frame]; statement, and in such case, frame(0); can be handy.

The diference between collision_circle and [collision] is that collision_circle only checks the distance with a circle in the edges of the processes, on the other side collision() check pixel by pixel between these processes. Consequently, collision_circle() is faster, but less accurate than collision().

Parameters


INT processID processTypeID - The ProcessID of the process or the ProcessTypeID of the type of processes to be checked.

Returns

INT : The ID of the collided process.


0 - No collision >0 - The processID of the process colliding with the current process


Example

Process SpaceShip( int file , int graph , int x , int y , int angle , int maxspeed , int maxturnspeed )
Private
    int speed;
    int collisionID;
    string text;
Begin
    write_string(0,0,0,0,&text);
    Loop
        // Handle movement
        speed+=key(_up)*(speed<maxspeed)-key(_down)*(speed>-maxspeed);
        angle+=(key(_left)-key(_right))*maxturnspeed;
        advance(speed);
        // Handle collision_box
        if( (collisionID = collision_circle(type main)))
            text = "collision with: " + collisionID;
        else
            text = "no collision";
        end
        frame;
    End
End

Process Main()
Private
    int map;
Begin

    // Create the graph for the ship
    map = new_map(20,20,8);
    map_clear(0,map,rgb(0,255,255));

    // Create the graph for the Main process
    graph = new_map(50,50,8);
    map_clear(0,graph,rgb(255,255,0));

    // Position the main process and create the ship
    x = y = z = 100;
    SpaceShip(0,map,100,100,0,20,5000);

    Repeat
        frame;
    Until(key(_ESC))

    let_me_alone();

End

Used in example: [write_string](), [key](), [collision_circle](), [new_map](), [advance](), [let_me_alone], [type]


exists()

Definition

INT Exists ( <INT processID|processTypeID> )

Checks if a [process] is alive, using its [processID] or checks if there is a process alive of a certain [processType], using its [processTypeID].

Parameters


INT processID processTypeID - The ProcessID of the process or the ProcessTypeID of the type of processes to be checked.

Returns

INT : The result of the check


0 (false) - The process with given processID is not alive or there are no processes alive of the given processTypeID. 1 (true) - The process with given processID is alive or there is at least one process alive of the given processTypeID.


Example

import "mod_proc"
import "mod_say"

Process Main()
Begin

    Proc();

    if(exists(id))
        say("I exist! (id)");
    end

    if(exists(0))
        say("0 exists!");
    else
        say("0 doesn't exist!");
    end

    if(exists(type proc))
        say("1- Proc exists!");
    else
        say("1- Proc doesn't exist!");
    end

    let_me_alone();

    if(exists(type proc))
        say("2- Proc exists!");
    else
        say("2- Proc doesn't exist!");
    end

End

Process Proc()
Begin
    Loop
        frame;
    End
End

Used in example: [exists](), [let_me_alone]()


get_id()

Definition

INT get_id ( <INT processTypeID> )

Returns a [ProcessID] of a [process] of the specified [ProcessType]. On the next call of get_id() in the same process and in the same frame, the next process will be returned of the given type. After a [frame] statement, get_id() is reset and will return the first process of the given processType. When there are no more processes of a given type, which have not been returned, it will return 0.

get_id(0) returns processes of any type.

Parameters


INT processTypeID - The [processTypeID] to get the processes' processIDs of.


Returns

INT : The [processID] of a process of the given processType.


0 - There are no more processes of the given processType, which have not been returned. >0 - The [processID] of a process of the given processType.


Example

Program example;
Begin
    signaltype(type Monkey,s_kill);
End

/**
 * Empty process
 */
Process Monkey()
Begin
End

/**
 * Signals every process of type 't' the signal 'signal'.
 */
Function int signaltype(int t, int signal)
Begin
    while( (x=get_id(t)) ) // while there is an unprocessed process left and store that in 'x'
        signal(x,signal); // signal the process with processID 'x'.
    end
End

// Of course, the very observant of you already noticed that signaltype(my_type,my_signal)
// does the same thing as the function signal(my_type,my_signal), but this is just to
// illustrate the workings.

/**
 * Signals every process the signal 'signal'.
 */
Function int signalall(int signal)
Begin
    while( (x=get_id(0)) ) // while there is an unprocessed process left and store that in 'x'
        signal(x,signal); // signal the process with processID 'x'.
    end
End

// get_id(0) returns a process of any type. This is a possible implementation of a
// function which signals all existing processes. Note that this can be dangerous to use,
// as in some cases you might want one or two processes to stay alive.

Used in example: [signal]()


get_real_point()

Definition

INT get_real_point( <INT controlpoint> , <INT POINTER x> , <INT POINTER y> )

Finds the actual position on the screen of the calling [process] and the specified [controlpoint] on this graphic. All process-related variables are taken into account, like [x], even [ctype]. These coordinates are then assigned to the variables pointed to by x and y.

Parameters


INT controlpoint - The [controlpoint] on the process' graphic of which the actual position is wanted. INT POINTER x - A pointer to an integer to which the X-coordinate will be assigned. INT POINTER y - A pointer to an integer to which the Y-coordinate will be assigned.


Returns

INT : Successrate


[false] - Error: no graphic; invalid controlpoint; [true] - Success.



get_status()

Definition

INT get_status ( <INT processID> )

Get the current status of a [ProcessID]. With this, you can check if a process is frozen, sleeping, dead, alive or non-existing.

Parameters


INT processID - The [ProcessID] signal was send to.


Returns

INT :


[false] - The specified processID does not exist (return status: 0). 1,2,3 or 4 - The state of the [processID].


Return states


0 - The specified process does not exist. 1 - The specified process is dead. 2 - The specified process is alive. 3 - The specified process is sleeping. 4 - The specified process is frozen.


Example

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_proc";
IMPORT "mod_grproc";
IMPORT "mod_key";

GLOBAL

  int proc1;
  int proc2;
  int proc3;
  int proc4;
  int proc5;

PROCESS main();

PRIVATE

BEGIN

   // create some processes
   proc1=dummy();
   proc2=dummy();
   proc3=dummy();
   proc4=dummy();

   // change the state
   signal(proc1,s_sleep);
   signal(proc2,s_freeze);
   signal(proc3,s_wakeup);
   signal(proc4,s_kill);

   // print the status of each instance            
   say("");
   say("status codes: ALIVE=2, SLEEP=3, FROZEN=4 ,DEAD=1, NON_EXISTING=0");
   say("");
   say("proc1 status: "+get_status(proc1)); // sleeping     (3)
   say("proc2 status: "+get_status(proc2)); // frozen       (4)
   say("proc3 status: "+get_status(proc3)); // alive        (2)
   say("proc4 status: "+get_status(proc4)); // dead         (1)
   say("proc5 status: "+get_status(proc5)); // not existing (0)

   LOOP

      // quit.
      IF (key(_esc))

         exit("",0);
      END
      FRAME;
   END
END

PROCESS dummy();

PRIVATE

BEGIN

   // endless loop
   LOOP
      FRAME;
   END
END

Used in example: [exit](), [key]


let_me_alone()

Definition

INT let_me_alone ( )

Kills all [processes] except the calling one.

To kill only one process, use [signal]().

Returns

INT : [true]

Example

Const
    screen_width = 320;
    screen_height = 200;
    screen_depth = 8;
End

/**
 * Description
 *   Generates an error. Puts the error in the console and stdout.txt and shows it onscreen
 *   for certain time. Immediately kills all other processes and quits the program after a
 *   certain time.
 *
 * Parameters
 *   String message   - The error message.
 *   int delay        - The time to display the error onscreen and after which the program will quit.
 *                      In 1/100seconds.
 *
 * Returns
 *   0 - Success.
 */
Process error(String message,int delay)
Begin

    // Put the error message in the console and in stdout.txt
    say("[ERROR] " + message);

    // Show the error message onscreen, the size adjust for the screen width
    set_text_color(rgb(255,0,0));
    graph = write_in_map(0,message,4);
    size = 100*(screen_width-10)/graphic_info(0,graph,G_WIDTH);
    x = screen_width/2;
    y = screen_height/2;

    // Kill all other processes
    let_me_alone();

    // Wait the specified time
    timer[0] = 0;
    Repeat
        frame;
    Until(timer[0]>delay)

    // Unload the used graph
    unload_map(0,graph);

    return 0;

End

Process Main();
Begin

    // Set the screen mode
    set_mode(screen_width,screen_height,screen_depth);

    // Generate an error
    error("ERROR, QUITTING IN 2 SECONDS",200);

    Repeat
        frame;
    Until(key(_esc))

End

signal()

Definition

INT signal ( <INT processID|processTypeID> , <INT signal> )

Allows a [process] or a range of processes/functions of certain [processType] to be controlled in a limited number of ways, by sending [signals].

Parameters


INT processID processTypeID - The [ProcessID] of the type of processes to send the signal to. INT signal - The [signal] that is to be sent to the target process(es).

Returns

INT :


[false]. [true].


Errors


Invalid signal - The specified [signal] is invalid.


Notes

To obtain the processType of a function, the operator [Type] can be used. For a process to send a signal to itself, the [local variable] [id] can be used. The parameter signal is passed by way of a set of [signals] which denote the signal to be sent. The parameter signal is one of the listed [signals]. To kill all processes at once, except the calling one, use [let_me_alone]().

To send a signal to all processes at once, except the calling one, use signal([[ALL_PROCESS]],signal).

To specify how a process reacts on an incoming signal, use [signal_action]().

A signal is carried out immediately, but this does not mean execution of processes is switched to the process, if you just woke it up. This can be achieved by using [[frame]](0); after the signal. A frame will cause Bennu to continue execution with the process having the lowest frame-percentage done and it will only continue execution with the current process after all other processes have had their turn. Moreover, using a frame-percentage of 0 will make sure there is nothing added to the done frame-percentage of the process, meaning it doesn't affect the framerate of the process.

Example

signal( get_id(type enemy) , s_kill ); // Kills a process of type enemy.
                                       // Becareful! If there is no enemy process alive, 
                                       // get_id() will return 0, which means signal()
                                       // will signal all processes.

signal( id , s_kill_tree );            // Kills the process that calls it, and all of its descendants

signal( Type player , s_freeze );      // Freezes all processes of type player so that they are
                                       //     still displayed, but do not execute any code.

signal(ALL_PROCESS,s_freeze);          // Freezes all processes except the one that called it.
                                       // Can be used to pause a game.

signal( someID , S_WAKEUP ); frame(0); // Wake up the process someID and let it execute once
                                       // (if not done this frame) before continuing.

signal_action()

Definition

INT signal_action ( [<INT processID|processTypeID> , ] INT signal , INT action )

Sets the reaction of one or more [processes] when they receive a certain nonforceful-[signal]. Only existing processes are affected, processes created afterwards are not.

Parameters


INT processID processTypeID - A [ProcessID] or ALL_PROCESS. INT signal - The code of a nonforceful-[signal] for which a reaction is to be specified. INT action - The [reaction])

Returns

INT : [true]

Notes

The reaction to an incoming forced signal (S_KILL_FORCE, S_SLEEP_FORCE, etc) cannot be changed and is S_DFL by default.

Example

// The current process ignores the kill signal from now on
signal_action(S_KILL,S_IGN);

// All currently existing processes ignore the kill signal from now on
signal_action(ALL_PROCESS,S_KILL,S_IGN);

// All currently existing processes of type 'Player' ignore the freeze signal from now on
signal_action(type Player,S_FREEZE,S_IGN);

xadvance()

Definition

INT xadvance ( <INT angle> , <INT distance> )

Moves a process a certain distance in a certain direction.

Parameters


INT angle - The [angle] in which to move the process, in thousandths of a degree. INT distance - The distance to move the process, in pixels.


Returns

INT : Successrate


[true] - Success. [false] - Error.


Example

Program example;
Global
    myproc;

Begin

    myproc=proc();

    Loop
        frame;
    End
End

Process proc();
Begin

    x=100;
    y=100;

    Loop
        xadvance(90000,10); //moves the process vertically (90 degrees) 10 pixels
        frame;
    End

End


Program interaction

exec()

Definition

INT exec ( <INT mode> , <STRING executable>, <INT number_of_arguments> , <STRING POINTER arguments> )

Executes the specified executable with the specified arguments in the specified mode.

Parameters


INT mode - The mode to call the executable ([_P_WAIT]). STRING executable - The executable to start. INT number_of_arguments - The number of arguments given with arguments STRING POINTER arguments - Pointer to an array of strings to be passed; number_of_arguments strings will be passed as arguments.


Returns

INT


-1 - Error. mode==_P_WAIT: - The exit status of the executable. mode==_P_NOWAIT: - The process ID of the executable. This is not a [ProcessID], it is a process ID of the operating system.


Notes

The mode parameter can be two things:


_P_WAIT - Wait for the executable to exit. _P_NOWAIT - Do not wait for the executable to exit.


Example

Open file.txt in notepad:

import "mod_sys"

Process Main()
Private
    string arg;
Begin
    arg = "file.txt";
    exec(_P_NOWAIT,"notepad.exe",1,&arg);
End

Used in example: [exec](), [pointer]


exit()

Definition

INT exit ( [<STRING message>] , [<INT code>] )

Exits the program. It can optionally pass a message or an error code thing.

Parameters


[STRING message] - A message to pass outside the program as it exits. [INT code] - A code to pass outside the program as it exits.


Returns

INT : [true]


get_desktop_size()

Syntax

INT get_desktop_size ( <INT POINTER width>, <INT POINTER height> )

Description

Get the desktop size.

Parameters


INT POINTER width - Pointer to where the desktop width will be written. INT POINTER height - Pointer to where the desktop height will be written.


Returns

INT : Successrate


[false] - Error. [true] - Ok.



get_modes()

Syntax

POINTER get_modes ( <INT depth>, <INT flags> )

Description

Returns a pointer to an array of available screen dimensions for the given [depth] and [render flags], sorted largest to smallest.

Returns NULL if there are no dimensions available for a particular format, or -1 if any dimension is okay for the given format.

Parameters


INT depth - [Color depth]. INT flags - Mode of rendering. See [render flags].


Returns

POINTER : A pointer to an array of available screen dimensions

Example

import "mod_say";
import "mod_video";

Process Main()
Private
    int * modes;
Begin
    // Modes will point to an array whose values are acceptable values for resolution

    // Get 8bpp acceptable modes when in fullscreen
    modes = get_modes(8, MODE_FULLSCREEN);
    say ("8bit modes");
    say ("----------");
    if (!modes)
        say ("no video modes available!");
    elsif (modes == -1 )
        say ("any video mode available!");
    else
        while (*modes)
            say ("> " + *modes++ + " x " + *modes++ );
        end
    end
    say ("");

    // Get 16bpp acceptable modes when in fullscreen
    modes = get_modes(16, MODE_FULLSCREEN);
    say ("16bit modes");
    say ("-----------");
    if (!modes)
        say ("no video modes available!");
    elsif (modes == -1 )
        say ("any video mode available!");
    else
        while (*modes)
            say ("> " + *modes++ + " x " + *modes++ );
        end
    end
    say ("");

    // Get 24bpp acceptable modes when in fullscreen
    modes = get_modes(24, MODE_FULLSCREEN);
    say ("24bit modes");
    say ("-----------");
    if (!modes)
        say ("no video modes available!");
    elsif (modes == -1 )
        say ("any video mode available!");
    else
        while (*modes)
            say ("> " + *modes++ + " x " + *modes++ );
        end
    end
    say ("");

    // Get 32bpp acceptable modes when in fullscreen
    modes = get_modes(32, MODE_FULLSCREEN);
    say ("32bit modes");
    say ("-----------");
    if (!modes)
        say ("no video modes available!");
    elsif (modes == -1 )
        say ("any video mode available!");
    else
        while (*modes)
            say ("> " + *modes++ + " x " + *modes++ );
        end
    end
    say ("");

End

Used in example: [say](), [MODE_FULLSCREEN]


get_window_pos()

Syntax

INT get_window_pos ( <INT POINTER x>, <INT POINTER y>)

Description

Get the X and Y position of the window.

Parameters


INT POINTER x - Pointer to where the X-coordinate of the window will be written. INT POINTER y - Pointer to where the Y-coordinate of the window will be written.


Returns

INT : Successrate


[false] - The system is in fullscreen. [true] - Success ok.



get_window_size()

Syntax

INT get_window_size ( <INT POINTER window_width> , <INT POINTER window_height> , <INT POINTER client_width> , <INT POINTER client_height> )

Description

Get the window and client size.

Parameters


INT POINTER window_width - Pointer to where the window width will be written. INT POINTER window_height - Pointer to where the window height will be written. INT POINTER client_width - Pointer to where the client width of window will be written. INT POINTER client_height - Pointer to where the client height of window will be written.


Returns

INT : Successrate


[false] - Error. [true] - Ok.


Example

import "mod_key"
import "mod_video"
import "mod_text"
import "mod_wm"
Global
    desktop_width = 640;
    desktop_height = 480;
    window_width = 0;
    window_height = 0;
    client_width = 0;
    client_height = 0;
End

Process Main()
Begin

    get_desktop_size(& desktop_width,& desktop_height);
    get_window_size ( & window_width,  &window_height , & client_width ,  & client_height );
    set_mode (desktop_width-window_width+client_width,desktop_height-window_height+client_height,32);
    set_window_pos(0,0);

    write(0,desktop_width/2,desktop_height/2+30,0,"ESC to exit");
    while (!key(_ESC) )
        frame;
    end
End

Used in example: [get_desktop_size](), [get_window_size](), [set_mode](), [set_window_pos](), [write]()


getenv()

Definition

STRING getenv ( <STRING variablename> )

Returns the value of an environment variable (like PATH).

Parameters


STRING variablename - The name of the variable to get the value of.


Returns

STRING : The value of the variable.


"" - The variable is invalid or empty. !"" - The value of the variable.



key()

Definition

INT key( <INT scancode> )

Checks if a certain key is being pressed.

Parameters


INT scancode - The [scancode] of the key to be checked.


Returns

INT : [true]: Whether the key is being pressed.

Notes

Take a look at the [scancodes] for a complete list.

Example

Program input_test;
Begin

    While( !key(_esc) )

        delete_text(ALL_TEXT);

        if( key(_left) && !key(_right) )  
            write(0,160,120,4, "LEFT");
        end;

        if( key(_right) && !key(_left) ) 
            write(0,160,120,4, "RIGHT"); 
        end;

        frame;

    End;

    exit();

End

Used in example: [delete_text](), [write](), [ALL_TEXT]

This will output the words LEFT or RIGHT according to the keys you press, or it will quit the program once ESCAPE is pressed.


minimize()

Definition

INT minimize ( )

Iconifies/minimizes the window.

Returns

INT : success


0 - If minimizing/iconification is not support or was refused by the window manager. !0 - Success.


Example

import "mod_key"
import "mod_wm"

Process Main()
Begin

    Repeat
        if(key(_M))
            while(key(_M)) frame; end
            minimize();
        end
        frame;
    Until(key(_ESC)||exit_status)

End

Used in example: [key](), [minimize](), [exit_status]


mode_is_ok()

Definition

INT mode_is_ok ( <INT width> , <INT height> , <INT depth>, <INT flags> )

Returns 0 if the requested mode is not supported under any bit depth,or returns the bits-per-pixel of the closest available mode with the given width, height and requested flags.

Parameters


INT width - Width of the screen in [pixels]. INT height - Height of the screen in [pixels]. INT depth - [Color depth]. INT flags - Mode of rendering. See [render flags].


Returns

INT : Whether the specified mode can be used.


0 - The specified mode cannot be used. >0 - The bits-per-pixel of the closest available mode for the given width, height and flags.


Example

import "mod_video"
import "mod_key"
import "mod_wm"

Process Main()
Begin
    if (is_mode_ok(640,400,16,0))
     set_mode(640,400,16);
    else
     set_mode(640,480,16);
    end
    Repeat
        frame;
    Until(key(_ESC)||exit_status)
End

Used in example: [is_mode_ok](), [key]


move_window()

Definition

INT move_window ( <INT x> , <INT y> )

Moves the [Bennu] window so that the top left of the window is on the specified (x,y).

Also called [Set window pos]().

Parameters


INT x - The new X coordinate of the top left of the window. INT y - The new Y coordinate of the top left of the window.


Returns

INT : [true]


set_fps()

Definition

INT set_fps ( <INT fps> , <INT skip> )

Sets the frames per second ([framerate]) your program aims to display. The more frames per second, the faster your program runs. Some computers might not be able to display the amount of frames you specified, and will show a lower fps. Therefore, it is important you choose a fps that is reasonable and can also be displayed by the somewhat slower computers. If you don't use this function then the default fps will be used (25 fps).

Parameters


INT fps - Frames per second to use. The default is 25. INT skip - Frames the program is allowed to skip to keep up with the specified framerate if it's running low on processor time. The default is 0.


Returns

INT : The FPS entered.

Notes

If you use Set_fps(0,0), then your program will run at the maximum speed your computer can possibly handle.

The current FPS can be read from the [global variable].

Errors

None.

Example

Program test;
Begin
    Set_fps(60,0);
    Loop
        Frame;
    End
End

set_icon()

Definition

INT set_icon ( <INT fileID> , <INT graphID> )

Set the window icon to a certain graph.

The icon will only be updated after [set_mode]() is called, so call set_icon() before set_mode(). The map used for the icon must be 32x32 large, but it can have different depths. After set_icon() and set_mode() have been called, the map used for the icon can be freed from memory using [unload_map]().

Parameters


INT fileID - The fileID of the [file]. INT graphID - The graphID of the graph to be used as an icon.


Returns

INT : [true]

Example

import "mod_key"
import "mod_map"
import "mod_wm"
import "mod_video"

Const
    screen_width  = 320;
    screen_height = 200;
    screen_depth  =  16;
End

Process Main()
Private
    int map;
    int iconsize      =  32;
Begin

    set_mode(screen_width,screen_height,screen_depth);

    map = new_map(iconsize,iconsize,screen_depth);
    map_clear(0,map,rgb(0,255,255));

    set_title("<-- Look at the cyan block!");
    set_icon(0,map);

    unload_map(0,map);

    Repeat
        frame;
    Until(key(_ESC)||exit_status)

End

Used in example: [set_mode](), [new_map](), [rgb](), [set_icon](), [unload_map](), [exit_status]


set_mode()

Syntax

INT set_mode ( <INT width> , <INT height> , [<INT depth>] , [<INT flags>] )

Description

Sets the screen resolution of your program, and optionally the colordepth of the screen and any [render flags] for extra options. If this command is not used, the default settings will take effect (320x240 at 32 bpp).

Some much used resolutions are: 320x240, 640x480, 800x600, 1024x768 and 1280x1024.

Parameters


INT width - Width of the screen in [pixels]. INT height - Height of the screen in [pixels]. INT [depth] - [Color depth]. INT [flags] - Mode of rendering. See [render flags].


Returns


INT : -1: error, setting the mode has failed INT : 0: sucess

INT : [true] (in versions prior rc282)

Notes

Any fpg files you load must have the same or a lower colordepth as you set for the screen.

Uncommon resolutions can also be used, for example 399x10, which will be the actual size of the window if you run in windowed mode. At full screen black edges might appear.

There is another method of calling set_mode(): with one parameter. In this parameter you must use the 4 right digits for the height and the rest fot the width. For example to set a 320x200 mode you can use set_mode(3200200). The maximum height that allow this method is 9999 pixels. This method is deprecated and its use is disadvised.

Example

import "mod_video"
import "mod_key"
import "mod_wm"

Process Main()
Begin
    set_mode(640,480,16);
    Repeat
        frame;
    Until(key(_ESC)||exit_status)

End

Used in example: [set_mode](), [key]


set_title()

Definition

INT set_title ( <STRING title> )

Sets the title of the program's window.

The title will only be updated after [set_mode]() is called, so call set_title() before set_mode().

Parameters


STRING title - The new title for the program's window.


Returns

INT : [true]

Example

Program icon;
Private
    int map;
    int screen_width  = 320;
    int screen_height = 200;
    int screen_depth  =   8;
    int iconsize      =  32;
Begin

    map = new_map(iconsize,iconsize,screen_depth);
    map_clear(0,map,rgb(0,255,255));

    set_icon(0,map);
    set_title("<-- Look at the cyan block!");
    set_mode(screen_width,screen_height,screen_depth);

    unload_map(0,map);

    Repeat
        frame;
    Until(key(_esc))

End

Used in example: [new_map](), [map_clear](), [set_icon], [unload_map]()



Regions

region_define()

Definition

INT region_define ( <INT regionID> , <INT x> , <INT y> , <INT width> , <INT height> )

Defines the boundaries of a [region].

There are 32 regions, range 0..31. Region 0 is always the whole screen and cannot be changed. Defining regions can be useful for the function [out_region](), the [local variable] and using them with [scrolls].

Also called [define_region]().

Parameters


INT regionID - The [regionID] of the region to define. INT x - The x coordinate of the top left corner of the region. INT y - The y coordinate of the top left corner of the region. INT width - The width of the region. INT height - The height of the region.


Returns

INT : The [regionID] specified.


region_out()

Definition

INT out_region ( <INT processID> , <INT regionID> )

Checks if the specified [process] is completely outside of the specified [region].

The check is not pixel perfect, but uses the [bounding box] of the process.

Also called [out_region]().

Parameters


INT processID - The [processID] of the process to check. INT regionID - The [regionID] of the region to check with.


Returns

INT : [true]: whether the process is completely outside the region.


[true] - The process is completely outside the region. [false] - The process is (partly) inside the region or invalid region or process specified.




Screen

put()

Definition

INT put ( <INT fileID> , <INT graphID> , <INT x> , <INT y> )

Draws ([blits] onto the [background].

For more advanced blitting, see:

  • [xput]()
  • [map_put]()
  • [map_xput]()
  • [map_xputnp]()

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to draw with. INT x - Where on the background's x-axis to put the graph. INT y - Where on the background's y-axis to put the graph.


Returns

INT : [true]

Notes

The x and y parameters denote where to draw the graph, that is, where the center of the to be drawn graph will be.

Errors


Unsupported color depth - The origin graph's color depth is greater than the destination graph's.


Example

import "mod_map"
import "mod_screen"
import "mod_key"

Process Main()
Private
    int map;
Begin

    // Create a new graph of size 100x100 and color depth of 8bit
    map = map_new(100,100,8);

    // Clear the map red
    map_clear(0,map,rgb(255,0,0));

    // Put it in the center of the screen
    put(0,map,160,100);

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [map_new](), [map_clear](), [key]()

This will result in something like:\


screen_clear()

Definition

INT screen_clear ( )

Clears the [background] of the screen, making it completely black.

Also called [clear_screen]().

Returns

INT : [true]

Notes

This is the same as '''[[map_clear]]'''(0,[[BACKGROUND]]). When the background is cleared in either way, [Bennu] knows the background is empty and will take advantage of this knowledge.

Errors


Unsupported color depth - The specified graph has a not supported color depth.



screen_get()

Definition

INT screen_get ( )

Creates a new [graphic] containing a copy of the lastly rendered frame.

The map will contain everything, including background, [processes] and [text](), the newly created graphic will be located in the [System file] of 0); the [graphID] will be returned. After the use of this graphic, it should be freed using [map_unload]().

Also called [get_screen]().

Returns

INT : [GraphID]


0 - Some error. >0 - The [GraphID] created.


Example

import "mod_key"
import "mod_screen"
import "mod_map"

Global
    int my_map;
End

Process Main()
Begin
    Repeat
        if(key(_F5))
            my_map = screen_get();
            png_save(0,my_map,"snapshot.PNG");
            map_unload(0,my_map);
            while(key(_F5)) frame; end
        end
        frame;
    Until(key(_ESC))
End

Used in example: [key](), [screen_get](), [png_save](), [map_unload]()


screen_put()

Definition

INT screen_put ( <INT fileID> , <INT graphID> )

Clears and draws ([blits] onto the [background] in the center.

For more advanced blitting, see:

  • [put]()
  • [xput]()

Also called [put_screen]().

Parameters


INT fileID - The [file] that holds the graph. INT graphID - The [graph] to draw with.


Returns

INT


0 - Invalid map. 1 - Success.


Notes

The center of the specified graph influences its placement.

The following codes are equivalent:

screen_put(f,g);

screen_clear();
put(f,g,graphic_info(0,BACKGROUND,G_WIDTH)/2,graphic_info(0,BACKGROUND,G_HEIGHT)/2);

See [screen_clear]() and [map_info]().

Errors


Invalid map - The specified map is invalid. Unsupported color depth - The origin graph's color depth is greater than the destination graph's.



xput()

Definition

INT xput ( <INT fileID> , <INT GraphID> , <INT x> , <INT y> , <INT angle> , <INT size> , <INT blitflags> , <INT region> )

Draws ([blits] onto the [background].

If the advanced parameters aren't needed, [put]() can be used.

Parameters


INT fileID - The [fileID] that holds the graphics. INT graphID - The [graphID] to draw with. INT x - Where on the background graphic's x-axis to put the graphic. INT y - Where on the background graphic's y-axis to put the graphic. INT angle - What [angle] to draw the graphic at. INT size - What [size] to draw the graphic at. INT blitflags - What [blit flags] to draw the graphic with. INT regionID - The [regionID] in which the graphic is only allowed to be drawn.


Returns

INT : [true]

Notes

The x and y parameters denote where to draw the graphic, that is, where the center of the to be drawn graphic will be. Blit flags can be used to give the drawing (blitting) a special effect.

When angle is 0 and size is 100, the speed is greater, because the graph doesn't need rotating or scaling.

Errors


Unsupported color depth - The graphic's color depth is greater than the background graphic's.




Scrolls

move_scroll()

Definition

INT Move_scroll ( <INT scrollnumber>)

The move_scroll function is a slighty more advanced function. It allow the scroll's internal coordinates x0, y0, x1 and y1 of the [scroll structure] to be updated in a forcefull way. This gives great flexibility when multiple [scroll windows] are used.

For instance, in a situation where multiple scroll windows are active on screen, and one scroll is controlled by the main player, the other scrolls can be updated manually. However, the function can also be usefull when there's only one scroll active. In that case you can have any process take control over the scroll.

Also called [scroll_move]().

Parameters


INT scrollnumber - The ID for the scroll window to be moved


Returns

INT : [true]

Example

IMPORT "mod_video";
IMPORT "mod_map";
IMPORT "mod_scroll";
IMPORT "mod_screen";
IMPORT "mod_key";
IMPORT "mod_proc";

GLOBAL

int graphics;
int counter;

PRIVATE

PROCESS main();

BEGIN
    set_fps(100, 0);
    graphics=load_fpg("help.fpg");
    start_scroll(0, graphics, 103, 102, 0, 15);

    scroll.camera=id; // assign the "main" process instance (this one) to the scroll's camera.
    priority=100;

    FROM counter=-2000 TO 2000 step 100;
        movable_process(counter);
    END

    say("Use the right and left cursors to move");

    graph=101;
    ctype=c_scroll;

    LOOP
        if (key(_right))
            x+=2;
            flags=0;
        END
        if (key(_left))
            x-=2;
            flags=1;
        END

        move_scroll(0); // Updates the scroll structure[], in this case affect scroll 0.

        FRAME;
    END
END

PROCESS movable_process(x_scroll);

PRIVATE

BEGIN
    ctype=c_scroll;
    z=100;
    graph=104;
    LOOP
        x=x_scroll-scroll.x0; 
        FRAME;
    END
END

Using Scrolling

For each [process] that you want to be part of a [scroll window], you must set the [local variable] to value [C_SCROLL]. It should also be noted that the local variable [c_number] is used for selecting in which scroll a process should be displayed. Additionally, you must set the camera property of the [scroll structure] to the [processID] of the process you wish to be followed.


start_scroll()

Definition

INT Start_scroll ( <INT scrollnumber> , <INT fileID> , <INT graphID> , <INT backgroundgraphID> , <INT regionnumber> , <INT lockindicator> , [ <INT destination fileID >, <INT destination graphID > ] )

This creates a [scroll window] in which it will perform a view against a background [graphic]. That is, by using a graphic bigger than the display window, a part of this graphic can be shown and shifted in any direction. After this function, the use of the struct [scroll] makes sense.

The parameters destination fileID and destination graphID are optional and may be omitted.

Also called [scroll_start]().

Parameters


INT scrollnumber - The ID for the new scroll window, so it can be referenced to later INT fileID - The [fileID] containing the scroll graphics INT graphID - The [graphID] of the main graphic to be scrolled INT backgroundgraphID - The graphID of the graphic for the background of the scroll window INT regionnumber - The [region] in which to put the scroll window INT lockindicator - A [bit flag] defining whether each of the two scroll planes is horizontally/vertically cyclical INT destination flileID - The [fileID] containing the destination graphics used in the scroll window, i.e. the systemfile. (optional) INT destination graphID - The [graphID] of the destination graphic where the scroll window will be drawn on. (optional)


Returns

INT : [true]

Notes

The locking indicator can be combinations of the following flags:


1 - The foreground will be displayed horizontally cyclical 2 - The foreground will be displayed vertically cyclical 4 - The background will be displayed horizontally cyclical 8 - The background will be displayed vertically cyclical


Combine them using the [bitwise OR] operator.

Using Scrolling

For each [process] that you want to be part of a [scroll window], you must set the [local variable] to value [C_SCROLL]. It should also be noted that the local variable [c_number] is used for selecting in which scroll a process should be displayed. Additionally, you must set the camera property of the [scroll structure] to the [processID] of the process you wish to be followed.

Example (scroll drawn on map)

In this example, a scroll is drawn on a map, so the advanced version with the parameters destination fileID and destination graphID are used.

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_proc";
IMPORT "mod_grproc";
IMPORT "mod_map";
IMPORT "mod_text";
IMPORT "mod_key";
IMPORT "mod_video";
IMPORT "mod_screen";
IMPORT "mod_draw";
IMPORT "mod_scroll";

GLOBAL

   int graphics_lib;

   int object1_id;

   int scroll_window;  
   int scroll_blit_graph;

PROCESS int main(); 

PRIVATE

BEGIN

    set_mode(640,480,8);
    set_fps(50,0);

    // load the fpg file with the graphics
    graphics_lib=load_fpg("graf2.fpg");

    // create a map to blit the scroll window on
    scroll_blit_graph=new_map(640,480,8);

    // display the "scroll_blit_graph".
    blit_graph();

    // (standard version)
    // int start_scroll (int scrollnumber, 
    //                   int file, 
    //                   int graph, 
    //                   int backgroundgraph, 
    //                   int regionnumber, 
    //                   int lockindicator); 

    // (advanced, extended version)
    // int start_scroll (int scrollnumber, 
    //                   int file, 
    //                   int graph, 
    //                   int backgroundgraph, 
    //                   int regionnumber, 
    //                   int lockindicator, 
    //                   int destination file, 
    //                   int destination graph); 

    // create an extended scroll, drawn on the "scroll_blit_graph".
    scroll_window=start_scroll(0,graphics_lib,1,0,0,3,0,scroll_blit_graph); 

    say("scroll_window status: "+scroll_window);

    // create the two objct processes.
    object1_id=object1(graphics_lib); 

    // write instructions  
    write(0 ,20,30,ALIGN_CENTER_LEFT,"Scroll extended (with destination map) test demo, instructions"); 

    write(0 ,20,40,ALIGN_CENTER_LEFT,"F3 and F4: decrease/increase size of destination map"); 
    write(0 ,20,50,ALIGN_CENTER_LEFT,"F5 and F6: decrease/increase angle of destination map"); 
    write(0 ,20,60,ALIGN_CENTER_LEFT,"F7 and F8: decrease/increase x of destination map"); 
    write(0 ,20,70,ALIGN_CENTER_LEFT,"F9 and F10: decrease/increase y of destination map"); 

    WHILE (NOT key(_esc))

        FRAME;
    END

    // stop scroll window.
    stop_scroll(0);

    // kill all processes, execpt the "main" process.
    let_me_alone();
END

PROCESS int object1 (int file);

PRIVATE

BEGIN

    graph=3;

    ctype=c_scroll;
    cnumber=c_0; // make this process visible in window 0

    scroll[0].camera=id;

    x=100;  
    y=100;

    LOOP

        // move main object
        IF (key(_up) AND y >0) 
           y-=5; 
        END
        IF (key(_down) AND y <800) 
           y+=5; 
        END
        IF (key(_left) AND x >0)  
           x-=5; 
        END
        IF (key(_right) AND x <2000) 
           x+=5; 
        END

        FRAME;
    END
END

// Process for handling the "destination graph" feature, i.e. the map on wich
// the mode7 windows are drawn.
PROCESS int blit_graph();

PRIVATE

BEGIN

   x=320;
   y=240;

   ctype=c_screen;

   file=0;
   graph=scroll_blit_graph; // set the graph to the map created in memory.

   LOOP

      // the controls for the "fancy stuff".
      IF (key(_f3) AND size >20)
         size-=10;
      END

      IF (key(_f4) AND size <1000)
         size+=10;
      END

      IF (key(_f5) AND angle >0)
         angle-=100;
      END

      IF (key(_f6) AND angle <360000)
         angle+=100;
      END

      IF (key(_f7) AND x >0)
         x-=10;
      END

      IF (key(_f8) AND x <1000)
         x+=10;
      END

      IF (key(_f9) AND y >0)
         y-=10;
      END

      IF (key(_f10) AND y <1000)
         y+=10;
      END

      FRAME;
   END
END

stop_scroll()

Definition

INT Stop_scroll ( <INT scrollnumber>)

This functions stops an active [scroll window]. There can be up to 10 (0-9) [scroll windows] active. When the scroll is stopped, all the processes in it will no longer be displayed. This function is usefull for switching the game's state from active gameplay to a loading screen state or similair situations. Another use is, when there are multiple scroll [regions] active, and the game changes from split screen to single screen. This way you can have individual control over the display of the scroll.

Also called [scroll_stop]().

Parameters


INT scrollnumber - The ID for the scroll window to be stopped


Returns

INT : [true]

Example

IMPORT "mod_video";
IMPORT "mod_map";
IMPORT "mod_scroll";
IMPORT "mod_screen";
IMPORT "mod_key";
IMPORT "mod_proc";

GLOBAL

int graphics;

PROCESS main();

BEGIN

    graphics=load_fpg("help.fpg");

    say("Press [ENTER] to activate the scroll window.");
    say("Press [SPACE] to stop the scroll.");

    LOOP
        IF (scan_code==_space)

            stop_scroll(0); // The scroll is stopped.

        END
        IF (scan_code==_enter)
            start_scroll(0, 0, 103, 102, 0, 15);
        END

        FRAME;
    END
END

Using Scrolling

For each [process] that you want to be part of a [scroll window], you must set the [local variable] to value [C_SCROLL]. It should also be noted that the local variable [c_number] is used for selecting in which scroll a process should be displayed. Additionally, you must set the camera property of the [scroll structure] to the [processID] of the process you wish to be followed.



Sorting

ksort()

Definition

INT ksort ( <VARSPACE array> , <VARSPACE sort-variable> , [<INT datacount>] )

Sorts a certain [array] according to a sort-variable within the elements and by sorting a certain number of elements. By default the whole array is sorted.

If the array elements contain only one variable each or the first one is the sort-variable, [sort]() can be used. For more advanced sorting, look at [quicksort]().

Parameters


VARSPACE array - The [array] to be sorted. VARSPACE sort-variable - The variable within each element to be used for the sorting. [INT datacount] - Number of elements to sort.


Returns

INT: Successrate


[true] - Sorting succeeded. [false] - Sorting failed, probably the type of sort-variable isn't supported.


Example

Program sorting;

Type _player
    String name;
    int score;
End

Const
    maxplayers = 5;
Global
    _player player[maxplayers-1];
Begin

    // Insert some values
    player[0].name = "That one bad looking dude";
    player[1].name = "Ah pretty lame guy";
    player[2].name = "Some cool dude";
    player[3].name = "OMG ZOMG guy";
    player[4].name = "This person is ok";

    player[0].score = 70;
    player[1].score = 30;
    player[2].score = 80;
    player[3].score = 90;
    player[4].score = 50;

    // Show array
    say("-------------------- unsorted");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

/* Sort by name ( quicksort() can't be used to sort Strings,
   as a String in Fenix is a pointer to the actual String,
   so it would sort the pointer addresses */

    // sort()
    sort(player); // sorts by name because name is the first variable in each element

    // Show array
    say("-------------------- name - sort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

    // ksort()
    ksort(player,player[0].name,maxplayers);

    // Show array
    say("-------------------- name - ksort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

/* Sort by score (sort() cannot be used here, because score is not the first variable) */

    // ksort()
    ksort(player,player[0].score,maxplayers);

    // Show array
    say("-------------------- score - ksort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

    // quicksort()
    quicksort(&player[0],sizeof(_player),maxplayers,sizeof(String),sizeof(int),0);

    // Show array
    say("-------------------- score - quicksort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

    // Wait until ESC is pressed
    Repeat
         frame;
    Until(key(_esc))

End

Used in example: [say](), [ksort](), [type], [pointer]


quicksort()

Definition

INT quicksort ( <VOID POINTER array> , <INT elementsize> , <INT elements> , <INT dataoffset> , <BYTE datasize> , <BYTE datatype> )

Sorts an [array] by the Quicksort ordering algorithm.

This function is very handy for user defined [types] for elements in which a sort-[variable] is present. For simple arrays or arrays in which the first variable is the sort-variable, [sort]() can be used. For arrays in which the sort-variable is a String, [ksort]() can be used.

Parameters


VOID POINTER array - [Pointer] to be sorted. INT elementsize - The size of an element in the array in bytes. INT elements - The number of elements in the array. INT dataoffset - The number of [bytes] in each element is relative to the start of that element. BYTE datasize - The size of the sort-variable in bytes. BYTE datatype - The datatype of the sort-variable. (0:[integer])


Returns

INT: [true]

Example

Program sorting;

Type _player
    String name;
    int score;
End

Const
    maxplayers = 5;
Global
    _player player[maxplayers-1];
Begin

    // Insert some values
    player[0].name = "That one bad looking dude";
    player[1].name = "Ah pretty lame guy";
    player[2].name = "Some cool dude";
    player[3].name = "OMG ZOMG guy";
    player[4].name = "This person is ok";

    player[0].score = 70;
    player[1].score = 30;
    player[2].score = 80;
    player[3].score = 90;
    player[4].score = 50;

    // Show array
    say("-------------------- unsorted");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

/* Sort by name ( quicksort() can't be used to sort Strings,
   as a String in Fenix is a pointer to the actual String,
   so it would sort the pointer addresses */

    // sort()
    sort(player); // sorts by name because name is the first variable in each element

    // Show array
    say("-------------------- name - sort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

    // ksort()
    ksort(player,player[0].name,maxplayers);

    // Show array
    say("-------------------- name - ksort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

/* Sort by score (sort() cannot be used here, because score is not the first variable) */

    // ksort()
    ksort(player,player[0].score,maxplayers);

    // Show array
    say("-------------------- score - ksort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

    // quicksort()
    quicksort(&player[0],sizeof(_player),maxplayers,sizeof(String),sizeof(int),0);

    // Show array
    say("-------------------- score - quicksort()");
    for(x=0; x<maxplayers; x++)
        say(player[x].name + " - " + player[x].score);
    end

    // Wait until ESC is pressed
    Repeat
         frame;
    Until(key(_esc))

End

Used in example: [say](), [ksort](), [type], [pointer]


sort()

Syntax

INT sort ( <VARSPACE array> , [<INT datacount>] )

Description

Sorts an [array] by sorting a certain number of elements, by using the first variable in each element. By default the whole array is sorted.

If the elements contain multiple variables, [ksort]() can be used to select the variable to be used for sorting. For more advanced sorting, look at [quicksort]().

Parameters


VARSPACE array - The [array] to be sorted. [INT datacount] - Number of elements to sort.


Returns

INT: Successrate


[true] - Sorting succeeded. [false] - Sorting failed. Look in the output for the error.


Example

import "mod_sort";
import "mod_key";
import "mod_say";

Type _player
    String name;
    int score;
End

Const
    maxplayers = 5;
End;

Process main()
Private
    _player player[maxplayers-1];
    int i=0;
Begin
    // Insert some values
    player[0].name = "That one bad looking dude";
    player[1].name = "Ah pretty lame guy";
    player[2].name = "Some cool dude";
    player[3].name = "OMG ZOMG guy";
    player[4].name = "This person is ok";

    player[0].score = 70;
    player[1].score = 30;
    player[2].score = 80;
    player[3].score = 90;
    player[4].score = 50;

    // Show array
    say("-------------------- unsorted");
    for(i=0; i<maxplayers; i++)
        say(player[i].name + " - " + player[i].score);
    end

/* Sort by name ( quicksort() can't be used to sort Strings,
   as a String in Bennu is a pointer to the actual String,
   so it would sort the pointer addresses */

    // sort()
    sort(player); // sorts by name because name is the first variable in each element

    // Show array
    say("-------------------- name - sort()");
    for(i=0; i<maxplayers; i++)
        say(player[i].name + " - " + player[i].score);
    end

    // ksort()
    ksort(player,player[0].name,maxplayers);

    // Show array
    say("-------------------- name - ksort()");
    for(i=0; i<maxplayers; i++)
        say(player[i].name + " - " + player[i].score);
    end

/* Sort by score (sort() cannot be used here, because score is not the first variable) */

    // ksort()
    ksort(player,player[0].score,maxplayers);

    // Show array
    say("-------------------- score - ksort()");
    for(i=0; i<maxplayers; i++)
        say(player[i].name + " - " + player[i].score);
    end

    // quicksort()
    quicksort(&player[0],sizeof(_player),maxplayers,sizeof(String),sizeof(int),0);

    // Show array
    say("-------------------- score - quicksort()");
    for(i=0; i<maxplayers; i++)
        say(player[i].name + " - " + player[i].score);
    end
End

Used in example: [say](), [ksort](), [type], [pointer]



Sound

fade_music_in()

Definition

INT fade_music_in ( <INT songID> , <INT num_loops> , <INT ms> )

Fades the music in, stepping up the volume from silence to the main song volume, i.e. set by the [Set_song_volume]() function.

Parameters


INT songID - The identification code of the song, returned by [load_song](). INT num_loops - The number of loops, a value of -1 will be an infinite loop. INT ms - Microseconds of fading (the duration).


Returns

INT : Error.


-1 - Error: sound inactive.


See also

[Fade_music_off]().


fade_music_off()

Definition

INT fade_music_off ( <INT ms> )

Fades off the song, played by [Play_song]().

Parameters


INT ms - Microseconds of fading (the duration).


Returns

INT : Error.


-1 - Error: sound inactive.


See also

[Fade_music_in]().


is_playing_song()

Definition

INT is_playing_song ( )

Checks to see if Bennu is playing a song file, started with [play_song]().

Returns

INT : Whether Bennu is playing a song at the moment of calling.


[true] - Bennu is playing a song. [false] - Bennu is not playing a song.


Example

program music_example;
global
    my_song;
    playing;
    paused;
    faded_in;
    v;
begin
    set_mode(640,480,16);

    my_song=load_song("beat.ogg");

    write(0,320,30,4,"Use the keyboard to control the music playback.");
    write(0,320,50,4,"Key [ENTER] starts / stops the song.");
    write(0,320,60,4,"Key [SPACE] pauses / resumes the song.");
    write(0,320,70,4,"Key [0] through key [9] changes the song volume.");
    write(0,320,80,4,"Key [F] fades the song in or out.");

    write(0,320,120,5,"Playing: ");
    write_int(0,320,120,3,&playing);

    write(0,320,140,5,"Paused: ");
    write_int(0,320,140,3,&paused);

    write(0,320,160,5,"Faded in: ");
    write_int(0,320,160,3,&faded_in);

    write(0,320,180,5,"Volume: ");
    write_int(0,320,180,3,&v);

    v=128;
    faded_in=true;

    repeat
        if(key(_enter))
            if(is_playing_song())
                stop_song();
                playing=false;
            else
                play_song(my_song,1);
                playing=true;
            end
            while(key(_enter))frame;end
        end

        if(key(_space))
            if(paused)
                paused=false;
                resume_song();
            else
                paused=true;
                pause_song();
            end
            while(key(_space))frame;end
        end

        if(key(_f))
            if(faded_in)
                faded_in=false;
                fade_music_off(100);
            else
                faded_in=true;
                fade_music_in(my_song,1,100);
            end
            while(key(_f))frame;end
        end

        if(key(_0))v=0;end
        if(key(_1))v=14;end
        if(key(_2))v=28;end
        if(key(_3))v=43;end
        if(key(_4))v=57;end
        if(key(_5))v=71;end
        if(key(_6))v=85;end
        if(key(_7))v=100;end
        if(key(_8))v=114;end
        if(key(_9))v=128;end

        set_song_volume(v);

    frame;
    until(key(_esc))

    exit();
end

Used in example: [key](), [set_mode](), [load_song](), [write_int](), [pause_song](), [play_song](), [stop_song](), [resume_song](), [fade_music_in](), [fade_music_off](), [set_song_volume]().


is_playing_wav()

Definition

INT is_playing_wav ( INT )

Checks to see if Bennu is playing a wave file on the indicated [Sound_channel], started with [play_wav]().

Parameters

INT channel: The [Sound_channel]

Returns

INT : Whether Bennu is playing a song at the moment of calling.


[true] - Bennu is playing a song. [false] - Bennu is not playing a song.


Example

Used in example:


load_song()

Definition

INT load_song ( <STRING filename>, [ <POINTER id>] )

Loads a song for later use with [play_song]().

There are multiple [filetypes] you can load using this [function]. Included are:

  • OGG Vorbis (.ogg). Good quality for [songs] and doesn't take too much space (it's similar to *.mp3).
  • MIDI (.mid). Takes very low space, but it's limited to samples of the soundcard.
  • Modules (.xm, .it, .s3m, .mod). Like MIDI, but Modules also contain the samples themselves.

Parameters


STRING filename - The music file to be loaded, including a possible path. POINTER id - Optional parameter, for loading a song in the background.


Returns

INT : [SongID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The songID of the newly created sound.


the following applies for versions prior rc282:

INT : [SongID]


-1 - Could not load music file (errormessage in console). >=0 - The SongID.


Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_song("archivo_gordo.ogg", &idsong);
      while(idsong==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idsong==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

Example

Program example;
Private
    int song;
Begin
    song = load_song("my_song.ogg");
    play_song(song,0);
    Repeat
        frame;
    Until(key(_ESC))
OnExit
    unload_song(song);
End

Used in example: [play_song](), [key]()


load_wav()

Definition

INT load_wav ( <STRING filename>, [ <POINTER id>] )

Loads a [sound effect] in the WAV format for later use with [play_wav]().

Parameters


STRING filename - The WAV file to be loaded, including a possible path. POINTER id - Optional parameter, for loading a wav in the background.


Returns

INT : [WaveID]


-2 - Waiting for the file to be loaded, see notes. -1 - There was an error loading the file. >=0 - The waveID of the newly created sound.


the following applies for versions prior rc282:

INT : [WaveID]


-1 - Error: sound inactive; opening file 0 - Could not load wave file. >0 - The [WaveID].


Notes

The optional parameter id was introduced in version rc282 and allows you to load resources in the background. It used with the [Offset] operator. See example below:

      load_wav("archivo_gordo.wav", &idwav);
      while(idwav==-2)
            say("Big File Loading ....");
            frame;
      end
      if(idwav==-1)
          say("Something went wrong!!");
          exit(); // o return
      end

      say("Big file loaded ok!!");

Example

Program
Private
    int wave;
Begin
    wave = load_wav("my_wav.wav");
    play_wav(wave,0);
    Loop
        frame;
    End
End

Used in example: [play_wav]()


pause_song()

Definition

INT pause_song ( )

Pauses the currently playing song.

Notes

The song pauses immediately, but can be resumed later by calling [resume_song](). For a nicer effect, you may want to fade the music out before pausing. See [fade_music_off]().

Returns

INT : Error.


-1 - Error: sound inactive. 0 - No error.


Example

program music_example;
global
    my_song;
    playing;
    paused;
    faded_in;
    v;
begin
    set_mode(640,480,16);

    my_song=load_song("beat.ogg");

    write(0,320,30,4,"Use the keyboard to control the music playback.");
    write(0,320,50,4,"Key [ENTER] starts / stops the song.");
    write(0,320,60,4,"Key [SPACE] pauses / resumes the song.");
    write(0,320,70,4,"Key [0] through key [9] changes the song volume.");
    write(0,320,80,4,"Key [F] fades the song in or out.");

    write(0,320,120,5,"Playing: ");
    write_int(0,320,120,3,&playing);

    write(0,320,140,5,"Paused: ");
    write_int(0,320,140,3,&paused);

    write(0,320,160,5,"Faded in: ");
    write_int(0,320,160,3,&faded_in);

    write(0,320,180,5,"Volume: ");
    write_int(0,320,180,3,&v);

    v=128;
    faded_in=true;

    repeat
        if(key(_enter))
            if(is_playing_song())
                stop_song();
                playing=false;
            else
                play_song(my_song,1);
                playing=true;
            end
            while(key(_enter))frame;end
        end

        if(key(_space))
            if(paused)
                paused=false;
                resume_song();
            else
                paused=true;
                pause_song();
            end
            while(key(_space))frame;end
        end

        if(key(_f))
            if(faded_in)
                faded_in=false;
                fade_music_off(100);
            else
                faded_in=true;
                fade_music_in(my_song,1,100);
            end
            while(key(_f))frame;end
        end

        if(key(_0))v=0;end
        if(key(_1))v=14;end
        if(key(_2))v=28;end
        if(key(_3))v=43;end
        if(key(_4))v=57;end
        if(key(_5))v=71;end
        if(key(_6))v=85;end
        if(key(_7))v=100;end
        if(key(_8))v=114;end
        if(key(_9))v=128;end

        set_song_volume(v);

    frame;
    until(key(_esc))

    exit();
end

Used in example: [key](), [set_mode](), [load_song](), [write_int](), [pause_song](), [play_song](), [stop_song](), [resume_song](), [fade_music_in](), [fade_music_off](), [set_song_volume]().


pause_wav()

Definition

INT pause_wav (INT < channel > )

Pauses the currently playing wave channel.

Notes

The sound channel pauses immediately, but can be resumed later by calling [resume_wav](). For a nicer effect, you may want to fade the music out before pausing. See [set_channel_volume]().

Parameters


INT channel - The WAV [sound channel].


Returns

INT : Error.


-1 - Error: sound channel inactive. 0 - No error.


Example

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_proc";
IMPORT "mod_key";
IMPORT "mod_sound";

GLOBAL
   int wav;
   int channel;

PROCESS main();  
BEGIN

  wav=load_wav("wav.wav");

  say("Test pause_wav...");
  say("ENTER = Pause Sound...");
  say("Press ESC to quit...");

  channel=play_wav(wav,-1);

  REPEAT

    IF(key(_enter))
      pause_wav(channel);
      FRAME(2500);
      resume_wav(channel);
    END

    FRAME;
  UNTIL(key(_esc))
END

Used in example: [key](), [resume_wav](), [play_wav]().


play_song()

Definition

INT play_song ( <INT songID> , <INT repeats> )

Plays a song.

Parameters


INT songID - [SongID](). INT repeats - Number of times to repeat the song. Use -1 for an infinite loop.


Returns

INT : Error.


-1 - Error: sound inactive; mixer error; invalid [songID]. 0 - No error.


Errors


Sound inactive - The sound is inactive. Invalid songID - The [songID] was invalid. Other - Some Mixer error.


Example

Program example;
Private
    int song;
Begin
    song = load_song("my_song.ogg");
    play_song(song,0);
    Loop
        frame;
    End
End

Used in example: [load_song]()


play_wav()

Definition

INT play_wav ( <INT waveID> , <INT repeats> , [<INT channel>] )

Plays a [sound effect] previously loaded with [load_wav]().

Parameters


INT waveID - The [WaveID] of the sound effect to be played. INT repeats - Number of times to repeat the sound effect. Use -1 for an infinite loop. [INT channel] - The [sound channel] is to be played on (-1 for any, default).


Returns

INT : The [sound channel] the [sound effect] is now playing on.


-1 - Error: sound inactive; invalid [waveID] >=0 - The [sound channel] is now playing on.


Example

Program
Private
    int wave;
Begin
    wave = load_wav("my_wav.wav");
    play_wav(wave,0);
    Loop
        frame;
    End
End

Used in example: [load_wav]()


reserve_channels()

Definition

INT reserve_channels ( <INT num_channels> )

This functions reserves the indicated number of [sound channels] from the default sound mixing setup. This is usefull if you want to create groups of sound channels, so that you can devide them for different tasks. When you indicate a 0, all reservations are removed. The channels are reserved starting from channel 0 to num_channels -1. Normally SDL_mixer starts without any channels reserved.

Parameters


INT num_channels - The number of channels to reserve.


Returns

INT : Status.


>0 - The number of reserved channels. -1 - Error: sound inactive.



resume_song()

Definition

INT resume_song ( )

Resumes a song, after it has been paused with the function [pause_song]().

Returns

INT : Error.


-1 - Error: sound inactive. 0 - No error.


Notes

The song will instantly start playing again with this function. For a nicer effect, you may want to fade the music in as you resume it. See [fade_music_in]().

Example

program music_example;
global
    my_song;
    playing;
    paused;
    faded_in;
    v;
begin
    set_mode(640,480,16);

    my_song=load_song("beat.ogg");

    write(0,320,30,4,"Use the keyboard to control the music playback.");
    write(0,320,50,4,"Key [ENTER] starts / stops the song.");
    write(0,320,60,4,"Key [SPACE] pauses / resumes the song.");
    write(0,320,70,4,"Key [0] through key [9] changes the song volume.");
    write(0,320,80,4,"Key [F] fades the song in or out.");

    write(0,320,120,5,"Playing: ");
    write_int(0,320,120,3,&playing);

    write(0,320,140,5,"Paused: ");
    write_int(0,320,140,3,&paused);

    write(0,320,160,5,"Faded in: ");
    write_int(0,320,160,3,&faded_in);

    write(0,320,180,5,"Volume: ");
    write_int(0,320,180,3,&v);

    v=128;
    faded_in=true;

    repeat
        if(key(_enter))
            if(is_playing_song())
                stop_song();
                playing=false;
            else
                play_song(my_song,1);
                playing=true;
            end
            while(key(_enter))frame;end
        end

        if(key(_space))
            if(paused)
                paused=false;
                resume_song();
            else
                paused=true;
                pause_song();
            end
            while(key(_space))frame;end
        end

        if(key(_f))
            if(faded_in)
                faded_in=false;
                fade_music_off(100);
            else
                faded_in=true;
                fade_music_in(my_song,1,100);
            end
            while(key(_f))frame;end
        end

        if(key(_0))v=0;end
        if(key(_1))v=14;end
        if(key(_2))v=28;end
        if(key(_3))v=43;end
        if(key(_4))v=57;end
        if(key(_5))v=71;end
        if(key(_6))v=85;end
        if(key(_7))v=100;end
        if(key(_8))v=114;end
        if(key(_9))v=128;end

        set_song_volume(v);

    frame;
    until(key(_esc))

    exit();
end

Used in example: [key](), [set_mode](), [load_song](), [write_int](), [pause_song](), [play_song](), [stop_song](), [resume_song](), [fade_music_in](), [fade_music_off](), [set_song_volume]().


resume_wav()

Definition

INT resume_wav (INT < channel > )

Resumes the currently paused wave channel, that was paused by [Pause_wav]().

Parameters


INT channel - The WAV [sound channel].


Returns

INT : Error.


-1 - Error: sound inactive. 0 - No error.


Example

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_proc";
IMPORT "mod_key";
IMPORT "mod_sound";

GLOBAL
   int wav;
   int channel;

PROCESS main();  
BEGIN

  wav=load_wav("wav.wav");

  say("Test pause_wav...");
  say("ENTER = Pause Sound...");
  say("Press ESC to quit...");

  channel=play_wav(wav,-1);

  REPEAT

    IF(key(_enter))
      pause_wav(channel);
      FRAME(2500);
      resume_wav(channel);
    END

    FRAME;
  UNTIL(key(_esc))
END

Used in example: [key](), [pause_wav](), [play_wav]().


reverse_stereo()

Definition

INT reverse_stero ( <INT channel> , <INT flip>)

This function swaps the stereo of the indicated [sound channel].

Parameters


INT channels - The channel of wich it's stereo is to be reversed. INT flip - The flip, (0 = normal , 1 = reverse).


Returns

INT : Status.


0 - Ok. -1 - There is an error.



set_Wav_Volume()

Syntax

INT set_wav_volume ( <INT waveID> , <INT volume> )

Description

Change the reproduction volume of the wav track.

With this function, it is possible to set the volume of the sound effects, etc.

Parameters


INT waveID - [waveID](). INT volume - New volume. (0..128)


Returns

(assumed) INT : Error.


-1 - Error: sound inactive. 0 - No error.


Notes

This function changes the reproduction volume of the wav track. The volume level can be set between 0 (silence) and 128 (original 100% volume of the track. The default volume is 128.

Example

global
    int my_wav;
    int v;
end

process main()
begin

    set_mode(640,480,16);

    my_wav = load_wav("beat.wav");

    write(0,320,30,4,"Use the keyboard to control the music playback.");
    write(0,320,50,4,"Key [ENTER] starts the wav.");
    write(0,320,60,4,"Key [0] through key [9] changes the song volume.");

    write(0,320,180,5,"Volume: ");
    write_int(0,320,180,3,&v);

    v = 128;

    repeat
        if(key(_ENTER))
            play_wav(my_wav,50);
            while(key(_ENTER))
                frame;
            end
        end

        if(key(_0)) v =   0; end
        if(key(_1)) v =  14; end
        if(key(_2)) v =  28; end
        if(key(_3)) v =  43; end
        if(key(_4)) v =  57; end
        if(key(_5)) v =  71; end
        if(key(_6)) v =  85; end
        if(key(_7)) v = 100; end
        if(key(_8)) v = 114; end
        if(key(_9)) v = 128; end

        set_wav_volume(v);

        frame;
    until(key(_ESC))

end

Used in example: [key](), [set_mode](), [write](), [play_wav]().

This example uses media: [beat.wav]


set_channel_volume()

Definition

INT set_channel_volume ( <INT channel> , <INT volume> )

Change the reproduction volume of the wave [sound channel]. With this function, it is possible to set the channels to different volumes.

Parameters


INT channel - The [sound channel]. INT volume - New volume. (0..128).


Returns

INT : Error.


-1 - Error: sound inactive. 0 - No error.


Notes

This function changes the reproduction volume of the sound channel. The volume level can be set between 0 (silence) and 128 (original 100% volume of the track. The default volume is 128.


set_distance()

Definition

INT set_distance ( <INT channel> , <INT distance> )

Set the "distance" of a [sound channel]. the distance specifies the location of the sound in relation to the listener. If you want also want to have control over the angle, see [Set_position]().

Parameters


INT channel - The [sound channel] to change the position of. INT distance - The distance (0-255).


Returns

INT : Status.


0 - Ok. -1 - Error: sound inactive.


Notes

Distance value's


0 - The sound is near (or at it's loudest). 255 - The sound is far away (very quite).



set_music_position()

Definition

INT set_music_position ( <FLOAT position> )

Set the position of the currently playing music, loaded with [Load_song]() and played with [Play_song]() It only works with the formats supported by those functions. It does not apply to wave files.

Parameters


FLOAT position - Jumps to position seconds from the beginning of the song.


Returns

INT : Status.


position - The position in the music. -1 - Error: sound inactive.



set_panning()

Definition

INT set_panning ( <INT channel> , <INT left> , <INT right> )

Sets the stereo panning of a [sound channel], i.e. set the volumes of the left and right speakers individually.

Parameters


INT channel - The [sound channel] to change the panning of. INT left - The volume of the left speaker (0-255). INT right - The volume of the right speaker (0-255).


Returns

INT : Status.


0 - Ok. -1 - Error: sound inactive.



set_position()

Definition

INT set_position ( <INT channel> , <INT angle> , <INT distance> )

Sets the position of a [sound channel]. With this function you can "emulate" a simple 3d audio effect. If you only want to control the distance, you can use [Set_distance]().

Parameters


INT channel - The [sound channel] to change the position of. INT angle - The angle (0-360). INT distance - The distance (0-255).


Returns

INT : Status.


0 - Ok. -1 - Error: sound inactive.


Notes

Angle value's


0 degrees - Sound is directly in front. 90 degrees - Sound is directly to the right. 180 degrees - Sound is directly behind. 270 degrees - Sound is directly to the left.


Distance value's


0 - The sound is near (or at it's loudest). 255 - The sound is far away (very quite).



set_song_volume()

Definition

INT set_song_volume ( <INT volume> )

Change the reproduction volume of the music track.

With this function, it is possible to set the background music to a different volume than the sound effects, etc.

Parameters


INT volume - New volume. (0..128).


Returns

INT : Error.


-1 - Error: sound inactive. 0 - No error.


Notes

This function changes the reproduction volume of the music track. The volume level can be set between 0 (silence) and 128 (original 100% volume of the track. The default volume is 128.

Example

program music_example;
global
    my_song;
    playing;
    paused;
    faded_in;
    v;
begin
    set_mode(640,480,16);

    my_song=load_song("beat.ogg");

    write(0,320,30,4,"Use the keyboard to control the music playback.");
    write(0,320,50,4,"Key [ENTER] starts / stops the song.");
    write(0,320,60,4,"Key [SPACE] pauses / resumes the song.");
    write(0,320,70,4,"Key [0] through key [9] changes the song volume.");
    write(0,320,80,4,"Key [F] fades the song in or out.");

    write(0,320,120,5,"Playing: ");
    write_int(0,320,120,3,&playing);

    write(0,320,140,5,"Paused: ");
    write_int(0,320,140,3,&paused);

    write(0,320,160,5,"Faded in: ");
    write_int(0,320,160,3,&faded_in);

    write(0,320,180,5,"Volume: ");
    write_int(0,320,180,3,&v);

    v=128;
    faded_in=true;

    repeat
        if(key(_enter))
            if(is_playing_song())
                stop_song();
                playing=false;
            else
                play_song(my_song,1);
                playing=true;
            end
            while(key(_enter))frame;end
        end

        if(key(_space))
            if(paused)
                paused=false;
                resume_song();
            else
                paused=true;
                pause_song();
            end
            while(key(_space))frame;end
        end

        if(key(_f))
            if(faded_in)
                faded_in=false;
                fade_music_off(100);
            else
                faded_in=true;
                fade_music_in(my_song,1,100);
            end
            while(key(_f))frame;end
        end

        if(key(_0))v=0;end
        if(key(_1))v=14;end
        if(key(_2))v=28;end
        if(key(_3))v=43;end
        if(key(_4))v=57;end
        if(key(_5))v=71;end
        if(key(_6))v=85;end
        if(key(_7))v=100;end
        if(key(_8))v=114;end
        if(key(_9))v=128;end

        set_song_volume(v);

    frame;
    until(key(_esc))

    exit();
end

Used in example: [key](), [set_mode](), [load_song](), [write_int](), [pause_song](), [play_song](), [stop_song](), [resume_song](), [fade_music_in](), [fade_music_off](), [set_song_volume]().


sound_close()

Definition

VOID sound_init ( )

Manually Closes the audio system. This is normally not needed, but may be necessary on some systems with SDL mixer issues. It is used in combination with [Sound_init](). (verification needed)

Parameters

This function has no parameters.

Returns

VOID : This function does not return anything.

See also

[Sound_init]()


sound_init()

Definition

INT sound_init ( )

Manually Initializes the audio system. This is normally not needed, but may be necessary on some systems with SDL mixer issues. (verification needed)

Parameters

This function has no parameters.

Returns

INT : Status/error.


0 - The audio device is opened. -1 - There's an error, failed to initialize the audio system.


See also

[Sound_close]()


stop_song()

Definition

INT stop_song ( )

Stops a song loaded with [load_song]() and played with [play_song]().

Parameters

This function has no parameters.

Returns

INT : Status


0 - The song is stopped.



stop_wav()

Definition

INT stop_wav ( INT )

Stops a the playback of sound of the indicated wave [sound channel].

Parameters

' INT' channel: the [sound channel].

Returns

INT : Status


-1 - There is an error.



unload_song()

Definition

INT unload_song ( <INT SongID> )

Frees the memory occupied by the song file, previously loaded with [load_song]().

Parameters


INT SongID - The [SongID] of the song to unload.


Returns

INT : Error.


-1 - Error: sound inactive; invalid [songID]. 0 - No error.


Notes

Instead of an INT a POINTER may also be used in the SongID argument.


unload_wav()

Definition

INT unload_wav ( <INT WaveID> )

Frees the memory occupied by the wave file, previously loaded with [load_wav]().

Parameters


INT WaveID - The [WaveID] of the sound to unload.


Returns

INT : Error.


-1 - Error: sound inactive; invalid [waveID]. 0 - No error.


Notes

Instead of an INT a POINTER may also be used in the WaveID argument.



Strings

asc()

Definition

BYTE asc ( <STRING character> )

Returns the [ASCII] value of the first character of the string character.

Parameters


STRING character - The string of which the ASCII value of the first character will be returned.


Returns

BYTE : The ASCII value of the first character of the string character.

Example

Program asciis;
Begin

    write(0,0, 0,0,asc("A"));
    write(0,0,10,0,asc("CAT"));

    Repeat
        frame;
    Until(key(_esc))

End

Used in example: [write]()


atof()

Definition

FLOAT atof ( <STRING str> )

Returns the [float] value of the number specified in a certain [string].

Parameters


STRING str - The string specifying a number of which the float value will be returned.


Returns

FLOAT : The float value of the number specified by the specified string.


atoi()

Definition

INT atoi ( <STRING str> )

Returns the [int] value of the number specified in a certain [string].

Parameters


STRING str - The string specifying a number of which the int value will be returned.


Returns

INT : The [int] value of the number specified by the specified string.


chr()

Definition

STRING chr ( <BYTE ASCIIvalue> )

Returns the character associated with ASCIIvalue.

Parameters


BYTE ASCIIvalue - The [ASCII] value of which the character is wanted.


Returns

STRING : The character associated with ASCIIvalue.

Example

Program chars;
Begin

    write(0,0, 0,0,chr(65));
    write(0,0,10,0,chr(67));

    Repeat
        frame;
    Until(key(_esc))

End

Used in example: [write]()


find()

Definition

INT find ( <STRING str> , <STRING searchstring> , [<INT startposition>] )

Returns the position of the firstly found appearance of a searchstring in str or -1 if not found. The starting position can be specified optionally.

Parameters


STRING str - The string in which to search. STRING searchstring - The string to search for. [INT startposition] - The position at which to start searching. Default is 0.


Returns

INT : The position of the firstly found appearance of searchstring in str or -1 if not found.

Example

In this example there's a very long string in wich we're going to look for 10 strings. Some of these are found (when the result is > -1), and others are deliberately bogus to show how you can detect if a string is not found. What you'll see, is that when you specify a start position greater then 0, and the word exists but your start position is behind the actual position of the first character of the word you're looking for, the function returns -1 (no match). If you specify 0 (the start of the string), you'll be safe, because it will return the fist occurance of the word or character when it exists in the string.

As you can see, the working of the find function works very similarly to the find and search/replace function that you get in most text editors.

#IFdef __VERSION__
IMPORT "mod_video";
IMPORT "mod_text";
IMPORT "mod_say";
IMPORT "mod_key";
IMPORT "mod_string";
IMPORT "mod_proc";
IMPORT "mod_map";
IMPORT "mod_draw";
IMPORT "mod_debug";
IMPORT "mod_sys";
IMPORT "mod_wm";
#ENDIF

GLOBAL

/* this is the big string in wich we're going to try the find() function on with a couple of tests. */
string string_to_find_in = "hello, world! this is a very long string in wich the 'find' function must find another string. let's try a few things.";

/* these are the strings we're going to test. */
string search_string0 = "wich";
string search_string1 = "wich";
string search_string2 = ".";
string search_string3 = "str";
string search_string4 = "hello";
string search_string5 = "find";
string search_string6 = "i don't exist in the string";
string search_string7 = "me neither";
string search_string8 = "must";
string search_string9 = "a";

/* return values for the tests. a return value of "-1" means that the string could not be found. */
int find_result0;
int find_result1;
int find_result2;
int find_result3;
int find_result4;
int find_result5;
int find_result6;
int find_result7;
int find_result8;
int find_result9;

/* we store the find positions here. */
int find_pos0;
int find_pos1;
int find_pos2;
int find_pos3;
int find_pos4;
int find_pos5;
int find_pos6;
int find_pos7;
int find_pos8;
int find_pos9;

PRIVATE

PROCESS main ();

PRIVATE

BEGIN

   /* experiment with these to try different results. */
   find_pos0 = 0;
   find_pos1 = 45;
   find_pos2 = 118;
   find_pos3 = 0;
   find_pos4 = 0;
   find_pos5 = 70;
   find_pos6 = 0;
   find_pos7 = 0;
   find_pos8 = 94;
   find_pos9 = 94;

   /* INT find ( <STRING str> , <STRING searchstring> , [<INT startposition>] ); */

   find_result0 = find (string_to_find_in, search_string0, find_pos0); /* search_string0 = "wich"; */

   find_result1 = find (string_to_find_in, search_string1, find_pos1); /* search_string1 = "wich"; */

   find_result2 = find (string_to_find_in, search_string2, find_pos2); /* search_string2 = "."; */

   find_result3 = find (string_to_find_in, search_string3, find_pos3); /* search_string3 = "str"; */

   find_result4 = find (string_to_find_in, search_string4, find_pos4); /* search_string4 = "hello"; */

   find_result5 = find (string_to_find_in, search_string5, find_pos5); /* search_string5 = "find"; */

   find_result6 = find (string_to_find_in, search_string6, find_pos6); /* search_string6 = "i don't exist in the string"; */

   find_result7 = find (string_to_find_in, search_string7, find_pos7); /* search_string7 = "me neither"; */

   find_result8 = find (string_to_find_in, search_string8, find_pos8); /* search_string8 = "must"; */

   find_result9 = find (string_to_find_in, search_string9, find_pos9); /* search_string9 = "a"; */

   /* 
             "hello, world! this is a very long string in wich the 'find' function must find another string. let's try a few things.";            
              |                                                                                                                    |
     char pos:0                                                                                                                    118
   */

   /* display the results in the console. */
   say("");
   say("looking for: '"+search_string0+"'");
   say ("search_string0 result: "+find_result0);
   IF (find_result0 == -1)
      say ("no match for: '"+search_string0+"' at the indicated position: "+find_pos0);
   ELSE
      say ("'"+search_string0+"'"+" found at position: "+find_result0);
   END

   say("");
   say("looking for: '"+search_string1+"'");
   say ("search_string1 result: "+find_result1);
   IF (find_result1 == -1)
      say ("no match for: '"+search_string1+"' at the indicated position: "+find_pos1);
   ELSE
      say ("'"+search_string1+"'"+" found at position: "+find_result1);
   END

   say("");
   say("looking for: '"+search_string2+"'");
   say ("search_string2 result: "+find_result2);
   IF (find_result2 == -1)
      say ("no match for: '"+search_string2+"' at the indicated position: "+find_pos2);
   ELSE
      say ("'"+search_string2+"'"+" found at position: "+find_result2);
   END

   say("");
   say("looking for: '"+search_string3+"'");
   say ("search_string3 result: "+find_result3);
   IF (find_result3 == -1)
      say ("no match for: '"+search_string3+"' at the indicated position: "+find_pos3);
   ELSE
      say ("'"+search_string3+"'"+" found at position: "+find_result3);
   END

   say("");
   say("looking for: '"+search_string4+"'");
   say ("search_string4 result: "+find_result4);
   IF (find_result4 == -1)
      say ("no match for: '"+search_string4+"' at the indicated position: "+find_pos4);
   ELSE
      say ("'"+search_string4+"'"+" found at position: "+find_result4);
   END

   say("");
   say("looking for: '"+search_string5+"'");
   say ("search_string5 result: "+find_result5);
   IF (find_result5 == -1)
      say ("no match for: '"+search_string5+"' at the indicated position: "+find_pos5);
   ELSE
      say ("'"+search_string5+"'"+" found at position: "+find_result5);
   END

   say("");
   say("looking for: '"+search_string6+"'");
   say ("search_string6 result: "+find_result6);
   IF (find_result6 == -1)
      say ("no match for: '"+search_string6+"' at the indicated position: "+find_pos6);
   ELSE
      say ("'"+search_string6+"'"+" found at position: "+find_result6);
   END

   say("");
   say("looking for: '"+search_string7+"'");
   say ("search_string7 result: "+find_result7);
   IF (find_result7 == -1)
      say ("no match for: '"+search_string7+"' at the indicated position: "+find_pos7);
   ELSE
      say ("'"+search_string7+"'"+" found at position: "+find_result7);
   END

   say("");
   say("looking for: '"+search_string8+"'");
   say ("search_string8 result: "+find_result8);
   IF (find_result8 == -1)
      say ("no match for: '"+search_string8+"' at the indicated position: "+find_pos8);
   ELSE
      say ("'"+search_string8+"'"+" found at position: "+find_result8);
   END

   say("");
   say("looking for: '"+search_string9+"'");
   say ("search_string9 result: "+find_result9);
   IF (find_result9 == -1)
      say ("no match for: '"+search_string9+"' at the indicated position: "+find_pos9);
   ELSE
      say ("'"+search_string9+"'"+" found at position: "+find_result9);
   END

END

Notes

A first character of a string is at position 0.


format()

Definition

STRING format ( <INT number> )

STRING format ( <FLOAT number> )

STRING format ( <FLOAT number>, <INT number>)

Formats nummerical data for use in a [string]. There are three variants of this function, the first one only formats integers, the second one a floating point number, and the third one uses a fixed number of decimals, as given with the second parameter.

Parameters


INT str - The number to format.



FLOAT str - The decimal number to format.


Returns

STRING : The string with the fomatted number.

Example

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_string";

GLOBAL

int count=400000;
float count2=2.50000;
float count3=456.0000;

PROCESS main();

BEGIN

   say("format test.");
   say("");
   say("");
   say(format(count));
   say(format(count2));
   say(format(count3));

   say(format(count2,0));
   say(format(count2,1));
   say(format(count2,2));
   say(format(count2,3));

   say(format(count3,0));
   say(format(count3,1));
   say(format(count3,2));
   say(format(count3,3));
END

The program outputs this list:

400,000
2.500000
456.000000
3
2.5
2.50
2.500
456
456.0
456.00
456.000

Notes

The format function seems to like US number formats, even on a european machine.


ftoa()

Definition

STRING ftoa ( <FLOAT value> )

Returns a [string] containing a certain [float] value.

Parameters


'''FLOAT ''' value - The value the returned string will contain.


Returns

STRING : The string containing the specified value, including sign and decimal point.


itoa()

Definition

STRING itoa ( <INT value> )

Returns a [string] containing a certain [int] value.

Parameters


INT value - The value the returned string will contain.


Returns

STRING : The string containing the specified value, including sign.


lcase()

Definition

STRING lcase ( <STRING str> )

Returns a [string] identical to a certain string, with the exception that all uppercase characters are replaced by their lowercase counterparts.

Parameters


STRING str - The string in "normal"-form.


Returns

STRING : The string in "lowercase"-form.


len()

Definition

INT len ( <STRING str> )

Returns the length, the number of characters, of a certain [string].

Also called [Strlen]().

Parameters


STRING str - The string of which the length will be returned.


Returns

INT : The length of the specified string.


lpad()

Definition

STRING lpad( <STRING str> , <INT length> )

Returns the string str, padding (adding spaces to) the front of the string if needed to make str of length length. The original string will remain unchanged.

If length is smaller or equal to the length of str, the returned string is str.

Parameters


STRING str - The string to pad (add spaces to). INT length - The minimal length of the returned string.


Returns

STRING: padded string

Example

import "mod_string"
import "mod_say"

Process Main()
Private
    string ABC = "ABC";
    string _ABC;
    string ABC__;
Begin

    ABC = lpad(ABC,2);
    _ABC = lpad(ABC,4);
    ABC__ = rpad(ABC,5);

    say('ABC = "' + ABC + '"');
    say('_ABC = "' + _ABC + '"');
    say('ABC__ = "' + ABC__ + '"');

End

Used in example: [say](), [rpad]()

Result:

ABC = "ABC"
_ABC = " ABC"
ABC__ = "ABC  "

rpad()

Definition

STRING rpad( <STRING str> , <INT length> )

Returns the string str, padding (adding spaces to) the back of the string if needed to make str of length length. The original string will remain unchanged.

If length is smaller or equal to the length of str, the returned string is str.

Parameters


STRING str - The string to pad (add spaces to). INT length - The minimal length of the returned string.


Returns

STRING: padded string

Example

import "mod_string"
import "mod_say"

Process Main()
Private
    string ABC = "ABC";
    string _ABC;
    string ABC__;
Begin

    ABC = lpad(ABC,2);
    _ABC = lpad(ABC,4);
    ABC__ = rpad(ABC,5);

    say('ABC = "' + ABC + '"');
    say('_ABC = "' + _ABC + '"');
    say('ABC__ = "' + ABC__ + '"');

End

Used in example: [say](), [rpad]()

Result:

ABC = "ABC"
_ABC = " ABC"
ABC__ = "ABC  "

strcasecmp()

Definition

INT strcasecmp( <STRING str1> , <STRING str2> )

Compares two strings case-insensitive and returns the result.

Parameters


STRING str1 - The first string. STRING str2 - The second string, to compare with the first string.


Returns

INT: difference


0 - The strings are equal. >0 - The ASCII value of the first differing characters is higher for str1. <0 - The ASCII value of the first differing characters is higher for str2.


Notes

If the strings differ, the ASCII difference between the first differing characters of the strings is actually returned. Let i be the index of the differing characters, then what is returned: ''str1''[''i'']-''str2''[''i''].

Example

import "mod_string"
import "mod_say"

Const
    AB = "AB";
    ABC = "ABC";
    CD = "CD";
    CD2 = "CD";
End

Process Main()
Begin

    say("strcasecmp(AB,ABC) = " + strcasecmp(AB,ABC));
    say("strcasecmp(AB,CD) = " + strcasecmp(AB,CD));
    say("strcasecmp(CD,AB) = " + strcasecmp(CD,AB));
    say("strcasecmp(CD,CD2) = " + strcasecmp(CD,CD2));

End

Used in example: [say](), [strcasecmp]()

Result:

strcasecmp(AB,ABC) = -67
strcasecmp(AB,CD) = -2
strcasecmp(CD,AB) = 2
strcasecmp(CD,CD2) = 0

strrev()

Definition

STRING strrev ( <STRING str> )

Returns a reversed version of a certain [string], meaning the characters are in reversed order.

Parameters


STRING str - The non reversed string.


Returns

STRING : The reversed string.


substr()

Syntax

INT substr ( <STRING str> , <INT startposition> , [<INT characters>] )

Description

Returns a subsection of a certain string.

Parameters


STRING str - The string of which a subsection will be returned. INT startposition - The position of the first character to be in the subsection. [INT characters] - The number of characters the subsection will hold. Negative values are special; see [Notes].


Returns

STRING : The subsection.

Notes

If the number of characters is a negative value, the following applies: the start of the subsection will be startposition; the end of the subsection will be the length of the string minus the absolute value of characters.

Example

Private                             
    String str = "This is my string.";
Begin

    // No specified number of characters
    say( substr(str,2)     + "<" ); // "is is my string."
    say( substr(str,-7)    + "<" ); // "string."

    // Specified number of characters
    say( substr(str,5,2)   + "<" ); // "is"

    // Number of characters greater than length of string
    say( substr(str,2,50)  + "<" ); // "is my string."
    say( substr(str,-7,50) + "<" ); // "string."

    // Negative number of characters
    say( substr(str,5,-5)  + "<" ); // "is my st"

    // Special case
    say( substr(str,0,0)   + "<" ); // "", but pre 0.92: "This is my string."

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [say]()


trim()

Definition

STRING trim ( <STRING str> )

Returns a copy of str without leading or ending whitespace (spaces, tabs, linefeeds, carriage returns).

Parameters


STRING str - The string to trim.


Returns

STRING: trimmed string

Example

import "mod_string"
import "mod_say"

Const
    _ABC_ = " ABC ";
End

Process Main()
Private
    string ABC;
Begin

    ABC = trim(_ABC_);
    say('_ABC_ = "' + _ABC_ + '"');
    say('ABC = "' + ABC + '"');

End

Used in example: [say]()

Result:

_ABC_ = " ABC "
ABC = "ABC"

ucase()

Definition

STRING ucase ( <STRING str> )

Returns a [string] identical to a certain string, with the exception that all lowercase characters are replaced by their uppercase counterparts.

Parameters


STRING str - The string in "normal"-form.


Returns

STRING : The string in "uppercase"-form.



Texts

delete_text()

Definition

INT delete_text ( <INT TextID> )

Deletes a certain [text] from the screen.

Parameters


INT TextID - [TextID] to be deleted.


Returns

INT : [true]

Notes

[Delete_text]) deletes all text from the screen.

Example

Program test;
Global
    my_text;
Begin
    my_text = write(0,320/2,200/2,4,"Press space to delete this.");
    Repeat
        if (key(_space))
            if(my_text>0)
                delete_text(my_text);
                my_text = 0;
            end
        end
        Frame;
    Until(key(_esc))
End

Used in example: [write](), [textID]

This will result in something like:\


get_text_color()

Definition

INT get_text_color( [<INT textID>] )

Gets the current text [color] (the [color] where texts will be written in).

Parameters

INT textID: The identification code of the text (optional parameter, introduced in version rc282).

Returns

INT: [color] the text will be written in, or 0 when there is a problem.

Notes

None.

Errors

<If someone knows, please edit!>

Example

Program test;
Global
    my_text;
    text_color;
Begin

    set_text_color( rgb(192,112,0) );
    text_color = get_text_color();

    write    (0,320/2    ,200/2,4,"The color of this text is:");
    write_int(0,320/2+100,200/2,4,&text_color);

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [set_text_color](), [write](), [key]()

This will result in something like:\


move_text()

Definition

INT move_text ( <INT TextID> , <INT x> , <INT y>, <INT z>)

Moves an existing [text] to another place on the screen.

Parameters


INT TextID - [Identifier of the text] you want to move. This identifier should have been appointed to a text earlier on. INT x - The new horizontal coordinate (of the control point) of your text. INT y - The new vertical coordinate (of the control point) of your text. INT z - The new depthplane (of the control point) of your text. (introduced in version r282)


Returns

INT : TRUE

Notes

The "z" argument is a newer feature, so it is not anvailible in all versions.

Errors

None.

Example

Program test;
Global
    My_text;
Begin
    My_text=write(0,320/2,200/2,4,"Press space to move this.");
    Loop
        If (key(_space))
            Move_text(My_text,rand(0,319),rand(0,199));
        End
        Frame;
    End
End

Used in example: [write](), [rand]()

This will result in something like:\

Example 2

import "mod_text";
import "mod_mouse";
import "mod_key";
import "mod_video";
import "mod_rand";
import "mod_map";

private
    txt[10];
    counter;
    tz;
begin
    set_mode(640,480,32);

    txt[0]=write_int(0,10,10,10,0,&counter);
    txt[1]=write_int(0,10,20,-5,0,&tz);
    txt[2]=write(0,10,10,0,0,"hello world");

    set_text_color(txt[1], rgb(255,0,0));

    while(!key(_ESC))

        counter++;

        move_text(txt[2], mouse.x, mouse.y, tz );

        set_text_color(txt[0], rand(0101010h, 0ffffffh));

        if ( key( _DOWN ) ) tz--; end
        if ( key( _UP ) ) tz++; end

        frame;
    end
end

Used in example: [write](), [write_int](), [rand](), [set_text_color]()


set_text_color()

Definition

INT set_text_color ( [INT < textID>] , <WORD color> )

Sets the current text color (the color where texts will be written in). This only affects 1 bit (2 color) fonts, which can be loaded with [load_font]() or [load_bdf](). 8 bit and 16 bit fonts already contain color information themselves and thus aren't affected.

Parameters


INT textID - The identification code of the text (optional). WORD color - The [color] to use for text.


Returns

INT : [true] if successful and [false] if failed. (Needs confirmation.)

VOID: in version rc282 this function returns nothing.

Notes

Be warned that values returned by the [Rgb]() function differ with the video card. So, directly filling out color numbers as color parameter in 16 bit color mode without using [Rgb]() is a bad idea, as RGB returns the correct color code for every video card

The optional argument textID is fairly new. It is introduced in version rc282.

Errors

None.

Example

Program awesome;
Global
    byte red=0;
    byte green=255;
    byte blue=0;

Begin

    set_text_color(rgb(red,green,blue));
    write(0,1,1,0,"Mijn potlood is bruin"); //this text will be green as an Irishman's ejecta

    set_text_color(rgb(255,0,0));
    write(0,1,11,0,"Je moeder"); //this text will be red

    Loop

        frame;
    End
End

Used in example: [write]()

This results in something like this:\

Example 2

import "mod_text";
import "mod_mouse";
import "mod_key";
import "mod_video";
import "mod_rand";
import "mod_map";

private
    txt[10];
    counter;
    tz;
begin
    set_mode(640,480,32);

    txt[0]=write_int(0,10,10,10,0,&counter);
    txt[1]=write_int(0,10,20,-5,0,&tz);
    txt[2]=write(0,10,10,0,0,"hello world");

    set_text_color(txt[1], rgb(255,0,0));

    while(!key(_ESC))

        counter++;

        move_text(txt[2], mouse.x, mouse.y, tz );

        set_text_color(txt[0], rand(0101010h, 0ffffffh));

        if ( key( _DOWN ) ) tz--; end
        if ( key( _UP ) ) tz++; end

        frame;
    end
end

Used in example: [write](), [write_int](), [key](), [move_text]()


text_height()

Definition

INT text_height ( <INT fontID> , <STRING text> )

Calculates the height in pixels of the specified text in the specified [font].

Parameters


INT FontID - [FontID] of the font for which the height of the text will be the calculated. STRING text - The text of which the height will be calculated.


Returns

INT : The height in pixels of the text in the font.


0 - Invalid or no text; invalid font. >0 - The height in pixels of the text in the font.


See also

  • [text_width]()

text_width()

Definition

INT text_width ( <INT fontID> , <STRING text> )

Calculates the width in pixels of the specified text in the specified [font].

Parameters


INT FontID - [FontID] of the font for which the width of the text will be the calculated. STRING text - The text of which the width will be calculated.


Returns

INT : The width in pixels of the text in the font.


0 - Invalid or no text; invalid font. >0 - The width in pixels of the text in the font.


See also

  • [text_height]()

write()

Definition

INT write ( <INT fontID> , <INT x> , <INT y> , [<INT z>] , <INT alignment> , <STRING text>)

Puts a dynamic text with a certain font on certain coordinates on the screen with a certain [alignment].

Parameters


INT fontID - The [FontID] of the font to be used for the text. INT x - The X coordinate of the text. INT y - The Y coordinate of the text. INT z - The depthplane of the text (optional, introduced in version rc282). INT alignment - The type of [alignment]. STRING text - The text to be used.


Returns

INT : [TextID]


-1 - Error. The text could not be obtained or was empty. >=0 - The [TextID] of the text.


Notes

There is a limit of 511 texts to simultaneously exist on the screen. The program will crash with an error when this number is reached.

The text depth can be changed by adjusting the global variable [text_z].

To write variables to the screen, rather use [write_int](), [write_string](), [write_float]() or [write_var]() than this command.

To write text on a map you can use the command [write_in_map]().

If you write texts with a font and you change any symbol of this font after, all written texts will be updated using the new changed symbols.

Example

Program texts;
Const
    maxtexts = 10;
Private
    int textid[maxtexts-1];
    string str;
    float flt;
Begin

    // Set FPS
    set_fps(60,0);

    // Write some texts
    textid[0] = write(0,0,0,0,"FPS:");
    textid[1] = write_int(0,30,0,0,&fps);
    textid[2] = write_string(0,160,95,1,&str);
    textid[3] = write_float(0,160,105,0,&flt);

    // Update the texts until ESC is pressed
    Repeat
        // Notice the texts get updated as the values of str and flt changes.
        // The same goes for the value of fps.
        str = "This program is running for " + timer/100 + " seconds.";
        flt = (float)timer/100;
        frame;
    Until(key(_esc));

    // Delete the texts
    for(x=0; x<maxtexts; x++)
        if(textid[x]!=0)
            delete_text(textid[x]);
        end
    end

End

Used in example: [set_fps](), [write_int](), [write_string](), [write_float](), [delete_text], [fps]

This will result in something like:\


write_float()

Definition

INT write_float ( <INT fontID> , <INT x> , <INT y> , [<INT z>] , <INT alignment> , <FLOAT POINTER var> )

Writes a [floating point variable] to the screen, which will be automatically updated when the value of the variable changes. The floating point variable will remain on the screen until deleted with [delete_text]().

Parameters


INT fontID - The [FontID] of the font to be used for the text. INT x - The X coordinate of the text. INT y - The Y coordinate of the text. INT z - The depthplane of the text (optional, introduced in version rc282). INT alignment - The type of [alignment]. FLOAT POINTER var - A [pointer].


Returns

INT : [TextID]


-1 - Error. >=0 - The [TextID] of the text.


Notes

There is a limit of 511 texts to simultaneously exist on the screen. The program will crash with an error when this number is reached.

The text depth can be changed by adjusting the global variable [text_z].

Instead of [write_float](), [write_var]() can be used for the same purpose, which is a more general function that allows you to write variables of any type to the screen.

Errors


Too many texts onscreen - There are too many texts on the screen.


Example

Program test;
Private
    float my_float=3.14159265;
Begin

    write_float(0,320/2,200/2,4,&my_float);

    Repeat
        Frame;
    Until(key(_ESC))

End

This will result in something like:\


write_in_map()

Definition

INT write_in_map ( <INT fontID> , <STRING text> , <INT alignment> )

Creates a new [graphic] in memory with the given text on it (without borders around the text) and puts it in the [system file].

Parameters


INT fontID - The [FontID] of the font to be used for the text. STRING text - The text to be used. INT alignment - The type of [alignment].


Returns

INT : [GraphID]


0 - Error. The text could not be obtained or was empty. !0 - The [GraphID].


Notes

This function creates a [graphic] containing the specified [font] and [height] determined by the physical size of the text; the graphic's size will fit the text exactly to the pixel. The graphic will be stored in memory with [FileID] 0 (using the [system file]), and can be obtained at any time by calling its [GraphID]. The graphic can also be unloaded from memory by using [unload_map]().

The centre of the graph ([control point] 0) is given according to the given [alignment]. This gives added functionality of being able to place the graph like texts, yet also using [flags], rotation, [collision](), etc.

Processes can adopt the graphic containing the text, or it can be displayed with some [maps functions], creating a very handy function.

Errors


Invalid font - The specified font does not exist or is invalid.


Example

Program example;
Begin
    Set_text_color(rgb(222,195,140));
    graph=write_in_map(0,"Game programming is awesome!",4);
    repeat
        x=mouse.x;
        y=mouse.y;
    frame;
    until(key(_esc))
End

Used in example: [set_text_color](), [rgb], [y]

This will result in something like:\


write_int()

Definition

INT write_int ( <INT fontID> , <INT x> , <INT y> , [<INT z>] , <INT alignment> , <INT POINTER var> )

Writes an [integer] to the screen, which will be automatically updated when the value of the integer changes. The integer will remain on the screen until deleted with [delete_text]().

Parameters


INT fontID - The [FontID] of the font to be used for the text. INT x - The X coordinate of the text. INT y - The Y coordinate of the text. INT z - The depthplane of the text (optional, introduced in version rc282). INT alignment - The type of [alignment]. INT POINTER var - A [pointer].


Returns

INT : [TextID]


-1 - Error. >=0 - The [TextID] of the text.


Notes

There is a limit of 511 texts to simultaneously exist on the screen. The program will crash with an error when this number is reached.

The text depth can be changed by adjusting the global variable [text_z].

Instead of [write_int](), [write_var]() can be used for the same purpose, which is a more general function that allows you to write variables of any type to the screen.

Errors


Too many texts onscreen - There are too many texts on the screen.


Example

Program test;
Private
    my_integer=0;
Begin

    write_int(0,320/2,200/2,4,my_integer);

    Repeat
        my_integer=rand(1,1000);
        frame;
    Until(key(_ESC))

End

Used in example: [rand]()

This will result in something like:\


write_string()

Syntax

INT write_string ( <INT fontID> , <INT x> , <INT y> , <INT alignment> , <STRING POINTER var> )

Description

Writes a [string] to the screen, which will be automatically updated when the value of the string changes. The string will remain on the screen until deleted with [delete_text]().

Parameters


INT fontID - The [FontID] of the font to be used for the text. INT x - The X coordinate of the text. INT y - The Y coordinate of the text. INT alignment - The type of [alignment]. STRING POINTER var - A [pointer].


Returns

INT : [TextID]


-1 - Error. The text could not be obtained or was empty. >=0 - The [TextID] of the text.


Notes

There is a limit of 511 texts to simultaneously exist on the screen. The program will crash with an error when this number is reached.

The text depth can be changed by adjusting the global variable [text_z].

Instead of [write_string](), [write_var]() can be used for the same purpose, which is a more general function that allows you to write variables of any type to the screen.

Errors


Too many texts onscreen - There are too many texts on the screen.


Example

import "mod_text"
import "mod_key"

Global
    string my_string="Bennu Game Development";
End
Process Main()
Begin

    write_string(0,320/2,200/2,4,&my_string);

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [write_string](), [key]()

This will result in something like:\


write_var()

Syntax

INT write_var ( <INT fontID> , <INT x> , <INT y> , [<INT z>] , <INT alignment> , <VARSPACE var> )

Description

Writes a variable of any kind to the screen, which will be automatically updated when the value of the variable changes. The variable will remain on the screen until deleted with [delete_text]().

Parameters


INT fontID - The [FontID] of the font to be used for the text. INT x - The X coordinate of the text. INT y - The Y coordinate of the text. INT z - The depthplane of the text (optional, introduced in version rc282). INT alignment - The type of [alignment]. VARSPACE var - The name of [any variable].


Returns

INT : [TextID]


-1 - Error. >=0 - The [TextID] of the text.


Notes

Please note that for the [varspace] var parameter no pointer should be filled out, while [write_int]() do require a pointer.

There is a limit of 511 texts to simultaneously exist on the screen. The program will crash with an error when this number is reached.

The text depth can be changed by adjusting the global variable [text_z].

Instead of [write_var](), [write_int]() could be used to write an [int] to the screen, [write_string]() for a [string]() for a [float].

Errors


Too many texts onscreen - There are too many texts on the screen.


Example

import "mod_text"
import "mod_key"

Global
    my_integer=0;
    string my_string="Bennu Game Development";
End

Process Main()
Begin

    write_var(0,0,0,0,my_string);
    write_var(0,320/2,200/2,4,my_integer);

    Repeat
        my_integer=rand(1,1000);
        frame;
    Until(key(_ESC))

End

Used in example: [write_var](), [rand]()

This will result in something like:\



Time

ftime()

Syntax

STRING ftime ( <STRING format> , <INT time> )

Description

Puts a certain time in a certain format.

It returns the specified [string], with certain keywords replaced with their corresponding values, according to the specified time (see [Notes]). The current time is fetched by use of the [function] [time]().

Parameters


STRING format - The format wanted. INT time - The time to be put in the formatted string.


Returns

STRING : The formatted string.

Notes

A list of keywords:


Keyword - Replaced by %a - the locale's abbreviated weekday name. %A - the locale's full weekday name. %b - the locale's abbreviated month name. %B - the locale's full month name. %c - the locale's appropriate date and time representation. %C - the century number (the year divided by 100 and truncated to an integer) as a decimal number [00-99]. %d - the day of the month as a decimal number [01,31]. %D - the same as %m/%d/%y. %e - the day of the month as a decimal number [1,31]; a single digit is preceded by a space. %h - the same as %b. %H - the hour (24-hour clock) as a decimal number [00,23]. %I - the hour (12-hour clock) as a decimal number [01,12]. %j - the day of the year as a decimal number [001,366]. %m - the month as a decimal number [01,12]. %M - the minute as a decimal number [00,59]. %n - a newline character. %p - the locale's equivalent of either a.m. or p.m. %r - the time in a.m. and p.m. notation; in the POSIX locale this is equivalent to %I:%M:%S %p. %R - the time in 24 hour notation (%H:%M). %S - the second as a decimal number [00,61]. %t - a tab character. %T - the time (%H:%M:%S). %u - the weekday as a decimal number [1,7], with 1 representing Monday. %U - the week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. %V - the week number of the year (Monday as the first day of the week) as a decimal number [01,53]. If the week containing 1 January has four or more days in the new year, then it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1. %w - the weekday as a decimal number [0,6], with 0 representing Sunday. %W - the week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. %x - the locale's appropriate date representation. %X - the locale's appropriate time representation. %y - the year without century as a decimal number [00,99]. %Y - the year with century as a decimal number. %Z - the timezone name or abbreviation, or by no bytes if no timezone information exists. %% - %.


Example

import "mod_timer"
import "mod_time"
import "mod_text"
import "mod_key"

Process Main()
Private
    String timestring; // The string holding the formatted time
Begin

    write_string(0,0,0,0,&timestring); // Display the timestring
    timer = 100; // Make it so it updates the timestring immediately

    Repeat
        if(timer>100) // Update the timestring every 1 second
            timer = 0;
            timestring = ftime("%d-%m-%Y %H:%M:%S",time());
        end
        frame;
    Until(key(_esc))

End

Used in example: [write_string](), [time](), [timer]


get_timer()

Syntax

INT get_timer ( )

Description

Returns the time the program has been running in milliseconds.

Returns

INT : The time the program has been running in milliseconds.


time()

Syntax

INT time ( )

Description

Returns the current time, in seconds from January 1st, 1970.

This function is mostly useful for the [function] [ftime](), to display time and date in a particular format. It is also useful in [rand_seed](), to have 'more randomness'.

Returns

INT : The current time, in seconds from January 1st, 1970.

Example

import "mod_time"
import "mod_timer"
import "mod_text"
import "mod_key"

Process Main();
Private
    String timestring; // The string holding the formatted time
Begin

    write_string(0,0,0,0,&timestring); // Display the timestring
    timer = 100; // Make it so it updates the timestring immediately

    Repeat
        if(timer>100) // Update the timestring every 1 second
            timer = 0;
            timestring = ftime("%d-%m-%Y %H:%M:%S",time());
        end
        frame;
    Until(key(_esc))

End

Used in example: [write_string](), [ftime](), [timer]



Variables


Global variables

Argc

[Up to Global Variables] [Up to Internal]


Definition

INT argc

Argc is a [global variable], holding the number of arguments passed when calling [BGDI], including the bytecode file. The arguments can be found in the global variable [argv].


Argv

[Up to Global Variables] [Up to Internal]


Definition

STRING[32] argv

Argv is a [global variable], holding the arguments with which [BGDI] was called, including the bytecode file.


argv[0] - The bytecode file (possibly without extension). argv[1] - First argument. argv[2] - Second argument. argv[n] - nth argument.


If an argument was not given, the corresponding string will be "" (empty string). The number of arguments passed can be found with [argc]. This means that argv[argc-1] is the last argument.

Example

import "mod_say"

Process Main()
Private
    int i;
Begin

    say("Bytecode file: " + argv[0]);

    i = 1;
    while(i<argc)
        say("Argument " + i + ": " + argv[i]);
        i++;
    end

End

Running this on Windows XP:

> bgdi argv mies noot "mies noot" "'mies noot'" "\"mies noot\"" 'mies noot'
Bytecode file: argv
Number of arguments: 8
Argument 1: mies
Argument 2: noot
Argument 3: mies noot
Argument 4: 'mies noot'
Argument 5: "mies noot"
Argument 6: 'mies
Argument 7: noot'

Running this on Linux:

$ bgdi argv mies noot "mies noot" "'mies noot'" "\"mies noot\"" 'mies noot'
Bytecode file: argv
Number of arguments: 7
Argument 1: mies
Argument 2: noot
Argument 3: mies noot
Argument 4: 'mies noot'
Argument 5: "mies noot"
Argument 6: mies noot

Here you can see some interesting things:


text produces an argument word for each word (words are separated by spaces) "text" produces the argument text "'text'" produces the argument 'text'. "\"text\"" produces the argument "text" 'text' doesn't combine multiple words into one argument on Windows, but it does on Linux.


The passing of arguments is totally unrelated to [Bennu] and is OS dependent. Usually the doubleqoutes (" ") work, but as you can see, the single quotes (' ') don't always work to combine multiple words into one argument.


Ascii

[Up to Global Variables]


Definition

INT ascii

Ascii is defined in the module [mod_key] and, in contrast to [scan_code], it contains the last character typed on the keyboard instead of the last key. That means “A” and “a” will have the same [scan_code], but different ascii value.

Example

import "mod_text"
import "mod_key"
import "mod_video"

process main()
begin
    set_mode(640,320);

    write( 0, 60, 10, 0, "Use lower and upper case characters to see the difference");
    write( 0, 60, 20, 0, "between ascii and scan_code.    (ESC to exit)  ");

    write( 0, 60, 40, 0, "ascii: ");
    write_var( 0, 110, 40, 0, ascii);

    write( 0, 26, 50, 0, "scan_code: ");
    write_var( 0, 110, 50, 0, scan_code);

    while ( !key(_esc))
        frame;
    end
end   

Dump_type

[Up to Global Variables]


Definition

INT dump_type = PARTIAL_DUMP

Dump_type is a [global variable], holding the current [dump_mode]. The mode can be changed by assigning a different mode to the variable. Default is [PARTIAL_DUMP].

See also [restore_type].


Exit_status

[Up to Global Variables]


Definition

INT exit_status

exit_status is a [predefined] [global variable], holding whether or not Bennu received a QUIT event this frame. A QUIT event is generated for example by pressing the X button of the window.


Value - Description [false] - There is no QUIT event. [true] - There is a QUIT event.



Fading

[Up to Global Variables]


Definition

INT fading = false

Fading is a [global variable], holding whether the screen is currently fading. This can be caused by the functions [fade]() or [fade_off](). Its value will be [true] if there is fading going on and [false] if not.

Example

Program faders;
Private
    int text_id;
Begin

    // Write something
    text_id = write(0,160,100,4,"Look at this fading text!");

    // Fade screen on and off
    fade_off_and_on();

    // Wait for ESC key
    Repeat
        frame;
    Until(key(_ESC))

    // Kill all other processes and clear up text
    let_me_alone();
    delete_text(text_id);

End

Process fade_off_and_on()
Begin
    Loop
        fade(0,0,0,4); // Fade to black
        while(fading) frame; end // Wait for the fading to finish
        fade(100,100,100,4); // Fade to normal
        while(fading) frame; end // Wait for the fading to finish
    End
End

Used in example: [write](), [let_me_alone](), [delete_text]()


Fileinfo

[Up to Global Variables]


Definition

Struct Fileinfo

Fileinfo is a [global variable] [struct], containing information about a file/directory entry, lastly returned by [glob]().

Members


Member name - Description STRING path - The path to the file/directory (without the name of the file/directory). STRING name - The name of the file/directory. INT directory - [true]: whether the file/directory is a directory or not INT hidden - [true]: whether the file is hidden or not INT readonly - [true]: whether the file is read only or not INT size - The size in bytes of the file/directory. STRING created - The date when the file/directory was created. *. Not available in Unix/Linux** STRING modified - The date when the file/directory was last modified. * STRING accessed - The date when the file/directory was last accessed. * STRING statechg - The date when the file/directory's inode was last modified. *. Only in Unix/Linux**


* - The strings created and modified are in the format: DD/MM/YYYY hh:mm.

** - In Unix/Linux the creation time is not stored. Instead it has a change time (ctime) that indicate when changes to the file or directory's inode (owner, permissions, etc.) were made.


Focus_status

[Up to Global Variables]


Definition

INT focus_status

focus_status is a [predefined] [global variable], holding whether or not the Bennu window has input focus.


Value - Description [false] - The Bennu window does not have input focus. [true] - The Bennu window has input focus.



Fps

[Up to Global Variables]


Definition

INT fps

The [global variable] holds the current frames per second on which [Bennu] is running. This means how many times a frame is executed every second and how many times the screen is updated every second.

If a different FPS is needed, the target FPS can be altered by use of [set_fps]().

If a more accurate FPS is needed, use [frame_time] to calculate it.

If you need to view the FPS in-game, please use the code (in a loop): write_int(0,0,0,0,&fps);


Frame_time

[Up to Global Variables]


Definition

FLOAT frame_time

Frame_time is a [global variable], holding the time passed the last frame. In other words: the difference in time between the start of the last frame and the current frame.

Doing a bit of physics, we see that:

: FPS = 1 / frame_time

Be advised that frame_time is in milliseconds accurate, so it can be 0 at times, so one might prevent such a case from happening:

: FPS = 1 / ( frame_time + (frame_time==0)*0.0001 );

This gives a sort of FPS which is accurate every frame.

Example

Display how long the program has been running, by use of frame_time:

Program timers;
Private
    int ft; // Help variable
    int i;  // how long the program has been running in 1/100s
    float f; // how long the program has been running in 1/100s
Begin

    set_mode(320,400,8);
    write_int   (0,0,300,0,&timer);
    write_int   (0,0,310,0,&i);
    write_float (0,0,320,0,&f);

    Repeat

        // Calculate how long the program has been running in 1/100s without a float
        ft %= 10; // keep the milliseconds from last time
        ft += frame_time*1000; // add the last passed time to it in milliseconds
        i += ft/10; // add it to the integer without the milliseconds

        // Calculate how long the program has been running in 1/100s with a float
        f+=frame_time*100;

        frame;
    Until(key(_ESC))

End

Used in example: [set_mode](), [write_int](), [write_float](), [timer]

Let a [process] wait for a certain time by calling this function:

Function int wait(float seconds)
Begin
    While( (seconds-=frame_time) > 0 ) frame; End
    return -seconds;
End

This can be done with a timer too, as is displayed [here].


Full_screen

[Up to Global Variables]


INT full_screen = false

Description

full_screen is a predefined [global variable]. It defines whether Bennu (libvideo to be more precise) will be rendered in windowed (default) or fullscreen mode.

The value of full_screen can be changed. [false] for windowed mode and [true] for fullscreen mode. For the change to have effect, [set_mode]() needs to be called afterwards.

See also

  • [graph_mode]
  • [scale_mode]

Graph_mode

[Up to Global Variables]


Definition

INT graph_mode

Graph_mode is a [global variable], holding the current [graph mode]. The mode can be changed by assigning a different mode to the variable. Default is 0 and after a call to [set_mode]() it reflects the set graph mode.

See also

  • [sound_mode]
  • [scale_mode]
  • [full_screen]

Mouse

[Up to Global Variables]


Definition

Struct Mouse

Mouse is a [global variable] [struct], containing information about the current state of the mouse. Also graphical settings can be configured to display a [graphic] following the mouse in a certain way.

Members


Member name - Description INT x - The [X]-coordinate of the mouse. INT y - The [Y]-coordinate of the mouse. INT graph - The [graphID] of the mouse. INT file - The [fileID] of the mouse is located. INT z - The [Z]-coordinate of the mouse. INT angle - The [angle] of the mouse process. INT size - The [size] of the mouse process. INT flags - The [render flags] of the mouse process. INT region - The [region] of the mouse process. INT left - [true]: whether the left mouse button is pressed. INT middle - [true]: whether the middle mouse button is pressed. INT right - [true]: whether the right mouse button is pressed. INT wheelup - [true]: whether the mouse wheel is scrolled upwards. INT wheeldown - [true]: whether the mouse wheel is scrolled downwards.


Example

import "mod_map"
import "mod_mouse"
import "mod_wm"

Process Main()
Private
    int dmap;
    int rmap;
    int gmap;
    int bmap;
    int ymap;
    int cmap;
    int mmap;
    int wmap;
Begin

    // Create a dark graph
    dmap = new_map(100,100,8);
    map_clear(0,dmap,rgb(50,50,50));

    // Create a red graph
    rmap = new_map(100,100,8);
    map_clear(0,rmap,rgb(255,0,0));

    // Create a green graph
    gmap = new_map(100,100,8);
    map_clear(0,gmap,rgb(0,255,0));

    // Create a blue graph
    bmap = new_map(100,100,8);
    map_clear(0,bmap,rgb(0,0,255));

    // Create a yellow graph
    ymap = new_map(100,100,8);
    map_clear(0,ymap,rgb(255,255,0));

    // Create a cyan graph
    cmap = new_map(100,100,8);
    map_clear(0,cmap,rgb(0,255,255));

    // Create a magenta graph
    mmap = new_map(100,100,8);
    map_clear(0,mmap,rgb(255,0,255));

    // Create a white graph
    wmap = new_map(100,100,8);
    map_clear(0,wmap,rgb(255,255,255));

    Repeat
        if(mouse.left) // +Red
            if(mouse.right) // +Green
                if(mouse.middle) // +Blue
                    mouse.graph = wmap;
                else
                    mouse.graph = ymap;
                end
            else
                if(mouse.middle) // +Blue
                    mouse.graph = mmap;
                else
                    mouse.graph = rmap;
                end
            end
        elseif(mouse.right) // +Green
            if(mouse.middle) // +Blue
                mouse.graph = cmap;
            else
                mouse.graph = gmap;
            end
        elseif(mouse.middle) // +Blue
            mouse.graph = bmap;
        else // Dark
            mouse.graph = dmap;
        end
        frame;
    Until(exit_status)

End

Used in example: [Mouse], [new_map](), [graph]

Shows some use of maps and the mouse.


Mouse_status

[Up to Global Variables]


Definition

INT mouse_status

mouse_status is a [predefined] [global variable], holding whether or not the mouse cursor is inside the Bennu window.


Value - Description [false] - The mouse cursor is outside the Bennu window. [true] - The mouse cursor is inside the Bennu window.



Os_id

[Up to Global Variables]


Definition

INT os_id

os_id is a [predefined] [global variable], holding the [OS code] of the operating system [Bennu] is currently running on while executing. Default is -1.


Regex_reg

[Up to Global Variables]


Definition

STRING[15] regex_reg

Regex_reg is a [global variable], holding 16 strings. It holds matches when the functions [Regex]() and [Regex_replace]() are used.

Examples

// import modules
IMPORT "mod_say";
IMPORT "mod_debug";
IMPORT "mod_regex";

GLOBAL

   string sourcetext="It's raining cat's and dogs";
   string searchtext="cat"; // the search pattern

   int status;

PROCESS main();

BEGIN

   // print the joined string
   say("");

   // looking for the position of the word "cat"
   status=regex(searchtext,sourcetext);

   say("match found at: "+status);
   say("");

   // the last character of a line. 
   status=regex("$","99 bottles of beer on the wall.");

   say(status+" is the last character position in 99 bottles of beer on the wall.");
   say("");

   say("regex_reg[0]="+regex_reg[0]);
   say("regex_reg[1]="+regex_reg[1]);
   say("regex_reg[2]="+regex_reg[2]);
   say("regex_reg[3]="+regex_reg[3]);

   say("regex_reg[4]="+regex_reg[4]);
   say("regex_reg[5]="+regex_reg[5]);
   say("regex_reg[6]="+regex_reg[6]);
   say("regex_reg[7]="+regex_reg[7]);

   say("regex_reg[8]="+regex_reg[8]);
   say("regex_reg[9]="+regex_reg[9]);
   say("regex_reg[10]="+regex_reg[10]);
   say("regex_reg[11]="+regex_reg[11]);

   say("regex_reg[12]="+regex_reg[12]);
   say("regex_reg[13]="+regex_reg[13]);
   say("regex_reg[14]="+regex_reg[14]);
   say("regex_reg[16]="+regex_reg[15]);
END

Restore_type

[Up to Global Variables]


Definition

INT restore_type = PARTIAL_RESTORE

Restore_type is a [global variable], holding the current [restore_mode]. The mode can be changed by assigning a different mode to the variable. Default is [PARTIAL_RESTORE].

See also [dump_type].


Scale_mode

[Up to Global Variables]


INT scale_mode = SCALE_NONE

Description

Scale_mode is a [global variable], holding the current or to be [scale mode]. The mode can be changed by assigning a different mode to the variable and then calling [set_mode](). Default is [SCALE_NONE].

See also

  • [sound_mode]
  • [graph_mode]

Scale_resolution

[Up to Global Variables]


INT scale_resolution = WWWWHHHH

Where WWWW is the Width and HHHH the Height. [Resolution_modes] can be used.

Description

Scale_resolution is a [global variable] used to resize the screen without changing the real resolution. That means the game still uses the resolution indicated by [set_mode]() but it's displayed on the screen at the one assigned to scale_resolution. Unlike [scale_mode] can work with 32bits but doesn't use any filter.

Scale_resolution takes effect after [set_mode]() only and cannot be used togheter with [scale_mode]. Assigning NULL will cancel the use of scale_resolution.

Example

//This example is a modification of an example taken from Oscar's Manual
Import "mod_video";
Import "mod_text";
Import "mod_key";
Import "mod_map";
Import "mod_proc";
Import "mod_draw";

Process Main()
begin
  set_mode(800,600,32);
  write(0,100,80,0,"SCALE_RESOLUTION's value:");
  write_var(0,300,80,0,scale_resolution);
  proceso();
  repeat
    if(key(_a)) scale_resolution=03200240;end
    if(key(_s)) scale_resolution=06400480;end
    if(key(_d)) scale_resolution=08000600;end
    if(key(_f)) scale_resolution=10240768;end
    if(key(_c)) scale_resolution=NULL;end
    set_mode(800,600,32);
    frame;
  until(key(_esc))
  let_me_alone();
end

Process proceso()
begin
  x=180;y=150;
  graph=map_new(60,60,32);
  drawing_map(0,graph);
  drawing_color(rgb(255,255,0));
  draw_fcircle(25,25,25);
  loop
    frame;
  end
end

Used in example: [set_mode](), [write](), [map_new](), [drawing_map](), [drawing_color](), [draw_fcircle]().

See also

[scale_resolution_orientation], [scale_resolution_aspectratio].


Scale_resolution_aspectratio

[Up to Global Variables]


INT scale_resolution_aspectratio = [Scale_resolution_aspectratio_modes].

Description

Scale_resolution_aspectratio is a global variable used to choose between stretching a screen resized by [scale_resolution] to fill the screen or keeping his aspect ratio.

Example

Import "mod_video";
Import "mod_text";
Import "mod_key";
Import "mod_map";
Import "mod_proc";
Import "mod_screen";

Process Main()
begin
  set_mode(800,600,32);
  write(0,20,20,0,"SCALE_RESOLUTION:");
  write_var(0,160,20,0,scale_resolution);
  write(0,20,30,0,"( Press R) ");
  write(0,20,50,0,"SCALE_RESOLUTION_ORIENTATION:");
  write_var(0,255,50,0,scale_resolution_orientation);
  write(0,20,60,0,"( Press 0, 1, 2 or  ) ");
  write(0,20,90,0,"SCALE_RESOLUTION_ASPECTRATIO:");
  write_var(0,255,90,0,scale_resolution_aspectratio);
  write(0,20,100,0,"( Press A ) ");
  Screen_put(0,png_load("mz800x600.png"));
  repeat
    //Activates/deactivates scale_resolution. 
    if(key(_r))
      while(key(_r)) frame; end   //Wait until the key is released
      if (scale_resolution==0);    //If scale_resolution is not active...
        scale_resolution=08000480; //...then resize the screen 
      else                         //If scale_resolution is already working...
        scale_resolution=NULL;     //...then stop it.
      end
    end 

    //This rotates the screen. Only works when SCALE_RESOLUTION is being used. 
    if(key(_0)) scale_resolution_orientation=SRO_NORMAL;end
    if(key(_1)) scale_resolution_orientation=SRO_LEFT;end
    if(key(_2)) scale_resolution_orientation=SRO_DOWN;end
    if(key(_3)) scale_resolution_orientation=SRO_RIGHT;end

    //This activates/deactivates the ASPECT RATIO. Only works when SCALE_RESOLUTION is being used. 
    if(key(_a))
      while(key(_a)) frame; end
      if (scale_resolution_aspectratio==0);
        scale_resolution_aspectratio=SRA_PRESERVE;
      else
        scale_resolution_aspectratio=SRA_STRETCH;
      end
    end 

    set_mode(800,600,32);
    frame;
  until(key(_esc))
  let_me_alone();
end

Used in example: [write](), [write_var](), [Screen_put]()

File used in example: Mz800x600.png by MZ.

See also

[scale_resolution], [scale_resolution_orientation]


Scale_resolution_orientation

[Up to Global Variables]


INT scale_resolution_orientation = [Scale_resolution_orientation_modes].

Description

Scale_resolution_orientation is a global variable used to rotate a screen resized by [scale_resolution] without changing the real orientation.

Example

Import "mod_video";
Import "mod_text";
Import "mod_key";
Import "mod_map";
Import "mod_proc";
Import "mod_screen";

Process Main()
begin
  set_mode(800,600,32);
  write(0,20,20,0,"SCALE_RESOLUTION:");
  write_var(0,160,20,0,scale_resolution);
  write(0,20,30,0,"( Press R) ");
  write(0,20,50,0,"SCALE_RESOLUTION_ORIENTATION:");
  write_var(0,255,50,0,scale_resolution_orientation);
  write(0,20,60,0,"( Press 0, 1, 2 or  ) ");
  write(0,20,90,0,"SCALE_RESOLUTION_ASPECTRATIO:");
  write_var(0,255,90,0,scale_resolution_aspectratio);
  write(0,20,100,0,"( Press A ) ");
  Screen_put(0,png_load("mz800x600.png"));
  repeat
    //Activates/deactivates scale_resolution. 
    if(key(_r))
      while(key(_r)) frame; end   //Wait until the key is released
      if (scale_resolution==0);    //If scale_resolution is not active...
        scale_resolution=08000480; //...then resize the screen 
      else                         //If scale_resolution is already working...
        scale_resolution=NULL;     //...then stop it.
      end
    end 

    //This rotates the screen. Only works when SCALE_RESOLUTION is being used. 
    if(key(_0)) scale_resolution_orientation=SRO_NORMAL;end
    if(key(_1)) scale_resolution_orientation=SRO_LEFT;end
    if(key(_2)) scale_resolution_orientation=SRO_DOWN;end
    if(key(_3)) scale_resolution_orientation=SRO_RIGHT;end

    //This activates/deactivates the ASPECT RATIO. Only works when SCALE_RESOLUTION is being used. 
    if(key(_a))
      while(key(_a)) frame; end
      if (scale_resolution_aspectratio==0);
        scale_resolution_aspectratio=SRA_PRESERVE;
      else
        scale_resolution_aspectratio=SRA_STRETCH;
      end
    end 

    set_mode(800,600,32);
    frame;
  until(key(_esc))
  let_me_alone();
end

Used in example: [write](), [write_var](), [Screen_put]()

File used in example: Mz800x600.png by MZ.

See also

[scale_resolution], [scale_resolution_aspectratio]


Scan_code

[Up to Global Variables]


Definition

INT scan_code

Scan_code is defined in the module [mod_key] and, in contrast to [ascii], it contains the last key pressed, not the last character. That means “A” and “a” will have the same scan_code, but different [ascii] value.

Notes

Take a look at the [scancodes] for a complete list.

Example

import "mod_text"
import "mod_key"
import "mod_video"

process main()
begin
    set_mode(640,320);

    write( 0, 60, 10, 0, "Use lower and upper case characters to see the difference");
    write( 0, 60, 20, 0, "between ascii and scan_code.    (ESC to exit)  ");

    write( 0, 60, 40, 0, "ascii: ");
    write_var( 0, 110, 40, 0, ascii);

    write( 0, 26, 50, 0, "scan_code: ");
    write_var( 0, 110, 50, 0, scan_code);

    while ( !key(_esc))
        frame;
    end
end   

Scroll

Definition

STRUCT[9] Scroll

Scroll is a global variable struct array, containing information about the current state of the ten available scrolls (0..9). It is used to influence the settings of a scroll window, initiated by start_scroll().

Members of the scroll struct

Member name Description
INT x0 The X-coordinate of the foreground graphic.*
INT y0 The Y-coordinate of the foreground graphic.*
INT x1 The X-coordinate of the the background graphic.*
INT y1 The Y-coordinate of the the background graphic.*
INT z The Z-coordinate of the scroll window (default: 512).**
INT camera The processID of the process to be followed (default: 0).***
INT ratio The ratio in percent the foreground will move related to the background (default: 200).***,****
INT speed The maximum speed of the foreground, 0 for no limit (default: 0).***
INT region1 The region in which the scroll won't move, -1 for none (default: -1).***
INT region2 The region in which the maximum speed is ignored, -1 for none (default: -1).***
INT flags1 The bit flags for the foreground graphic.
INT flags2 The bit flags for the background graphic.
INT follow The scrollID of the scroll window to follow, -1 means none (default: -1).
INT[6] reserved Seven reserved integers.
* These fields become read only when the scroll window is in automatic mode (see notes).
** Processes on the scroll use this z value (see notes).
*** These fields only make sense when the scroll window is in automatic mode (see notes).
**** The ratio is in percent: 200 means the background moves twice as slow.

Notes

There are two main methods of controlling a scroll window. One is the manual way, thus changing the values of the x0,y0,x1 and y1 manually. This mode is used when the camera field is not set (is 0). When it is set with a processID, the scroll window is in automatic mode and will follow that process' coordinates and will try to keep it centered. This can be influenced by other members of the scroll struct.

The foreground is the plane to be controlled and the background moves relative to the foreground. If you want to move the background manually, you first need to set the scroll ratio to 0.

Processes in a scroll take over the z value of that scroll's z. Between processes on the same scroll the local variable z of that process does have the expected effect.


Sound_channels

[Up to Global Variables]


Definition

INT sound_channels = 8

Sound_channels is a [global variable], holding the number of sound channels, which is set when sound is used for the first time, meaning altering the value of this variable will have no effect after sound has been initialized. This number can range from 1 to 32 and the default is 8.

See also

  • [sound_mode]
  • [sound_freq]

Sound_freq

[Up to Global Variables]


Definition

INT sound_freq = 22050

Sound_freq is a [global variable], holding the set sound frequency, which is set when sound is used for the first time, meaning altering the value of this variable will have no effect after sound has been initialized. The higher the frequency, the higher the quality is. Accepted frequencies are:

  • 44100: high quality (recommended)
  • 22050: medium quality (default)
  • 11025: low quality (not recommended)

See also

  • [sound_mode]
  • [sound_channels]

Sound_mode

[Up to Global Variables]


Definition

INT sound_mode = MODE_STEREO

Sound_mode is a [global variable], holding the set [sound mode], which is set when sound is used for the first time, meaning altering the value of this variable will have no effect after sound has been initialized. The mode can be changed by assigning a different mode to the variable. Default is [MODE_STEREO].

See also

  • [graph_mode]
  • [sound_freq]
  • [sound_channels]

Text_flags

[Up to Global Variables]


Definition

INT text_flags = 0

Text_flags is a [global variable]. When a [dynamic text] is created ([write] value will equal the value of text_flags at the moment of creation. The default value is 0.

See also

  • [text_z]
  • [TextID]

Text_z

[Up to Global Variables]


Definition

INT text_z = -256

Text_z is a [global variable]. When a [dynamic text](), etc), its [z] value will equal the value of text_z at the moment of creation. The default value is -256.

See also

  • [z]
  • [text_flags]
  • [TextID]

Timer

[Up to Global Variables]


Definition

INT[9] timer

Timer is a [global variable], holding ten integers. Each [frame] a certain value is added to all of them. This value is the difference in time between the start of the last frame and the current frame, in 1/100 seconds.

So when all the timers are never altered, their values will be 1234 when the program has been running for about 12.34 seconds.

Examples

Display how long the program has been running

import "mod_timers"
import "mod_key"
import "mod_text"

Process Main()
Begin

    write_int(0,0,100,0,&timer[0]);

    Repeat
        frame;
    Until(key(_ESC))

End

Used in example: [write_int](), [key]

This can be done more accurately with the use of [frame_time], which is in milliseconds.

Let a [process] wait for a certain time by calling this function

Function int wait(int t)
Begin
    t += timer[0];
    While(timer[0]<t) frame; End
    return t-timer[0];
End

This can be done without a timer too, as is displayed [here].


Window_status

[Up to Global Variables]


Definition

INT window_status

window_status is a [predefined] [global variable], holding whether or not the Bennu window is visible. For example the window is not visible when it is minimized.


Value - Description [false] - The Bennu window is not visible. [true] - The Bennu window is visible.




Local variables

Angle

[Up to Local Variables]


Definition

INT angle = 0

Angle is a predefined [local variable] which holds the angle (measured in 1/1000 of a degree) at which the [graphic] (assigned by the local variable [graph]) will be drawn. It also influences the result of the [function]().

An angle of 0 means to the right, 90000 means up, 180000 means left and 270000 and -90000 mean down.

Example

To make the graphic of a process spin:

import "mod_grproc"
import "mod_map"
import "mod_wm" // for exit_status
import "mod_key" // for key()

Process Main()
Begin
    graph = map_new(100,100,8);  //Create a cyan square and assign it to 'graph'
    map_clear(0,graph,rgb(0,255,255));
    x = 160;     //Position the graphic's center
    y = 100;     //in the center of the screen
    Repeat
        angle += 1000;    //increase the angle of graphic by 1000 each frame. 1000 = 1 degree.
        frame;
    Until(key(_ESC) || exit_status)
OnExit
    map_unload(0,graph);
End

Used in example: [map_new](), [map_clear](), [map_unload](), [exit_status], [x]

This process will spin the cyan square by 1 degree each frame.


Bigbro

[Up to Local Variables]


Definition

INT bigbro

Bigbro is a predefined [local variable]. Bigbro holds the [ProcessID] of the [process] that was immediately called before by the [father] of the current [process]. There are several other local variables which refer to the ProcessID of a related process:

  • [Father]
  • [Son]
  • [Smallbro]

C_number

[Up to Local Variables]


Definition

The cnumber is variable that is used when there's more then one [scroll] window active, i.e. in a splitscreen configuration with two or more scroll or mode7 windows.

The cnumber indicates in wich window(s) the process is visible. It is only necessary for processes that are intended to visible in a scroll or mode7 window. The default value is 0, wich means that the process is visible in all scroll or mode7 windows. Up to 10 scroll or mode7 windows can be defined, wich are numbered from 0 to 9, wich are enumerated by the predefined constants [C_0], [C_2], [C_5], [C_8].

The cnumbers can be added, and the sum of these indicate the visibility. If there, are for instance 4 scroll windows active, (numbered 0, 1, 2, and 3) and a specific process should only be visible in windows 0 and 2, then you should use:

cnumber = C_0 + C2; // this is 1+4

It is possible to change the value of the cnumber in runtime, wich can be handy in certain situations.

Look for more information about scrolls and mode7 in the articles of the [Start_scroll]() and [Start_mode7]() functions.


Ctype

[Up to Local Variables]


Definition

Coordinatetype modes are used to set the type of coordinatesytem to be used, by assigning them to the [local variable]. Different coordinatesystems have different ways of interpreting the coordinates of a process. There's another local variable which influences the interpretation of a process' coordinate, which is [Resolution].

How to change in which individual [scroll] or [Mode7]-view the process is visible, see [C_number] and [its constants].

List


Constant - Value - Relative to C_SCREEN - 0 - The [ screen]'s top left corner, coordinate (0,0). C_SCROLL - 1 - The foreground graphic of the [scroll] in which the process is shown. C_M7 - 2 - The main graphic of the [Mode7]-view.



Father

[Up to Local Variables]


Definition

INT father

Father is a predefined [local variable]. Father holds the [ProcessID] of the [process] that called the current [process]. There are several other local variables which refer to the ProcessID of a related process:

  • [Son]
  • [Bigbro]
  • [Smallbro]

Example

Program example;
Begin
    first_process();
    Loop
        frame;
    End
End

Process first_process()  // Declaration of the first process
Begin
    second_process();  // Call the second process
    Loop
        frame; // This loop makes "first_process()" a process rather than a function
    End
End

Process second_process()  //declaration of another process
Begin
    x = father.x; // These two lines use the father variable to move this process
    y = father.y; // to the position of first_process, as the father variable here
                  // holds the ProcessID of "first_process()"
    Loop
        frame;  
    End
End

Used in example: [process], [function]


File

: This is about the [filetype]. Did you mean the local variable [file] or the function [file]()?


[Up to Filetypes]


Description

A file is a container for [graphics], identified by a non-negative [integer] (0 or higher). It holds all information about the contained graphics ([pixels], [width], [depth], name, etc). Each of these graphics have a unique identifier inside the file (positive [int]).

A file can be created for example by loading an [FPG] (Fichero Para Gráficos, meaning "file for graphics") into it, by using [fpg_load](), which creates a new file with the graphics from the loaded FPG and returns a unique identifier. Another option is to create a new, empty one by using [fpg_new](). Don't let the name fpg_new() fool you: fpg_new() has nothing to do with the filetype FPG. This is because the FPG format is only for files and not for internal use. There are more ways to load graphics into a file.

A file can be used by using the [local variable] or by using the identifier in the various [functions] with a file parameter.

Don't forget to unload it with [fpg_unload]() after use.

Example

import "mod_map"
import "mod_grproc"
import "mod_key"
import "mod_wm"

Global
    int file_id;
    int file_id2;
End

Process Main()
Begin

    // Load FPG
    file_id = load_fpg("example.fpg");
    file_id2 = load_fpg("example2.fpg");

    // Set locals for display of graph
    file = file_id;
    graph = 1;
    x = y = 50;

    // assign Ship to use example2.fpg
    Ship(300,100,5,file_id2,1); // undefined in this sample

    Repeat
        frame;
    Until(key(_ESC)||exit_status)

End

Used in example: [load_fpg](), [key], [file]. [process]

Media in example: [example.fpg]

Note: nothing will be seen unless you have an [FPG] "example.fpg" with a [graphic] with ID 1.


Flags

[Up to Local Variables]


Definition

INT flags = 0

Flags is a predefined [local variable] which is used to manipulate how the [graphic] of a [process], assigned to its local variable [graph], is displayed.

To alter the effect, change the value of this local variable by assigning it [blit flags]. Like most [bit flags], constants can be added together to combine effects. A horizontally mirrored translucent graphic would need flags B_TRANSLUCENT (4) and B_HMIRROR (1), so flags = B_TRANSLUCENT|B_HMIRROR (5) will do the trick.

Example

To make the graphic of a process spin:

Program mirror
Begin
    mirror_graphic();
    Loop
        frame;
    End
End
Process mirror_graphic()
Begin
    graph = new_map(50,50,8);
    map_clear(0,graph,rgb(0,255,255));
    x = 100;     //Position the graphic 100 pixels
    y = 100;     //from the top and left of the screen
    Loop
        if (key(_l))
            flags = B_HMIRROR; //if you press the L key, your graphic is horizontally mirrored
        else
            flags = 0;
        end       
        frame;
    End
End

The process will mirror its graphic when the key L is held down.


Graph

[Up to Local Variables]


Definition

INT graph = 0

Graph is a predefined local variable which holds the [GraphID] of the process. A [graphic] can be assigned to the process by assigning the [GraphID] of that graphic to graph. Assign 0 to the local variable graph to have the process display no graph. Keep in mind that this doesn't free the memory used by the graphic; to free it, use [unload_map]().

Example

Process cyan_graphic()
Begin
    graph = new_map(100,100,8);   // create a new 100x100x8 map.
    map_clear(0,graph,rgb(0,255,255));   // clear it cyan-colored
    x = 100;     //Position the graphic 100 pixels
    y = 100;     //from the top and left of the screen
    Repeat
        frame;
    Until(key(_ESC))
End

Used in example: [new_map](), [map_clear], [x]


Height

[Up to Local Variables]


Definition

The predefined local variable height is used in [Mode7] windows, and it is assigned to each process. It is therefore only relevant in the coordinate system of mode7 ([Ctype]). It is used to define the height of the process graphics in relation to the semi-3d field. This is not to be confused with the local variable [Z], as that is used to control the depth of the graphical layers.

The height is normally a positive number, because the height of the bottom is 0, and all the processes are placed above it. When the height variable is not defined, it is 0 by default. The graphic base is placed at the indicated height, with the exception when [controlpoint] number 0 is changed (the default is overruled by the [Center_set]() function). In that case, the controlpoint will be placed at that height.


Id

[Up to Local Variables]


Definition

INT id

id is a predefined [local variable]. It contains the [process]' [processID].


Priority

[Up to Local Variables]


Definition

INT priority = 0

priority is a predefined [local variable], holding the priority of the [process]; default is 0.

Using this priority, the order of process-execution can be influenced, because processes with a higher priority are executed before processes with a lower priority.

Example

import "mod_say"
import "mod_proc"
import "mod_timers"

Process A()
Begin
    priority = 0; // Default
    Loop
        say("[" + timer[0] + "] " + "A");
        frame(100000000); // This is very high because Bennu runs without limiter here
    End
End

Process main()
Private
    int f=0;
Begin
    priority = 1; // Set to higher priority than A
    A();
    Repeat
        f++;
        say("[" + timer[0] + "] " + "Main");
        frame(100000000); // This is very high because Bennu runs without limiter here
    Until(f==5)
OnExit
    let_me_alone();
End

Used in example: [say](), [let_me_alone], [priority]

Possible output:

[0] A
[0] Main
[26] Main
[26] A
[50] Main
[50] A
[74] Main
[74] A
[98] Main
[98] A

It can be seen here that regardless of priority, A is first executed, because A is called by Main. As soon as A reaches its [frame] statement, Main continues until its frame statement and this concludes the first frame. The second frame it is shown that the priority has effect: Main is executed before A.


Region

[Up to Local Variables]


Definition

Local variable

INT region = 0

Region is a predefined [local variable]. Region holds the [RegionID] of the [region]' [graphic] should only be displayed in. By default this is region 0, the whole screen.

The graphic of the process is only displayed in its region, even if the x and y coordinates are outside of the region, the part inside the region will still be displayed.

Concept

A region is a rectangular field inside the screen. It can be defined with [define_region]() and can be useful for displaying graphics in only certain parts of the screen and for the function [region_out](). There are 32 regions (0..31) and region 0 is the whole screen.


Reserved

[Up to Local Variables]


Definition

Struct Reserved

Reserved is a [local variable] [struct], containing information that is reserved for [Bennu]'s internals. However, sometimes you may wish to use certain members of it. Using in the sense of reading only, do not under any circumstances alter their values, unless you know what you are doing.

If it's not documented what these members do, their use is reasonably limited. If you want to know what these members do, your programming goals are of a level, where you can also look in the [sourcecode]. This is because most of these members would require a lengthy explanation about what they do and why.

Members


Member name - Description INT ID_scan - Internal use only (formerly [got]). INT process_type - The [ProcessTypeID] of the process. INT type_scan - Internal use only (formerly [got] from within the process). INT status - The status of the process, containing a [status code]. INT changed - Internal use only. INT xgraph_flags - Internal use only ([blit flags]). INT saved_status - Internal use only (for [signals]). INT prev_z - Previous [z] value. INT distance1 - Not used. INT distance2 - Not used. INT frame_percent - Internal use only. INT box_x0 - The x-coordinate of the topleft corner of the process' [graphic] (process.x-graphic.width/2). INT box_y0 - The y-coordinate of the topleft corner of the process' graphic (process.y-graphic.height/2). INT box_x1 - The x-coordinate of the bottomright corner of the process' graphic (process.x+graphic.width/2). INT box_y1 - The y-coordinate of the bottomright corner of the process' graphic (process.y+graphic.height/2).



Resolution

[Up to Local Variables]


Definition

Local variable

INT resolution = 0

[Resolution] is used to alter the precision of the position of [processes] on screen; the level of precision is defined by the value of resolution.

This simulating of fractions in positions is useful for calculations or animations in need of a high precision in order to work properly. It causes the coordinates of all processes to be interpreted as being multiplied by the value of the local variable resolution, associated with that process. So when a process' [graphic] is displayed, it will appear as if the process' [x] and [y] values were divided by the value of resolution. A resolution of 0 is interpreted as if it were 1.

The default value of [resolution] is 0, so set it to 1 if the correct value is needed.

Screen Resolution

The resolution of a screen is the dimensions of the screen in pixels. [Bennu]'s default screen resolution is 320×200 pixels. This can be altered by use of [set_mode]().

Example

import "mod_grproc"
import "mod_time"
import "mod_key"
import "mod_video"
import "mod_map"
import "mod_draw"
import "mod_proc"
import "mod_wm"

Process Main()
Begin

    // Set screen resolution to 320x200 with a color depth of 8bit
    set_mode(320,200,8);

    // Set the FPS to 60
    set_fps(60,0);

    // Set resolution for this process (try changing it to see the effect)
    resolution = 100;

    // Create a 200x200 cyan circle and assign its graphID to the local variable graph
    graph = map_new(200,200,8);
    drawing_map(0,graph);
    drawing_color(rgb(0,255,255));
    draw_fcircle(100,100,99);

    // Set size
    size = 10;

    // Set the coordinates at screen position (160,180).
    x = 160 * resolution;
    y = 180 * resolution;

    // Move around in circles while leaving a trail behind
    Repeat
        trail(x,y,graph,(int)(0.2*size),get_timer()+1000); // create a mini reflection of this process,
                                                // lasting one second
        advance(3*resolution); // advance (3 * resolution) units (= 3 pixels)
        angle+=2000; // turn 2 degrees left
        frame;
    Until(key(_ESC)||exit_status)

OnExit

    let_me_alone();
    map_unload(0,graph);

End

Process trail(x,y,graph,size,endtime)
Begin

    // Get the resolution of the process calling this one
    resolution = father.resolution;

    // Remain existent until the specified endtime was reached
    Repeat
        frame;
    Until(get_timer()>=endtime)

End

Used in example: [set_mode](), [set_fps](), [drawing_map](), [drawing_color](), [draw_fcircle](), [get_timer](), [let_me_alone](), [map_unload](), [resolution], [size], [angle]

Here are a few screenshots with different resolutions to display the effect it can have.

The effect is clearly visible, so when you are moving processes with graphics around the screen, you might want to consider using a resolution of at least 10 in those processes.


Size

[Up to Local Variables]


Definition

INT size = 100

Size is a predefined [local variable] that can be used to stretch or compress a graphic, equally along the horizontal axis and vertical axis. It is defined as a percentage of the original graphic size. The graphics's center will remain at the drawing coordinates when the graphic is drawn.

This variable only has effect for the appearance of a [process] when its local variables [size_x] and [size_y] are both 100. When either is not equal to 100, [size] doesn't affect the appearance of the graphic.

Example

To make the [graphic] of a [process] continually stretch:

Process Main()
Begin
    graph = new_map(50,50,8); // Create a new graphic
    x = 100;                  // Position the graphic 100 pixels
    y = 100;                  // from the top and left of the screen
    Loop
        size += 1;            // Increase the height and width of the graphic by 1 percent each frame.
        frame;
    End
OnExit
    unload_map(0,graph);
End

Used in example: [new_map], [y], [unload_map]()

See also

  • [size_x]
  • [size_y]

Size_x

[Up to Local Variables]


Definition

INT size_x = 100

Size_x is a predefined [local variable] that can be used to stretch or compress a graphic along its horizontal axis. It is defined as a percentage of the original graphic size. The graphics's center will remain at the drawing coordinates when the graphic is drawn.

When either [size_x] of a [process] are unequal to [code]100[/code], that process' [size] has no effect.

Example

To make the [graphic] of a [process] continually stretch horizontally:

Process Main()
Begin
    graph = new_map(50,50,8); // Create a new graphic
    x = 100;                  // Position the graphic 100 pixels
    y = 100;                  // from the top and left of the screen
    Loop
        size_x += 1;          // Increase the width of the graphic by 1 percent each frame.
        frame;
    End
OnExit
    unload_map(0,graph);
End

Used in example: [new_map](), [[x], [y], [unload_map]()

See also

  • [size]
  • [size_y]

Size_y

[Up to Local Variables]


Definition

INT size_y = 100

Size_y is a predefined [local variable] that can be used to stretch or compress a graphic along its vertical axis. It is defined as a percentage of the original graphic size. The graphics's center will remain at the drawing coordinates when the graphic is drawn.

When either [size_x] of a [process] are unequal to [code]100[/code], that process' [size] has no effect.

Example

To make the [graphic] of a [process] continually stretch vertically:

Process Main()
Begin
    graph = new_map(50,50,8); // Create a new graphic
    x = 100;                  // Position the graphic 100 pixels
    y = 100;                  // from the top and left of the screen
    Loop
        size_y += 1;          // Increase the height of the graphic by 1 pixel each frame.
        frame;
    End
OnExit
    unload_map(0,graph);
End

Used in example: [new_map](), [[x], [y], [unload_map]()

See also

  • [size]
  • [size_x]

Smallbro

[Up to Local Variables]


Definition

INT smallbro

Smallbro is a predefined [local variable]. Smallbro holds the [ProcessID] of the [process] that was immediately called after by the [father] of the current [process]. There are several other local variables which refer to the ProcessID of a related process:

  • [Father]
  • [Son]
  • [Bigbro]

Son

[Up to Local Variables]


Definition

INT son

Son is a predefined [local variable]. Son holds the [ProcessID] of the [process] that was last called by the current [process]. There are several other local variables which refer to the ProcessID of a related process:

  • [Father]
  • [Bigbro]
  • [Smallbro]

X

: This is about the [local variable]. Did you mean the scan code [_X]?


[Up to Local Variables]


Definition

INT x = 0

X is a predefined [local variable] that defines the vertical position of the process graph in the screen.

See also

  • [y]
  • [z]

Xgraph

[Up to Local Variables]


Definition

The predefined local variable xgraph is assigned to each process. It is the so called "extended" graphic, and it allows graphics to be displayed that are controlled by the nearest process [Angle]. When the xgraph is defined, the normal variable [Graph] is ignored, and the graphic used for display is determined by the angle.

So when the angle changes, a different graphic is selected from a table (defined as an [Array]). The standard value of xgraph is 0, so normally it isn't used unless it is explicitly specified. Xgraps are usefull in combination with [Mode7], to create graphics with perspectives. This mechanism is similair to how Wolfenstein3D, Doom and Duke Nukem 3D render their sprites. So it's not true 3d, but just a bunch of sprites wich perspective depends on the viewing angle.

How to use it

First, you'll have to make sprites for all intended perspective's. To more angle's you wish, the more perspectives you'll need.

Second, you must place the graphics in order of their angle, in clockwise fashion.

Third, you'll have to make a table with the graphic codes.

GLOBAL

perspective_table[]=4,10,11,12,13; // the length doesn't matter, but the more perspectives you wish, 
                                   // the more graphics you need to have.

Fourth, you'll have to assing the table offset to the xgraph.

xgraph=&perspective_table; // xgraph get's the offset adress of the array.

The [Offset] operator is get's the adress of the data, this is related to pointers.

Remarks

When xgraph is defined, it has to be set to 0 in order to deactivate it.

When a graphic code in the table has a negative number, this graphic will be mirrored horizontally.


Y

: This is about the [local variable]. Did you mean the scan code [_Y]?


[Up to Local Variables]


Definition

INT y = 0

Y is a predefined [local variable] that defines the horizontal position of the process graph in the screen.

See also

  • [x]
  • [z]

Z

: This is about the [local variable]. Did you mean the scan code [_Z]?


[Up to Local Variables]


Definition

INT z = 0

Z is a predefined [local variable] that defines the depth position of the process [graph] in the [screen]. This variable affects what process [graph] will be drawn before other one. A process with higher z will be drawn beneath a process with a lower z.

See also

  • [x]
  • [y]


Constants

Alignment modes

Blit flags

Blur modes

Color depths (MISSING)

Coordinatenumber flags (MISSING)

Coordinatetype modes (MISSING)

Crypt modes (MISSING)

Dump modes (MISSING)

Graph modes (MISSING)

Graphical infotypes (MISSING)

Grayscale modes (MISSING)

Joystick constants (MISSING)

OS codes (MISSING)

Pathfind flags (MISSING)

Predefined graphcodes (MISSING)

Process statuscodes (MISSING)

Readwrite modes (MISSING)

Render flags (MISSING)

Resolution modes (MISSING)

Restore modes (MISSING)

Scale modes (MISSING)

Scale resolution aspectratio modes (MISSING)

Scale resolution orientation modes (MISSING)

Scancodes

Definition

Scancodes are used to identify keys. This is used in the function [key]() and the [global variable] [scan_code]. Note that the global variable [ascii] is very different from this.

List

Constant Value
_ESC 1
_1 2
_2 3
_3 4
_4 5
_5 6
_6 7
_7 8
_8 9
_9 10
_0 11
_MINUS 12
_PLUS 13
_BACKSPACE 14
_TAB 15
_Q 16
_W 17
_E 18
_R 19
_T 20
_Y 21
_U 22
_I 23
_O 24
_P 25
_L_BRACHET 26
_R_BRACHET 27
_ENTER 28
_C_ENTER 28
_CONTROL 29
_A 30
_S 31
_D 32
_F 33
_G 34
_H 35
_J 36
_K 37
_L 38
_SEMICOLON 39
_APOSTROPHE 40
_WAVE 41
_L_SHIFT 42
_BACKSLASH 43
_Z 44
_X 45
_C 46
_V 47
_B 48
_N 49
_M 50
_COMMA 51
_POINT 52
_SLASH 53
_C_BACKSLASH 53
_R_SHIFT 54
_C_ASTERISK 55
_PRN_SCR 55
_ALT 56
_SPACE 57
_CAPS_LOCK 58
_F1 59
_F2 60
_F3 61
_F4 62
_F5 63
_F6 64
_F7 65
_F8 66
_F9 67
_F10 68
_NUM_LOCK 69
_SCROLL_LOCK 70
_HOME 71
_C_HOME 71
_UP 72
_C_UP 72
_PGUP 73
_C_PGUP 73
_C_MINUS 74
_LEFT 75
_C_LEFT 75
_C_CENTER 76
_RIGHT 77
_C_RIGHT 77
_C_PLUS 78
_END 79
_C_END 79
_DOWN 80
_C_DOWN 80
_PGDN 81
_C_PGDN 81
_INS 82
_C_INS 82
_DEL 83
_C_DEL 83
_F11 87
_F12 88
_LESS 89
_EQUALS 90
_GREATER 91
_ASTERISK 92
_R_ALT 93
_R_CONTROL 94
_L_ALT 95
_L_CONTROL 96
_MENU 97
_L_WINDOWS 98
_R_WINDOWS 99

Seek modes (MISSING)

Signal actions (MISSING)

Signals

Description

Signals are used to specify the signal to be sent to a [process] or all processes of a [processType], by passing one of them to the function [signal]() as the signal [parameter]. The reaction a process has on an incoming signal can be influenced by [signal_action]().

List


Constant - Value - Description S_KILL - 0 - Kill the process. S_WAKEUP - 1 - Wakeup the process. S_SLEEP - 2 - Put the process to sleep. S_FREEZE - 3 - Freeze the process. S_KILL_FORCE - 50 - Kill the process forcefully. S_WAKEUP_FORCE - 51 - Wakeup the process forcefully. S_SLEEP_FORCE - 52 - Put the process to sleep forcefully. S_FREEZE_FORCE - 53 - Freeze the process forcefully. S_KILL_TREE - 100 - Kill the process and all its connected descendants. S_WAKEUP_TREE - 101 - Wakeup the process and all its connected descendants. S_SLEEP_TREE - 102 - Put the process and all its connected descendants to sleep. S_FREEZE_TREE - 103 - Freeze the process and all its connected descendants. S_KILL_TREE_FORCE - 150 - Kill the process and all its connected descendants forcefully. S_WAKEUP_TREE_FORCE - 151 - Wakeup the process and all its connected descendants forcefully. S_SLEEP_TREE_FORCE - 152 - Put the process and all its connected descendants to sleep forcefully. S_FREEZE_TREE_FORCE - 153 - Freeze the process and all its connected descendants forcefully.


A descendant is connected when all its ascendants up until the process are still alive.

Note: The constants S_FORCE, S_TREE and ALL_PROCESS are for internal use only.

More info

General

Tree

In addition to these there are the following signals that have the same effect, but affect a range of processes, not just a single process:

These will have the effect of their non-tree counterparts, but will affect the process indicated by the [processID] parameter and all of the processes created by those processes, either directly, or indirectly. So if an S_KILL_TREE signal is sent to a process, that process will die, all of the processes that it created will die, and all of the processes that they created will die, and so on. The exception to this is where there is an [orphan process], that is a process to whose [father] is already dead, because the grandfather process of the orphaned process cannot know the orphaned process is a descendant of his.

Forcefully

All normal (=non forced) signals have a forceful equivalent, meaning they get carried out whether the target process ignores it or not:

Normal incoming signals can be influenced by [signal_action](), but these signals cannot be influenced. This means that sending a process S_KILL_FORCE it will be killed.


Sound modes (MISSING)