100% found this document useful (1 vote)
1K views

Manual Blitz Basic 3D

Uploaded by

Jürgen Lillge
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views

Manual Blitz Basic 3D

Uploaded by

Jürgen Lillge
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 432

BLITZ

BASIC
3D
MANUAL ripped by
Ampóstata
From the original
HTML files
Learning how to program Blitz BASIC
You want to learn the first steps so you can evantually write a game? Well you've come to the right place.

Blitz Basic uses a specially designed and easy to use programming language so that it is easy to follow and requires
no previous knowledge of programming, just a love of games and your ideas.

So, welcome to the BASIC guide to Blitz - where the only restrictions are your imagination. The sole purpose of this
section is to teach you how to write your own Blitz Basic programs. The traditional description of a program is a
task that you want your computer to perform via a set of instructions. The task is described to the computer using an
instruction set Blitz Basic can understand. The instructions in your program must be written using a set of rules
known as Syntax. You must follow these rules if you are to write Blitz Basic programs. With lots of practice and a
sprinkle of determination you will gain a firm and confident understanding about the general rules of BASIC and
how to use them as a programmer - When you have this working knowledge of Blitz Basic, the types of games you
create are entirely up to you, but with a little imagination you could be writing the next hit game.

If you didn't know - BASIC is an acronym for Beginners All-purpose Symbollic Instruction Code. In this mini
course you'll learn the BASIC language as implemented in Blitz and the planning of good programming structures.

Hello World Hello Me or Hello sheep! Hello cup of tea!

OK - lets start with the Print command - this simply prints any text onto your screen - like this:

print "Hello sheep"


print "Hello cup of tea"
End

just simply type it into your ide...

...and click on the red rocket to run....


Well done - you've just written your first Blitz program.

You can also include comments/notes in your programs - this is highly recommended and is good programming
practice also. You do this by placing a semi-colon (;) into your program then just type your text eg:

Print "George Bray" ; This piece of code is for printing your name to the screen

You can also stop the machine with the End command - this will break your program at any point that you want it to
end.

You can give your code a title too by typing AppTitle "gamenamehere"

OK let's learn how Blitz works in interpreting your programs and what you'll need to know to write them...

Data

These are the main items in programming. Data is represented to in three basic forms. The first is a whole number
which is known as an Integer eg. 8,20,100,1000. The second type is a Real Number, this allows decimal points eg.
1.2, 48.20, 100.4, 3000.201. The third type of data is a String which is basically something that is not a number, all
strings consist of characters enclosed within quotation marks. A string can include numbers eg "A", "1", "Blitz
Basic", "Commodore 64", "Sheep".

Variables

A Variable is used to store Data - to simplify this - Imagine a Variable as being one big box and within that box you
can store an item plus more boxes if required. An example would be:

A=2+2

You can also print the contents of a variable to the screen:

A=2+2
Print A

Another example would be:

A=1
B=2
C=A+B
PRINT C

If we break this down - we have 3 variables here A & B - which store 2 numbers and finally variable C which is a
calculation that is based on the values stored within variables A & B so the calculation is actually C = 1 + 2. The
result is then stored in C and printed to the screen.

Variables can also store Real Numbers and Strings In order to allow a variable to store these other types of data,
you must make sure you tell the computer whether it is a Integer, Real Number, or a String variable. To specify a
real number variable, you must add a hash sign (#) as the last character of the variable name. If you want your
variable to store a string, you must add a dollar sign ($) as the last character of the variable name eg:

A# = 1.2
B$ = vic20
Print A#:Print B$

You can also create mathematical functions using String variables eg:

A$ = "Welcome to "
B$ = "the world "
C$ = "of programming."
D$ = A$ + B$ + C$
Print D$

When you run this program, it will print Welcome to the world of programming on your screen.

Easy eh?

Arrays

Arrays are very important because you can store lots of data under a single name. You can even pinpoint an item of
data and use it from within an array. If for example you want to store 7 days of the week, you would have to create 7
different variables eg.

day0$ = "Monday"
day1$ = "Tuesday"
upto
day6$ = "Sunday"

But with an Array you can create a different kind of variable that can store more than one item of data. eg. For days
of the week you might go:

Dim day$(6) ; Dim the array... 7 elements (0 to 6)


day$(0)="Monday" ; Set the array data
day$(1)="Tuesday"

You can then just include:

Print day$(3)

Which would print Thursday

To print the seven days of the week we would include a FOR NEXT loop for example:

For loop = 0 to 6
Print day$(loop) ; loops through and prints the data.
Next ; this continues until loop is equal to 6 then continues with the next line of your program.

You can also you the STEP command when creating a FOR/NEXT loop eg. If you were to create a FOR/NEXT
loop followed by STEP 2 the computer would count up the for next loop in increments of 2 eg. 2, 4, 6. So if we were
to apply this to our days of the week program:

For loop = 0 to 6 step 2

The computer would then print only Monday Wednesday Friday & Sunday.
You can also step backwards by placing a minus (-) sign after the command with the number of steps backwards you
would like to take:

For A = 10 To 0 step -2
Print A
Next

This would print: 10 8 6 4 2 0

One final point on Arrays - As documented earlier they are very versatile as they can store many levels of data so
by:

Dim day(7,5)

Here we are setting up the arrays 0 - 6 but for each one there is another 5 boxes of data numbered 0 - 4 upon which
more data can be stored. So if you think back to your boxes - here we have 7 boxes with 5 boxes inside, so in all you
can store 35 values (7x5) in this array. So data entry into the Array you would create something like this:

day(0,0) = 10
day(0,1) = 20
day(0,2) = 30
day(0,3) = 40
day(0,4) = 50
day(1,0) = 100
day(1,1) = 200
day(1,2) = 300
day(1,3) = 400
day(1,4) = 500

As you can see arrays need to be declared as a particular type - Integer, Real Number & String. You can have an
array of integer, real numbers or strings but you cannot have multiple types in the same array.

Mathematical Commands

The dreaded mathematical side of computers but DON'T PANIC - I'm no mathematician either. I'll just give you a
quick run down on the "boring" side of things - don't worry - with a little patience you will be familiar with all these
functions in no time as we will make the computer do all the hard work. Just relax - make a nice steaming hot cup of
tea & read on.....

OK - lets start with the easiest stuff - Add, Subtract, Divide and Multiply. In computer terms these are represented
by(+) (-) (/) (*) respectively. A simple example would be:

A=2+2
B=2*2
C=2-2
D=2/2
Print A: Print B: Print C: Print D

The result would print: 4 4 0 1 to the screen - But you knew that.... You can also assign letters in mathematical
functions:

A+B
A-B
A*B
A/B
Boolean Stuff

This is where you must have a cup of tea in your hand because it's time to focus! Once you've cracked this - you are
well away to mastering the normally hated mathematical side of programming...

OK - Here goes...Sitting comfortably?

Boolean operators allow your program to perform logical operations on your data.

We have the AND and OR operator - this works with any integer.

The basics are (study the logic in these examples - it is pretty straight forward)

agecategory$=Input("What is the age restriction on this film 15 or 18? ") ; Asks a moderator to set the age
rating for a film
age$=Input("What is your age: ") ; Then asks a viewer their age
If agecategory$ = 18 And age$<18 Or agecategory$ = 15 and age$< 15 Then Print "Your are not allowed to
view this film - Sorry" ; using AND OR expressions decides if they are too young
If agecategory$ = 18 And age$>18 Or agecategory$ = 15 And age$>15 Then Print "Enjoy your film." ; Using
AND OR expressions decides if they are old enough
WaitMouse ; waits for the mouse button to be pressed
End ; Once the mouse button has been pressed - Ends the program.

We can compare not only numbers, but strings (text) also. We have seen '=' used in 'agecategory$ = 18' so what does
'less than' & 'more than' mean for strings? One thing it does not mean is 'shorter than', so we don't make that
mistake. We make the definition that one string is less than another if it come first in alphabetical order, thus

Smith < Smythe


Smythe > Smith
Sheep < Shop
Shop > Sheep

all hold. <= means is 'is less than or equal to'and so on - just as for numbers.

We then have the NOT operator.

This is simply used to say:

If agecategory$ not <> 18 - Is the same as A = B. It really is that straight forward.

You will discover how useful these operators become when writing conditions for your programs.

Storing DATA using the READ command

Storing data will become an important and useful way to hold and read numbers or strings (text) easily. These can
be used for storing many different types of data eg. Level Data (formations that aliens might attack or data for
landscapes/scenery within your game etc). Here's a basic example of the READ/DATA commands:

Example1

Read a,b,c ;read next 3 data items into variables a, b and c


Print a+","+b+","+c ;print out their values
Data 1,2,3 ;the actual data items

Example 2
Restore second ;start reading data from the '.second' label
Read a,b,c ;read in data
Print a+","+b+","+c ;print out variables
Restore first ;start reading data from the '.first' label
Read a,b,c ;read in data
Print a+","+b+","+c ;print out values
.first
Data 1,2,3 ;data items
.second
Data 4,5,6 ;more data items

You may have notice that I threw in the RESTORE command within example 2. This is used to reset the data
pointer at any time. In a games programming environment you may need to read the same data again eg. If you want
to clear the screen & redraw it using your data table - by resetting the pointer the Read command will start at the top
of the data list and you can read it again.

GOTO Command

I always remember this command by saying goat-to in my head when calling this command :) - OK - type in
following:

Print "Emily & Ellis were here today"


Goto goat

.goat
Print "So was George and his furry animals"

So here we are printing our text - then jumping to a label called .goat the program then continues reading the rest of
your program from the label you have set downwards.

Subroutines

Often a particular sequence of commands gets used several times too within a program. You may be able to avoid
writing the sequence several times by judicious use of GOTO commands; but this isn't always good enough. The
command GOSUB is like a GOTO that remembers where it came from on meeting another command RETURN
the program jumps back to the line after the particular GOSUB that it originally started from. The GOSUB must be
followed by a label eg. Gosub sheep which sends the program to the series of commands beginning on line .sheep -
The part of the program that lies between .sheep and the RETURN command is known as a subroutine. An
example of the GOSUB command would be:

Print "Baa Baa" ; Prints text to the screen


Gosub sheep ; Goes to the subroutine .sheep
WaitMouse ; The computer return(s) here! - waits for the mouse button to be pressed
End ; End(s) the program when the mouse button has been pressed.

.sheep ; subroutine sheep


Print "Blitz Basic" ; Prints text to the screen
Return ; Return(s) to the next line after gosub command.

FOR NEXT Commands

OK - I'll breifly explain the FOR...NEXT commands - these beasts have already been used in an earlier example if
you never realised! These two commands create a technique known as a loop - so your computer performs any
given task several times. Try out the following program. follows.
For a = 0 To 100 ; set up loop with a as a counter ranging from 0 (start) to 100 (finish)
Print a ; prints the current value of a
Next ; Is a 100? No, it's 1. Add 1 to a to get 2 and go back to line Print a
Your program continues here... ; When a does equal 100 the program ends the loop and continues to run here.

The result will be that the computer prints the numbers 0-100 on your screen.

STEP size

When you are creating a loop - you can also write it as below.

For a = 0 To 100 Step 10 ; The same as the previous example except the computer will count in STEPS of 10 at a
time
Print a ; Prints the current value of a
Next ; If a does not equal 100 then add 10 to it and goes to the line above Print
Your program continues here... ; When a does equal 100 the program ends the loop and continues to run here.

So the program will now give the result:

0
10
20
30
40
50
60
70
80
90
100

As opposed to printing out 1-100 sequencially - as per previous FOR...NEXT loop example.

Functions

Using functions - Part 1

Now that you are getting to grips with the very "basics" of Basic programming (eg. For...Next)! A function allows
you to run a commonly used piece of code. For example, this is a function which prints "Hello" to the screen
whenever you "call" it:

Function PrintHello ()
Print "Hello"
End Function
For a=1 To 5 ; Let's print "Hello" 5 times by calling the PrintHello () function:
PrintHello ()
Next

Now run the program to see the result.

Using Functions - Part 2

OK, now we'll modify the function so that it'll print whatever we want, which can be different each time we call it.
The function:

Function PrintSomething (a$)


Print a$
End Function
; In this case, we "pass" a string (either a string variable such as blah$, or a piece of text enclosed in quotes, eg.
("Hello there") to the function
PrintSomething ("Hello, I'm gonna be printed.")
PrintSomething ("So am I.")
; Using a string variable
sentence$="This is also being printed to the screen." PrintSomething (sentence$)
So, whatever is put within the brackets () when you call it is "passed" to the function. If you look at the function
itself, you'll see that it takes the form "PrintSomething (a$)", which means it's expecting you to pass a string
variable, as we've done above.

Note that "a$" could be named anything at all - "b$" "sometext$" whatever.

Look inside the function, and it takes whatever is passed into its "a$" parameter and uses it in the Print call ("Print
a$").

As an exercise, try changing "a$" to "b$". Make sure you change "a$" to "b$" all throughout the function, or it won't
work! Do that before continuing, then run it.

Here's what you should have ended up with:

Function PrintSomething (b$)


Print b$
End Function

Now try changing the string to something of your own choosing (as long as it ends with the $ string sign!)

Using functions - Part 3

OK, so that was a very simple function call, where a function basically acted like any other command. Now we'll
look at another way to call functions. We can have them perform a calculation and "return" a value to us.

The function:

Function JoinString$ (a$)


Return "You passed: "+a$
End Function
; Again, we "pass" a string to the function, but this time, we store what the function returns.

mysentence$=JoinString ("Hello, I'm gonna be printed.") Print mysentence$

Run the program as before - now what happens here?

First of all, looking at the function itself, we know we're returning a string from the function (it's joining "You
passed: " onto whatever string you pass to it), so we add a $ (string) sign to the name of the function ("JoinString"),
which gives us "JoinString$". The "Return" statement passes the joined string back to where we called it.
Remember, this is why we added a "$" to the name; we're returning this STRING. Calling the function, we simply
pass whatever string we want, and it's received into our string variable (in this case, "mysentence$"). So
mysentence$ becomes "You passed: Hello, I'm gonna be printed." once we call the function.

Some exercises:
Try changing the name of the variable "mysentence$" to something of your own, eg. b$, something$, whatever.
Note that you'll have to change it in the Print statement too! Run it.

Change the "You passed: " string within the function to something else, and change the string you're passing
("Hello, I'm gonna be printed"). Run it. Try a few different things.

Using Functions - Part 4

By default, a function returns either:

0 - (zero) for numeric values "" - (an empty string) for string type functions

Function AddOneAndOne ()
a=1+1
End Function ; This will return 0, because we haven't told it to actually return the result of 1+1!
Print "Result of AddOneAndOne: "+AddOneAndOne () ; Try adding a line saying "Return a" (without the
quotes!) to the AddOneAndOne function, then run it again. NOW it returns the value!
Function GimmeString$ ()
a$="If you can read this, you must have fixed this function!"
End Function
b$=GimmeString ()
If b$=""
b$="GimmeString doesn't return a value!"
Else Print b$
EndIf
Print "Result of GimmeString (): "+b$

Exercise: add the necessary line to the function so that it returns a$, then run it again.

IF...THEN Commands

The IF statement works out the condition of something as either true or false. If the condition is true then the
statement after THEN is executed, but otherwise it is skipped over. The most useful conditions compare two
number or two strings. You can test whether two numbers are equal, or whether one is bigger than the other and they
can test whether two strings are equal, or whether one come before the other in alphabetical order. They use the
relations =,<,>,<=,>=, and <>. If you've not experienced these signs before they represent the following:

Sign Meaning

= Equals
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
<> is unequal to

Take the following example:

.start ; sets up the label start


question$ = Input ("Shall I tell you the meaning of life yes/no? " ; prints a question - waits for users input
If question$ = "no" Then Print "Alright, Then I won't"; IF input = no THEN print text
If question$ = "yes" Then Print "42" ; IF input = yes THEN print text
If question$ <> "yes" Or "no" Then Goto start ; IF input is not equal to either yes or no THEN GOTO start

We can also achieve the same effect with numbers too:


number = Input ("How old are you ") ; prints a question - waits for users input
If number < 18 Then Print "You are under 18" ; IF input is smaller than 18 THEN print text
If number > 18 Then Print "You are over 18" ; IF input is greater than 18 THEN print text
If number = 18 Then Print "you are 18" ; IF input is equal to 18 THEN print text

The expression IF THEN can be any combination of values, variables, arrays and operators providing the
expressions are logical.

IF ENDIF

On a similar principal to the IF command - instead of a THEN command ENDIF points to the end of the commands
to be executed - the example below shows you this principle:

commodore = 20 ; sets up the variable for commodore


atari = 20 ; sets up the variable for atari
If commodore = atari ; IF both variables are the same...(execute the code between here and ENDIF)
Print "Welcome to the machine - commodore and atari..." ; code to be executed if the values are the same.
EndIf ; Execute and ENDIF they are equal

The above code is the same as typing:

IF commodore = atari THEN PRINT "Welcome to the machine - commodore and atari..."

If you change the values of commodore and atari - so they are both different - see the end result?

You can also make your program follow a different chain of events if the values are not equal to. Here we introduce
the ELSE command - so you would point this to a different piece of code that you wanted to execute - like below:

IF commodore = atari
PRINT "The values are equal to"
ELSE
PRINT "The values are different"
ENDIF

You must remember that when the command THEN is not used you must use ENDIF - You will should also note
that ENDIF is used whether or not the ELSE command is used.

Types

Using normal arrays (as documented earlier) we can store important information about, for example, our players'
positions:

player = 3
x = 640
y = 480

Dim players (player, x, y)

players (2, 100, 100) ; this sets player 2's on-screen position to x = 100, y = 100

This is fine, but what if we want to add more players? We have to re-Dim the array with the maximum number of
players! It can also be quite difficult to remember what each element in the array stands for when you have a lot of
elements, eg.
Dim playerdata (player, x, y, animframe, weaponselected, lives, rockets, jewelscollected, blah, blah2)

Try just changing the "rockets" element later on when you can't see the actual list of elements without scrolling all
the way back up!

A way around this general awkwardness is to use types. Whereas with the array, we made a "playerdata" array, here
we'll make a "playerdata" type instead:

Type playerdata
Field player
Field x
Field y
Field animframe
Field weaponselected
Field lives
Field rockets
Field jewelscollected
Field blah
Field blah2
End Type

Think it looks complicated? Well, let's take a look:

Type playerdata

This line simply creates a new type (you'll also hear types referred to as "objects", so this might be called a
"playerdata object").

Field player
Field whatever

The field lines simply say what information we want to hold in the playerdata object.

End Type

This just signifies the end of our type definition. Don't forget it!

OK, in the array example, we wanted to change the rocket element (we'll give 'em 1000 rockets), which would mean
typing something like:

playerdata (player, x, y, animframe, weaponselected, lives, 1000, jewelscollected, blah, blah2)

Ouch, what a lot of typing! And I hope you remembered the order of the items (gosh, and you probably had to scroll
all the way back up to find the definition of the array elements as well)! The efficient (read: cleverly lazy)
programmer will use types instead. Using our playerdata type:

playerdata\rockets = 1000

Now, not only is that shorter, but we didn't have to remember where to place the rockets value either (in fact, we
couldn't even accidentally put it in the wrong place, since we're specifically saying "makes the rockets value equal
1000").

Note the way we access the type data, with a backslash like this: \

To read the jewelscollected value into a temporary variable and show the value, we'd do this:
temp = playerdata\jewelscollected : Print temp

Of course, there's nothing to stop us printing the value directly:

Print playerdata\jewelscollected

One very important aspect of using types is that you must tell Blitz that you're going to be assigning a variable with
a custom type. If we want to make two players using the playerdata type, we do this:

player1.playerdata = New playerdata


player2.playerdata = New playerdata

This can be read as "create a new playerdata object called player1" and "create a new playerdata object called
player1". From here on, we can do whatever we like with our newly defined player objects.

It's important to remember this step, as you can't simply do this:

player1.playerdata\rockets = 1000

...without first creating the player1 playerdata object, as above!

To recap, if we want to use an object called "zoolook", of type "whatever", we do this:

; Define our object structure:

Type whatever
Field something
; As many fields of information as needed for the zoolook objects
End Type

zoolook.whatever = New whatever

Now we can use our zoolook object.

Where types can become really powerful is if we just need a heap of similar objects (for instance, the aliens in a
"Space Invaders" clone), and want an easy way to define and manipulate them.

Type invader
Field x
Field y
End Type

We can set up a huge number of alien invaders with a simple loop:

For a = 1 to 100
alien.invader = New invader
alien\x = Rnd (GraphicsWidth)
alien\y = Rnd (GraphicsHeight)
Next

This appears to keep redefining a single object over and over! The strange thing about types, though, is that when
we create a new object, we're actually creating a *reference* to an object, rather than the object itself.

Every time you say:

something.mycustomtype = New mycustomtype ; a new "customtype" called "something"


...you're saying "create a new 'mycustomtype' object, and give me a reference to it; call my reference 'something'".

Although we can refer to them individually if we define objects with individual names (eg player1.playerdata,
player2.playerdata), we can also ignore the names completely. If we give the same name to more than one item of a
particular type, we're just adding to a hidden list of those objects, which we don't need to access individually. To
draw all of our aliens, we'd simply do this:

For nasties.invader = Each invader


DrawImage invaderimage, nasties\x, nasties\y
Next<br
...and all of our aliens are drawn!

Note the importance of giving our For...Next variable (nasties) an "invaders" type while we read through our list of
"invaders".

So, to recap, whenever we create a new object, we're really adding to a hidden list of objects of that type. When we
want to be able to refer to each individual object, we give each a different name:

Type playerdata
Field x
Field y
End Type

player1.playerdata = New playerdata


player2.playerdata = New playerdata

The computer adds each object to its hidden list of "playerdata" objects, which might look like this:

xxxxx1.playerdata [player1]
xxxxx2.playerdata [player2]

...but it doesn't matter to us how the computer stores its hidden list - we just refer to player1 and player2.

If we don't need to be able to access each item individually, we can do this:

Type blah
Field whatever
End Type

For a = 1 to 3
myobject.blah = New blah
myobject\whatever = 5
Next

The above example creates a hidden list of "blah" objects, and sets the "whatever" value of each to 5. To the
computer, they might be stored in some abstract form which we have no knowledge of, eg:

xxxx1.blah [myobject]
xxxx2.blah [myobject]
xxxx3.blah [myobject]

Obviously, we can't read individual objects from this list, because we gave them all the same name! But we don't
care; we didn't want to - we can read them "en masse" by using the For...Each...Next loop:

For a.blah = Each blah


Print a\whatever
Next

Taken apart, we get this:

For a.blah = Each blah

This reads each "blah" object in turn into a temporary object called "a", which has a "blah" type (so it can store the
same data as our "blah" objects).

Print a\whatever

This prints out the contents of the temporary "a" variable's "whatever" field.

Next

This is just the normal "Next" used in a For...Next loop.


There's a lot more to types (hence their awesome power!), but this has basics, which will get you started!

OK Now that you've covered the Basics look in the Blitz manual for a synopsis of the more advanced
commands :) REMEMBER: Look in the Blitz Basic samples folder for lots of example code for you to play
around with and more importantly - learn whilst having fun.
Getting Started with BlitzBasic

• My First Program

• Variables

• My First Game

• Getting Graphic

• Double Buffering

• My Second Game

My First Program

After sampling some of the fine example programs included in the BlitzBasic package you are hopefully
itching to try some of your own code.

BlitzBasic is intended as both a friendly introduction to programming computers as well as a language


capable of producing polished video game software.

First up, the traditonal hello world program. A simple one line program that prints the message "hello
world" on the screen. Select the File-New menu option and enter the following text:

Print "Hello World!"

If you press the F5 key to compile and run and a message greeting the world appears then
congratulations! you have just authored your first BlitzBasic program.

The following code illustrates prompting the user of your program for some input.

a=Input("enter a number sweety:")

Print "the value of a is " + a

Note: see how we add text and an integer variable together to print them both on the same line.

Variables

Variables in Blitz are used to store integers, floats and strings.

The first time a float or a string variable is used in your program it must be denoted with # or $ symbols .

If the "a=" in the program is changed to "a$=" Blitz will treat a as a string variable which can then contain
any text the user enters instead of the integer number it originally converted the user's reply into.
a$=Input("enter a number sweety:")

Print "the value of a is " + a

Suggestion: change the "a$=" to "a#=" and enter the number 22.95. What's going on?

My First Game

The following program gives the user 5 turns to guess the random number.

; guessing game

turnsleft=5

sheep=Rnd(20)

While (turnsleft>0)

turnsleft=turnsleft-1

guess=Input("guess how many sheep I have in my room:")

If guess<sheep Then Print "more than that!"

If guess>sheep Then Print "oh, not that many!

If guess=sheep Then Exit

Wend

If turnsleft=0 Then Print "game over dude" Else Print "good guess!"

There are three variables used in this program: turnsleft, sheep and guess.

To begin with, turnsleft is set to 5 and sheep is set to a random number between 0 and 20. The program
then enters a "while" loop asking the player to guess a number, and comparing their answer which is
placed in the variable guess with the value in sheep.

After playing the game a few times, you may notice that the number of sheep does not vary much. Try
adding the following line to the top of the program to "seed" the random number generator using the time
of day in milliseconds.

SeedRnd MilliSecs()

Congratulations, you have just doubled the playability of the game with one line of code!

Getting Graphic
BlitzBasic is not designed for building text based application such as our initial guessing game. It is also
not designed for building applications featuring friendly graphics user interfaces filled with windows and
sliders.

The only thing BlitzBasic has been designed for is the very serious business of video game development.

The following program initializes a 640x480 video display then plots points at random positions until the
user presses the escape key.

; getting graphic

Graphics 640,480

While Not KeyDown(1)

Plot Rnd(640),Rnd(480)

Wend

Once again we rely on the random number generator to provide an interesting result. Try adding the
following color command before the plot statement to vary the color of the dots.

Color Rnd(256),Rnd(256),Rnd(256)

Although this may seem like a simple program, creating a DirectX display such as featured here using
traditional methods can be a complex task. BlitzBasic makes it so easy!

Double Buffering

The following code illustrates the typical "main loop" of a game. For a video game to display smoothly
animated graphics it must use a technique called "Double Buffering".

The following program shows one frame (the FrontBuffer) while drawing to another frame (the
BackBuffer).

; double buffering

Graphics 640,480

SetBuffer BackBuffer()

While Not KeyDown(1)

Flip

Cls

Line 320,240,320+100*Cos(a),240+100*Sin(a)

a=a+1

Wend
In BlitzBasic the Flip command performs the double buffering by swapping the back and front buffers. The
Cls command clears the screen and the Line command draws a line.

Note: the flip command also synchronizes to the video refresh which on standard VGA monitors is 60
frames per second.

The program draws a line from the center of the screen (320,240) at an angle of a degrees, 100 pixels
long.

Try changing the program to add 6 to the value of a. If the frame rate of your monitor is 60 frames per
second, and a is incrementing by 6 each frame, in theory it should increment by 360 every second which
is equivalent to a complete rotation in the world of degrees.

My Second Game

The following introduces the basic skeleton of a simple video game.

The status variable contains the "state" of the game, which is either displaying a title page or allowing the
player to steer round the screen. Extra states such as player dies with cosmic explosion and gameover
screen would be added to extend the game further.

Reading through the program, the display is initialized in a similar manned to the previous example using
the Graphics and SetBuffer commands. The main loop, then uses the Flip command to perform the
double buffering (allowing us to draw to one screen while the other is displayed) and then either prints a
message informing the user to press Enter to start or calls the UpdatePlayer() function.

; eat the dots

Graphics 640,480

SetBuffer BackBuffer()

Global status=0,x#=0,y#=0,speed#=1,dir=1

; main loop

While Not KeyHit(1)

; refresh screen

Flip

Cls

Color 255,255,0

Rect 0,0,640,480,0

; select state

Select status

Case 0
Locate 100,100

Print "Press Enter To Start"

If KeyHit(28) InitGame()

Case 1

UpdatePlayer()

End Select

Wend

What UpdatePlayer() function you ask? And if the user presses Enter what's this InitGame() function?

Unlike traditional BASIC languages where we would implement these functions as subroutines and call
them with the Gosub command BlitzBasic features user defined functions.

Add the following two functions at the bottom of the above program to allow the program to run.

The first function initializes the variables we will need inorder to steer the players rectangle around the
screen. Note how these variables have been declared at the top of the program as Global which allows
us to access them from inside functions such as InitGame().

Function InitGame()

x=320

y=240

speed=1

dir=1

status=1

End Function

This second function changes the players direction depending on the arrow key they are pressing or the
direction of the joystick. The code then moves the players position (x,y) depending on the dir variable
which corresponds to up, right, down and left respectively.

Function UpdatePlayer()

; steer player

If KeyDown(200) Or JoyY()<-0.5 dir=0

If KeyDown(205) Or JoyX()>0.5 dir=1

If KeyDown(208) Or JoyY()>0.5 dir=2

If KeyDown(203) Or JoyX()<-0.5 dir=3


; move player

Select dir

Case 0 y=y-speed

Case 1 x=x+speed

Case 2 y=y+speed

Case 3 x=x-speed

End Select

; draw player

Color 255,255,255

Rect x,y,10,10

End Function

After adding the InitGame() and UpdatePlayer() code the game should run.

Next it's time to add some deadly rocks and some yummy food.

In order to do this we create some new Types that will hold all the information we need for each rock and
food. To begin with these Types will simply hold the x and y position of each rock and food element we
create for our game.

Place the following Type declarations at the top of the program.

Type food

Field x,y

End Type

Type rock

Field x,y

End Type

The following code then needs to be added to the InitGame() function, insert it after the line that reads
status=1.

This code creates 20 rocks that will kill the player and 20 food that will speed the player up. The New
command creates a new object and also adds it to a list. We set the position of each rock and food by
setting the x and y fields of each new object created using the backslash \ character to denote which field.

For i=0 To 20

r.rock=New rock
r\x=Rnd(640)

r\y=Rnd(480)

Next

For i=0 To 20

f.food=New food

f\x=Rnd(640)

f\y=Rnd(480)

Next

We now need a function that draws all the food and rocks each frame and checks if the player has
collided with any.

Note how we can loop through each food and rock element that exist using the For..Each command pair.
This is another great feature of BlitzBasic that keeps programs simple and easy to read.

We use the RectsOverlap command to check of the players position (x,y) collides with each food or rock
element (f \ x , f \ y) or (r \ x , r \ y). If the player collides with some food we delete that piece of food and
increase the player's speed. If the player collides with a rock we end the game by resetting the status
variable.

Function UpdateRocksandFood()

; draw food and check if eaten

Color 0,255,0

For f.food=Each food

Rect f\x,f\y,10,10

If RectsOverlap(x,y,10,10,f\x,f\y,10,10)

speed=speed+0.2

Delete f

EndIf

Next

; draw rocks and check for roadkill

Color 255,0,255

For r.rock=Each rock

Rect r\x,r\y,10,10

If RectsOverlap(x,y,10,10,r\x,r\y,10,10)
status=0

EndIf

Next

End Function

Oops, one last thing, don't forget to call the UpdateRocksandFood() function from the main loop, just after
the UpdatePlayer() call should do nicely.

UpdateRocksandFood()

OK, after playing the game, a few things should become evident.

First, the player should die if they hit the outer wall. We could do this by checking if their position does not
collide with the main screen rectangle (0,0,640,480). Try adding the following code to the UpdatePlayer
function.

If Not RectsOverlap(x,y,10,10,0,0,630,470) status=0

Secondly, each time the game starts more rocks and food appear. This is because we never delete the
food and rocks remaining from the last game. Insert the following code before the code that creates the
new food and rocks in the InitGame() function.
Comments

You add comments to your programs using the ';' character. Everything following the ';' until the end of the line will be ignored, this is useful
for commenting your code - so you can always look through and follow each line in a logical manner.

The following code shows comments in use;

; Begin the Redraw Function


Function Redraw()
...
End Function

This code also shows a legal use of comments;

Function Redraw() ; Begin the Redraw Function


...
End Function

Identifiers

Identifiers are used for constant names, variable names, array names, function names and custom type names.

Identifiers must start with an alphabetic character, and may be following be any number of alphanumeric characters, or the underscore ('_')
character.

These are all valid identifiers:

- Hello
- Score

- player1

- time_to_live

- t__

Indentifiers are not case sensitive.

For example, 'Test', 'TEST' and 'test' are all the same identifiers.

However, it is allowed for identifiers to be reused for functions and custom types names.

For example, you can have a variable called 'test', a function called 'test' and custom type name called 'test'. Blitz will be able to tell which
one you are refering to by the context in which it is used.

Basic Data Types

There are 3 basic data types:

Integer values are numeric values with no fractional part in them. For example: 5,-10,0 are integer values. All integer values in your program
must be in the range -2147483648 to +2147483647.

Floating point values are numeric values that include a fractional part. For example: .5, -10.1, 0.0 are all floating point values.

Strings values are used to contain text. For example: "Hello", "What's up?", "***** GAME OVER *****", ""

Typically, integer values are faster than floating point values, which are themselves faster than strings.

Constants

Constants may be of any basic data type. Constants are variables that have fixed values that will not change (ever) during the course of your
program. These are useful tools for things like screen resolution variables, etc.

Floating point constants must include a decimal point.

For example:

'5' is an integer constant, but '5.0' is a floating point constant.

String constants must be surrounded by quotation marks, for example:

"This is a string constant".

The 'Const' keyword is used to assign an identifier to a constant. For example:

Const one_hundred=100

You can then use the identifier 'one_hundred' anywhere in your program instead of '100'.

A more useful example might be:

Const width=640,height=480

You can then use the more readable 'width' and 'height' throughout your program instead of '640' and '480'.

Also, if you ever decide to change the width and height values, you only have to do so at one place in the program.

There are two built-in Integer constants - 'true' and 'false'. 'true' is equal to 1, and 'false' is equal to 0.
There is also a built in floating point constant for Pi.

Variables

Variables may be of any basic data type, or a custom type. A variable's type is determined by a special character that follows its identifier.

Variable Types

These special characters are called 'type tags' and are:

% = For integer variables

# = For floating point variables

$ = For string variables

.{typename} For custom type variables

Here are some examples of valid variables:

Score%

Lives%

x_speed#

y_speed#

name$

title$

ali.Alien

player.Player

The type tag only needs to be added the first time you use a variable, after that you can leave the type tag off if you wish.

If you don't supply a type tag the first time a variable is used, the variable defaults to an integer.

It is illegal to use the same variable name with a different type. For example, if you already have an integer variable called 'name%', it is
illegal to also have a string variable called 'name$'

Setting Variables

The '=' keyword is used to assign a value to a variable. For example:

score%=0

... assigns the value '0' to the integer variable 'score'.

Variable Scope

Variables may also be either 'global', or 'local'. This refers to where in a program a variable may be used.
- Global variables can be used from anywhere in the program.

- Local variables can only be used within the function they are created in.

The 'Global' keyword is used to define one or more global variables. For example:

Global Score=0,Lives=3,Player_up=1

... defines 3 global variables.

Similarly, 'Local' is used to define local variables:

Local temp_x=x,temp_y=y

If you use a variable without defining it as either local or global, it defaults to being local.

Arrays

Arrays are created using the standard BASIC 'Dim' statement, and may be of any number of dimensions. For example:

Dim arr(10)

Creates a one dimensional array called 'arr' with 11 elements numbered 0...10.

Arrays may be of any basic type, or a custom type.

The type of an array is specified using a type tag. For example:

Dim Deltas#(100)

Creates an array called 'Deltas' of 101 floating point elements.

If the type tag is omitted, the array defaults to an integer array.

An array may be dimensioned at more than one point in a program, each time an array is dimensioned, it's previous contents are discarded.
Arrays may be dimensioned inside functions, but a corresponding 'Dim' statement of the same array must also appear somewhere in the
main program. For example:

Dim test(0,0)

Function Setup( x,y )

Dim test(x,y)

End Function

Expressions and Conversions

The following operators are supported, listed in order of precedence:

New,First,Last custom type operators (unary)

Before,After object operators (unary)

Int,Float,Str type conversion operators (unary)

+,-,~ arithmetic posate(?), negate, bitwise complement (unary)

^ arithmetic 'to-the-power-of' (binary)

*,/,Mod arithmetic multiply, divide, remainder (binary)

Shl,Shr,Sar bitwise shift operators (binary)

+,- arithmetic add, subtract (binary)


,<=,>=,=,<> comparison operators (binary)

And,Or,Xor bitwise And, Or and Exclusive Or (binary)

Not logical Not (unary)

Unary operators take one operand, while binary operators take two.

Arithmetic operators produce a result of the same type as the operands. For example, adding two integers produces an integer result.

If the operands of a binary arithmetic or comparison operator are not of the same type, one of the operands is converted using the following
rules:

- If one operand is a custom type object, the other must be an object of the same type, or 'Null'.

Else if one operand is a string, the other is converted to a string.

Else if one operand is floating point, the other is converted to floating point.

Else both operands must be integers.

When floating point values are converted to integer, the value is rounded to the nearest integer. When integers and floating point values are
converted to strings, an ascii representation of the value is produced.

When strings are converted to integer or floating point values, the string is assumed to contain an ascii representation of a numeric value and
converted accordingly. Conversion stops at the first non-numeric character in the string, or at the end of the string.

The only arithmetic operation allowed on string is '+', which simply concatenates the two operands.

Int, Float and Str can be used to convert values. They may be optionally followed by the appropriate type tag - ie: 'Int%', 'Str$' and 'Float#'.

Comparison operators always produce an integer result: 1 for true, 0 for false.

If one of the operators is a custom type object, the other must be an object of the same type, or 'Null', and the only comparisons allowed are
'=' and '<>'.

Bitwise and logical operators always convert their operands to integers and produce an integer result.

The Not operator returns 0 for a non-zero operand, otherwise 1. When an expression is used to conditionally execute code - for example, in
an 'If' statement - the result is converted to an integer value. A non-zero result means true, a zero result means false.

Program Flow

The following constructs are available for controlling program flow.

If ... Then

If {expression} Then {statements1} Else {statements2}

Evaluates the 'If' expression and, if true, executes the 'Then' statements. If false, the 'Else' statement are executed, the 'Else' part is optional
- statements are executed until the end of the line.

If {expression1}
{statements1}
Else If {expression2}
{statements2}
Else If {expression3}
{statements3}
Else
{statements4}
EndIf
This form of the If statement allows for more than one line of statements. The 'Else If' and 'Else' parts are optional. The 'Else' part is executed
only if none of the 'If' or 'Else If' expressions were true.

While ... Wend

While {expression}
{statements}
Wend

A While loop continues executing until {expression} evaluates to false. {expression} is evaluated at the start of each loop.

For ... Next

For {variable}={initalvalue} To {finalvalue} Step {step}


{statements}
Next

A For/Next loop first assigns {initialvalue} to {variable} and then starts looping. The loop continues until {variable} reaches {finalvalue} and
then terminates. Each loop, the value {step} is added to {variable}. If a step value is omitted, a default value of 1 is used.

For {variable}=Each {typename}


{statements}
Next

This form of the For/Next loop allows you to iterate over all objects of a custom type.

Repeat ... Until/Forever

Repeat
{statements}
Until {expression}

A Repeat loop continues executing until {expression} evaluates to true. {expression} is evaluated at the end of each loop.

Repeat
{statements}
Forever

A Repeat/Forever loop simply executes {statements} until the program ends, or an 'Exit' command is executed.

Select ... Case

Select {expression}
Case {expressions1}
{statements1}
Case {expressions2}
{statements2}
Default
{statements3}
End Select

First the 'Select' expression is evaluated. It is then compared with each of the 'Case' expression lists. If it matches a 'Case', then the
statements in the 'Case' are executed.

If the 'Select' expression matches none of the 'Case' expressions, the statements in the optional 'Default' section are executed.

Breaking Out Of A Loop

The 'Exit' command may be used to break out of any For...Next, While...Wend, Repeat...Until or Repeat...Forever loop.

Using Includes

Blitz also supports the 'Include' command. Include allows source code from an external file to be compiled as if it were part of the main
program. Include must be followed by a quote enclosed filename. For example...

Include "anotherfile.bb"
Include allows you to break your program up into smaller, more manageable chunks.

Functions

A function is defined using the 'Function' keyword:

Function {funcname}{typetag}( {params} )


{statements}
End Function

{funcname} is any valid identifier.

{typetag} is the type of value returned by the function. If {typetag} is omitted, the function returns an integer value by default.

{params} is a comma separated list of variables which is passed to the function when it is called, each parameter may be given an optional
type tag. Parameters are always local.

A function may use the 'Return' statement to return a result. Return may optionally be followed by an expression.

If there is no Return statement, or a Return without any expression is used, the function returns a default value of 0 for numeric functions, an
empty string ("") for string functions, or a 'Null' object for custom type functions.

Custom Types

Introduction - What Are They?

TYPE is your best friend. It is used to create a 'collection' of objects that share the same parameters and need to be interated through quickly
and easily.

Think about SPACE INVADERS. There are many aliens on the screen at one time. Each of these aliens have a few variables that they all
need: x and y coordinates plus a variable to control which graphic to display (legs out or legs in). Now, we could make hundreds of variables
like invader1x, invader1y, invader2x, invader2y, etc. to control all the aliens, but that wouldn't make much sense would it? You could use an
array to track them; invader(number,x,y,graphic), and the loop through them with a FOR ... NEXT loop but that is a lot of work! The TYPE
variable collection was created to handle just this sort of need.

TYPE defines an object collection. Each object in that collection inherits its own copy of the variables defined by the TYPE's FIELD
command. Each variable of each object in the collection can be read individually and can be easily iterated through quickly. Use the FIELD
command to assign the variables you want between the TYPE and END TYPE commands.

If it helps, think of a TYPE collection as a database. Each object is a record of the database, and every variable is a field of the record. Using
commands like BEFORE, AFTER, and FOR ... EACH, you can move change the pointer of the 'database' to point to a different record and
retrieve/set the variable 'field' values.

Not a database guru? Need another example? Okay. Let's say you are setting up an auditorium for a speech or event and you are putting up
hundreds of chairs for the spectators. The chairs have to be in a certain place on the floor, and some will need to be raised up a bit higher
than others (visiting dignitaries, the mayor is coming, etc.). So being the computer genius you are, you start figuring out how you can layout
the chairs with the least amount of effort. You realize that the floor is checkered, so its really a huge grid! This will make it easy! You just
need to number the floor on a piece of graph paper and put into the grid how high each chair should be, based on where the boss told you
the important people are to sit. So, for each chair, you will have a row and column on the graph paper (x and y location) and a level to adjust
the chair to (height). Good, we are organized. Now, even though we have it all on paper, we still have to do the work of placing all the chairs.
After you are done, let's say your boss walks up to you and says "they aren't centered right .. move'em all over 1 square". Ah crap! You have
them all perfect, and even though it is a simple thing to move a chair one square to the right (after all, their order and height won't change) -
you still have to move each and every chair! Should would be nice if you could just wave your hand and say "For each chair in the room, add
1 square to its x location" and have it just magically happen. Alas, in the real world, get busy - you've got a lot of chairs to move!

In Blitz, you could have set up a TYPE called CHAIR, set the TYPE's FIELDS as X, Y, and HEIGHT. You would then create as many chairs
as you need with the NEW command (each time you call NEW, it makes a new chair, with its OWN X, Y, and HEIGHT variables) and assign
them the X, Y, and HEIGHT values you decide upon.

In our example above, when the boss told you to move the chairs over 1 box, you probably groaned inside. That's a lot of work! In Blitz, we
could use four lines of code to adjust all our CHAIR objects to the new position (using FOR ... EACH commands).

Defining A Type
Custom types are defined using the 'Type' keyword. For example:

Type MyType
Field x,y
End Type

Creates a custom type called 'MyType' with 2 fields - x and y.

Fields within a custom type may themselves be of any basic type or custom type. Type tags are used to determine the type of a field. For
example:

Type MyType
Field x,y
Field description$
Field delta_x#,delta_y#
End Type

Creating a Type Instance

You can create variables or arrays of custom types using a '.' type tag followed by the type name. For example:

Global mine.MyType Dim all_mine.MyType( 100 )

Before a custom type variable or array element can be used, it must be initialized using the 'New' operator. For example:

mine.MyType=New MyType

The 'New' operator creates an 'object' of type 'MyType', and returns a 'pointer' to the new object. The identifier following the 'New' operator
must be a valid custom type name.

The fields within a custom type are accessed using the '\' character. For example: mine\x=100 Print mine\x

Destroying a Type Instance

When you've finished with an object, you should delete it using the 'Delete' command. For example:

Delete mine

This releases the memory used by the object.

Determining Existance

The special keyword 'Null' is used to represent non-existent objects. An object is non-existent if it hasn't been initialized yet using 'New', or
has been released using 'Delete'. For example:

mine.MyType=New MyType
If mine<>Null
Print "exists!"
Else
Print "doesn't exist!"
EndIf
Delete mine
If mine<>Null
Print "exists!"
Else
Print "doesn't exist!"
EndIf

...will print the following:

exists!
doesn't exist!

Each custom type has an associated list of objects known as a 'type list'. When an object is created using 'New', it is automatically added to
the type list. When an object is released using 'Delete', it is removed from the type list. This list is dynamic - once an instance has been
deleted, its place in the collection is deleted and all the other objects after it will 'move up' in the collection hiearchy.

Iteration Through Type Lists


The 'First', 'Last', 'After' and 'Before' operators allow you to access type lists. The 'First' operator returns the object at the start of the type list.
For example:

mine.MyType=First MyType

This sets the 'mine.MyType' variable to the first object of custom type 'MyType'.

Similarly, 'Last' returns the object at the end of the list.

If the type list is empty, 'First' and 'Last' return 'Null'.

You can use 'After' to find the object after an object, and 'Before' to find the object before an object.

For example:

mine.MyType=First MyType ;mine=first object in the type list


mine=After( mine ) ;mine=second object
mine=After( mine ) ;mine=third object
mine=Before( mine ) ;mine=second object
mine=Before( mine ) ;mine=first again!

'After' and 'Before' return 'Null' if there is no such object. For example:

mine.MyType=Last MyType ;mine=last object


mine=After( mine ) ;object after last does not exist!

When an object is created using 'New', it is placed at the end of it's type list by default.
However, You can move objects around within the type list using Insert. For example:

mine1.MyType=New MyType
mine2.MyType=New MyType
Insert mine2 Before mine1

This has the effect of placing the 'mine2' object before the 'mine1' object in the type list.
You can also use 'After' instead of 'Before' with Insert.

Here's an example of moving an object to the start of it's type list:

Insert mine Before First MyType

A special form of For...Next allows you to easily iterate over all object of a custom type. For example:

For mine.MyType=Each MyType


Next

This will cause the variable 'mine.MyType' to loop through all existing objects of cutom type MyType.

Finally, the 'Delete Each' command allows you to delete all objects of a particular type. For example:

Delete Each MyType

For f.food=Each food Delete f Next

For r.rock=Each rock Delete r Next


Keywords

The following keywords are built into Blitz, and may not be used as identifiers (variables, function names, labels, etc.):

After, And, Before, Case, Const, Data, Default, Delete, Dim, Each, Else, ElseIf, End, EndIf, Exit, False, Field, First, Float, For,
Forever, Function, Global, Gosub, Goto, If, Insert, Int, Last, Local, Mod, New, Next, Not, Null, Or, Pi, Read, Repeat, Restore,
Return, Sar, Select, Shl, Shr, Step, Str, Then, To, True, Type, Until, Wend, While, Xor, Include
.

INSTRUCCIONES 2D
Abs (number)
Definition:

Returns the absolute (positive) value of a number.

Parameter Description:

number = any valid number or numeric variable

Command Description:

Use this command to return the absolute value of a number; meaning its positive value. A negative 3 would
become a positive 3. If what you want is a number without a fraction (say, convert 3.1415 into 3) use the
Int() command.

Example:

number=-3

Print "The absolute value of " + number + " is: " + Abs(number)

WaitKey()

AcceptTCPStream (serverhandle)
Definition:

Accepts an incoming TCP/IP stream.

Parameter Description:

serverhandle = the server handle assigned when the server was created

Command Description:

Accepts an incoming TCP/IP stream, and returns a TCP/IP stream if one is available, or 0 if not.

See CreateTCPServer and CloseTCPServer.

Example:

; CreateTCPServer, CloseTCPServer, AcceptTCPStream Example


; This code is in two parts, and needs to be run seperately on the same machine

; --- Start first code set ---


; Create a server and listen for push

svrGame=CreateTCPServer(8080)

If svrGame<>0 Then
Print "Server started successfully."
Else
Print "Server failed to start."
End
End If

While Not KeyHit(1)


strStream=AcceptTCPStream(svrGame)
If strStream Then
Print ReadString$(strStream)
Delay 2000
End
Else
Print "No word from Apollo X yet ..."
Delay 1000
End If
Wend

End

; --- End first code set ---

; --- Start second code set ---


; Copy this code to another instance of Blitz Basic
; Run the above code first, then run this ... they will 'talk'

; Create a Client and push data

strmGame=OpenTCPStream("127.0.0.1",8080)

If strmGame<>0 Then
Print "Client Connected successfully."
Else
Print "Server failed to connect."
WaitKey
End
End If

; write stream to server


WriteString strmGame,"Mission Control, this is Apollo X ..."
Print "Completed sending message to Mission control..."

; --- End second code set ---

ACos (number)
Definition:

Returns the smallest angle (in degrees) satisfying the arc cosine (inverse cosine) of the supplied argument.

Parameter Description:

number=float or integer representing a ratio of the "X" coordinate to the tangential displacement.

Command Description:

This command is used for translating X/Y coordinate values to angles. Remember that the computer screen
uses an inverted y-axis (values get larger the further down the screen).

Example:
Graphics 640,480
Repeat
Cls
; Determine the positions and the length of the hypotenuse
x# = MouseX() ; displacement across the screen.
y# = MouseY() ; displacement down the screen.
r# = Sqr((x#*x#)+(y#*y#)) ; length of the hypotenuse.

; Draw the axes


Color 104,104,104
Line x#,0,x#,y# ; draw a line from the top to the cursor.
Line 0,y#,x#,y# ; draw a line from the left to the cursor.
Locate x#+10,y#-10 : Write "X=" : Print x#
Locate x#-10,y#+10 : Write "Y=" :Print y#

; reset any drawing to the top right


Origin 0,0

; Draw the angled line


Color 255,255,255
Line 0,0,x#,y# ; draw a line from the top right corner of the screen to the cursor.
theta# = ACos(x#/r#) ; the angle between the x axis and the y axis.
Locate 60,10 : Write "Angle:" : Print theta

; Draws an arc showing the angle.


For degrees#=0 To theta#; Step though all the degrees in the angle
; The next line calculates the X and Y coordinates of the point of the circle using the Sin and Cos
; commands, and multiplies it by 50 (to get a larger radius, try and change it).
cy=Sin(degrees#)*50
cx=Cos(degrees#)*50
Plot cx,cy ; Draw the current point on the circle.
Next ; Give us another angle

Flip
; Use the ESCAPE key to quit
Until KeyDown(1)

After custom_type_variable
Definition:

Move the object pointer to the next object in the Type collection.

Parameter Description:

custom_type_variable = not the Type name, but the custom Type name

Command Description:

If you haven't read up on the TYPE command, you might want to do so before continuing.

Use this to assign a custom Type object to the next object in the collection. See the example.

Example:

; Define a crafts Type

Type crafts
Field x
Field y
Field dead
Field graphic
End Type

; Create 100 crafts, with the unique name of alien


For t = 1 To 100
alien.crafts = New crafts
alien\x = Rnd(0,640)
alien\y = Rnd(0,480)
alien\dead = 0
alien\graphic = 1
Next

; Move to the first object


alien.crafts = First crafts

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

; move to the next alien object


alien = After alien

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

; move to the last alien object


alien.crafts = Last crafts

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

; move to the second to the last alien object


alien = Before alien

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

And
Definition:

Logical operator comparative command for testing expressions.

Parameter Description:

None.

Command Description:

AND is a logical operator for doing conditional checks of multiple values and/or expressions. Use this to ensure
that two or more conditions are true, usually in an IF ... THEN conditional. See example and see OR, NOT, and
XOR.

Example:

; AND example

name$=Input$("Enter your name:")


pw$=Input$("Password:")

if name$="Shane" and pw$="bluedog" then


print "Access granted! Welcome!"
else
print "Your name or password was not recogized"
end if

AppTitle string
Definition:

Sets the title bar of the program.

Parameter Description:

string = any legal string variable

Command Description:

Allows you to set the text of the program's Title Bar.

Example:

; Set the title bar

AppTitle "Super Invaders V1.0"

Asc (string$)
Definition:

Returns the ASCII value of the first letter of a string.

Parameter Description:

string$ = any valid string variable (only the first character's ASCII value will be returned).

Command Description:

This will return the ASCII value of the first letter of a string.

Example:

a$=Input$("Enter a letter:")
Print "The ASCII value of the letter is:" + Asc(a$)

ASin (number)
Definition:

Returns the smallest angle (in degrees) satisfying the arc sine (inverse sine) of the supplied argument.

Parameter Description:

number=float or integer representing a ratio of the "Y" coordinate to the tangential displacement.

Command Description:

This command is used for translating X/Y coordinate values to angles. Remember that the computer screen
uses an inverted y-axis (values get larger the further down the screen).

Example:

Graphics 640,480
Repeat
Cls
; Determine the positions and the length of the hypotenuse
x# = MouseX() ; displacement across the screen.
y# = MouseY() ; displacement down the screen.
r# = Sqr((x#*x#)+(y#*y#)) ; length of the hypotenuse.
; Draw the axes
Color 104,104,104
Line x#,0,x#,y# ; draw a line from the top to the cursor.
Line 0,y#,x#,y# ; draw a line from the left to the cursor.
Locate x#+10,y#-10 : Write "X=" : Print x#
Locate x#-10,y#+10 : Write "Y=" :Print y#

; reset any drawing to the top right


Origin 0,0

; Draw the angled line


Color 255,255,255
Line 0,0,x#,y# ; draw a line from the top right corner of the screen to the cursor.
theta# = ASin(y#/r#) ; the angle between the x axis and the y axis.
Locate 60,10 : Write "Angle:" : Print theta

; Draws an arc showing the angle.


For degrees#=0 To theta#; Step though all the degrees in the angle
; The next line calculates the X and Y coordinates of the point of the circle using the Sin and Cos
; commands, and multiplies it by 50 (to get a larger radius, try and change it).
cy=Sin(degrees#)*50
cx=Cos(degrees#)*50
Plot cx,cy ; Draw the current point on the circle.
Next ; Give us another angle

Flip
; Use the ESCAPE key to quit
Until KeyDown(1)
End
ATan2 (xvalue,yvalue)
Definition:

Returns the angle from the X axis to a point (y,x).

Parameter Description:

(yvalue,xvalue)

Command Description:

Aside from its basic trig usage, this nifty command will allow you to derive an angle based on the x and y
speed of a travelling object.

Example:

; Atan2 example

; Set graphics w/double buffering


Graphics 640,480,16,0
SetBuffer BackBuffer()

; Starting point for our travelling box


x=0
y=0

; random speed values for travelling


xSpeed=Rand(5)
ySpeed=Rand(5)

; repeat until the ESC or box travels off the screen


While Not KeyHit(1) Or y > 480 Or x > 640
Cls
; Draw our box
Rect x,y,10,10,1
; increment the box location based on random speed
x=x+xSpeed
y=y+yspeed
; print the angle of our box travel
Text 0,0,ATan2(yspeed,xspeed)
Flip
Wend

ATan (float)
Definition:

Returns the angle from the X axis to a point (y,x).

Parameter Description:

float = floating point value (degrees)

Command Description:

Aside from its basic trig usage, this nifty command will allow you to derive an angle based on the x and y
speed of a travelling object. Also see ATan2.
Example:

; Set graphics w/double buffering


Graphics 640,480,16,0
SetBuffer BackBuffer()

; Starting point for our travelling box


x=0
y=0

; random speed values for travelling


xSpeed#=Rand(5)
ySpeed#=Rand(5)

; repeat until the ESC or box travels off the screen


While Not KeyHit(1) Or y > 480 Or x > 640
Cls
; Draw our box
Rect x,y,10,10,1
; increment the box location based on random speed
x=x+xSpeed
y=y+yspeed
; print the angle of our box travel
Text 0,0,ATan(yspeed/xspeed)
Flip
Wend

AutoMidHandle true/false
Definition:

Automatically sets the image handle of loaded images to the middle of the image.

Parameter Description:

true = images load with midhandle set as default


false = images load with default image handles at 0,0

Command Description:

When an image is loaded with LoadImage, the image handle (the location within the image where the image is
'drawn from') is always defaulted to the top left corner (coordinates 0,0). This means if you draw an image
that is 50x50 pixels at screen location 200,200, the image will begin to be drawn at 200,200 and extend to
250,250.

The MidHandle command moves the image's handle to the middle of the image. See this command for more
information about the image's handle.

This command eliminates the need for the MidHandle command by making ALL subsequently loaded images
default to having their image handles set to mid.

Note about the term 'handle'. There are two types of 'handles' we discuss in these documents. One is the
location within an image - as discussed in this command. The other is a 'file handle', a variable used to hold an
image, sound, or font loaded with a command. See LoadImage for more information about file handles.

Example:

; MidHandle/ImageXHandle()/ImageYHandle()/AutoMidHandle

; Initiate Graphics Mode


Graphics 640,480,16

; Set up the image file handle as a global


Global gfxBall

; Load the image - you may need to change the location of the file
gfxBall=LoadImage ("C:\Program Files\Blitz Basic\samples\ball.bmp")

; Until the user presses ESC key ...


While Not KeyHit(1)
Text 0,0,"Default Image Handle for gfxBall... Press ESC ..."
Text 0,14,"X handle-" + ImageXHandle(gfxBall) ; Print the location of the image handle x location
Text 0,28,"Y handle-" + ImageYHandle(gfxBall) ; Print the location of the image handle y location
DrawImage gfxBall,200,200,0 ; draw the image at 200,200
Wend

; Clear the screen


Cls

; Set the ball's handle to the center of the image


MidHandle gfxBall

; Until the user presses ESC key ... show the new information
While Not KeyHit(1)
Text 0,0,"New Image Handle for gfxBall... Press ESC ..."
Text 0,14,"X handle-" + ImageXHandle(gfxBall)
Text 0,28,"Y handle-" + ImageYHandle(gfxBall)
DrawImage gfxBall,200,200,0
Wend

; Makes all images load up with their handles in the center of the image
AutoMidHandle True
Cls

; Load the image again


gfxBall=LoadImage ("C:\Program Files\Blitz Basic\samples\ball.bmp")

; Until the user presses ESC key ... show the new information
While Not KeyHit(1)
Text 0,0,"Automatic image handle of gfxBall... Press ESC ..."
Text 0,14,"X handle-" + ImageXHandle(gfxBall)
Text 0,28,"Y handle-" + ImageYHandle(gfxBall)
DrawImage gfxBall,200,200,0
Wend

AvailVidMem()
Definition:

Returns the available free video memory.

Parameter Description:

None.

Command Description:

This command will return the total bytes of available free video memory. Use this to keep track of your
resources!
Example:

Print "Your available video memory is: " + AvailVidMem()

BackBuffer()
Definition:

Indicates the BackBuffer drawing buffer.

Parameter Description:

None.

Command Description:

This is a value usually used with SETBUFFER to denote the secondary non-visible drawing buffer called the
Back Buffer. In MOST gaming situations, you will want to be using the BackBuffer() for drawing operations
then using Flip to bring that buffer to the FrontBuffer() where it can be seen. There are other uses for the
command, but this is the biggie. See SETBUFFER for more info, and check out the example. Once again - if
you set drawing operations to the BackBuffer() you will NOT see any of them until you call FLIP.

Example:

; Flip/Backbuffer()/Rect Example

; Set Graphics Mode


Graphics 640,480

; Go double buffering
SetBuffer BackBuffer()

; Setup initial locations for the box


box_x = -20 ; negative so it will start OFF screen
box_y = 100

While Not KeyHit(1)


Cls ; Always clear screen first
Rect box_x,box_y,20,20,1 ; Draw the box in the current x,y location
Flip ; Flip it into view
box_x = box_x + 1 ; Move the box over one pixel
If box_x = 640 Then box_x=-20 ; If it leaves the Right edge, reset its x location
Wend

BankSize (bankhandle)
Definition:

Returns the size of a bank.

Parameter Description:

bankhandle=handle assigned to the bank when created.

Command Description:
Use this command to determing the size of an existing bank. See CreateBank, ResizeBank, and CopyBank.

Example:

; BankSize, ResizeBank, CopyBank Example

; create a bank
bnkTest=CreateBank(5000)

; Fill it with rand Integers


For t = 0 To 4999
PokeByte bnkTest,t,Rand(9)
Next

; Resize the bank


ResizeBank bnkTest,10000

; Copy the first half of the bank to the second half


CopyBank bnkTest,0,bnkTest,5000,5000

; Print final banksize


Print BankSize(bnkTest)

Before custom_type_variable
Definition:

Move the object pointer to the previous object in the Type collection.

Parameter Description:

custom_type_variable = not the Type name, but the custom Type name

Command Description:

If you haven't read up on the TYPE command, you might want to do so before continuing.

Use this to assign a custom Type object to the previous object in the collection. See the example.

Example:

; Define a crafts Type

Type crafts
Field x
Field y
Field dead
Field graphic
End Type

; Create 100 crafts, with the unique name of alien


For t = 1 To 100
alien.crafts = New crafts
alien\x = Rnd(0,640)
alien\y = Rnd(0,480)
alien\dead = 0
alien\graphic = 1
Next

; Move to the first object


alien.crafts = First crafts

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

; move to the next alien object


alien = After alien

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

; move to the last alien object


alien.crafts = Last crafts

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

; move to the second to the last alien object


alien = Before alien

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

Bin$ (integer)
Definition:

Converts an integer value to a binary value.

Parameter Description:

integer = any valid integer or integer variable

Command Description:

Converts integer values into binary values. If you don't know what binary is, you don't need to know this
command :)

Example:

intValue="64738"
Print "The binary value of "+intValue+" is: " + bin$(intValue)

Case value
Definition:
Begins the set of commands in a SELECT structure if the value of SELECT is met.

Parameter Description:

value = any valid value of the SELECT variable

Command Description:

When using a SELECT structure, the CASE command defines the starting point of command execution if the
SELECT value matches the CASE value. If the SELECT value doesn't match the CASE value, the commands
following it are ignored until the next CASE, DEFAULT, or END SELECT command is encountered. See SELECT
and the example for a better understanding.

Example:

; SELECT/CASE/DEFAULT/END SELECT Example


; Assign a random number 1-10
mission=Rnd(1,10)

; Start the selection process based on the value of 'mission' variable


Select mission

; Is mission = 1?
Case 1
Print "Your mission is to get the plutonium and get out alive!"

; Is mission = 2?
Case 2
Print "Your mission is to destroy all enemies!"

; Is mission = 3?
Case 3
Print "Your mission is to steal the enemy building plans!"

; What do do if none of the cases match the value of mission


Default
Print "Missions 4-10 are not available yet!"

; End the selection process


End Select

Ceil# (float)
Definition:

Rounds a decimal floating variable up to the nearest whole number.

Parameter Description:

float=floating point number

Command Description:

Many times, you will need to round up or down a floating point decimal variable. This command rounds it up to
the nearest whole number. Use Floor# to round the number down.

Example:
; Floor#/Ceil# Example

; Set a floating point variable


myVal#=0.5

; Round it up
Print Floor#(myval)

;Round it down
Print Ceil#(myval)

ChangeDir directory/path
Definition:

Changes the currently selected directory for file operations.

Parameter Description:

directory/path = full path to directory/folder

Command Description:

This command will change the currently selected directory for disk operations, useful for advanced file
operations. Use CURRENTDIR$() to see what the current directory is.
Use a directory/path of ".." to change to the parent of the current directory, unless you are at the root
directory of the drive, then no change happens.

Example:

; ChangeDir example

ChangeDir "c:\winnt\system32"
Print "The folder has been changed to: " + currentdir$()

ChannelPan channel_handle, pan#


Definition:

Pans sound channel between the left and right channels.

Parameter Description:

channel_handle = variable assigned to the channel when played


pan# = panning floating value to denote channel playback

Command Description:

When you want to do real sound panning effects, this is the command you'll use. This will allow you to pan the
sound channels on a 'per channel' basis between the left and right speakers. This command makes it very
easy to produce some really killer stereophonic effects!

The pan value is between -1 and 1 with 0 being perfect center. -1 is full left, and 1 is full right. To make it
somewhere in between, try -.5 for 50% left or .75 for 75% right.

Example:
; Channel examples

Print "Loading sound ..."


; Load the sample - you'll need to point this to a sound on your computer
; For best results, make it about 5-10 seconds...
sndWave=LoadSound("level1.wav")
; Prepare the sound for looping
LoopSound sndWave

chnWave=PlaySound(sndWave)

Print "Playing sound for 2 seconds ..."


Delay 2000

Print "Pausing sound for 2 seconds ..."


PauseChannel chnWave
Delay 2000

Print "Restarting sound ..."


ResumeChannel chnWave
Delay 2000

Print "Changing Pitch of sound ..."


ChannelPitch chnWave, 22000
Delay 2000

Print "Playing new pitched sound ..."


Delay 2000

Print "Left speaker only"


ChannelPan chnWave,-1
Delay 2000

Print "Right speaker only"


ChannelPan chnWave,1
Delay 2000

Print "All done!"


StopChannel chnWave

ChannelPitch channel_handle, hertz


Definition:

Alters the hertz pitch of a playing sound channel.

Parameter Description:

channel_handle = variable assigned to the channel when played


hertz = pitch to apply to the channel (try 8000-44000)

Command Description:

You can alter the hertz pitch of a sound channel that is playing (or in use and just paused). I'm sure you can
think of numerous uses for this command! Use the frequency of your sound as the 'baseline' for pitch change.
So if your sample is at 11025 hertz, increase the pitch to 22050 to make the pitch higher, 8000 to make it
lower, etc. While similar to SoundPitch, this command let's you change the pitch individually of each and every
channel in use.

Example:
; Channel examples

Print "Loading sound ..."


; Load the sample - you'll need to point this to a sound on your computer
; For best results, make it about 5-10 seconds...
sndWave=LoadSound("level1.wav")
; Prepare the sound for looping
LoopSound sndWave

chnWave=PlaySound(sndWave)

Print "Playing sound for 2 seconds ..."


Delay 2000

Print "Pausing sound for 2 seconds ..."


PauseChannel chnWave
Delay 2000

Print "Restarting sound ..."


ResumeChannel chnWave
Delay 2000

Print "Changing Pitch of sound ..."


;StopChannel chnWave
ChannelPitch chnWave, 22000
Delay 2000

Print "Playing new pitched sound ..."


Delay 2000

Print "Left speaker only"


ChannelPan chnWave,-1
Delay 2000

Print "Right speaker only"


ChannelPan chnWave,1
Delay 2000

Print "All done!"


StopChannel chnWave

ChannelPlaying (channel_handle)
Definition:

Checks to see if a sound channel is still playing.

Parameter Description:

channel_handle = variable assigned to the channel when played

Command Description:

Often you will need to know if a sound channel has completed playing or not. This command will return 1 if the
sound is still playing or 0 if it has stopped. Use this to restart your background music or some other sound
that might have stopped unintentionally.

Note: This command currently doesn't seem to work with a channel assigned to CD track playback.

Example:
; Channel examples

Print "Loading sound ..."


; Load the sample - you'll need to point this to a sound on your computer
; For best results, make it about 5-10 seconds...
sndWave=LoadSound("level1.wav")

Print "Playing full sample until sound is done ..."


chnWave=PlaySound(sndWave)
While ChannelPlaying(chnWave)
Wend
Print "All done!"

ChannelVolume channel_handle, volume#


Definition:

Adjusts the volume level of a sound channel.

Parameter Description:

channel_handle = variable assigned to the channel when played


volume# = volume level floating value between 0 and 1

Command Description:

While SoundVolume happily changes the volume of the entire program, this command will let you adjust
volume rates on a 'per channel' basis. Extremely useful.

The volume value is a floating point value between 0 and 1 (0 = silence, .5 = half volume, 1= full volume).
You can do other cool stuff like ChannelPitch and ChannelPan too!

Example:

; Channel examples

Print "Loading sound ..."


; Load the sample - you'll need to point this to a sound on your computer
; For best results, make it about 5-10 seconds...
sndWave=LoadSound("level1.wav")
; Prepare the sound for looping
LoopSound sndWave

chnWave=PlaySound(sndWave)

Print "Playing sound for 2 seconds ..."


Delay 2000

Print "Pausing sound for 2 seconds ..."


PauseChannel chnWave
Delay 2000

Print "Restarting sound ..."


ResumeChannel chnWave
Delay 2000

Print "Changing volume of sound ..."


ChannelVolume chnWave, .5
Delay 2000
Print "Playing new half-volume sound ..."
Delay 2000

Print "Left speaker only"


ChannelPan chnWave,-1
Delay 2000

Print "Right speaker only"


ChannelPan chnWave,1
Delay 2000

Print "All done!"


StopChannel chnWave

Chr$ (integer)
Definition:

Converts an ASCII code to its corresponding character string.

Parameter Description:

integer = valid ASCII code integer value

Command Description:

Use this command to convert a known ASCII code (for example 65) to its character string equivelant (i.e. the
letter "A").

Example:

Print " The character for ASCII value 65 is: " + Chr$(65)

CloseDir filehandle
Definition:

Closes a directory previously opened with the ReadDir command.

Parameter Description:

filehandle = valid filehandle assigned from the ReadDir command

Command Description:

Once you are finished with NextFile$ on the directory previously opened for read with the ReadDir command,
use this command to close the directory. This is good programming practice!

Example:

; ReadDir/NextFile$/CloseDir example

; Define what folder to start with ...


folder$="C:\"

; Open up the directory, and assign the handle to myDir


myDir=ReadDir(folder$)

; Let's loop forever until we run out of files/folders to list!


Repeat
; Assign the next entry in the folder to file$
file$=NextFile$(myDir)

; If there isn't another one, let's exit this loop


If file$="" Then Exit

; Use FileType to determine if it is a folder (value 2) or a file and print results


If FileType(folder$+"\"+file$) = 2 Then
Print "Folder:" + file$
Else
Print "File:" + file$
End If
Forever

; Properly close the open folder


CloseDir myDir

; We're done!
Print "Done listing files!"

CloseFile filehandle
Definition:

Closes a file previously opened with a file operations command.

Parameter Description:

filehandle = variable defined with the WriteFile or OpenFile command

Command Description:

Use this command to close a file previously opened. You should always close a file as soon as you have
finished reading or writing to it.

Example:

; Reading and writing custom types to files using ReadFile, WriteFile and CloseFile

; Initialise some variables for the example


Type HighScore
Field Name$
Field Score%
Field Level%
End Type

Best.HighScore = New HighScore


Best\Name = "Mark"
Best\Score = 11657
Best\Level = 34

; Open a file to write to


fileout = WriteFile("mydata.dat")

; Write the information to the file


WriteString( fileout, Best\Name )
WriteInt( fileout, Best\Score )
WriteByte( fileout, Best\Level )

; Close the file


CloseFile( fileout )

; Open the file to Read


filein = ReadFile("mydata.dat")

; Lets read the Greatest score from the file


Greatest.HighScore = New HighScore
Greatest\Name$ = ReadString$( filein )
Greatest\Score = ReadInt( filein )
Greatest\Level = ReadByte( filein )

; Close the file once reading is finished


CloseFile( fileout )

Print "High score record read from - mydata.dat "


Print
Write "Name = "
Print Greatest\Name
Write "Score = "
Print Greatest\Score
Write "Level = "
Print Greatest\Level

WaitKey()

CloseTCPServer serverhandle
Definition:

Closes a TCP server.

Parameter Description:

serverhandle = handle assigned when the server was created.

Command Description:

Closes a TCP/IP server previously created with the CreateTCPServer command.

Example:

; CreateTCPServer, CloseTCPServer, AcceptTCPStream Example


; This code is in two parts, and needs to be run seperately on the same machine

; --- Start first code set ---


; Create a server and listen for push

svrGame=CreateTCPServer(8080)

If svrGame<>0 Then
Print "Server started successfully."
Else
Print "Server failed to start."
End
End If
While Not KeyHit(1)
strStream=AcceptTCPStream(svrGame)
If strStream Then
Print ReadString$(strStream)
Delay 2000
End
Else
Print "No word from Apollo X yet ..."
Delay 1000
End If
Wend

End

; --- End first code set ---

; --- Start second code set ---


; Copy this code to another instance of Blitz Basic
; Run the above code first, then run this ... they will 'talk'

; Create a Client and push data

strmGame=OpenTCPStream("127.0.0.1",8080)

If strmGame<>0 Then
Print "Client Connected successfully."
Else
Print "Server failed to connect."
WaitKey
End
End If

; write stream to server


WriteString strmGame,"Mission Control, this is Apollo X ..."
Print "Completed sending message to Mission control..."

; --- End second code set ---

CloseTCPStream streamhandle
Definition:

Closes the specified TCP stream.

Parameter Description:

streamhandle = handle assigned when the stream was opened.

Command Description:

Once you've completed the use of your TCP/IP stream, close the connection you opened with OpenTCPStream
with this command.

Example:

; OpenTCPStream/CloseTCPStream Example

Print "Connecting..."
tcp=OpenTCPStream( "www.blitzbasement.com",80 )

If Not tcp Print "Failed.":WaitKey:End

Print "Connected! Sending request..."

WriteLine tcp,"GET http://www.blitzbasement.com HTTP/1.0"


WriteLine tcp,Chr$(10)

If Eof(tcp) Print "Failed.":WaitKey:End

Print "Request sent! Waiting for reply..."

While Not Eof(tcp)


Print ReadLine$( tcp )
Wend

If Eof(tcp)=1 Then Print "Success!" Else Print "Error!"

CloseTCPStream tcp

WaitKey
End

CloseUDPStream udp_stream

Parameters:

udp_stream - UDP stream handle

Description:

Closes a UDP stream.

Example:

None.

Cls
Definition:

Clears the current current drawing buffer.

Parameter Description:

None.

Command Description:

This command will wipe the current drawing buffer clean of any graphics or text present and reset the drawing
buffer back to the color defined in the ClsColor command

Example:
;set ClsColor to red
ClsColor 255,0,0

;set current drawing buffer to the color set by the ClsColor command
Cls

ClsColor red,green,blue
Definition:

Selects the color for the Cls command.

Parameter Description:

red, green and blue = number between 0 and 255

Command Description:

This changes the color for subsequent CLS calls. Use this command when you need CLS to 'clear' the screen
with some other color than black.

Example:

;set ClsColor to red


ClsColor 255,0,0

;set current drawing buffer to the color set by the ClsColor command
Cls

Color red,green,blue
Definition:

Sets the drawing color for all drawing operations with a red, green, blue color value.

Parameter Description:

red = value of red component (0-255)


green = value of green component (0-255)
blue = value of blue component (0-255)

Command Description:

This command sets the drawing color (using RGB values) for all subsequent drawing commands (Line, Rect,
Text, etc.) You must be in Graphics mode to execute this command.

Example:

; Color, ColorRed(), ColorBlue(), ColorGreen() Example

; Gotta be in graphics mode


Graphics 640,480

; Change the random seed


SeedRnd MilliSecs()
; Let's set the color to something random
Color Rnd(0,255),Rnd(0,255),Rnd(0,255)

; Now let's see what they are!


While Not KeyHit(1)
Text 0,0,"This Text is printed in Red=" + ColorRed() + " Green=" + ColorGreen() + " Blue=" + ColorBlue() +
"!"
Wend

ColorBlue()
Definition:

Returns the blue component of the current drawing color.

Parameter Description:

None.

Command Description:

Use this command to return the blue component of the RGB color of the current drawing color. Use ColorRed()
and ColorGreen() for the other two color components.

Example:

; Color, ColorRed(), ColorBlue(), ColorGreen() Example

; Gotta be in graphics mode


Graphics 640,480

; Change the random seed


SeedRnd MilliSecs()

; Let's set the color to something random


Color Rnd(0,255),Rnd(0,255),Rnd(0,255)

; Now let's see what they are!


While Not KeyHit(1)
Text 0,0,"This Text is printed in Red=" + ColorRed() + " Green=" + ColorGreen() + " Blue=" + ColorBlue() +
"!"
Wend

ColorGreen()
Definition:

Returns the green component of the current drawing color.

Parameter Description:

None.

Command Description:
Use this command to return the green component of the RGB color of the current drawing color. Use
ColorRed() and ColorBlue() for the other two color components.

Example:

; Color, ColorRed(), ColorBlue(), ColorGreen() Example

; Gotta be in graphics mode


Graphics 640,480

; Change the random seed


SeedRnd MilliSecs()

; Let's set the color to something random


Color Rnd(0,255),Rnd(0,255),Rnd(0,255)

; Now let's see what they are!


While Not KeyHit(1)
Text 0,0,"This Text is printed in Red=" + ColorRed() + " Green=" + ColorGreen() + " Blue=" + ColorBlue() +
"!"
Wend

ColorRed()
Definition:

Returns the red component of the current drawing color.

Parameter Description:

None.

Command Description:

Use this command to return the red component of the RGB color of the current drawing color. Use ColorBlue()
and ColorGreen() for the other two color components.

Example:

; Color, ColorRed(), ColorBlue(), ColorGreen() Example

; Gotta be in graphics mode


Graphics 640,480

; Change the random seed


SeedRnd MilliSecs()

; Let's set the color to something random


Color Rnd(0,255),Rnd(0,255),Rnd(0,255)

; Now let's see what they are!


While Not KeyHit(1)
Text 0,0,"This Text is printed in Red=" + ColorRed() + " Green=" + ColorGreen() + " Blue=" + ColorBlue() +
"!"
Wend
CommandLine$()
Definition:

Reads command line parameters passed at runtime.

Parameter Description:

None.

Command Description:

If you are writing an application or game that allows starting with special parameters on the command line,
you can use this command to retrieve the parameters.

For example, you might want to start the program with a debug variable set so you can track stuff during
execution. So, you could offer the ability to run the executatble with a /debug parameter. If they execute the
program with the parameter, then you can set a flag inside your game.

To simulate the command line passing in the editor, select PROGRAM->PROGRAM COMMAND LINE from the
pulldowns and enter a value to be passed at runtime.

See the example.

Example:

; CommandLine$() Example
; Be sure to use PROGRAM->PROGRAM COMMAND LINE from the
; pull down and put /debug in there to test with.

a$=CommandLine$()

If a$="/debug" Then
Print "Debug mode is on!"
debug=1
Else
Print "No debugging activated."
debug=0
End If

Const variablename
Definition:

Declare a variable as a constant and assign it a value.

Parameter Description:

variablename = any valid variable name and its assignment

Command Description:

This delares a variable as a constant (a variable whose value will never change and cannot be changed) and
assigns the value to it.

Assign constants to values you know will not change in your game (screen width, height - scoring values -
etc). This reduces the load of the variable memory, since Blitz knows it will never change size unlike other
variables which can grow and shrink in size based on what value it holds.
Example:

; CONST Example

Const scrWidth=640
Const scrHeight=480
Const alienscore=100

Graphics scrWidth,scrHeight

Print "The point value for shooting any alien is always " + alienscore

CopyBank src_bank,src_offset,dest_bank,dest_offset,count
Definition:

Copies data from one bank to another.

Parameter Description:

src_bank = handle of source memory bank


src_offset = offset location to start copying from
dest_bank = handle of destination memory bank
dest_offset = offset location to start writing to
count = how many bytes to copy

Command Description:

Copies data from one meomry bank to another. If copying between the same banks, handles overlapping
memory ranges.

Example:

; BankSize, ResizeBank, CopyBank Example

; create a bank
bnkTest=CreateBank(5000)

; Fill it with rand Integers


For t = 0 To 4999
PokeByte bnkTest,t,Rand(9)
Next

; Resize the bank


ResizeBank bnkTest,10000

; Copy the first half of the bank to the second half


CopyBank bnkTest,0,bnkTest,5000,5000

; Print final banksize


Print BankSize(bnkTest)

CopyFile from$, to$


Definition:

Copies a file on the disk to a new location.


Parameter Description:

from$ = valid path/filename to the file to be copied


to$ = valid path/filename to copy the file to

Command Description:

Use this command to copy a file from one location to another. Perhaps you'll write your own installer and need
to copy files from the installation folder to the installed location folder. Make sure you do your own validation
to ensure that the files/paths are valid and accurate before executing this command.

Example:

file$="c:\autoexec.bat"
destination$="a:\autoexec.bat"

Print "Press any key to copy your Autoexec.bat file to floppy"

WaitKey()

CopyFile file$,destination$

CopyImage (handle)
Definition:

Duplicates a previously loaded image to a new handle.

Parameter Description:

handle=the variable you gave the handle to when you loaded the image

Command Description:

Instead of loading a graphic twice in two different handles, you can load the image ONCE then use the
CopyImage command to make as many copies in memory as you want.

Why would you want to do this? So you still have a copy of the original image in case you want to alter a copy
later for another purpose.

Example:

; CopyImage Example

; Load an image and give its handle to gfxOld variable


gfxOld=LoadImage("mypicture.bmp")

; Duplicate the gfxOld image to a new handle variable


gfxNew=CopyImage(gfxOld)

CopyPixel src_x,src_y,src_buffer,dest_x,dest_y,[dest_buffer]
Definition:

Copys pixels from one image buffer to another.


Parameter Description:

src_x = x location of the source pixel to copy


src_y = y location of the source pixel to copy
src_buffer = buffer to copy from
dest_x = x location to write pixel to
dest_y = y location to write pixel to
dest_buffer = optional

Command Description:

Use this to directly copy pixels from one buffer to another. You do not need to LockBuffer to use this
command, but it will make the operations faster.

Although fast, this command will not be fast enough to perform real-time screen effects.

Example:

; CopyPixel/CopyPixelFast commands

Graphics 640,480,16

; Draw a bunch of crap on the screen


For t= 1 To 1000
Color Rnd(255),Rnd(255),Rnd(255)
Rect Rnd(640),Rnd(480),Rnd(150),Rnd(150),Rnd(1)
Next

Delay 3000

; Copy the top half of the screen over the bottom half
; using fast pixels and locked buffers
For x = 1 To 640
For y = 1 To 240
LockBuffer FrontBuffer()
CopyPixelFast x,y,FrontBuffer(),x,y+241
UnlockBuffer FrontBuffer()
Next
Next

Delay 3000

; Draw the left half of the screen over the right half
; using the slower direct pixel access
For x = 1 To 320
For y = 1 To 480
CopyPixel x,y,FrontBuffer(),x+320,y
Next
Next

CopyPixelFast src_x,src_y,src_buffer,dest_x,dest_y,[dest_buffer]
Definition:

Quickly copies pixels from one image buffer to another.

Parameter Description:

src x = x location of the source pixel to copy


src_y = y location of the source pixel to copy
src_buffer = buffer to copy from
dest_x = x location to write pixel to
dest_y = y location to write pixel to
dest_buffer = optional

Command Description:

Use this to directly copy pixels from one buffer to another. You MUST use LockBuffer on BOTH image buffers
to use this command.

Although very fast, this command will not be fast enough to perform real-time screen effects.

Example:

; CopyPixel/CopyPixelFast commands

Graphics 640,480,16

; Draw a bunch of crap on the screen


For t= 1 To 1000
Color Rnd(255),Rnd(255),Rnd(255)
Rect Rnd(640),Rnd(480),Rnd(150),Rnd(150),Rnd(1)
Next

Delay 3000

; Copy the top half of the screen over the bottom half
; using fast pixels and locked buffers
For x = 1 To 640
For y = 1 To 240
LockBuffer FrontBuffer()
CopyPixelFast x,y,FrontBuffer(),x,y+241
UnlockBuffer FrontBuffer()
Next
Next

Delay 3000

; Draw the left half of the screen over the right half
; using the slower direct pixel access
For x = 1 To 320
For y = 1 To 480
CopyPixel x,y,FrontBuffer(),x+320,y
Next
Next

CopyRect
src_x,src_y,src_width,src_height,dest_x,dest_y,[src_buffer],[dest_buffer]
Definition:

Copies a rectangle of graphics from one buffer to another.

Parameter Description:

src_x = source top left x location to begin copying from


src_y = source top left y location to begin copying from
src width = width of source area to copy
src_height = height of source area to copy
dest_x = destination top left x location to copy to
dest_y = destination top left y location to copy to
src_buffer = handle to the source image buffer (optional)
dest_buffer = handle to the destination image buffer (optional)

Command Description:

Copies a rectangle of graphics from one buffer to another. If a buffer is omitted, the current buffer is used.

Example:

; CopyRect Example

; Turn on graphics mode


Graphics 800,600,16

; create a blank image


gfxBlank=CreateImage (300,300)

; Fill the screen with random boxes in random colors


For t = 1 To 1000
Rect Rand(800),Rand(600),Rand(100),Rand(100),Rand(0,1)
Color Rand(255),Rand(255),Rand(255)
Next

; Wait a couple of seconds so the user can see it


Delay 2000

; Copy graphics randomly from the front buffer to the blank image
CopyRect Rand(800),Rand(600),300,300,0,0,FrontBuffer(),ImageBuffer(gfxBlank)

; Clear the screen, draw the copied to image, wait for user to hit a key
Cls
DrawImage gfxBlank,0,0
WaitKey

CopyStream

Parameters:

src_stream --
dest_stream --
[buffer_size] --

Description:

CopyStream () ...

Example:

; Example

Cos (Number)
Definition:

The Cos command is a trigonometry function, that returns a number between -1 and 1. This value represents
the "X" coordinate of point x,y.

Parameter Description:

number=float or integer representing a value in degree

Command Description:

This command is used for translating angle values to coordinates, but there are a few things you have to take
into account when doing it. First of all the Cos() command assumes the point you want is at radius 1 (pixel),
next it uses a circle where 0 degrees is due EAST and increases in a counterclockwise direction, then you've
got to take into account the the Y axis on a computer screen is up-side-down compared to a normal
mathematical coordinate system.

See also ASin, Cos, ACos, Tan, Atan, ATan2

Example:

Graphics 640,480; Change to graphics mode, nothing tricky yet.


Origin 320,240 ; Move the point of orign for all drawing commands to the middle of the screen.

For degrees=0 To 359; Step though all the degrees in a circle (360 in all)
Delay(5); Wait 5 milli secsonds.

; The next line calculates the Y coordinate of the point of the circle using the Sin
; command, and multiplies it by 100 (to get a larger radius, try and change it).
y=Sin(degrees)*100

y=-y ; Invert Y coordinate to represent it properly on screen.

; The next line calculates the X coordinate of the point of the circle using the Cos,
; command, and multiplies it by 100 (to get a larger radius, try and change it).
x=Cos(degrees)*100

Rect x,y,1,1 ; Draw the current point on the circle.

Next ; Give us another angle

MouseWait ; Wait for the mouse.


End ; Terminate the program.

CountGfxDrivers()
Definition:

Returns the number of graphic drivers on the system.

Parameter Description:

None.

Command Description:

Some computers may have more than one video card and/or video driver installed (a good example is a
computer system with a primary video card and a Voodoo2 or other pass-through card). Once you know how
many drivers there are, you can iterate through them with GfxDriverName$ and display them for the user to
choose from. Once the user has chosen (or you decide), you can set the graphics driver with SetGfxDriver.
Normally, this won't be necessary with 2D programming.

Example:

; GfxDriver Examples

; Count how many drivers there are


totalDrivers=CountGfxDrivers()
Print "Choose a driver to use:"

; Go through them all and print their names (most people will have only 1)
For t = 1 To totalDrivers
Print t+") " + GfxDriverName$(t)
Next

; Let the user choose one


driver=Input("Enter Selection:")

; Set the driver!


SetGfxDriver driver
Print "Your driver has been selected!"

CountGFXModes()
Definition:

Returns the number of video graphic modes available.

Parameter Description:

None.

Command Description:

Use this command to return the number of video modes the user's video card can display in. Use the
GFXModeWidth, GFXModeHeight, and GFXModeDepth with each number of video mode to determine the width,
height, and color depth capabilities of each mode. See example.

Example:

; CountGFXModes()/GfxModeWidth/GfxModeHeight/GfxModeDepth example

intModes=CountGfxModes()

Print "There are " + intModes + "graphic modes available:"

; Display all modes including width, height, and color depth


For t = 1 To intModes
Print "Mode " + t + ":
Print "Width=" + GfxModeWidth(t)
Print "Height=" + GfxModeHeight(t)
Print "Height=" + GfxModeDepth(t)
Next

CountHostIPs( host_name$ )
Parameters:

host_name$ - name of host

Description:

Searches for hosts with the specified name, and returns the number of matching hosts found.

Example:

None.

CPUTimer()
Definition:

Returns the current value of the CPU timer.

Parameter Description:

None.

Command Description:

This returns a constantly counting up timer, apparently from the CPU. Seems to always be negative. This
could be useful for soem randomize seed, but for any sort of 'time tracking', I would use Millisecs(). This
command could be outdated, and just not removed from the product.

Example:

;CPUTIMER() example

While Not keyhit(1)


Print CPUTimer()
Wend

CreateBank (size)
Definition:

Create a data bank.

Parameter Description:

size = size of memory bank in bytes

Command Description:

The bank commands allow you to make your own memory bank to perform your own read and write
operations to. This is useful for compression/decompression, level data, and tons of other uses.

This command allocates the memory and creates a handle to the bank.

Example:
; Bank Commands Example

bnkTest=CreateBank(500)

For t = 1 To 50
PokeByte bnkTest,t,Rnd(255)
PokeInt bnkTest,t+1,Rnd(10000)
PokeShort bnkTest,t+2,Rnd(10000)
PokeFloat bnkTest,t+3,Rnd(-.999,.999)
Next

For t = 1 To 50
Print PeekByte (bnkTest,t)
Print PeekInt (bnkTest,t+1)
Print PeekShort (bnkTest,t+2)
Print PeekFloat (bnkTest,t+3)
Next

Freebank bnkTest

CreateDir path/name
Definition:

Creates a directory/folder on a storage device.

Parameter Description:

path/name = full path and name for new directory

Command Description:

Creates a directory (file folder) at the destination specified. Do not use a trailing slash at the end of the
path/name parameter. You cannot be sure the directory was created with this command, so you will need to
verify its existance yourself (use the FILETYPE command).

Example:

; CREATEDIR example

fldr$="c:\winnt\system32\myfolder"
createDir fldr$
Print "Folder created!"

CreateImage (width,height[,frames])
Definition:

Create a new image in memory and give its handle to a variable.

Parameter Description:

width=width of the new image (or its frames)


height=height of the new image
frames= optional number of frames (assumed to be a single frame)
Command Description:

Sometimes you want to create a completely new graphic on the fly (using other images, drawing commands,
etc.) instead of loading one. This command will let you create a new image with a single frame or multiple
frames for animation. You specify the width, height, and optional number of frames. The example should be
pretty self-explainatory.

Example:

; CreateImage/TileImage/ImageBuffer example

; Again, we'll use globals even tho we don't need them here
; One variable for the graphic we'll create, one for a timer
Global gfxStarfield, tmrScreen

; Declare graphic mode


Graphics 640,480,16

; Create a blank image that is 320 pixels wide and 32 high with 10 frames of 32x32
gfxStarfield=CreateImage(32,32,10)

; loop through each frame of the graphic we just made


For t = 0 To 9
; Set the drawing buffer to the graphic frame so we can write on it
SetBuffer ImageBuffer(gfxStarfield,t)
; put 50 stars in the frame at random locations
For y = 1 To 50
Plot Rnd(32),Rnd(32)
Next
Next

; Double buffer mode for smooth screen drawing


SetBuffer BackBuffer()

; Loop until ESC is pressed


While Not KeyHit(1)

; Only update the screen every 300 milliseconds. Change 300 for faster or
; slower screen updates
If MilliSecs() > tmrScreen+300 Then
Cls ; clear the screen

; Tile the screen with a random frame from our new graphic starting at
; x=0 and y=0 location.
TileImage gfxStarfield,0,0,Rnd(9)
Flip ; Flip the screen into view
tmrScreen=MilliSecs() ; reset the time
End If
Wend

CreateNetPlayer (name$)
Definition:

Creates a new local player on the network game.

Parameter Description:

name$ = any valid string holding the player's name.


Command Description:

Creates a new local player. This also causes a special message to be sent to all remote machines (see
NetMsgType). This returns an integer player number to be used in sending/receiving messages. Note that you
must create at least one player before you can send and receive messages.

Example:

; CreateNetPlayer example

newGame = StartNetGame()
; Check the status of the new game.
If newGame = 0 Then
Print "Could not start or join net game."
End

ElseIf newGame = 1
Print "Successfully joined the network game"
ElseIf newGame = 2
Print "A new network game was started!"
EndIf

; Create a random player name


name$="Player" + Rand(100)

; Get a unique player id number for the player


; and create the player
playerID=CreateNetPlayer(name$)

If playerID = 0 Then
Print "Player could not be created!"
Else
Print "Player " + name$ + " was created and given ID#" + playerID
End If
WaitKey()

CreateTCPServer (port)
Definition:

Creates a TCP server on the specified port.

Parameter Description:

port = the port to use when creating the server

Command Description:

Creates a TCP/IP server with the designated port. Use this for communications between other clients and the
local box. See OpenTCPStream, CloseTCPServer, and CloseTCPStream for more information.

Returns a TCP/IP server handle if successful or 0 if not.

Example:

; CreateTCPServer, CloseTCPServer, AcceptTCPStream Example


; This code is in two parts, and needs to be run seperately on the same machine

; --- Start first code set ---


; Create a server and listen for push

svrGame=CreateTCPServer(8080)

If svrGame<>0 Then
Print "Server started successfully."
Else
Print "Server failed to start."
End
End If

While Not KeyHit(1)


strStream=AcceptTCPStream(svrGame)
If strStream Then
Print ReadString$(strStream)
Delay 2000
End
Else
Print "No word from Apollo X yet ..."
Delay 1000
End If
Wend

End

; --- End first code set ---

; --- Start second code set ---


; Copy this code to another instance of Blitz Basic
; Run the above code first, then run this ... they will 'talk'

; Create a Client and push data

strmGame=OpenTCPStream("127.0.0.1",8080)

If strmGame<>0 Then
Print "Client Connected successfully."
Else
Print "Server failed to connect."
WaitKey
End
End If

; write stream to server


WriteString strmGame,"Mission Control, this is Apollo X ..."
Print "Completed sending message to Mission control..."

; --- End second code set ---

CreateTimer (frequency)
Definition:

Creates a timer to track a frequency.

Parameter Description:

frequency = usually a framerate like 50 or 60

Command Description:
Use this command in conjunction with the WaitTimer command to control the speed of program execution
(fps). You will use this in your main screen redraw loop to control the playback speed to match the proper
speed. This will prevent your games from playing back too fast on computers faster than yours. Use of this
system is VERY GOOD practice, as your game will be played on a variety of computers.

Example:

; Create the timer to track speed


frameTimer=CreateTimer(60)

; Your main screen draw loop


While Not KeyHit(1)
WaitTimer(frameTimer) ; Pause until the timer reaches 60
Cls
; Draw your screen stuff
Flip
Wend

CreateUDPStream( [port] )

Parameters:

port (optional) - port number

Description:

Creates a UDP stream at the specified port, and returns a UDP stream handle. If no port is specified, a free
port will be allocated and you can then use UDPStreamPort() to find out the allocated port.

Example:

None.

CurrentDate$()
Definition:

Returns the current system date.

Parameter Description:

None

Command Description:

Returns the current date in the format: DD MON YYYY (i.e. 10 DEC 2000).

Example:

; Print the current date to the screen

Print "The date is:" + CurrentDate$()


CurrentDir$()
Definition:

Returns a string containing the currently selected directory.

Parameter Description:

None.

Command Description:

This command will return the currently selected directory for disk operations, useful for advanced file
operations. Use CHANGEDIR to change the current directory. The value returned doesn't have a trailing slash -
aside from the root directory of the drive.

Example:

; CurrentDir$() example

; Print the current directory until ESC key


While Not KeyHit(1)
Print CurrentDir$()
Wend

CurrentTime$()
Definition:

Returns the current system time.

Parameter Description:

None

Command Description:

Returns the current time in the format: HH:MM:SS (i.e. 14:31:57).

Example:

; Print the current time to the screen

Print "The Time is:" + CurrentTime$()

Data list_of_values
Definition:

Creates a list of constant values to be parsed through within your program

Parameter Description:
list_of_values = a list of comma delimited values (strings must be inside quotes)

Command Description:

Data is used to create neat, comma delimited lists of values of a constant nature that you will be reading (and
probably reusing) during the execution of your game. You may store level information (number of enemies,
stars, etc) there or just about anything you can think of! You can easily mix datatypes (strings, integers,
floats) in your Data statements, as long as they are read properly with the Read command later. You will need
to use the Restore command to point to the .Label that begins your Data statements. See the related
commands for more information and more examples.

Example:

Print "Here we go!"

; Restore to the start of the Data statements


Restore startData

; Get the first number which is the total number of users


Read Users

; Print them all!


For T = 1 To Users
Read firstname$
Read age
Read accuracy#
Read lastname$
Print firstname$ + " " + lastname$ + " is " + age + " years old with " + accuracy# + " accuracy!"
Next

While Not KeyHit(1)


Wend
End

.startData
Data 3
Data "Shane", 31, 33.3333, "Monroe"
Data "Bob", 28, 12.25, "Smith"
Data "Roger", 54, 66.66, "Rabbit"

DebugLog message
Definition:

Writes a message to the debug log for debugging purposes.

Parameter Description:

message = message text string value

Command Description:

You power programmers will just love this. You have your own debug log to write to!

For those not familiar to this sort of thing, think of the Debug log like your own private 'in program notepad'.
Use this to write messages to yourself during program execution. For example, you could write the graphic
modes that the user has on his system, or just little alerts to let you know your code execution made it to a
certain point in the execution without interrupting it. I'm sure you'll find a lot of uses for this! See the example
if you're still lost.

Example:

; DebugLog Example

; Let's start graphics mode


Graphics 640,480,16

; Now, let's load an image that doesn't exist!


gfxPlayer=LoadImage("noimagefound.jpg")
If gfxPlayer=0 Then
DebugLog "Player's Graphics failed to load!"
End If

; This is supposed to generate an error. Press F9 to see the log!


While Not KeyHit(1)
DrawImage gfxPlayer,100,100
Wend

Default
Definition:

Specifies the set of commands that executes in a Select structure if none of the CASEs are met.

Parameter Description:

None.

Command Description:

In a SELECT structure, you may wish to execute code if none of the cases you specify are met. All code after
DEFAULT to END SELECT will be executed if no case is met. See SELECT, CASE, and the example for more.

Example:

; SELECT/CASE/DEFAULT/END SELECT Example


; Assign a random number 1-10
mission=Rnd(1,10)

; Start the selection process based on the value of 'mission' variable


Select mission

; Is mission = 1?
Case 1
Print "Your mission is to get the plutonium and get out alive!"

; Is mission = 2?
Case 2
Print "Your mission is to destroy all enemies!"

; Is mission = 3?
Case 3
Print "Your mission is to steal the enemy building plans!"

; What do do if none of the cases match the value of mission


Default
Print "Missions 4-10 are not available yet!"
; End the selection process
End Select

Delay milliseconds
Definition:

Pause program execution for a certain time.

Parameter Description:

milliseconds = the amount of milliseconds to delay. 1000=1 second

Command Description:

This command stops all program execution for the designated time period. All execution stops. If you need
program execution to continue, consider trapping time elapsed with a custom timer function using Millisecs().

Example:

; Delay for 5 seconds

Delay 5000

Delete custom_type_name
Definition:

Delete an object from a custom TYPE collection.

Parameter Description:

custom_type_name = the custom name of an existing object

Command Description:

If you haven't read up on the TYPE command, you might want to do so before continuing.

Use the Delete command to remove an object from the Type collection. Use the commands FIRST, LAST,
BEFORE, and NEXT to move the object pointer to the object you want to delete, then issue the Delete
command with the custom Type name.

This is often used in a FOR ... EACH loop when a collision happens and you wish to remove the object (an alien
ship object for example) from the collection.

Example:

; Move them all over 1 (like the description example from TYPE command)
; If the chair isn't on the screen anymore, delete that chair object from the
; collection.

For room.chair = Each chair


room\x = room\x + 1
if room\x > 640 then
Delete room
Next

DeleteDir directory/path
Definition:

Deletes a specified folder/directory.

Parameter Description:

directory/path = full path/name of directory

Command Description:

Deletes a specified folder/directory from the device. Note: This only works on EMPTY directories - you cannot
delete a folder with other folders or files inside with this command. Do not apply a trailing slash.

Example:

; DeleteDir example

DeleteDir "C:\test"

DeleteFile path/filename
Definition:

Deletes a specified file.

Parameter Description:

path/filename = full path/filename to the file to delete

Command Description:

Deletes a specified file from the drive. You will need to make sure the file exists before execution and be sure
its been deleted AFTER execution. Use FILETYPE to determine this.

Example:

; DELETEFILE example

DeleteFile "C:\test\myfile.bb"

DeleteNetPlayer playerID
Definition:

Deletes a local player from the network game.


Parameter Description:

playerID = value assigned when player was created with CreateNetPlayer

Command Description:

Using the playerID generated by the CreateNetPlayer command, this command will remove the designated
player from the network game.

This also causes a special message to be sent to all remote machines (see NetMsgType).

Example:

; DeleteNetPlayer example

newGame = StartNetGame()
; Check the status of the new game. If newGame = 0 Then
Print "Could not start or join net game."
End

ElseIf newGame = 1
Print "Successfully joined the network game"
ElseIf newGame = 2
Print "A new network game was started!"
EndIf

; Create a random player name


name$="Player" + Rand(100)

; Get a unique player id number for the player


; and create the player
playerID=CreateNetPlayer(name$)

If playerID = 0 Then
Print "Player could not be created!"
Else
Print "Player " + name$ + " was created and given ID#" + playerID
WaitKey()
; delete the player!
DeleteNetPlayer playerID
Print "The local player was deleted!"
End If
waitkey()

Dim variable(elements)
Definition:

Dimensions an array variable for storage.

Parameter Description:

variable = variable of desired type (string, floating, integer)


elements = number of elements to be created. Can be multi-dimensional.

Command Description:

Prepares an array using the specified variable type as its type and specified elements for the number of
containers it should hold. You may use as many dimension elements as you like (just watch your memory).
There is no way in Blitz to 'Redimension' arrays, so define them accordingly. Use the proper notation on the
declaration variable to make it a string($), floating(#), or integer type array. Note: Arrays always start at
ZERO reference - so variable(0) is always the first element.

To use this command effectively, you must understand arrays. Think of an array like a variable that has
multiple slots to hold many values, all under the same variable name. Before TYPEs came around, this was the
best way to track repeating elements (say, alien ships) because you can iterate through an array collection
easily.

Take for example, you want to track 100 aliens on the screen. You could have two variables - alienx and
alieny. By making these arrays - alienx() and alieny() and each having 100 elements each, you could easily
set or retrieve the first alien's location by using alienx(1), alieny(1). The next alien's coordinates would be
alienx(2), alienx(2) and so on. This makes it easy to use a FOR ... NEXT or EACH loop to go through all the
elements.

Arrays are also useful for 'multi-dimensional' notation too. Instead of tracking our 100 aliens in the method
mentioned above, you could use a single variable: alien(100,1). The first element collection are the 100 aliens,
the second element is the X and Y location of that alien - the 0 element being the alien's X location, and the 1
element being the alien's Y location. So to set the position of alien 57 to X=640,Y=480 you could do this:

alien(57,0)=640
alien(57,1)=480
DrawImage imgAlien,alien(57,0),alien(57,1)

Of course, TYPEs are a much better way of doing this sort of multiple value sort of routine.

Arrays are great for tracking collections of items with a single, common element - but often times TYPEs will
prove to be more useful.

Example:

; DIM example
; Create a collection of 100 random numbers

; Declare our array


Dim nums(100)

; Fill each element with a random number


For T = 1 to 100
nums(t) = Rnd(1,100)
Next

DottedIP$( IP )

Parameters:

IP - integer IP address

Description:

Converts an integer IP address to dotted internet notation.

Example:

None.
DrawBlock image,x,y,[frame]
Definition:

Draws an image at a location without regards to transparency.

Parameter Description:

image = variable of the image handle


x = x location to draw the image
y = y location to draw the image
frame = image's frame to draw (optional - default is 0)

Command Description:

This is similar to the DrawImage command except that any transparency or MaskImage is ignored and the
entire image (including masked colors) is drawn. The frame is optional.

Example:

; DrawBlock Example

; Turn on graphics mode


Graphics 640,480,16

; Create new empty graphic to store our circle in


gfxCircle=CreateImage(50,50)

; Draw the circle image


; Set drawing operations to point to our new empty graphic
SetBuffer ImageBuffer(gfxCircle)
Color 255,0,0
; Note the extra space between the circle and the edge of the graphic
Oval 10,10,30,30,1

; Let's not forget to put the drawing buffer back!


SetBuffer BackBuffer()
; Set the CLS color to white
ClsColor 255,255,255

; Let the user move the circle graphic around a white screen
; putting the graphic at the MouseX,Y coordinates
While Not KeyHit(1)
Cls
DrawBlock gfxCircle,MouseX(),MouseY()
Flip
Wend

DrawBlockRect image,x,y,rect_x,rect_y,rect_width,rect_height,[frame]
Definition:

Draws a rectangular area of an image at the designated location without transparency.

Parameter Description:

image = variable holding the image handle


x = x location on the screen to draw the image
y = y location on the screen to draw the image
rect_x = starting x location within the image to draw
rect_y = starting y location within the image to draw
rect_width = the height of the area to draw
rect_height = the width of the area to draw
frame = optional frame number of image to draw

Command Description:

This command will let you draw a rectangular PORTION of an image to the designated location on the screen.
The transparent/masked portions of the original image will be ignored and drawn with the image.

This is handy if you are doing something like revealing part of a screen when the player uncovers something
(think QIX). You could load the 'picture' into an image, then when the player clears a rectangular region, you
could paste that portion of the final image onto the playfield. If you want to draw the image portion with
transparency or masking, use DrawImageRect instead.

Example:

; DrawBlockRect Example

; Turn on graphics mode


Graphics 640,480,16

; Create new empty graphic to store our circle in


gfxCircle=CreateImage(50,50)

; Draw the circle image


; Set drawing operations to point to our new empty graphic
SetBuffer ImageBuffer(gfxCircle)
Color 255,0,0
; Note the extra space between the circle and the edge of the graphic
Oval 10,10,30,30,1
SetBuffer FrontBuffer()

; Set the screen to white so you can see the transparent areas
ClsColor 255,255,255
Cls

; Let's draw portions of the circle randomly


While Not KeyHit(1)
; We take random sized portions of the circle and put them
; at a random location ... wash, rinse, and repeat
DrawBlockRect gfxCircle,Rnd(640),Rnd(480),0,0,Rnd(50),Rnd(50),0
Delay 100
Wend

DrawImage handle,x,y,[frame]
Definition:

Draws an image or frame of an animImage on the screen.

Parameter Description:

handle = variable image handle previously designated


x = the 'x' location of the screen to display the graphic
y = the 'y' location of the screen to display the graphic
frame = the frame number of the AnimImage to display (optional; 0 is assumed)
Command Description:

This command draws a previously loaded graphic. This command draws both single image graphics (loaded
with the LoadImage command) as well as animated images (loaded with the LoadAnimImage command).

You specify where on the screen you wish the image to appear. You can actually 'draw' off the screen as well
by using negative values or positive values that are not visible 'on the screen'.

Finally, if you are using an animated image (loaded with the LoadAnimImage), you can specify which frame of
the imagestrip is displayed with the DrawImage command.

One of the most common problems new Blitz programmers face when using drawing commands is that even
though they draw the graphic to the screen, they never see it!

Remember, Blitz Basic is fast ... too fast for the human eye. You will have to either continuously draw the
image over and over again (like the way a cartoon or TV works), clearing the screen each time a change is
made (this is called double buffering); or you will need to delay Blitz's execution long enough in 'human time'
to let you SEE the picture. We will do the double buffering approach.

Example:

; LoadImage and DrawImage example

; Declare a variable to hold the graphic file handle


Global gfxPlayer

; Set a graphics mode


Graphics 640,480,16

; Set drawing operations for double buffering


SetBuffer BackBuffer()

; Load the image and assign its file handle to the variable
; - This assumes you have a graphic called player.bmp in the
; same folder as this source code
gfxPlayer=LoadImage("player.bmp")

; Let's do a loop where the graphic is drawn wherever the


; mouse is pointing. ESC will exit.
While Not KeyHit(1)
Cls ; clear the screen
DrawImage gfxPlayer,MouseX(),MouseY() ; Draw the image!
Flip ; flip the image into view and clear the back buffer
Wend

DrawImageRect image,x,y,rect_x,rect_y,rect_width,rect_height,[frame]
Definition:

Draws a rectangular area of an image at the designated location.

Parameter Description:

image = variable holding the image handle


x = x location on the screen to draw the image
y = y location on the screen to draw the image
rect_x = starting x location within the image to draw
rect_y = starting y location within the image to draw
rect_width = the height of the area to draw
rect height = the width of the area to draw
frame = optional frame number of image to draw

Command Description:

This command will let you draw a rectangular PORTION of an image to the designated location on the screen.
The transparent/masked portions of the original image will be drawn transparent, just as you normally would
draw an image.

This is handy if you are doing something like revealing part of a screen when the player uncovers something
(think QIX). You could load the 'picture' into an image, then when the player clears a rectangular region, you
could paste that portion of the final image onto the playfield. If you want to draw the image portion with no
transparency or mask, use DrawBlockRect instead.

Example:

; DrawImageRect Example

; Turn on graphics mode


Graphics 640,480,16

; Create new empty graphic to store our circle in


gfxCircle=CreateImage(50,50)

; Draw the circle image


; Set drawing operations to point to our new empty graphic
SetBuffer ImageBuffer(gfxCircle)
Color 255,0,0
; Note the extra space between the circle and the edge of the graphic
Oval 10,10,30,30,1
SetBuffer FrontBuffer()

; Let's draw portions of the circle randomly


While Not KeyHit(1)
; We take random sized portions of the circle and put them
; at a random location ... wash, rinse, and repeat
DrawImageRect gfxCircle,Rnd(640),Rnd(480),0,0,Rnd(50),Rnd(50),0
Delay 100
Wend

Each type_variable
Definition:

Used to iterate through a collection of TYPE objects.

Parameter Description:

type_variable = A previously declared TYPE object

Command Description:

If you haven't read up on the TYPE command, you might want to do so before continuing.

The For .. Each loop allows you to walk through each object in the Type collection. This is perfect for updating
a large group of objects (such as a group of alien invaders). Do look over the Type command.

Example:
; Move them all over 1 (like the description example from TYPE command)

For room.chair = Each chair


room\x = room\x + 1
Next

Else If
Definition:

Performs an additional IF condition check during an IF ... THEN conditional structure.

Parameter Description:

None

Command Description:

During a standard IF ... THEN conditional structure, you may wish to check another condition if the original
condition fails. This 'nested IF' situation can get WAY out of hand, and once you have more than two nested
conditionals, you should consider a SELECT/CASE structure. See the example.

Example:

; ELSE IF Example

; Input the user's name


name$=Input$("What is your name? ")

; Doesn't the person's name equal SHANE?


If name$ = "Shane" Then

Print "You are recognized, Shane! Welcome!"

Else If name$="Ron" then


Print "You are recognized too, Ron! Welcome!"

Else
Print "Sorry, you don't belong here!"

; End of the condition checking


End If

Else
Definition:

Begins the code to be executed in the event the IF conditional fails.

Parameter Description:

None.

Command Description:
There are times during an IF ... THEN conditional that you will want code to execute in the event that the
conditional is NOT met. The ELSE command begins that block of code, and is terminated by the END IF
command. See example.

Example:

; ELSE example

name$=Input$("What is your name?")

If name$="Shane" then
Print "Hello Shane!"
Else
Print "I have NO clue who you are!"
End If

ElseIf
Definition:

Alternate command for the END IF command, it performs an additional IF condition check during an IF ...
THEN conditional structure.

Parameter Description:

None

Command Description:

During a standard IF ... THEN conditional structure, you may wish to check another condition if the original
condition fails. This 'nested IF' situation can get WAY out of hand, and once you have more than two nested
conditionals, you should consider a SELECT/CASE structure. See the example.

Example:

; ELSEIF Example

; Input the user's name


name$=Input$("What is your name? ")

; Doesn't the person's name equal SHANE?


If name$ = "Shane" Then

Print "You are recognized, Shane! Welcome!"

ElseIf name$="Ron" then


Print "You are recognized too, Ron! Welcome!"

Else
Print "Sorry, you don't belong here!"

; End of the condition checking


End If
End Function
Definition:

Denotes the end of a Function structure.

Parameter Description:

None.

Command Description:

This line terminates a FUNCTION structure. Upon reaching this line, Blitz will branch program execution to the
next command following the original call to the function. See the FUNCTION command for more information.

Example:

; End Function Example

; Get the user's name


name$=Input$("Enter Your Name:")

; Call a function to print how many letters the name has


numletters(name$);

;The program basically ends here, because functions don't run unless called.

; The actual function


Function numletters(passedname$)
Print "Your name has " + Len(passedname$) + " letters in it."
End Function

End If
Definition:

Closing element of an IF/THEN condition checking structure.

Parameter Description:

None.

Command Description:

END IF signals the end of an IF THEN condition check. See IF for more information. You can also use ENDIF as
a single word command - it functions identically.

Example:

; IF THEN Example

; Input the user's name


name$=Input$("What is your name? ")

; Doesn't the person's name equal SHANE?


If name$ = "Shane" Then

Print "You are recognized, Shane! Welcome!"


Else

Print "Sorry, you don't belong here!"

; End of the condition checking


End If

End Select
Definition:

The closing command in a SELECT structure.

Parameter Description:

None.

Command Description:

This command ends the SELECT structure. If you are using DEFAULT commands, this is the ending point of
that command set's execution. See SELECT, CASE, and DEFAULT for more information.

Example:

; SELECT/CASE/DEFAULT/END SELECT Example


; Assign a random number 1-10
mission=Rnd(1,10)

; Start the selection process based on the value of 'mission' variable


Select mission

; Is mission = 1?
Case 1
Print "Your mission is to get the plutonium and get out alive!"

; Is mission = 2?
Case 2
Print "Your mission is to destroy all enemies!"

; Is mission = 3?
Case 3
Print "Your mission is to steal the enemy building plans!"

; What do do if none of the cases match the value of mission


Default
Print "Missions 4-10 are not available yet!"

; End the selection process


End Select

End Type
Definition:

The last command of the TYPE ... END TYPE object creation.
Parameter Description:

None

Command Description:

If you haven't read up on the TYPE command, you might want to do so before continuing.

After assigning all the Field variables in your Type object, use this to finish the creation of the Type.

Example:

; Define the CHAIR Type

Type CHAIR
Field X
Field Y
Field HEIGHT
End Type

End
Definition:

Stops the program execution and exits the program.

Parameter Description:

None

Command Description:

Use this command to stop your program running. You will be returned to the editor if running from there, or
the program will completely exit if running a compiled EXE version.

Example:

; If the game is over, then quit

if gameOver=1 then End

EndGraphics
Definition:

Ends the graphics mode.

Parameter Description:

None

Command Description:

This command ends the graphics mode, and puts Blitz back into 'text' mode (for lack of a better term).
Example:

; End Graphics Example

; Enter graphics mode


Graphics 640,480,16

; Print hello 10 times on the graphic screen


For t = 1 To 10
Print "Hello"
Next

; Wait for a left mouse button


While Not MouseHit(1)
Wend

; End the graphics mode


EndGraphics

; Print again, this time to the text screen


For t = 1 To 10
Print "There"
Next

EndIF
Definition:

Another acceptable version of the END IF statement

Parameter Description:

None.

Command Description:

Terminates an IF ... THEN condition structure. See END IF for more information.

Example:

; IF THEN Example

; Input the user's name


name$=Input$("What is your name? ")

; Doesn't the person's name equal SHANE?


If name$ = "Shane" Then

Print "You are recognized, Shane! Welcome!"

Else

Print "Sorry, you don't belong here!"

; End of the condition checking


EndIf
EOF (filehandle|stream)
Definition:

Checks to see if the End Of File (or stream) has been reached.

Parameter Description:

filehandle|stream = a valid variable set with the OpenFile, ReadFile command, or OpenTCPStream (v1.52+)

Command Description:

Checks to see if the End of File of an opened file or stream has been reached. Use this to determine if you
should continue to pull more information from a file/stream or not. Use this to read a text file of unknown
length (say a README.TXT) and display it. See example.

Eof returns 1 if eof has been reached or, in the case of a TCP stream, the stream has been 'nicely' closed.

Eof returns -1 if something has gone wrong during stream processing.

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; EOF sample

file$="c:\autoexec.bat"

filein = ReadFile(file$)

Print "Here is your Autoexec.bat file ..."

; Loop this until we reach the end of file


While Not Eof(filein)
Print ReadLine$(filein)
Wend

ExecFile (filename$)
Definition:

Runs an external executable program from within a Blitz program.

Parameter Description:

filename$ = any valid variable or path/filename to the executable program

Command Description:

Use this command to halt execution of your program and run an external program.

The usefulness of this command is really mostly for calling some system level command, launching a browser,
etc. Without the ability to playback a movie (for cutscenes, etc) I would think the most useful part of this is
command would be calling a self-contained .exe movie (a la BLINK) to play as an intro, then when its
completed, return to your program for continued execution.

Note: This command uses ShellExecute to allow you to 'open' any file (like a .doc or .txt) file with its default
associated program.
Example:

; ExecFile sample - RUN THIS WINDOWED!


; Win9x users will need to change location of calc.exe

filename$="c:\winnt\system32\calc.exe"

Print "Press any key to run CALC.EXE!"

WaitKey()

ExecFile(filename$)

Print "Press any key to quit."

WaitKey()

Exit
Definition:

Exits a loop prematurely.

Parameter Description:

None

Command Description:

This command will allow you to leave a For .. Next loop as well as many other types of loops prematurely
(assuming a condition was met or other planned event). It exits the IMMEDIATE loop - you'll need one for
each 'nest' of loops you want to exit from.

Example:

; EXIT Command sample

For t = 1 To 100
Print t
If t = 50 Then Exit
Next

Exp (number)
Definition:

Returns the base of the natural system of logarithms e, raised to the power of the supplied argument.

Parameter Description:

number=float or integer

Command Description:

Exp() is the exponential function. Logarithms to the base e are called the Natural or Napierian logarithms. The
Exp() and Log functions use the transcendental number e as a base (approx 2.718). Exp() is the inverse of the
antilogarithm Log function. See also: Log Log10

Example:

; To find the value of e


print Exp(1) ; i.e. e^1, returns 2.718281
; To find the value of e^5
print Exp(5) ; returns 148.413162

False
Definition:

A boolean expression used in comparisons. Actually returns a value of 0.

Parameter Description:

None.

Command Description:

FALSE is a keyword to denote a negative result in a conditional statement. Often times, FALSE is implied and
doesn't need to be directly referenced - or a NOT command is used in the comparison. FALSE can also be used
as a RETURN value from a FUNCTION. Also see the TRUE command. See the example.

Example:

; FALSE example

; Assign test a random number of 0 or 1


test= Rnd(0,1)

; FALSE is implied because of the NOT


If not test=1 Then
Print "Test was valued at 0"
End If

; Let's set test to be false


test=False

; Pointlessly test it
If test=False Then
Print "Test is false"
else
print "Test is true"
End If

Field variable
Definition:

Assigns a variable for use into a TYPE object structure.

Parameter Description:
variable = any legal variable

Command Description:

If you haven't read up on the TYPE command, you might want to do so before continuing.

When you define a custom Type, you need to assign some variables to track within in. Using the Field
command within the Type .. End Type commands, you set a variable that can be used for EACH object created
with the NEW command.

Example:

; Define the CHAIR Type

Type CHAIR
Field X
Field Y
Field HEIGHT
End Type

; Create 100 new chairs using FOR ... NEXT using the collection name of ROOM

For tempx = 1 to 10
For tempy = 1 to 10
room.chair = New Chair
room\x = tempx
room\y = tempy
room\height = Rnd(0,10) ; set a random height 0 to 10
Next
Next

; Move them all over 1 (like the description example from TYPE command)

For room.chair = Each chair


room\x = room\x + 1
Next

FilePos (filehandle)
Definition:

Returns the current position within a file that is being read, written or modified.

Parameter Description:

filehandle = the variable returned by the Readfile WriteFile or OpenFile when the file was opened. The value
returned is the offset from the start of the file. ( 0 = Start of the file )

Command Description:

This command returns the current position within a file that is being processed following ReadFile, WriteFile or
OpenFile. The returned integer is the offsets in bytes from the start of the file to the current read/write
position. Note, this is zero when pointing to the first byte of the file.

By using FilePos and SeekFile the position within the file that is being read or written can be determined and
also changed. This allows a file to be read and updated without having to make a new copy of the file or
working through the whole file sequentially. This could be useful if you have created a database file and you
want to find and update just a few records within it. It is also possible to create an index file that contains
pointers to where each record starts in a data file.

Example:

; Changing part of a file using OpenFile, SeekFile, FilePos


; note FilePos is used in the SearchFile function at the end of this example

; Open/create a file to Write


fileout = WriteFile("mydata.dat")

; Write the information to the file


WriteInt( fileout, 1 )
WriteInt( fileout, 2 )
WriteInt( fileout, 3 )
WriteInt( fileout, 4 )
WriteInt( fileout, 5 )

; Close the file


CloseFile( fileout )

DisplayFile( "The file as originally written", mydata.dat" )


Position = SearchFile( 4 , "mydata.dat" )
Write "Value 4 was found "
Write Position
Print " bytes from the start."
Print

; Open the file and change the value 3 to 9999

file = OpenFile("mydata.dat")
SeekFile( file, Position ) ; Move to the found location
WriteInt( file, 9999 ) ; Replace the original value with 9999
CloseFile( file )

DisplayFile( "The file after being modified", "mydata.dat" )


WaitKey()
End ; End of program

; **** Function Definitions follow ****

; Read the file and print it


Function DisplayFile( Tittle$, Filename$ )
Print tittle$
file = ReadFile( Filename$ )
While Not Eof( file )
Number = ReadInt( file )
Print Number
Wend
CloseFile( file )
Print
End Function

; Search a file of integers for the Wanted data value


; Note the need to subtract 4 from the location since having read it
; we are now pointing at the next Integer also Return() was placed
; after closing the file so it is closed properly
Function SearchFile( Wanted, Filename$ )
file = ReadFile( Filename$ )
While Not Eof( file )
If ReadInt( file ) = Wanted Then Location = FilePos( file ) - 4
Wend
CloseFile( file )
Return( Location )
End Function

FileSize (filename$)
Definition:

Returns the size of the requested file - in bytes.

Parameter Description:

filename$ = any valid variable with path/filename

Command Description:

Often it will be useful to return the size of a file. File size is important for copying, reading, and other file
evolutions.

Example:

; Windows 9x users will need to change location of calc.exe

filename$="c:\winnt\system32\calc.exe"

Print "The size of the file is: " + FileSize(filename$)

Print "Press any key to quit."

WaitKey()

FileType (filename$)
Definition:

Checks to see if the designated filename exists or is a directory.

Parameter Description:

filename$ = any valid variable with path/filename

Command Description:

This command checks the filename you pass and determines if it exists and whether or not it is a valid
filename or if it is a directory. Here are the values it returns:

1 = The filename exists


0 = The filename doesn't exist
2 = The filename is not a file - but a directory

Use this to validate that a file exists before you do something to it.

Example:

; Windows 9x users will need to change location of calc.exe

filename$="c:\winnt\system32\calc.exe"
if fileType(filename$)=1 then Print "The file exists!"
if fileType(filename$)=0 then Print "File not found!"
if fileType(filename$)=2 then Print "This is a directory!"

Print "Press any key to quit."

WaitKey()

FindGfxMode (width,height,depth)
Definition:

Returns the mode number of a graphic mode meeting your criteria.

Parameter Description:

width = width, in pixels (i.e. 640)


height = height, in pixels (i.e. 480)
depth = color depth (i.e. 16, 24, 32)

Command Description:

Use this command to determine which of the user's graphic card mode supports the parameters you supply.
You can get a full detailed list of the video card modes - see CountGFXModes().

Example:

; FindGFXMode example

; change values to see different mode numbers


mode=FindGfxMode(800,600,16)

; If there is a mode, tell user


If mode > 0 Then
Print "The mode you requested is: " + mode
Else
Print "That mode doesn't exist for this video card."
End If

; Wait for ESC press from user


While Not KeyHit(1)
Wend

First type_variable
Definition:

Move the Type object pointer to the first object in the collection.

Parameter Description:

type_variable = the actual Type name, not the custom Type name

Command Description:
If you haven't read up on the TYPE command, you might want to do so before continuing.

Use this to assign a custom Type object to the first object in the collection. See the example.

Example:

; Define a crafts Type

Type crafts
Field x
Field y
Field dead
Field graphic
End Type

; Create 100 crafts, with the unique name of alien


For t = 1 To 100
alien.crafts = New crafts
alien\x = Rnd(0,640)
alien\y = Rnd(0,480)
alien\dead = 0
alien\graphic = 1
Next

; Move to the first object


alien.crafts = First crafts

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

; move to the next alien object


alien = After alien

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

; move to the last alien object


alien.crafts = Last crafts

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

; move to the second to the last alien object


alien = Before alien

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

Flip [vwait]
Definition:
In a double buffering environment, flips the BackBuffer into view.

Parameter Description:

vwait = set to TRUE to wait for vertical blank to finish

Command Description:

When you are double buffering (or doing all drawing operations to the BackBuffer(), at some point, after
you've drawn all your elements - you will need to 'flip' that Backbuffer into the visible FrontBuffer() so it can
be seen. This command will perform this function. This allows you to draw massive amounts of information
quickly, then flip it into view. See BackBuffer() for more info.

Example:

; Flip/Backbuffer()/Rect Example

; Set Graphics Mode


Graphics 640,480

; Go double buffering
SetBuffer BackBuffer()

; Setup initial locations for the box


box_x = -20 ; negative so it will start OFF screen
box_y = 100

While Not KeyHit(1)


Cls ; Always clear screen first
Rect box_x,box_y,20,20,1 ; Draw the box in the current x,y location
Flip ; Flip it into view
box_x = box_x + 1 ; Move the box over one pixel
If box_x = 640 Then box_x=-20 ; If it leaves the Right edge, reset its x location
Wend

Float variable/value
Definition:

Convert integer value to a floating point number.

Parameter Description:

variable/value = integer value or variable

Command Description:

Use this command to transform an integer value to a floating point value (presumably to perform a floating
point related math function on it). Blitz does a good job of adding dissimilar number types, but if you want to
play by the rules and/or port code to/from Blitz, remember to convert your integers to floating point before
doing math upon them with dissimilar types.

Example:

; Float example

a=100
b#=2.5
c#=Float a

Print b# + c#

Floor# (float)
Definition:

Rounds a decimal floating variable down to the nearest whole number.

Parameter Description:

float=floating point number

Command Description:

Many times, you will need to round up or down a floating point decimal variable. This command rounds it
down to the nearest whole number. Use Ceil# to round the number up.

Example:

; Floor#/Ceil# Example

; Set a floating point variable


myVal#=0.5

; Round it up
Print Floor#(myval)

;Round it down
Print Ceil#(myval)

FlushJoy
Definition:

Flushes out all the queued up joystick button presses.

Parameter Description:

None.

Command Description:

There are many times when you aren't interested in the dozens of possible joystick button pressed the player
might have made before you are checking for one in particular. Or perhaps you want to pause the game and
wait for any joystick button to be hit, but you don't want a 'queued' button press bypassing this. Use this
command before you specifically want to poll a joystick button hit from the user.

Example:

; FlushJoy sample

FlushJoy
Print "Press a joystick button to exit!"

WaitJoy()

End

FlushKeys
Definition:

Flushes all the currently queued keystrokes.

Parameter Description:

None.

Command Description:

This command 'resets' or 'empties out' the queue holding the keyboard inputs. Can't make it much easier than
that.

Example:

; clear all keystrokes from the queue


FlushKeys

FlushMouse
Definition:

Flushes out all the queued up mouse button presses.

Parameter Description:

None.

Command Description:

There are many times when you aren't interested in the dozens of possible mouse button pressed the player
might have made before you are checking for one in particular. Or perhaps you want to pause the game and
wait for any mouse button to be hit, but you don't want a 'queued' button press bypassing this. Use this
command before you specifically want to poll a mouse button hit from the user.

Example:

; Flushmouse sample

FlushMouse

Print "Press a mouse button to exit!"

WaitMouse()

End
FontHeight()
Definition:

Returns the height of the currently selected font.

Parameter Description:

None.

Command Description:

This returns the height, in pixels, of the currently selected font (using SetFont - previously loaded with
LoadFont).

Example:

; FontWidth()/FontHeight example

; enable graphics mode


Graphics 800,600,16

; Set global on font variable


Global fntArial

;Load fonts to a file handle variables


fntArial=LoadFont("Arial",13,False,False,False)

; set the font and print sizes


SetFont fntArial
Text 400,0,"The font width of the widest character is:"+ FontWidth(),True,False
Text 400,30,"The height of the font is:"+ FontHeight(),True,False

; Standard 'wait for ESC' from user


While Not KeyHit(1)
Wend

; Clear all the fonts from memory!


FreeFont fntArial

FontWidth()
Definition:

Returns the width of the widest character of the currently selected font.

Parameter Description:

None.

Command Description:

This returns the width, in pixels, of the currently selected font (using SetFont - previously loaded with
LoadFont). This command returns the width of the WIDEST character of the font.

Example:
; FontWidth()/FontHeight example

; enable graphics mode


Graphics 800,600,16

; Set global on font variable


Global fntArial

;Load fonts to a file handle variables


fntArial=LoadFont("Arial",13,False,False,False)

; set the font and print sizes


SetFont fntArial
Text 400,0,"The font width of the widest character is:"+ FontWidth(),True,False
Text 400,30,"The height of the font is:"+ FontHeight(),True,False

; Standard 'wait for ESC' from user


While Not KeyHit(1)
Wend

; Clear all the fonts from memory!


FreeFont fntArial

For variable
Definition:

First command of the FOR ... NEXT loop.

Parameter Description:

variable = any valid variable name

Command Description:

The first command of the FOR ... NEXT loop, this command is used to assign a variable to a range of numbers
in sequence and execute a set of code that many times. Using the STEP command allows you to skip a certain
value between each loop of the code.

This is frequently used when a specific pattern of numbers is needed to perform an evolution (moving
something from point A to point B, adding a value to a score incrementally, etc). This allows you to assign a
variable with the current value of the loop. See the example for more.
Note: Unlike many BASIC languages, the NEXT command does NOT use the FOR command's variable as an
identifier. If you have nested FOR ... NEXT commands, the language will automatically match the NEXT with
the nearest FOR command.

Example:

; Print the values 1 through 10


For t = 1 To 10
Print t
Next

; Print the values 1,3,5,7,9


For t = 1 To 10 Step 2
Print t
Next
Forever
Definition:

Used in a REPEAT loop to make the loop run endlessly.

Parameter Description:

None.

Command Description:

Replace the UNTIL command in a REPEAT ... UNTIL loop to make the loop run forever. Remember, the
program execution will continue indefinately until either you break out of it programmatically! This is often
known as 'the infinate loop'. Once more for the cheap seats: "Make sure you provide a means for breaking out
of the loop". Use EXIT (to leave the loop) or END to quit the program.

Example:

; FOREVER Example

Repeat
If KeyHit(1) Then Exit
Print "You are trapped in an infinate loop! Press ESC!"
Forever

Print "The infinate loop has ended!"

FreeBank bank
Definition:

Frees a memory bank from memory.

Parameter Description:

bank = variable containing handle to valid bank

Command Description:

This releases a memory bank allocated with the CreateBank command.

Example:

; Bank Commands Example

bnkTest=CreateBank(500)

For t = 1 To 50
PokeByte bnkTest,t,Rnd(255)
PokeInt bnkTest,t+1,Rnd(10000)
PokeShort bnkTest,t+2,Rnd(10000)
PokeFloat bnkTest,t+3,Rnd(-.999,.999)
Next

For t = 1 To 50
Print PeekByte (bnkTest,t)
Print PeekInt (bnkTest,t+1)
Print PeekShort (bnkTest,t+2)
Print PeekFloat (bnkTest,t+3)
Next

Freebank bnkTest

FreeFont fonthandle
Definition:

Deletes a previously loaded font and frees its memory.

Parameter Description:

fontname = string containing font name


height = font height desired
bold = set to TRUE to load font as BOLD
italic = set to TRUE to load font as ITALIC
underlined set to TRUE to load font as UNDERLINED

Command Description:

This removes a TrueType font previously loaded into memory (though the LoadFont command).

Note: Blitz doesn't work with SYMBOL fonts, like Webdings and WingDings.

Example:

; LoadFont/SetFont/FreeFont example

; enable graphics mode


Graphics 800,600,16

; Set global on font variables


Global fntArial,fntArialB,fntArialI,fntArialU

;Load fonts to a file handle variables


fntArial=LoadFont("Arial",24,False,False,False)
fntArialB=LoadFont("Arial",18,True,False,False)
fntArialI=LoadFont("Arial",32,False,True,False)
fntArialU=LoadFont("Arial",14,False,False,True)

; set the font and print text


SetFont fntArial
Text 400,0,"This is just plain Arial 24 point",True,False

SetFont fntArialB
Text 400,30,"This is bold Arial 18 point",True,False

SetFont fntArialI
Text 400,60,"This is italic Arial 32 point",True,False

SetFont fntArialU
Text 400,90,"This is underlined Arial 14 point",True,False

; Standard 'wait for ESC' from user


While Not KeyHit(1)
Wend

; Clear all the fonts from memory!


FreeFont fntArial
FreeFont fntArialB
FreeFont fntArialI
FreeFont fntArialU

FreeImage handle
Definition:

Removes the designated image from memory.

Parameter Description:

handle=variable that holds the image handle of a previously loaded image

Command Description:

When you are done with an image, use this command to delete the image from memory and free up that
memory for other use. Good housekeeping. Get in the habit!

Example:

; FreeImage command

; Global, as always, for graphics


Global gfxPlayer

; Enter graphics mode and start double buffering


Graphics 640,480,16
SetBuffer BackBuffer()

; Load the image-assign the handle to gfxPlayer


gfxPlayer=LoadImage("player.bmp")

; draw the image at random until ESC pressed


While Not KeyHit(1)
Cls
DrawImage gfxPlayer,Rnd(640),Rnd(480)
Flip
Wend

; Erase the image from memory!


FreeImage gfxPlayer

FreeSound sound_variable
Definition:

Delete the sound and free up the memory it was using.

Parameter Description:

sound_variable - and valid variable previously created with the LoadSound command.

Command Description:
When you are finished using a sound effect, you should free up the memory its using and delete the sound.
This command will delete a sound instance variable created with the LoadSound command.

Why would you want to do this? Perhaps you have different sets of sounds for different levels of your game?
Perhaps your music loop changes from level to level. You want to do the RIGHT thing and manage your own
resources. Just because you CAN load every sample for the whole game at once, consider someone that
doesn't have as much memory as you do. You want to ensure that your game appeals to the widest audience
possible. Note: You don't have to manually free these resources when your program terminates - Blitz does
this automatically.

Example:

; Load a sound into memory


sndOneUp=LoadSound("audio\1up.wav")

; Free the memory up and delete the sound


FreeSound sndOneUp

FreeTimer (timer_variable)
Definition:

Destroys the timer specified and frees up its memory.

Parameter Description:

timer = any valid timer variable created with the CreateTimer command.

Command Description:

This command will destroy a timer variable created with the with the CreateTimer command and free the
memory it was using. It is a good practice to destroy elements in your game you are no longer using.

Example:

; Create the timer to track speed


frameTimer=CreateTimer(60)

; Your main screen draw loop


While Not KeyHit(1)
WaitTimer(frameTimer) ; Pause until the timer reaches 60
Cls
; Draw your screen stuff
Flip
Wend

; Kill the timer


FreeTimer(frameTimer)

FrontBuffer()
Definition:

Designates the front buffer as the drawing buffer.


Parameter Description:

None

Command Description:

Its important to understand buffers when writing a game.

What the player can see at any given time is usually the front buffer. Anything you draw to this buffer is
IMMEDIATELY visible to the player. This sounds fast (and it is) but the problem is that when you are drawing
to the front buffer - like a piece of paper and pencil - anything you draw on the screen overwrites anything
else that exists in the same space. So, if you want to 'save' any portion of the screen from being overwritten
by another drawing operation, YOU - the programmer - have to copy the area 'under' the location of the new
operation to an image so you can replace it later. Imagine taking a piece of paper with a picture of some
mountains, and making an airplane pass in front of them, inch by inch. Every time the plane moves, you have
to draw the new area that will be under the plane next on another sheet of paper (so you know what it looked
like) then draw the plane over the new place. Next time you move, you will repeat this, then draw the image
back in the OLD plane location. This process is labor-intensive and largely unnecessary thanks to a process
called DOUBLE BUFFERING (see BackBuffer(). Double buffering is used for pretty much all games for high-
action with lots of objects on the screen.

So, if double buffering rocks so much, why would you WANT to ever draw to the front buffer? Sometimes, you
just want to draw crap to the screen, without caring what you overwrite. You don't have to worry about
redrawing the screen over and over again in double buffering in this case. Just set the buffer to FrontBuffer()
and you can write directly to the screen in real time.

Example:

; FrontBuffer()/Rect Example

; Engage graphics mode


Graphics 640,480,16

; Set the drawing buffer to front - instant drawing ops!


SetBuffer FrontBuffer()

; Repeat this until user presses ESC


While Not KeyHit(1)
; Set a random color
Color Rnd(255),Rnd(255),Rnd(255)
; Draw a rectangle at a random location, with a random width and height
; plus randomly choose if the rectangle is solid or just an outline
Rect Rnd(640),Rnd(480),Rnd(50),Rnd(50),Rnd(0,1)
; Blitz is so dang fast, we need a delay so you can watch it draw!
Delay 10
Wend

Function name
Definition:

Begins a standalone snippet of code that is callable from your program.

Parameter Description:

name = any valid name text that is not a keyword of Blitz.

Command Description:
A function is a routine of commands you may choose to call frequently within your program. Functions are
considered 'proper' practice in this situation, instead of using GOSUB commands.

Functions are independant of your 'main code' and will only execute if they are called. They have their own
namespace, and variables created outside a function are NOT available within the function (this goes for TYPE
structures as well) unless you declare the variable or Type structure as GLOBAL.

You can pass variables into functions, as well as RETURN boolean values (True/False) back to the calling code.

The practical use of functions is to help seperate your code into managable chunks for subsequent perfection
of a routine. You may put all your screen updates into a single function, for example. Or perhaps your scoring
system where you pass it what alien has been destroyed and it updates the player's score.

Once the function reaches the END FUNCTION command, it returns program execution to the next line
following the function call.

Functions can be a bit daunting until you realize they really are their own little programs within your program.
See the example for more.

Example:

; Function Example

; Get the user's name


name$=Input$("Enter Your Name:")

; Call a function to print how many letters the name has


numletters(name$);

; Let's get something BACK from the function


thefirst$=firstletter(name$)

; Now print results


Print "Was the first letter an 'S'? (1=True/0=False)" + thefirst$

;The program basically ends here, because functions don't run unless called.

; The actual function


Function numletters(passedname$)
Print "Your name has " + Len(passedname$) + " letters in it."
End Function

; Function to see if the first letter is S


Function firstletter(passedname$)

; If the first letter is an 'S' then return from the function a true value
If Left$(passedname$,1) = "S" Then
Return True

; Otherwise, return false


Else

Return False

End If
End Function

GetColor x, y
Definition:
Sets the current drawing color to the color of the pixel designated.

Parameter Description:

x = x coordinate of pixel
y = y coordinate of pixel

Command Description:

This command works like a 'color picker' in your favorite paint program. By specifying

Example:

; GetColor Example

Graphics 320,200
SetBuffer BackBuffer()

For t = 1 To 1000
Color Rnd(255), Rnd(255), Rnd(255)
Rect Rnd(320),Rnd(200),10,10,1
Next

GetColor 100,100
Print "Box at 100,100 is RGB:" + ColorRed() + "," + ColorGreen() + "," + ColorBlue() + "!"
Flip
While Not KeyHit(1)
Wend

GetJoy ([port])
Definition:

Checks to see if a joystick button has been pressed - returns the number of the button or 0 if no button is
pressed.

Parameter Description:

port = optional joystick port to read

Command Description:

Unlike the other similar commands (JoyDown and JoyHit), this command doesn't need to know which button
you are trying to test for. It looks for any joystick button, then returns the number the user pressed. Since
you are polling all the buttons instead of just a specific one, this may be a tad less efficient than using
JoyDown or JoyHit. Use this command in conjunction with Select/Case for maximum efficiency!

Example:

; GetJoy Example

While Not KeyHit(1)


button=GetJoy()
If button <> 0 Then
Print "You pressed joystick button #" + button
End If
Wend

GetKey()
Definition:

Checks for a keypress and returns its ASCII value.

Parameter Description:

None

Command Description:

This command will check to see if a key has been pressed and will return its ASCII value. Not all keys have
ASCII values - if you need to trap SHIFT, ALT, or other non-ASCII compliant key, try KeyHit or KeyDown.

Example:

; GetKey Example

Print "Please press any ASCII key ..."

While Not value


value=GetKey()
Wend

Print "You pressed key with an ASCII value of:" + value

GetMouse()
Definition:

Checks to see if a mouse button has been clicked - returns the number of the button or 0 if no button is
clicked.

Parameter Description:

None.

Command Description:

Unlike the other similar commands (MouseDown and MouseHit), this command doesn't need to know which
button you are trying to test for. It looks for any mouse button, then returns the number the user clicked.
Since you are polling all the mouse buttons instead of just a specific one, this may be a tad less efficient than
using MouseDown or MouseHit. Use this command in conjunction with Select/Case for maximum efficiency!

Example:

; GetMouse Example

While Not KeyHit(1)


button=GetMouse()
If button <> 0 Then
Print "You pressed mouse button #" + button
End If
Wend

GfxDriverName$ (index)
Definition:

Returns the title of a graphic driver.

Parameter Description:

index = index number obtained with CountGfxDrivers command

Command Description:

Some computers may have more than one video card and/or video driver installed (a good example is a
computer system with a primary video card and a Voodoo2 or other pass-through card).

Once you know how many drivers there are using CountGfxDrivers(), you can iterate through them with this
command and display them for the user to choose from. Once the user has chosen (or you decide), you can
set the graphics driver with SetGfxDriver.

Normally, this won't be necessary with 2D programming.

Example:

; GfxDriver Examples

; Count how many drivers there are


totalDrivers=CountGfxDrivers()
Print "Choose a driver to use:"

; Go through them all and print their names (most people will have only 1)
For t = 1 To totalDrivers
Print t+") " + GfxDriverName$(t)
Next

; Let the user choose one


driver=Input("Enter Selection:")

; Set the driver!


SetGfxDriver driver
Print "Your driver has been selected!"

GFXModeDepth (mode)
Definition:

Returns the color depth capability of the selected video mode.

Parameter Description:

None.

Command Description:
Once you determine the video modes available by the video card using CountGFXModes(), you can iterate
through them and determine the width, height, and color depth capabilities of each mode. Use this command
to get the color depth of the mode. Use the GFXModeWidth and GFXModeHeight to get the remaining
parameters.

Example:

; CountGFXModes()/GfxModeWidth/GfxModeHeight/GfxModeDepth example

intModes=CountGfxModes()

Print "There are " + intModes + "graphic modes available:"

; Display all modes including width, height, and color depth


For t = 1 To intModes
Print "Mode " + t + ":
Print "Width=" + GfxModeWidth(t)
Print "Height=" + GfxModeHeight(t)
Print "Height=" + GfxModeDepth(t)
Next

GfxModeExists (width,height,depth)
Definition:

Checks to see if the designated graphic mode exists.

Parameter Description:

width = width, in pixels (i.e. 640)


height = height, in pixels (i.e. 480)
depth = color depth (i.e. 16, 24, 32)

Command Description:

Use this command to verify whether or not the user's video card can use this graphic mode. Returns TRUE if
the mode exists, FALSE if not. If you want to know what mode number this mode is, use FindGFXMode.

Example:

; GFXModeExists example

; If there is a mode, tell user


mode=GfxModeExists(800,800,16)

If mode=1 Then
Print "The mode you requested exists!"
Else
Print "Sorry, that mode doesn't exist."
End If

; Wait for ESC press from user


While Not KeyHit(1)
Wend

GFXModeHeight (mode)
Definition:

Returns the height capability of the selected video mode.

Parameter Description:

None.

Command Description:

Once you determine the video modes available by the video card using CountGFXModes(), you can iterate
through them and determine the width, height, and color depth capabilities of each mode. Use this command
to get the height of the mode. Use the GFXModeWidth and GFXModeDepth to get the remaining parameters.

Example:

; CountGFXModes()/GfxModeWidth/GfxModeHeight/GfxModeDepth example

intModes=CountGfxModes()

Print "There are " + intModes + "graphic modes available:"

; Display all modes including width, height, and color depth


For t = 1 To intModes
Print "Mode " + t + ":
Print "Width=" + GfxModeWidth(t)
Print "Height=" + GfxModeHeight(t)
Print "Height=" + GfxModeDepth(t)
Next

GFXModeWidth (mode)
Definition:

Returns the width capability of the selected video mode.

Parameter Description:

None.

Command Description:

Once you determine the video modes available by the video card using CountGFXModes(), you can iterate
through them and determine the width, height, and color depth capabilities of each mode. Use this command
to get the width of the mode. Use the GFXModeHeight and GFXModeDepth to get the remaining parameters.

Example:

; CountGFXModes()/GfxModeWidth/GfxModeHeight/GfxModeDepth example

intModes=CountGfxModes()

Print "There are " + intModes + "graphic modes available:"

; Display all modes including width, height, and color depth


For t = 1 To intModes
Print "Mode " + t + ":
Print "Width=" + GfxModeWidth(t)
Print "Height=" + GfxModeHeight(t)
Print "Height=" + GfxModeDepth(t)
Next

Global variable
Definition:

Declares global variables for use with your program.

Parameter Description:

variable = any valid variable/TYPE name

Command Description:

There are two types of variables in Blitz Basic; local variables and global variables. Global variables can be
utilized anywhere in your program (i.e. the main program look and all functions. Use global variables when
you need to track a value across your entire program (player score, lives, etc. You can also define TYPEs as
global as well.

Example:

Global player1score ; Declare player 1's score as global


Global graph.Cursor ; Declare the Cursor TYPE as global

Gosub label
Definition:

Branches execution of a program to a designated label with the intention of returning to the original calling
code.

Parameter Description:

label = any valid exisiting label

Command Description:

This branches the flow of the program to a designated label, with the understanding that there will be a Return
later on in the called code to resume execution of the program where the Gosub was called. With the use of
Functions inside of Blitz, it isn't very practical to use Gosubs, but you may still find it useful. If you do not
require the need to return execution back to the Gosub statement, you may use Goto instead. See the
example.

Example:

Print "The program starts ..."


Gosub label1
Print "The Program ends ..."

; wait for ESC key before ending


While Not KeyHit(1)
Wend

End
.label1
Print "We could do all sorts of things in this part of the program..."
Print "But, we'll just go back to the original code, instead ..."
Return

Goto label
Definition:

Branches execution of a program to a designated label.

Parameter Description:

label = any valid exisiting label

Command Description:

This branches the flow of the program to a designated label. With the use of Functions inside of Blitz, it isn't
very practical to use Gotos, but you may still find it useful. If you require the need to return execution back to
the calling statement, you may use Gosub instead. See the example.

Example:

Print "The program starts ..."


Goto label1
Print "This line never gets printed .."
End

.label1
Print "We just jumped here!"

; wait for ESC key before ending


While Not KeyHit(1)
Wend

GrabImage image,x,y,[frame]
Definition:

Grabs a portion of the current drawing buffer and sticks it into an image.

Parameter Description:

image = variable of image handle


x = starting x location to grab
y = starting y location to grab
frame = optional frame to insert the grabbed image into

Command Description:

Quite possibly one of the most useful yet underdocumented, confusing commands in the Blitz Basic language
is GrabImage.
This command allows you to grab a portion of the current drawing buffer (this could be an image too if you've
set it as an ImageBuffer) and stick it into an image.

There are a million and one uses for this command, so I'll let you use your imagination. However, the
command doesn't make much sense as it is documented, so let me clarify.

First, you must use CreateImage to create a new blank image in which to grab to. Whatever size you create
the image, THAT is how much of the buffer will be grabbed from the x,y location you specify in GrabImage.

For example, you create a new image with a size of 50 pixels by 50 pixels. When you call GrabImage, you
choose x=100, y=100. The area you will grab and put into your new image will be 100,100 to 150,150. If you
attempt to GrabImage into an image variable that hasn't been created yet, you will get an error.

Note: You can REPLACE an existing image with a grabbed one.

See the example for a more practical look.

Example:

; GrabImage example

; Turn on graphics
Graphics 640,480,16

; We'll be drawing right to the front buffer


SetBuffer FrontBuffer()

; You must create an empty image to grab from first


gfxGrab=CreateImage(100,100)

; Draw random rectangles on the screen until the


; user presses ESC
While Not KeyHit(1)
; random color
Color Rnd(255),Rnd(255),Rnd(255)
; super random rectangles
Rect Rnd(640),Rnd(480),Rnd(100),Rnd(100),Rnd(1)
Delay 50
Wend

; Now, grab an image, starting at 100,100 and put it in gfxGrab


GrabImage gfxGrab,100,100

; Clear screen and show user the grabbed image


Cls
Text 0,0, "Here is your grabbed image! Press a mouse key ..."
DrawImage gfxgrab,50,50

; Wait for a mouse press


WaitMouse()

Graphics width, height, color depth,[mode]


Definition:

Sets the graphics mode for the screen.

Parameter Description:

width = width of screen in pixels (640, 800, etc)


height = height of screen in pixels (480, 600, etc)
color depth = depth in bits (16, 24, or 32 bit - use 16 if possible!)
mode = Video mode (see description); Optional

Command Description:

This command sets Blitz into 'graphics' mode with the specified width, height, and color depth (in bits). This
command must be executed before any graphic related commands can be used. Color depth is OPTIONAL and
should be left blank if possible - Blitz will determine the best color mode automatically for the user's video
card.

Valid graphic width and height varies GREATLY from card to card so to be sure your users can display the
mode you wish, use the GfxModeExists command to be sure before you try and set the mode yourself.
Common resolutions that are probably safe are 640x480 and 800x600. Try to avoid odd screen modes like
640x400 as MANY MANY cards cannot display them. Chances are if you can set your Windows screen
resolution to a particular resolution, then Blitz will behave in that resolution also.

Remember, each step higher in resolution and color depth mark a large jump in system requirements and may
be inversely proportionate to system performance. If you use the lowest resolution and depth possible to meet
your desired game parameters, it will allow more people with lesser systems than your own still play and
enjoy your game. This is why many games still support a 640x480 mode :)

An extra parameter is used at the end of the command after the color depth. Here are the parameters:

0 : auto - windowed in debug, fullscreen in non-debug (this is the default)


1 : fullscreen mode
2 : windowed mode
3 : scaled window mode

Example:

;GRAPHICS Example

; Set The Graphic Mode


Graphics 800,600

; Now print something on the graphic screen


Text 0,0, "This is some text printed on the graphic screen (and a white box)! Press ESC ..."

; Now for a box


Rect 100,100,200,200,1

While Not KeyHit(1)


Wend

GraphicsBuffer()
Definition:

Returns the handle of the current graphics buffer.

Parameter Description:

None

Command Description:

Use this command to get which buffer Blitz is currently writing to.
Example:

; GraphicsWidth(), GraphicsHeight(), GraphicsDepth(), GraphicsBuffer() example

; Set a graphics mode and buffer


Graphics 640,480,16
SetBuffer FrontBuffer()

; Print the details


Print "Screen width is: " + GraphicsWidth()
Print "Screen height is: " + GraphicsHeight()
Print "Screen color depth is: " + GraphicsDepth()
Print "Current buffer handle is: " + GraphicsBuffer()

; Wait for ESC before exiting


While Not KeyHit(1)
Wend

GraphicsDepth()
Definition:

Returns the color depth of the current graphics mode.

Parameter Description:

None

Command Description:

This command will tell you the color depth of the current graphics mode.

Example:

; GraphicsWidth(), GraphicsHeight(), GraphicsDepth(), GraphicsBuffer() example

; Set a graphics mode and buffer


Graphics 640,480,16
SetBuffer FrontBuffer()

; Print the details


Print "Screen width is: " + GraphicsWidth()
Print "Screen height is: " + GraphicsHeight()
Print "Screen color depth is: " + GraphicsDepth()
Print "Current buffer handle is: " + GraphicsBuffer()

; Wait for ESC before exiting


While Not KeyHit(1)
Wend

GraphicsHeight()
Definition:

Returns the height, in pixels, of the current graphics mode.

Parameter Description:
None

Command Description:

This command will tell you the height, in pixels, of the current graphics mode.

Example:

; GraphicsWidth(), GraphicsHeight(), GraphicsDepth(), GraphicsBuffer() example

; Set a graphics mode and buffer


Graphics 640,480,16
SetBuffer FrontBuffer()

; Print the details


Print "Screen width is: " + GraphicsWidth()
Print "Screen height is: " + GraphicsHeight()
Print "Screen color depth is: " + GraphicsDepth()
Print "Current buffer handle is: " + GraphicsBuffer()

; Wait for ESC before exiting


While Not KeyHit(1)
Wend

GraphicsWidth()
Definition:

Returns the width, in pixels, of the current graphics mode.

Parameter Description:

None

Command Description:

This command will tell you the width, in pixels, of the current graphics mode.

Example:

; GraphicsWidth(), GraphicsHeight(), GraphicsDepth(), GraphicsBuffer() example

; Set a graphics mode and buffer


Graphics 640,480,16
SetBuffer FrontBuffer()

; Print the details


Print "Screen width is: " + GraphicsWidth()
Print "Screen height is: " + GraphicsHeight()
Print "Screen color depth is: " + GraphicsDepth()
Print "Current buffer handle is: " + GraphicsBuffer()

; Wait for ESC before exiting


While Not KeyHit(1)
Wend
HandleImage image,x,y
Definition:

Set a new handle location on an existing image.

Parameter Description:

image = variable holding the file handle to the image


x = x location of the new image handle location
y = y location of the new image handle location

Command Description:

When an image is loaded with LoadImage, the image handle (the location within the image where the image is
'drawn from') is always defaulted to the top left corner (coordinates 0,0). This means if you draw an image
that is 50x50 pixels at screen location 200,200, the image will begin to be drawn at 200,200 and extend to
250,250.

This command moves the image handle from the 0,0 coordinate of the image to the specified x and y location
in the image. You can retrieve an image's current location handle using the ImageXHandle and ImageYHandle.
Finally, you can make all images automatically load with the image handle set to middle using the
AutoMidHandle command.

Note about the term 'handle'. There are two types of 'handles' we discuss in these documents. One is the
location within an image - as discussed in this command. The other is a 'file handle', a variable used to hold an
image, sound, or font loaded with a command. See LoadImage for more information about file handles.

Also See: MidHandle

Example:

;HandleImage Example

Graphics 800,600,16

gfxPlayer=LoadImage("player.bmp")
HandleImage gfxPlayer,20,20
DrawImage gfxPlayer,0,0
WaitKey

Hex$ (integer)
Definition:

Converts an integer value to a hexidecimal value.

Parameter Description:

integer = any valid integer or integer variable

Command Description:

Converts integer values into hexidecimal values. If you don't know what hex is, you don't need to know this
command :)

Example:

intValue="64738"
Print "The hexidecimal value of "+intValue+" is: " + hex$(intValue)

HidePointer

Parameters:

n/a

Description:

HidePointer is for use in windowed display modes, and simply hides the Windows pointer when it is moved
over your game's window. You can bring it back via ShowPointer. It has no effect in full-screen modes.

Example (using ShowPointer):

Graphics 640, 480, 0, 2

HidePointer

Print "Move pointer over window and press a key..."


WaitKey

ShowPointer

Delay 1000

HostIP( host_index )

Parameters:

host_index - index number of host

Description:

Returns an integer IP address for the specified host. host_index must be in the range 1...CountHostIPs().

Example:

None.

HostNetGame (gamename$)
Definition:

Starts a hosted network game.

Parameter Description:

gamename$ = string value designating the game's name

Command Description:
This allows you to bypass the 'standard' networked game dialog box (normally using StartNetGame) and start
a hosted game directly. A value of 2 is returned if the hosted game has started successfully.

Example:

; HostNetGame example

joinResults=HostNetGame("ShaneGame")

Select joinResults
Case 2
Print "Successfully started host game!"
Default
Print "Game was unable to start!"
End Select
waitkey()

If
Definition:

Checks a condition and executes code if the condition is met.

Parameter Description:

None.

Command Description:

Use this to check the value of a variable or to see if a condition is true or false. The code between IF and END
IF (or ENDIF) is executed if the condition is true. Using NOT, you can also act if the condition is NOT true - or
use ELSE to perform a different set of commands than if the condition is met. Lastly, you can use 'nested' or
multiple IFs through the use of ELSE IF (or ELSEIF) to do LOTS of condition checking. If you get too deep in
condition checking, consider using SELECT structures instead.

Example:

; IF THEN Example

; Input the user's name


name$=Input$("What is your name? ")

; Doesn't the person's name equal SHANE?


If name$ = "Shane" Then

Print "You are recognized, Shane! Welcome!"

Else

Print "Sorry, you don't belong here!"

; End of the condition checking


End If

ImageBuffer (handle[,frame])
Definition:

Used to denote an image and frame to direct drawing operations to.

Parameter Description:

handle=variable holding the image's handle


frame=optional frame to draw to if using an imagestrip image

Command Description:

There are 1000 reasons for this command. Simply put, you may want to 'draw' on an existing image you've
loaded (LoadImage or LoadAnimImage) or created (CreateImage). You could, for example, have a blank wall
graphic and you want to add 'graffiti' to it based on the user action (Jet Grind Radio baybeee! Sorry...).
Instead of trying to draw a dozen images all over the wall, just use the SetBuffer command to denote the wall
graphic as the 'target' buffer, and draw away! Next time you display that graphic (DrawImage), you will see
your changes! This is a powerful command!

Example:

; CreateImage/TileImage/ImageBuffer example

; Again, we'll use globals even tho we don't need them here
; One variable for the graphic we'll create, one for a timer
Global gfxStarfield, tmrScreen

; Declare graphic mode


Graphics 640,480,16

; Create a blank image that is 320 pixels wide and 32 high with 10 frames of 32x32
gfxStarfield=CreateImage(32,32,10)

; loop through each frame of the graphic we just made


For t = 0 To 9
; Set the drawing buffer to the graphic frame so we can write on it
SetBuffer ImageBuffer(gfxStarfield,t)
; put 50 stars in the frame at random locations
For y = 1 To 50
Plot Rnd(32),Rnd(32)
Next
Next

; Double buffer mode for smooth screen drawing


SetBuffer BackBuffer()

; Loop until ESC is pressed


While Not KeyHit(1)

; Only update the screen every 300 milliseconds. Change 300 for faster or
; slower screen updates
If MilliSecs() > tmrScreen+300 Then
Cls ; clear the screen

; Tile the screen with a random frame from our new graphic starting at
; x=0 and y=0 location.
TileImage gfxStarfield,0,0,Rnd(9)
Flip ; Flip the screen into view
tmrScreen=MilliSecs() ; reset the time
End If
Wend
ImageHeight (image handle)
Definition:

Return the height of the designated image, in pixels.

Parameter Description:

image handle = variable assigned when the image was loaded

Command Description:

Use this command and ImageWidth to return the size of the given image (using the handle assigned when the
image was loaded with LoadImage) in pixels.

Example:

; ImageHeight/ImageWidth Example

; Global, as always, for graphics


Global gfxPlayer

; Enter graphics mode and start double buffering


Graphics 640,480,16
SetBuffer BackBuffer()

; Load the image-assign the handle to gfxPlayer


gfxPlayer=LoadImage("player.bmp")

; Print the image dimensions


Print "The image height is: " + ImageHeight(gfxPlayer)
Print "The image width is: " + ImageWidth(gfxPlayer)

; Wait until ESC is pressed so you can see the output


While Not KeyHit(1)
Wend

ImageRectCollide (image,x,y,frame,rect x,rect y,rect width,rect height)


Definition:

Checks to see if an image and designated rectangle area have collided.

Parameter Description:

image = Image to test collision against


x = image's x location
y = image's y location
frame = image's frame
rect x = x location start of the rect to test
rect y = y location start of the rect
rect width = width of the rect
rect height = height of the rect

Command Description:

There are many times when you need to see if an image has collided with (or is touching) a specific
rectangular area of the screen. This command performs pixel perfect accurate collision detection between the
image of your choice and a specified rectangle on the screen.
The usefulness of this comes into play when you think of a game like Monkey Island - when you might have a
backdrop on the screen showing a room that has items in it the player can interact with using a mouse pointer
graphic. In some cases, the items on the screen you wish to interact with will be seperate (often animated or
moving) images of their own. For this situation, you would be better off using ImagesCollide or ImagesOverlap
to detect the collision between pointer graphic and the image.

Howevever, should your program just need to detect a graphic (like a mouse pointer) over at a particular
location/region of the screen (often called a 'hot spot'), this command works great!

As with any collision in Blitz, you will need to know the PRECISE location of the graphic you wish to test
collision with, as well as the x, y, width, and height of the screen area (rect) you wish to test.

The example blatently uses graphics that are much smaller than their container to show you how accurate this
command really is. The ImageRectOverlap example is identical to this one - and shows how inaccurate the
overlapping method can be with graphics of this nature.

Example:

; ImageRectCollide Example

; Turn on graphics mode


Graphics 640,480,16

; Create new empty graphic to store our circle in


gfxCircle=CreateImage(50,50)

; Draw the circle image


; Set drawing operations to point to our new empty graphic
SetBuffer ImageBuffer(gfxCircle)
Color 255,0,0
; Note the extra space between the circle and the edge of the graphic
Oval 10,10,30,30,1

; Let's not forget to put the drawing buffer back!


SetBuffer BackBuffer()
Color 0,0,255

; Locate our box to a random, visible screen location


hotX=Rnd(50,610)
hotY=Rnd(50,430)
hotW=Rnd(20,100)
hotH=Rnd(20,100)

; Repeat the loop until we've had a collision


Repeat
; Attach our mouse to the circle to move it
circleX=MouseX()
circleY=MouseY()
; Standard double buffer technique; clear screen first
Cls
; Draw our rectangle
Rect hotX,hotY,hotW,hotH,0
DrawImage gfxCircle,circleX,circleY
; Standard double buffer technique; flip after all drawing is done
Flip
; We test the locations of our rectangle area and circle to see if they have pixel collided
Until ImageRectCollide (gfxCircle,circleX,circleY,0,hotX,hotY,hotW,hotH)

; Loop is over, we must've collided!


Text 0,0, "WE'VE HAD A COLLISION! PRESS A MOUSE BUTTON"
; Can't see the text until we flip ..
Flip
; Wait for a mouse click
WaitMouse()
; End our graphics mode
EndGraphics

ImageRectOverlap (image,x,y,rect x,rect y,rect width,rect height)


Definition:

Tests to see if an image and a rectangular screen area (rect) have overlapped.

Parameter Description:

image = Image to test collision against


x = image's x location
y = image's y location
rect x = x location start of the rect to test
rect y = y location start of the rect
rect width = width of the rect
rect height = height of the rect

Command Description:

There are many times when you need to see if an image has collided with (or is touching) a specific
rectangular area of the screen. This command performs a collision detection between the image of your choice
and a specified rectangle on the screen. Transparent pixels are ignored during the collision process, making
this command a bit inaccurate for odd shaped graphics. See ImageRectCollide for pixel perfect collisions
between an image and rectangular area of the screen.

The usefulness of this comes into play when you think of a game like Monkey Island - when you might have a
backdrop on the screen showing a room that has items in it the player can interact with using a mouse pointer
graphic. In some cases, the items on the screen you wish to interact with will be seperate (often animated or
moving) images of their own. For this situation, you would be better off using ImagesCollide or ImagesOverlap
to detect the collision between pointer graphic and the image.

Howevever, should your program just need to detect a graphic (like a mouse pointer) over at a particular
location/region of the screen (often called a 'hot spot'), this command works great!

As with any collision in Blitz, you will need to know the PRECISE location of the graphic you wish to test
collision with, as well as the x, y, width, and height of the screen area (rect) you wish to test.

The example blatently uses graphics that are much smaller than their container to show you how inaccurate
this command can really be - if not used carefully. The ImageRectCollide example is identical to this one - and
shows how accurate the pixel-perfect collision method can be with graphics of this nature.

Example:

; ImageRectOverlap Example

; Turn on graphics mode


Graphics 640,480,16

; Create new empty graphic to store our circle in


gfxCircle=CreateImage(50,50)

; Draw the circle image


; Set drawing operations to point to our new empty graphic
SetBuffer ImageBuffer(gfxCircle)
Color 255,0,0
; Note the extra space between the circle and the edge of the graphic
Oval 10,10,30,30,1

; Let's not forget to put the drawing buffer back!


SetBuffer BackBuffer()
Color 0,0,255

; Locate our box to a random, visible screen location


hotX=Rnd(50,610)
hotY=Rnd(50,430)
hotW=Rnd(20,100)
hotH=Rnd(20,100)

; Repeat the loop until we've had a collision


Repeat
; Attach our mouse to the circle to move it
circleX=MouseX()
circleY=MouseY()
; Standard double buffer technique; clear screen first
Cls
; Draw our rectangle
Rect hotX,hotY,hotW,hotH,0
DrawImage gfxCircle,circleX,circleY
; Standard double buffer technique; flip after all drawing is done
Flip
; We test the locations of our rectangle area and circle to see if they have overlapped
Until ImageRectOverlap (gfxCircle,circleX,circleY,hotX,hotY,hotW,hotH)

; Loop is over, we must've collided!


Text 0,0, "WE'VE HAD A COLLISION! PRESS A MOUSE BUTTON"
; Can't see the text until we flip ..
Flip
; Wait for a mouse click
WaitMouse()
; End our graphics mode
EndGraphics

ImagesCollide (image1,x1,y1,frame1,image2,x2,y2,frame2)
Definition:

Checks to see if two images have collided.

Parameter Description:

image1 = first image to test


x1 = image1's x location
y1 = image1's y location
frame1 = image1's frame to test (optional)
image2 = second image to test
x2 = image2's x location
y2 = image2's y location
frame2 = image2's frame to text (optional)

Command Description:

This is THE command to get pixel-perfect collisions between images. It will not consider transparent pixels
during the collision check (basically, only the 'meat' of the image will invoke a collision). This makes it perfect
for most situations where you have odd-shaped graphics to text against.

The ImagesOverlap command is MUCH faster, however, but can only determine if ANY of the two images have
overlapped (this INCLUDES transparent pixels). This method works if you have graphics that completely fill
their container and/or you don't plan on needing pinpoint accuracy.

As with any collision detection system in Blitz, you will need to know the variable names of the two images,
and their X and Y locations at the moment collision checking occurs.

The example blatently uses graphics that are much smaller than their container to show you how accurate this
command really is. The ImagesOverlap example is identical to this one - and shows how inaccurate the
overlapping method can be with graphics of this nature.

Example:

; ImagesCollide Example

; Turn on graphics mode


Graphics 640,480,16

; Create two new empty graphics to store our circle and box in
gfxBox=CreateImage(50,50)
gfxCircle=CreateImage(50,50)

; Draw the box image first


; Set drawing operations to point to our new empty graphic
SetBuffer ImageBuffer(gfxBox)
; Change drawing color to blue
Color 0,0,255
;Draw our box (note that it has a 10 pixel space around it)
Rect 10,10,30,30,1

; Repeat for the circle graphic


SetBuffer ImageBuffer(gfxCircle)
Color 255,0,0
; Note the extra space between the circle and the edge of the graphic
Oval 10,10,30,30,1

; Let's not forget to put the drawing buffer back!


SetBuffer BackBuffer()

; Locate our box to a random, visible screen location


boxX=Rnd(50,610)
boxY=Rnd(50,430)

; Repeat the loop until we've had a collision


Repeat
; Attach our mouse to the circle to move it
circleX=MouseX()
circleY=MouseY()
; Standard double buffer technique; clear screen first
Cls
; Draw our objects at the designated location
DrawImage gfxBox,boxX,boxY
DrawImage gfxCircle,circleX,circleY
; Standard double buffer technique; flip after all drawing is done
Flip
; We test the locations of our box and circle to see if they have pixel collided
Until ImagesCollide (gfxBox,boxX,boxY,0,gfxCircle,circleX,circleY,0)

; Loop is over, we must've collided!


Text 0,0, "WE'VE HAD A COLLISION! PRESS A MOUSE BUTTON"
; Can't see the text until we flip ..
Flip
; Wait for a mouse click
WaitMouse()
; End our graphics mode
EndGraphics

ImagesOverlap (image1,x1,y1,image2,x2,y2)
Definition:

Checks to see if two graphic images have overlapped.

Parameter Description:

image1 = first image to test


x1 = image1's x location
y1 = image1's y location
image2 = second image to test
x2 = image2's x location
y2 = image2's y location

Command Description:

This is a very fast, simple collision type command that will allow you to determine whether or not two images
have overlapped each other. This does not take into account any transparent pixels (see ImagesCollide).

As with any collision detection system in Blitz, you will need to know the variable names of the two images,
and their X and Y locations at the moment collision checking occurs.

In many cases, you might be able to get away with using this more crude, yet quite fast method of collision
detection. For games where your graphics are very squared off and pixel-perfect accuracy isn't a must, you
can employ this command to do quick and dirty overlap checking.

The example blatently uses graphics that are much smaller than their container to show you how inaccurate
this command can be - if not used wisely. The ImagesCollide example is identical to this one - and shows how
pixel-perfect collision works.

You might be able to get away with this on some more classical games like Robotron, Defender, Dig Dug, etc.

Example:

; ImagesOverlap Example

; Turn on graphics mode


Graphics 640,480,16

; Create two new empty graphics to store our circle and box in
gfxBox=CreateImage(50,50)
gfxCircle=CreateImage(50,50)

; Draw the box image first


; Set drawing operations to point to our new empty graphic
SetBuffer ImageBuffer(gfxBox)
; Change drawing color to blue
Color 0,0,255
;Draw our box (note that it has a 10 pixel space around it)
Rect 10,10,30,30,1

; Repeat for the circle graphic


SetBuffer ImageBuffer(gfxCircle)
Color 255,0,0
; Note the extra space between the circle and the edge of the graphic
Oval 10,10,30,30,1
; Let's not forget to put the drawing buffer back!
SetBuffer BackBuffer()

; Locate our box to a random, visible screen location


boxX=Rnd(50,610)
boxY=Rnd(50,430)

; Repeat the loop until we've had a collision


Repeat
; Attach our mouse to the circle to move it
circleX=MouseX()
circleY=MouseY()
; Standard double buffer technique; clear screen first
Cls
; Draw our objects at the designated location
DrawImage gfxBox,boxX,boxY
DrawImage gfxCircle,circleX,circleY
; Standard double buffer technique; flip after all drawing is done
Flip
; We test the locations of our box and circle to see if they have overlapped
Until ImagesOverlap (gfxBox,boxX,boxY,gfxCircle,circleX,circleY)

; Loop is over, we must've collided!


Text 0,0, "WE'VE HAD A COLLISION! PRESS A MOUSE BUTTON"
; Can't see the text until we flip ..
Flip
; Wait for a mouse click
WaitMouse()
; End our graphics mode
EndGraphics

ImageWidth (image handle)


Definition:

Return the width of the designated image, in pixels.

Parameter Description:

image handle = variable assigned when the image was loaded

Command Description:

Use this command and ImageHeight to return the size of the given image (using the handle assigned when the
image was loaded with LoadImage) in pixels.

Example:

; ImageHeight/ImageWidth Example

; Global, as always, for graphics


Global gfxPlayer

; Enter graphics mode and start double buffering


Graphics 640,480,16
SetBuffer BackBuffer()

; Load the image-assign the handle to gfxPlayer


gfxPlayer=LoadImage("player.bmp")
; Print the image dimensions
Print "The image height is: " + ImageHeight(gfxPlayer)
Print "The image width is: " + ImageWidth(gfxPlayer)

; Wait until ESC is pressed so you can see the output


While Not KeyHit(1)
Wend

ImageXHandle image
Definition:

Returns the X location of the specified image's image handle.

Parameter Description:

image = variable holding the image's file handle

Command Description:

It is occasionally useful to determine the location of an image's image handle. This command returns the X
coordinate. Use ImageYHandle to get the Y coordinate. Please see MidHandle for more information on the
image's image handle.
Note about the term 'handle'. There are two types of 'handles' we discuss in these documents. One is the
location within an image - as discussed in this command. The other is a 'file handle', a variable used to hold an
image, sound, or font loaded with a command. See LoadImage for more information about file handles.

Example:

; MidHandle/ImageXHandle()/ImageYHandle()/AutoMidHandle

; Initiate Graphics Mode


Graphics 640,480,16

; Set up the image file handle as a global


Global gfxBall

; Load the image - you may need to change the location of the file
gfxBall=LoadImage ("C:\Program Files\Blitz Basic\samples\ball.bmp")

; Until the user presses ESC key ...


While Not KeyHit(1)
Text 0,0,"Default Image Handle for gfxBall... Press ESC ..."
Text 0,14,"X handle-" + ImageXHandle(gfxBall) ; Print the location of the image handle x location
Text 0,28,"Y handle-" + ImageYHandle(gfxBall) ; Print the location of the image handle y location
DrawImage gfxBall,200,200,0 ; draw the image at 200,200
Wend

; Clear the screen


Cls

; Set the ball's handle to the center of the image


MidHandle gfxBall

; Until the user presses ESC key ... show the new information
While Not KeyHit(1)
Text 0,0,"New Image Handle for gfxBall... Press ESC ..."
Text 0,14,"X handle-" + ImageXHandle(gfxBall)
Text 0,28,"Y handle-" + ImageYHandle(gfxBall)
DrawImage gfxBall,200,200,0
Wend

; Makes all images load up with their handles in the center of the image
AutoMidHandle True
Cls

; Load the image again


gfxBall=LoadImage ("C:\Program Files\Blitz Basic\samples\ball.bmp")

; Until the user presses ESC key ... show the new information
While Not KeyHit(1)
Text 0,0,"Automatic image handle of gfxBall... Press ESC ..."
Text 0,14,"X handle-" + ImageXHandle(gfxBall)
Text 0,28,"Y handle-" + ImageYHandle(gfxBall)
DrawImage gfxBall,200,200,0
Wend

ImageYHandle image
Definition:

Returns the Y location of the specified image's image handle.

Parameter Description:

image = variable holding the image's file handle

Command Description:

It is occasionally useful to determine the location of an image's image handle. This command returns the Y
coordinate. Use ImageXHandle to get the X coordinate. Please see MidHandle for more information on the
image's image handle.
Note about the term 'handle'. There are two types of 'handles' we discuss in these documents. One is the
location within an image - as discussed in this command. The other is a 'file handle', a variable used to hold an
image, sound, or font loaded with a command. See LoadImage for more information about file handles.

Example:

; MidHandle/ImageXHandle()/ImageYHandle()/AutoMidHandle

; Initiate Graphics Mode


Graphics 640,480,16

; Set up the image file handle as a global


Global gfxBall

; Load the image - you may need to change the location of the file
gfxBall=LoadImage ("C:\Program Files\Blitz Basic\samples\ball.bmp")

; Until the user presses ESC key ...


While Not KeyHit(1)
Text 0,0,"Default Image Handle for gfxBall... Press ESC ..."
Text 0,14,"X handle-" + ImageXHandle(gfxBall) ; Print the location of the image handle x location
Text 0,28,"Y handle-" + ImageYHandle(gfxBall) ; Print the location of the image handle y location
DrawImage gfxBall,200,200,0 ; draw the image at 200,200
Wend

; Clear the screen


Cls
; Set the ball's handle to the center of the image
MidHandle gfxBall

; Until the user presses ESC key ... show the new information
While Not KeyHit(1)
Text 0,0,"New Image Handle for gfxBall... Press ESC ..."
Text 0,14,"X handle-" + ImageXHandle(gfxBall)
Text 0,28,"Y handle-" + ImageYHandle(gfxBall)
DrawImage gfxBall,200,200,0
Wend

; Makes all images load up with their handles in the center of the image
AutoMidHandle True
Cls

; Load the image again


gfxBall=LoadImage ("C:\Program Files\Blitz Basic\samples\ball.bmp")

; Until the user presses ESC key ... show the new information
While Not KeyHit(1)
Text 0,0,"Automatic image handle of gfxBall... Press ESC ..."
Text 0,14,"X handle-" + ImageXHandle(gfxBall)
Text 0,28,"Y handle-" + ImageYHandle(gfxBall)
DrawImage gfxBall,200,200,0
Wend

Include filename
Definition:

Includes more Blitz Basic source code into your code from an external file.

Parameter Description:

filename = full path and filename of your .bb include code

Command Description:

Includes are a cheap substitute for Function Folding (grin). Seriously, Includes offers the programmer a means
of keeping distinct code seperate by taking 'working' subroutines, functions, variable assignments - heck, ANY
code and placing it into an external .bb file. This external file can be 'included' into another Blitz program - and
when you run the program, Blitz will 'included' that external code just as if it cut and pasted it right into your
source code before it runs. For example, you could create a small Blitz program for displaying your 'intro'
screen/effect and save it off as 'intro.bb'. Then, give it to all your programmers so they can 'include' that
source code at the beginning of their game. Many programmers find it useful to write functions, test them,
and once working 100% properly, save them off as their own source code and just include them in their main
program. This keeps code segregated, readable, and modularly changeable.

For debugging purposes, if you run a program with included files, and one of the includes has an error, Blitz
will automagically load the include, and display the error/debug information there. Nice, huh?

Hopefully Function Folding will be supported in future versions of Blitz, since many people use Includes to
'simulate' this feature.

Note: The example only shows you the calling code using the INCLUDE command - it will not run unless you
create the included files yourself.

Example:
; INCLUDE Example

; Include the source code that has all our variables in it


Include "myvariables.bb"

; Get the TYPEs from an external source code include


Include "myTYPES.bb"

Input$ (prompt$)
Definition:

Get input from the user.

Parameter Description:

prompt$ = any valid string (optional)

Command Description:

This command will retrieve a string value from the user with an optional prompt on the screen (if not in a
graphic mode) or on the current drawing buffer being used by the program. Usually you will assign this
command's value to a string for later use.

Example:

; Get the user's name and print a welcome

name$=Input$("What is your name?")


Write "Hello there, " + name$ + "!"

Insert
Definition:

Insert the current TYPE object into another location in the TYPE collection.

Parameter Description:

None.

Command Description:

I'm not sure the practical usage of this command, but basically, you can control where you INSERT the current
TYPE object into the TYPE collection. When you create a new Type object with the NEW command, it is
automatically appended to the END of the collection. Using INSERT along with BEFORE and AFTER (and
electively FIRST and LAST) to put the Type object exactly where you want it. Sounds confusing - and chances
are likely you'll never need this ability. But its here if you need it. Check the example.

Example:

; INSERT example

; Define a CHAIR type with a created field to track what order it was created in.
Type CHAIR
Field created
End Type

; Create 10 chairs, setting created field to the order of creation


For t = 1 To 10
room.chair= New Chair
room\created = t
Next

; Make a NEW chair (the 11th)


room.chair= New Chair

; Set its created value to 11


room\created=11

; Now, let's insert this chair BEFORE the first one in the collection
Insert room Before First Chair

; Let's iterate through all the chairs, and show their creation order
For room.chair = Each chair
Print room\created
Next

Instr (string1$, string2$, offset)


Definition:

Finds the position of an occurance of one string within another.

Parameter Description:

string1$ = the string you wish to search


string2$ = the string to find
offset = valid integer starting position to being search (optional)

Command Description:

This command will allow you to search for an occurance of a string within another string. The command
returns the location (number of characters from the left) of the string you are looking for. Command returns a
Zero if no matches are found.

Example:

name$="Shane R. Monroe"
location = Instr( name$,"R.",1)
Print "Your string contains 'R.' at position number " + location + "!"

Int (value)
Definition:

Returns the integer portion of a number.

Parameter Description:
value = any valid variable or number

Command Description:

Returns the integer value of an expression or value. Use this to convert a floating point number to a straight
integer value. See Example.

Example:

; Int Example

myNum#=3.14
Print "The integer value of " + mynum# + " is: " + Int(myNum#)

JoinNetGame (gamename$,serverIP$)
Definition:

Joins a network game in progress.

Parameter Description:

gamename$ = valid string containing game name to join


serverIP$ = IP address of computer hosting game

Command Description:

Use this command to join a network game, bypassing the dialog box normally endured with the StartNetGame
command.
This returns 0 if the command failed, or 1 if the game was joined successfully.

Example:

; JoinNetGame example
; Note; run the HostNetGame example code on the other computer
; you wish to join with

gamename$="ShaneGame"
; Change this to match the other computer's IP!
serverIP$="0.0.0.0"

; Make the join attempt


joinResults=JoinNetGame(gamename$,serverIP$)

Select joinResults
Case 1
Print "Joined the game successfully!"
Default
Print "Joining the game was unsuccessful."
End Select
WaitKey()

JoyDown (button,[port])
Definition:
Returns TRUE if the specified joystick button is being held down.

Parameter Description:

button = number of joystick button to check


port = number of joystick port to check (optional)

Command Description:

This command (and its counterparts KeyDown and MouseDown) is used to detect if a joystick button is being
held down. You must check for each joystick button independantly with its corresponding number (unlike
KeyDown which returns WHICH key is being held down). Also see JoyHit.

Example:

; JoyDown Example

; Until user presses ESC, show the mouse button pressed


While Not KeyHit(1)
button$="No"
For t = 1 To 5
If JoyDown(t) Then button$=Str(t)
Print button$ + " joystick button pressed!"
Next
Wend

JoyHit (button,[port])
Definition:

Returns the number of times a specified joystick button has been hit.

Parameter Description:

button = number of joystick button to check


port = number of joystick port to check (optional)

Command Description:

This command returns the number of times a specified joystick button has been hit since the last time you
called the JoyHit() command. Also see KeyHit and MouseHit.

Example:

; JoyHit Example

; Set up the timer


current=MilliSecs()
Print "Press FireButton 1 a bunch of times for five seconds..."

; Wait 5 seconds
While MilliSecs() < current+5000
Wend

; Print the results


Print "Pressed button " + JoyHit(1) + " times."
JoyType ([port])
Definition:

Returns the type of joystick attached to the computer.

Parameter Description:

port = number of joystick port to check (optional)

Command Description:

This command returns the type of joystick that is currently connected to the computer. It returns 0 if there is
none, 1 for digital, and 2 for analog.

Example:

; JoyType() example

; Check to see what stick is present - print the proper message


Select JoyType()
Case 0
Print "Sorry, no joystick attached to system!"
Case 1
Print "Digital joystick is attached to system!"
Case 2
Print "Analog joystick is attched to system!"
End Select

; Wait for user to hit ESC


While Not KeyHit(1)
Wend

JoyWait ([port])
Definition:

Waits for a joystick button to be pressed, then returns the number.

Parameter Description:

port = number of joystick port to check (optional)

Command Description:

This command makes your program halt until a jpystick button is pressed on the joystick. Used alone, it
simply halts and waits for a button press. It can also be used to assign the pressed button's code value to a
variable. See example. In MOST CASES, you are not going to want to use this command because chances are
likely you are going to want things on the screen still happening while awaiting the button press. In that
situation, you'll use a WHILE ... WEND awaiting a JoyHit value - refreshing your screen each loop. As with any
joystick command, you MUST have a DirectX compatible joystick plugged in and properly configured within
Windows for it to work. See your joystick documentation for more information.

Example:

; JoyWait() example
; Check to see what stick is present - print the proper message
Print "Press a button on the joystick"

button=JoyWait()

; Wait for user to hit ESC


Print "You pressed button # " + button + "! Hit ESC To End"

While Not KeyHit(1)


Wend

JoyX ([port])
Definition:

Returns the X-axis coordinate of the joystick.

Parameter Description:

port = number of joystick port to check (optional)

Command Description:

This command returns the value of the x-axis of the joystick. The range is -1 to 1 (full left to full right). The
value returned is a floating point number. See the example.

Example:

; JoyX()/JoyY() example

While Not KeyHit(1)


Cls
Text 0,0,"Joy X Value: " + JoyX() + " - Joy Y Value:" + JoyY()
Wend

JoyXDir ([port])
Definition:

Returns the X-axis direction of the joystick.

Parameter Description:

port = number of joystick port to check (optional)

Command Description:

This command returns the direction of the x-axis of the joystick being pressed. The value is -1 (left) or 1
(right). The value returned is an integer number. See the example. Perfect for digital joysticks.

As with any joystick command, you MUST have a DirectX compatible joystick plugged in and properly
configured within Windows for it to work. See your joystick documentation for more information.

Example:
; JoyXDir() example

While Not KeyHit(1)


Cls
Text 0,0,"Joy X Direction: " + JoyXDir()
Wend

JoyY ([port])
Definition:

Returns the Y-axis coordinate of the joystick.

Parameter Description:

port = number of joystick port to check (optional)

Command Description:

This command returns the value of the x-axis of the joystick. The range is -1 to 1 (full up to full down). The
value returned is a floating point number. See the example.

Example:

; JoyX()/JoyY() example

While Not KeyHit(1)


Cls
Text 0,0,"Joy X Value: " + JoyX() + " - Joy Y Value:" + JoyY()
Wend

JoyYDir ([port])
Definition:

Returns the Y-axis direction of the joystick.

Parameter Description:

port = number of joystick port to check (optional)

Command Description:

This command returns the direction of the Y-axis of the joystick being pressed. The value is -1 (up) or 1
(down). The value returned is an integer number. See the example. Perfect for digital joysticks.

As with any joystick command, you MUST have a DirectX compatible joystick plugged in and properly
configured within Windows for it to work. See your joystick documentation for more information.

Example:

; JoyYDir() example

While Not KeyHit(1)


Cls
Text 0,0,"Joy Y Direction: " + JoyYDir()
Wend

JoyZ ([port])
Definition:

Returns the Z-axis coordinate of the joystick.

Parameter Description:

port = number of joystick port to check (optional)

Command Description:

This command returns the value of the x-axis of the joystick. The range is -1 to 1 (Max to none). The value
returned is a floating point number. See the example.

As with any joystick command, you MUST have a DirectX compatible joystick plugged in and properly
configured within Windows for it to work. See your joystick documentation for more information.

Example:

; JoyZ() example

While Not KeyHit(1)


Cls
Text 0,0,"Joy Z Value: " + JoyZ()
Wend

JoyZDir ([port])
Definition:

Returns the Z-axis direction of the joystick.

Parameter Description:

port = number of joystick port to check (optional)

Command Description:

This command returns the direction of the Z-axis of the joystick being pressed. The value is -1 (up) or 1
(down). The value returned is an integer number. See the example. Perfect for digital joysticks.

As with any joystick command, you MUST have a DirectX compatible joystick plugged in and properly
configured within Windows for it to work. See your joystick documentation for more information.

Example:

; JoyZDir() example

While Not KeyHit(1)


Cls
Text 0,0,"Joy Z Direction: " + JoyZDir()
Wend
KeyDown (scancode)
Definition:

Returns TRUE if the specified key on keyboard is being held down.

Parameter Description:

scancode = corresponding key scancode

Command Description:

This command (similar to its counterparts MouseDown and JoyDown) is used to detect if a key is being held
down. This command returns a 0 if the key is not held down, a 1 if the key is held down. See ScanCodes.

Example:

; KeyDown() example

Print "Hold down ENTER key!"


Delay 3000
While Not KeyHit(1)
If KeyDown(28) Then
Print "Enter is being pressed!"
Else
Print
End If
Wend

KeyHit (scancode)
Definition:

Returns the number of times a specified key has been hit.

Parameter Description:

scancode = the scancode for the key to test

Command Description:

This command returns the number of times a specified key has been hit since the last time you called the
KeyHit() command. Check the ScanCodes for a complete listing of scancodes.

Example:

; KeyHit Example

; Set up the timer


current=MilliSecs()
Print "Press ESC a bunch of times for five seconds..."

; Wait 5 seconds
While MilliSecs() < current+5000
Wend
; Print the results
Print "Pressed ESC " + KeyHit(1) + " times."

.variable
Definition:

Sets a callable label within your program.

Parameter Description:

variable = any valid existing label variable

Command Description:

A label is like a callable bookmark within your program. It basically tells Blitz where to start something; either
program execution (through a Goto or Gosub command) or where to start reading Data (through the Read
command). While most 'professional' programmers loathe and hate the use of 'branching' commands like
Goto/Gosub, you will likely find it useful regardless. Use Return to jump back to the original code that called
the label via the Gosub command (you cannot Return from a Goto command).
In addition, you MUST use labels to read Data values using the Read command. Check out the Read command
for use of it in a Data statement environment.

Example:

; The program starts here, but we'll branch to other labels

Gosub start
Gosub label3
Gosub label2

; Let's wait for ESC to be pressed before ending


While Not KeyHit(1)
Wend
End

.start
Print "We start here ..."
Return

.label2
Print "This is label 2"
Return

.label3
Print "This is label 3"
Return

Last type_variable
Definition:

Move the Last object pointer to the Last object in the collection.

Parameter Description:
type_variable = the actual Type name, not the custom Type name

Command Description:

If you haven't read up on the TYPE command, you might want to do so before continuing.

Use this to assign a custom Type object to the last object in the collection. See the example.

Example:

; Define a crafts Type

Type crafts
Field x
Field y
Field dead
Field graphic
End Type

; Create 100 crafts, with the unique name of alien


For t = 1 To 100
alien.crafts = New crafts
alien\x = Rnd(0,640)
alien\y = Rnd(0,480)
alien\dead = 0
alien\graphic = 1
Next

; Move to the first object


alien.crafts = First crafts

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

; move to the next alien object


alien = After alien

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

; move to the last alien object


alien.crafts = Last crafts

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic

; move to the second to the last alien object


alien = Before alien

Print alien\x
Print alien\y
Print alien\dead
Print alien\graphic
Left$ (string$, length)
Definition:

Return a certain number of the leftmost characters of a string.

Parameter Description:

string$ = any valid string variable


length = a valid integer value up to the length of the string.

Command Description:

Use this command to get a certain number of the leftmost letters of a string. You will use this to truncate
strings to make them fit somewhere, or to control the number of characters input.

Example:

name$="Shane Monroe"
Print "The left 3 letters of your name are: " + Left$(name$,3)

Len (string$)
Definition:

Returns the number of characters in a string.

Parameter Description:

string$ = any valid string variable

Command Description:

This will let you determine the length (number of letters, spaces, characters, numbers, etc) inside a string.
You can use this to ensure the player enters the right number of letters (like 3 letters for a high score table).
Quite useful for 'string parsing' with other commands.

Example:

name$="Shane Monroe"
Print "There are " + Len(name$) + " characters in your name!"

Line x,y,x1,y1
Definition:

Draws a line in the current drawing color from x,y to x1,y1.

Parameter Description:

x=starting x location of the line


y=starting y location of the line
x1=ending x location of the line
y1=ending y location of the line
Command Description:

This command draws a line, in the current drawing color, from one point on the screen to another (from the
x,y to x1,y1 location). See example.

Example:

; Line example
Graphics 800,600,16

; Wait for ESC to hit


While Not KeyHit(1)
; Set a random color
Color Rnd(255),Rnd(255),Rnd(255)
; Draw a random line
Line Rnd(800),Rnd(600),Rnd(800),Rnd(600)
Wend

LoadAnimImage (filename,width,height,first,count)
Definition:

Loads an 'image strip' for use as an 'animated image' to be drawn later and return a handle.

Parameter Description:

filename = string designating full path and filename to image.


width=width in pixels of each frame in the image.
height=height in pixels of each frame in the image.
first=the frame to start with (usually 0)
count=how many frames you are using of the imagestrip

Command Description:

While similar to LoadImage, the LoadAnimImage loads a single image that is made up of 'frames' of seperate
images (presumably to be used as frames of a graphic animation).

Like the LoadImage command, this command returns a file handle - a unique number to denote the graphic.
Use a variable (usually GLOBAL) to contain this number, as you will need it to actually DRAW the image with
the DrawImage command. See LoadImage command for more details.

The imagestrip itself consists of 2 or more frames, horizontally aligned in a single graphic image. There is no
spaces between the frames, and each frame must be the same width and height. For examples, look at the file
kaboom.bmp or sparks.bmp included in the C:\Program Files\BlitzBasic\samples\graphics folder of your
computer. There are some free utilities floating around to help you do this.

When drawing the image to the screen with the DrawImage command, you specify which frame to draw with
the frame parameter.

To actually make your image animate, you'll need to cycle through the frames (like a flip book, cartoon, or any
other video) quickly to give the illusion of motion. Our example will show you how to use one of the sample
imagestrips and make it animate. While it may seem confusing, we are going to do some timer work as well as
a little weird math.

Please look over the example (if your like me, over and over :). Note: You may need to change the location of
the file to suit your system.

Example:
; LoadAnimImage/MaskImage Example
; With animation timers

; Even though we don't have any functions, let's do variables global


; One variable will hold the handle for the graphic, one will hold the
; current frame we are displaying, and one will hold the milliseconds
; timer so we can adjust the animation speed.
Global gfxSparks, frmSparks, tmrSparks

; Standard graphic declaration and double buffering setup


Graphics 640,480,16
SetBuffer BackBuffer()

; Load the imagestrip up and denote the frames 32x32 - for a total of 3 frames
gfxSparks=LoadAnimImage("c:\Program Files\BlitzBasic\samples\Graphics\spark.bmp",32,32,0,3)

; We mask the image's color pink to be the 'transparent' color - look at the
; image in your favorite editor to see more why we use masking.
MaskImage gfxSparks,255,0,255

; Loop until ESC


While Not KeyHit(1)
Cls ; Standard clear screen

; The next statment checks to see if 100 milliseconds has passes since we
; last changed frames. Change the 100 to higher and lower values to
; make the animation faster or slower.
If MilliSecs() > tmrSparks + 100 Then
tmrSparks=MilliSecs() ; 'reset' the timer
frmSparks=( frmSparks + 1 ) Mod 3 ; increment the frame, flip to 0 if we are out
End If
DrawImage gfxSparks,MouseX(),MouseY(),frmSparks ; draw the image
Flip ; show the buffer
Wend

LoadBuffer (buffer, filename$)


Definition:

Loads an image directly into a buffer in Blitz.

Parameter Description:

buffer = system or image buffer


filename$ = string containing full path and filename of image

Command Description:

There are a hundred and one uses for this command, but probably most often used would be to display a title
screen or some other 'one time viewing only' image to the front buffer (as in our example).

You can also load to an image buffer or back buffer. The image is scaled to match the buffer size. This
command returns 1 if the command was successful, 0 if there was an error.

Example:

; LoadBuffer example

; Set graphics mode


Graphics 800,600,16

; Load an image directly to the front buffer (your location may be different)
LoadBuffer (FrontBuffer(),"C:\Program Files\Blitz Basic\samples\blitzanoid\gfx\title.bmp")

; wait for ESC so user gets to see the screen


While Not KeyHit(1)
Wend

LoadFont (fontname$,height,bold,italic,underlined)
Definition:

Loads a TrueType font into memory.

Parameter Description:

fontname = string containing font name


height = font height desired
bold = set to TRUE to load font as BOLD
italic = set to TRUE to load font as ITALIC
underlined set to TRUE to load font as UNDERLINED

Command Description:

This loads a TrueType font into memory for future use with printing commands such as Text. You will need to
make the font active by using SetFont before writing any text with the new font.

Note: Blitz doesn't work with SYMBOL fonts, like Webdings and WingDings.

Be sure to free the memory used by the font went you are done using the FreeFont command.

If the font fails to load for whatever reason, this command will return a zero.

Example:

; LoadFont/SetFont/FreeFont example

; enable graphics mode


Graphics 800,600,16

; Set global on font variables


Global fntArial,fntArialB,fntArialI,fntArialU

;Load fonts to a file handle variables


fntArial=LoadFont("Arial",24,False,False,False)
fntArialB=LoadFont("Arial",18,True,False,False)
fntArialI=LoadFont("Arial",32,False,True,False)
fntArialU=LoadFont("Arial",14,False,False,True)

; set the font and print text


SetFont fntArial
Text 400,0,"This is just plain Arial 24 point",True,False

SetFont fntArialB
Text 400,30,"This is bold Arial 18 point",True,False

SetFont fntArialI
Text 400,60,"This is italic Arial 32 point",True,False
SetFont fntArialU
Text 400,90,"This is underlined Arial 14 point",True,False

; Standard 'wait for ESC' from user


While Not KeyHit(1)
Wend

; Clear all the fonts from memory!


FreeFont fntArial
FreeFont fntArialB
FreeFont fntArialI
FreeFont fntArialU

LoadImage (Filename)
Definition:

Loads an image into memory and assigns it a handle.

Parameter Description:

filename = string designating full path and filename to image.

Command Description:

This command loads an image from disk and assigns it a file handle. You will use the DrawImage command to
display the graphic later. The demo version of Blitz Basic supports BMP files; the full retail version of Blitz
Basic supports JPG and PNG format as well.

Many multimedia loading commands for fonts, graphics, and sounds require the use of FILE HANDLES. You'll
need to have a good understanding of file handles if you are going to successfully use Blitz Basic.

A file handle is a variable (usually GLOBAL) that holds a unique identifier for a loaded item (font, image,
sound, music, etc.). This unique number is used later for subsequent operations to designate the loaded item.
This file handle allocates the memory to hold the item.

You will find file handles used all over Blitz. See the example for some well-documented code.

Example:

; LoadImage and DrawImage example

; Declare a variable to hold the graphic file handle


Global gfxPlayer

; Set a graphics mode


Graphics 640,480,16

; Set drawing operations for double buffering


SetBuffer BackBuffer()

; Load the image and assign its file handle to the variable
; - This assumes you have a graphic called player.bmp in the
; same folder as this source code
gfxPlayer=LoadImage("player.bmp")

; Let's do a loop where the graphic is drawn wherever the


; mouse is pointing. ESC will exit.
While Not KeyHit(1)
Cls ; clear the screen
DrawImage gfxPlayer,MouseX(),MouseY() ; Draw the image!
Flip ; flip the image into view and clear the back buffer
Wend

LoadSound (filename$)
Definition:

Load a sound file into memory.

Parameter Description:

filename$ = valid string with path/filename to the sound file

Command Description:

This command loads a sound file (.WAV or .MP3) into memory. It returns a number if successful, or 0 if there
was a problem loading the sound. You must assign value this returns to a variable (preferably a Global
variable) for subsequent playback using (PlaySound). Look at the example.

Example:

; Assign a global variable for the sound


Global sndPlayerDie

; Load the sound file into memory

sndPlayerDie=LoadSound("sounds/die.wav")

; Play the sound

PlaySound sndPlayerDie

Local variable
Definition:

Declares a variable as local.

Parameter Description:

variable = any valid variable name

Command Description:

This command is probably just here for compatibility with other BASIC languages. LOCAL will let you specify
that the variable you are defining is available ONLY to the program or Function you are assigning it in. In order
to get a variable to be accessible anywhere in your program, you need to make it GLOBAL. I say it is only here
for compatibility because whenever you assign a variable that isn't Global, it is automatically assigned as a
LOCAL variable. You can optionally assign a value to the variable at the time of declaration. See example.

Example:

; Local example
; set lives to 5 for the main program loop
Local lives=5

; Call a function
while not keyhit(1)
showlives()
Wend

Function showlives()
; For this function, lives will be 10!
Local lives=10
Print lives
End Function

Locate x,y
Definition:

Locates the text commands starting point on the screen.

Parameter Description:

x=x coordinate on the screen


y=y coordinate on the screen

Command Description:

Sometimes you want to place the PRINT and Input$ commands at a specific location on the screen. This
command locates the 'cursor' to the designated location.

Example:

; Locate example

strName$=Input$("What is your name?")

Locate 100,200

Print "Hello there, " + strName$

While Not KeyHit(1)


Wend

LockBuffer buffer
Definition:

Locks a buffer for high speed pixel operations.

Parameter Description:

buffer = any valid screen/image buffer (optional)

Command Description:
After you use LockBuffer on a buffer, the only graphics commands you can use are the read/write pixel
commands ReadPixel, WritePixel, ReadPixelFast, WritePixelFast, CopyPixelFast, and CopyPixel. You must
UnlockBuffer before using other graphics commands.

The buffer parameter isn't required. If omitted, the default buffer set with SetBuffer will be used.

See the other commands for more information.

Example:

; High Speed Graphics Commands

Graphics 640,480,16

; Draw a bunch of crap on the screen


For t= 1 To 1000
Color Rnd(255),Rnd(255),Rnd(255)
Rect Rnd(640),Rnd(480),Rnd(150),Rnd(150),Rnd(1)
Next

Delay 3000

; Copy the top half of the screen over the bottom half
; using fast pixels and locked buffers
For x = 1 To 640
For y = 1 To 240
LockBuffer FrontBuffer()
WritePixelFast x,y+241,ReadPixelFast(x,y)
UnlockBuffer FrontBuffer()
Next
Next

Delay 3000

; Draw the left half of the screen over the right half
; using the slower direct pixel access
For x = 1 To 320
For y = 1 To 480
WritePixel x+320,y,ReadPixel(x,y)
Next
Next

Log10 (number)
Definition:

Returns the common logarithm of the supplied argument (base 10).

Parameter Description:

number=float or integer

Command Description:

Log10() is the logarithm (or inverse exponential) function to base 10. Logarithms to the base 10 are called the
common logarithms. The Log10() functions uses 10 as a base. It follows the series 10^x. This function is
useful for finding the power of a number in base 10. See also: Exp Log

Example:
; To find the value of Log10(10^5)
x=5
y = 10^x
Print y ; i.e. 10^5 = 10*10*10*10*10: returns 100000
Print Log10(y) ; ie. Log10(10^5) = Log10(10000): returns 5.000000

Log (number)
Definition:

Returns the natural logarithm of the supplied argument.

Parameter Description:

number=float or integer

Command Description:

Log() is the logarithmic (or inverse exponential) function. Logarithms to the base e are called the Natural or
Napierian logarithms. The Exp() and Log() functions uses the transcendental number e as a base (approx
2.718). Log() is the inverse of the Exponential Exp() function. Log(e) = 1 See also: Exp Log10

Example:

; To find the value of Log(e^5)


e# = Exp(1)
x# = 5
y# = e#^x#
Print y ; i.e. e^5 = e*e*e*e*e: returns 148.413131
Print Log(y) ; ie. Log(e^5) = Log(10000): returns 5.000000

LoopSound sound_variable
Definition:

Sets up a previously loaded sound to play in a constant loop once the sound is played.

Parameter Description:

sound_variable = variable previously assigned with a LoadSound command.

Command Description:

This command sets up play back a sound file (.WAV or .MP3) in an endless loop (like for background music).
You must load a variable with a sound file using the LoadSound command. Use a Global variable to ensure
your sound loop can be played from anywhere in your program. Note: This command doesn't actually PLAY the
sound loop, just sets it up for looping. You still need to execute the PlaySound command to hear the sound.

Example:

; Assign a global variable for the sound loop


Global sndMusicLoop

; Load the sound loop file into memory

sndMusicLoop=LoadSound("sounds/loop1.wav")
; Set the sound loop

LoopSound sndMusicLoop

PlaySound sndMusicLoop

Lower$ (string$)
Definition:

Convert a string to all lower case.

Parameter Description:

string$ = any valid string variable

Command Description:

This will take a string and convert it all to lower case letters. Pretty straight forward.

Example:

name$="ShAnE MoNrOe"
Print "The original name is: " + name$
Print "In lower case it is: " + Lower$(name$)

LSet$ (string$, length)


Definition:

Pads a string with spaces to a specified value, left aligning the string.

Parameter Description:

string$ = any valid string or string variable


length = how long you want the new string to be (including padding)

Command Description:

If you have a string that is say, 10 letters long, but you want to make it a full 25 letters, padding the rest of
the string with spaces, this command will do so, leaving the original string value left justified.

Example:

name$="Shane R. Monroe"
Print "New Padded Name: '" + LSet$(name$,40) + "'"

MaskImage handle,red,green,blue
Definition:
Set the image's mask or transparent color.

Parameter Description:

handle=the variable you assigned the handle to when you loaded the image.
red=the red color value (0-255)
green=the green color value (0-255)
blue=the blue color value (0-255)

Command Description:

Blitz Basic assumes that when you load an image (using LoadImage or LoadAnimImage) for drawing (using
DrawImage command), you want the color black (RGB color 0,0,0) on your image to be transparent (or see
through). There WILL come a time when you want some other color to be that masked color. This command
will let you set that mask color using the color's RGB values (I use Paint Shop Pro to determing the Red,
Green, and Blue values). The example is a bit bloated for other commands, but I'm pretty sure you'll
understand.

Example:

; LoadAnimImage/MaskImage Example
; With animation timers

; Even though we don't have any functions, let's do variables global


; One variable will hold the handle for the graphic, one will hold the
; current frame we are displaying, and one will hold the milliseconds
; timer so we can adjust the animation speed.
Global gfxSparks, frmSparks, tmrSparks

; Standard graphic declaration and double buffering setup


Graphics 640,480,16
SetBuffer BackBuffer()

; Load the imagestrip up and denote the frames 32x32 - for a total of 3 frames
gfxSparks=LoadAnimImage("c:\Program Files\BlitzBasic\samples\Graphics\spark.bmp",32,32,0,3)

; We mask the image's color pink to be the 'transparent' color - look at the
; image in your favorite editor to see more why we use masking.
MaskImage gfxSparks,255,0,255

; Loop until ESC


While Not KeyHit(1)
Cls ; Standard clear screen

; The next statment checks to see if 100 milliseconds has passes since we
; last changed frames. Change the 100 to higher and lower values to
; make the animation faster or slower.
If MilliSecs() > tmrSparks + 100 Then
tmrSparks=MilliSecs() ; 'reset' the timer
frmSparks=( frmSparks + 1 ) Mod 3 ; increment the frame, flip to 0 if we are out
End If
DrawImage gfxSparks,MouseX(),MouseY(),frmSparks ; draw the image
Flip ; show the buffer
Wend

Mid$ (string$, offset, characters)


Definition:
Retrieves a certain number of characters within a string, from a particular position.

Parameter Description:

string$ = any valid string


offset = location within the string to start reading
characters = how many characters to read frm the offset point

Command Description:

Use this command to grab a set of characters from within a string. You can choose WHERE to start in the
string, and how many characters to pick. You'll probably use this to 'decode' or 'walk through' a string to get
each character out of it for conversion or validation. See the Example.

Example:

name$="Shane Monroe"
For T = 1 To Len(name$)
Print Mid$(name$,t,1)
Next

MidHandle image
Definition:

Sets the image handle of the specified image to the middle of the image.

Parameter Description:

image = variable holding the file handle to the image

Command Description:

When an image is loaded with LoadImage, the image handle (the location within the image where the image is
'drawn from') is always defaulted to the top left corner (coordinates 0,0). This means if you draw an image
that is 50x50 pixels at screen location 200,200, the image will begin to be drawn at 200,200 and extend to
250,250.

This command moves the image handle from the 0,0 coordinate of the image to the exact middle of the
image. Therefore, in the same scenario above, if you were to draw a 50x50 pixel image at screen location
200,200 with its image handle set to Mid with this command, the image would start drawing at 175,175 and
extend to 225,225.

You can manual set the location of the image's handle using the HandleImage command. You can retrieve an
image's handle using the ImageXHandle and ImageYHandle. Finally, you can make all images automatically
load with the image handle set to middle using the AutoMidHandle command.

Note about the term 'handle'. There are two types of 'handles' we discuss in these documents. One is the
location within an image - as discussed in this command. The other is a 'file handle', a variable used to hold an
image, sound, or font loaded with a command. See LoadImage for more information about file handles.

Example:

; MidHandle/ImageXHandle()/ImageYHandle()/AutoMidHandle

; Initiate Graphics Mode


Graphics 640,480,16
; Set up the image file handle as a global
Global gfxBall

; Load the image - you may need to change the location of the file
gfxBall=LoadImage ("C:\Program Files\Blitz Basic\samples\ball.bmp")

; Until the user presses ESC key ...


While Not KeyHit(1)
Text 0,0,"Default Image Handle for gfxBall... Press ESC ..."
Text 0,14,"X handle-" + ImageXHandle(gfxBall) ; Print the location of the image handle x location
Text 0,28,"Y handle-" + ImageYHandle(gfxBall) ; Print the location of the image handle y location
DrawImage gfxBall,200,200,0 ; draw the image at 200,200
Wend

; Clear the screen


Cls

; Set the ball's handle to the center of the image


MidHandle gfxBall

; Until the user presses ESC key ... show the new information
While Not KeyHit(1)
Text 0,0,"New Image Handle for gfxBall... Press ESC ..."
Text 0,14,"X handle-" + ImageXHandle(gfxBall)
Text 0,28,"Y handle-" + ImageYHandle(gfxBall)
DrawImage gfxBall,200,200,0
Wend

; Makes all images load up with their handles in the center of the image
AutoMidHandle True
Cls

; Load the image again


gfxBall=LoadImage ("C:\Program Files\Blitz Basic\samples\ball.bmp")

; Until the user presses ESC key ... show the new information
While Not KeyHit(1)
Text 0,0,"Automatic image handle of gfxBall... Press ESC ..."
Text 0,14,"X handle-" + ImageXHandle(gfxBall)
Text 0,28,"Y handle-" + ImageYHandle(gfxBall)
DrawImage gfxBall,200,200,0
Wend

Millisecs()
Definition:

Return the system's timer value in milliseconds.

Parameter Description:

None

Command Description:

This command will return to you the system timer value in milliseconds.

This is incredibly useful for precision timing of events. By reading this value into a variable, and checking it
against the CURRENT time in milliseconds, you can perform 'waits' or check time lapses with a high degree of
accuracy. A common use of this command is to seed the random number generator with the SeedRnd
command.

Example:

; This prints STILL WAITING! for three seconds then ends.


oldTime=MilliSecs()
While MilliSecs() < oldTime + 3000
Print "Still waiting!"
Wend

Mod
Definition:

Returns the amount by which a number exceeds the largest integer multiple of the divisor that is not greater
than that number.

Parameter Description:

None

Command Description:

Basically, this will divide your number as many times as possible by the divisor, then return you the remaining
amount.

Example:

; MOD Example

; Divide 10 by 3 until you reach a point that you can't ; Then print the remaining value - in this case, 1 Print
10 MOD 3

MouseDown (button)
Definition:

Returns TRUE if the specified mouse button is being held down.

Parameter Description:

button = 1: Left Button, 2: Right Button, 3: Middle Button

Command Description:

This command (and its counterparts KeyDown and JoyDown) is used to detect if a mouse button is being held
down. You must check for each mouse button independantly with its corresponding number (unlike KeyDown
which returns WHICH key is being held down). Also see MouseHit.

Example:

; MouseDown Example

; Until user presses ESC, show the mouse button pressed


While Not KeyHit(1)
button$="No"
If MouseDown(1) Then button$="Left"
If MouseDown(2) Then button$="Right"
If MouseDown(3) Then button$="Middle"

Print button$ + " mouse button pressed!"


Wend

MouseHit (button)
Definition:

Returns the number of times a specified mouse button has been hit.

Parameter Description:

button = button code (1=Left, 2=Right, 3-Middle)

Command Description:

This command returns the number of times a specified mouse button has been hit since the last time you
called the MouseHit() command. Also see KeyHit and JoyHit.

Example:

; MouseHit Example

; Set up the timer


current=MilliSecs()
Print "Press left mouse button a bunch of times for five seconds..."

; Wait 5 seconds
While MilliSecs() < current+5000
Wend

; Print the results


Print "Pressed left button " + MouseHit(1) + " times."

MouseWait()
Definition:

Halts program execution until a mouse button is pressed and returns its button code.

Parameter Description:

None.

Command Description:

This command makes your program halt until a mouse button is pressed on the mouse. Used alone, it simply
halts and waits for a button press. It can also be used to assign the pressed button's code value to a variable.
See example.
In MOST CASES, you are not going to want to use this command because chances are likely you are going to
want things on the screen still happening while awaiting the button press. In that situation, you'll use a WHILE
... WEND awaiting a MouseHit value - refreshing your screen each loop.

Example:

; MouseWait Example

Print "Press a mouse button please..."


mseButton=MouseWait()
Print "You pressed mouse button #" + mseButton

MouseX()
Definition:

Returns the mouse's X screen coordinate.

Parameter Description:

None

Command Description:

This command returns the mouse's X location on the screen. Use this with the DrawImage command to make
a custom mouse pointer, or to control something directly on the screen with the mouse. Use MouseY() to get
the Y coordinate.

Example:

; LoadAnimImage/MaskImage MouseX()/MouseY() Example


; With animation timers

; Even though we don't have any functions, let's do variables global


; One variable will hold the handle for the graphic, one will hold the
; current frame we are displaying, and one will hold the milliseconds
; timer so we can adjust the animation speed.
Global gfxSparks, frmSparks, tmrSparks

; Standard graphic declaration and double buffering setup


Graphics 640,480,16
SetBuffer BackBuffer()

; Load the imagestrip up and denote the frames 32x32 - for a total of 3 frames
gfxSparks=LoadAnimImage("c:\Program Files\BlitzBasic\samples\Graphics\spark.bmp",32,32,0,3)

; We mask the image's color pink to be the 'transparent' color - look at the
; image in your favorite editor to see more why we use masking.
MaskImage gfxSparks,255,0,255

; Loop until ESC


While Not KeyHit(1)
Cls ; Standard clear screen

; The next statment checks to see if 100 milliseconds has passes since we
; last changed frames. Change the 100 to higher and lower values to
; make the animation faster or slower.
If MilliSecs() > tmrSparks + 100 Then
tmrSparks=MilliSecs() ; 'reset' the timer
frmSparks=( frmSparks + 1 ) Mod 3 ; increment the frame, flip to 0 if we are out
End If
DrawImage gfxSparks,MouseX(),MouseY(),frmSparks ; draw the image at MouseX and Y
Flip ; show the buffer
Wend

MouseXSpeed()
Definition:

Returns the changes in the mouse location since the LAST call to the command

Parameter Description:

None.

Command Description:

Often you'd like to find the difference between where the mouse WAS to where it is NOW. You can use this
command and MouseYSpeed() in pairs to find out the changes in the mouse location between calls.

You really have to use these commands TWICE to get anything out of them. Each call you make returns the
difference in location since the LAST time you called it.

In the example, when you run it, move the mouse to a location, press left mouse button. This makes the first
call. Then, move the mouse and press right mouse button. The second call will return the difference since the
first call and display it for you.

Example:

; MouseXSpeed()/MouseYSpeed() examples

; Set graphics mode and double buffering


Graphics 800,600,16
SetBuffer BackBuffer()

; repeat until right mouse button is pressed


Repeat
Cls ; Clear screen
Rect MouseX(),MouseY(),2,2,1 ; draw a small box where the mouse is
; if user hits left mouse, take note of where it is and call mousexspeed/mouseyspeed
If MouseHit(1) Then startx=MouseXSpeed():starty=MouseYSpeed()

; When user hits right mouse button, record the difference between last call
; and this call to the mousey/xspeed commands.
If MouseHit(2) Then endx=MouseXSpeed():endy=MouseYSpeed()
Flip ; flip screen into view
Until endx ; end the loop when we have a value for endx

; display results
Text 0,0,"Changes in mouse coordinates: " + endx + "," + endy
Flip ; flip changes into view

; Wait for escape


While Not KeyHit(1)
Wend
MouseY()
Definition:

Returns the mouse's Y screen coordinate.

Parameter Description:

None

Command Description:

This command returns the mouse's Y location on the screen. Use this with the DrawImage command to make
a custom mouse pointer, or to control something directly on the screen with the mouse. Use MouseX() to get
the X coordinate.

Example:

; LoadAnimImage/MaskImage MouseX()/MouseY() Example


; With animation timers

; Even though we don't have any functions, let's do variables global


; One variable will hold the handle for the graphic, one will hold the
; current frame we are displaying, and one will hold the milliseconds
; timer so we can adjust the animation speed.
Global gfxSparks, frmSparks, tmrSparks

; Standard graphic declaration and double buffering setup


Graphics 640,480,16
SetBuffer BackBuffer()

; Load the imagestrip up and denote the frames 32x32 - for a total of 3 frames
gfxSparks=LoadAnimImage("c:\Program Files\BlitzBasic\samples\Graphics\spark.bmp",32,32,0,3)

; We mask the image's color pink to be the 'transparent' color - look at the
; image in your favorite editor to see more why we use masking.
MaskImage gfxSparks,255,0,255

; Loop until ESC


While Not KeyHit(1)
Cls ; Standard clear screen

; The next statment checks to see if 100 milliseconds has passes since we
; last changed frames. Change the 100 to higher and lower values to
; make the animation faster or slower.
If MilliSecs() > tmrSparks + 100 Then
tmrSparks=MilliSecs() ; 'reset' the timer
frmSparks=( frmSparks + 1 ) Mod 3 ; increment the frame, flip to 0 if we are out
End If
DrawImage gfxSparks,MouseX(),MouseY(),frmSparks ; draw the image at MouseX and Y
Flip ; show the buffer
Wend

MouseYSpeed()
Definition:

Returns the changes in the mouse location since the LAST call to the command.

Parameter Description:
None.

Command Description:

Often you'd like to find the difference between where the mouse WAS to where it is NOW. You can use this
command and MouseXSpeed() in pairs to find out the changes in the mouse location between calls.

You really have to use these commands TWICE to get anything out of them. Each call you make returns the
difference in location since the LAST time you called it.

In the example, when you run it, move the mouse to a location, press left mouse button. This makes the first
call. Then, move the mouse and press right mouse button. The second call will return the difference since the
first call and display it for you.

Example:

; MouseXSpeed()/MouseYSpeed() examples

; Set graphics mode and double buffering


Graphics 800,600,16
SetBuffer BackBuffer()

; repeat until right mouse button is pressed


Repeat
Cls ; Clear screen
Rect MouseX(),MouseY(),2,2,1 ; draw a small box where the mouse is
; if user hits left mouse, take note of where it is and call mousexspeed/mouseyspeed
If MouseHit(1) Then startx=MouseXSpeed():starty=MouseYSpeed()

; When user hits right mouse button, record the difference between last call
; and this call to the mousey/xspeed commands.
If MouseHit(2) Then endx=MouseXSpeed():endy=MouseYSpeed()
Flip ; flip screen into view
Until endx ; end the loop when we have a value for endx

; display results
Text 0,0,"Changes in mouse coordinates: " + endx + "," + endy
Flip ; flip changes into view

; Wait for escape


While Not KeyHit(1)
Wend

MouseZ

Parameters:

n/a

Description:

MouseZ returns the current position of the mousewheel on a suitable mouse. It starts off at zero when your
program begins. The value of MouseZ increases as you move the wheel away from you and decreases as you
move it towards you.

Example:
Graphics 640, 480, 0, 2

SetBuffer BackBuffer ()

Repeat
Text 20, 20, "Mouse wheel position: " + MouseZ ()
Until KeyHit (1)

End

MouseZSpeed

Parameters:

n/a

Description:

MouseZSpeed returns -1 if the mousewheel on a suitable mouse is being rolled backwards (towards user), 0 if
it is not being moved, and 1 if it is being rolled forwards.

Example:

Graphics 640, 480, 0, 2


SetBuffer BackBuffer ()

Repeat

Cls

Select MouseZSpeed ()
Case -1
result$ = "Backwards"
Case 0
; result$ = "No movement"
Case 1
result$ = "Forwards"
End Select

Text 20, 10, "NOTE: MouseZSpeed () = 0 is not listed here, to avoid confusion!"
Text 20, 40, result$
Flip

Until KeyHit (1)

End

MoveMouse x,y
Definition:

Moves the mouse pointer to a designated location on the screen.

Parameter Description:

x = the x coordinate on the screen to move the mouse


y = the y coordinate on the screen to move the mouse

Command Description:
Although the mouse isn't visible on the screen, the mouse location is still being tracked and you can attach a
graphic to it. However, there are times when you want to put the pointer to a specific location on the screen.
Use this command to move the mouse to a designated location.

Example:

; MoveMouse Example

Graphics 640,480
For t = 1 To 2
Print "Move the mouse around and push the left button."
WaitMouse()
Print "The mouse is currently located at: " + MouseX() + "," + MouseY() + "."
Next
Print "Now I'll move the mouse ..."
MoveMouse 320,320
Print "The mouse is NOW located at: " + MouseX() + "," + MouseY() + "."
Print "Click mouse button to quit."
WaitMouse()

NetMsgData$()
Definition:

Returns the actual message of a network message.

Parameter Description:

None.

Command Description:

First off, this ONLY works when you have joined a network game via StartNetGame or JoinNetGame and you
have created a player via CreateNetPlayer (you must create a player, even if it is just to lurk). You must've
received the message already, determined by the RecvNetMsg() command - and probably determined the type
of message with (NetMsgType().

The string value returned from this command is the actual message text that was sent.

You will use NetMsgType(), NetMsgFrom(), and NetMsgTo() to get other important information from the
message and act on it.

The example requires that you run it on a remote machine while the local computer runs the example in the
SendNetMsg command.

Example:

; NetMsgData$() example
; --------------------
; Run this program on the REMOTE computer to 'watch'
; the activity of the SendNetMsg example. Run that
; example on local machine.
;
; This program will tell you when a player involved in
; the game hits a wall ...

; We'll use this instead of JoinHostGame - make it easier


StartNetGame()
; Create a player - a player must be created to
; receive mesages!
playerID=CreateNetPlayer("Shane")

; Loop and get status


While Not KeyHit(1)

; Check to see if we've received a message


If RecvNetMsg() Then

; if we did, let's figure out what type it is


; we know it will be a user message, though
msgType=NetMsgType()

; 1-99 means a user message


If msgType>0 And msgType

; Let's see who the message was from


msgFrom=NetMsgFrom()

; Let's get the message!


msgData$=NetMsgData$()

; Print the message


Print msgData$
Print "(Message was to:"+ NetMsgTo() + ")"
End If
End If
Wend

NetMsgFrom()
Definition:

Returns the sender's ID of a network message.

Parameter Description:

None.

Command Description:

First off, this ONLY works when you have joined a network game via StartNetGame or JoinNetGame and you
have created a player via CreateNetPlayer (you must create a player, even if it is just to lurk). You must've
received the message already, determined by the RecvNetMsg() command - and probably determined the type
of message with (NetMsgType().

The value returned from this command denotes the sender's ID number assigned to them when they were
created with CreateNetPlayer command. Use this to perform actions on the player on the local machine.

You will use NetMsgType(), NetMsgTo(), and NetMsgData$() to get other important information from the
message and act on it.

The example requires that you run it on a remote machine while the local computer runs the example in the
SendNetMsg command.

Example:

; NetMsgFrom() example
; --------------------
; Run this program on the REMOTE computer to 'watch'
; the activity of the SendNetMsg example. Run that
; example on local machine.
;
; This program will tell you when a player involved in
; the game hits a wall ...

; We'll use this instead of JoinHostGame - make it easier


StartNetGame()

; Create a player - a player must be created to


; receive mesages!
playerID=CreateNetPlayer("Shane")

; Loop and get status


While Not KeyHit(1)

; Check to see if we've received a message


If RecvNetMsg() Then

; if we did, let's figure out what type it is


; we know it will be a user message, though
msgType=NetMsgType()

; 1-99 means a user message


If msgType>0 And msgType

; Let's see who the message was from


msgFrom=NetMsgFrom()

; Let's get the message!


msgData$=NetMsgData$()

; Print the message


Print msgData$
End If
End If
Wend

NetMsgTo()
Definition:

Returns the ID of the recipient of a network message.

Parameter Description:

None.

Command Description:

First off, this ONLY works when you have joined a network game via StartNetGame or JoinNetGame and you
have created a player via CreateNetPlayer (you must create a player, even if it is just to lurk). You must've
received the message already, determined by the RecvNetMsg() command - and probably determined the type
of message with (NetMsgType().

The value returned from this command denotes the messages's intended recipient's ID number assigned to
them when they were created with CreateNetPlayer.

You will use NetMsgType(), NetMsgFrom(), and NetMsgData$() to get other important information from the
message and act on it.

The example requires that you run it on a remote machine while the local computer runs the example in the
SendNetMsg command.

Example:

; NetMsgTo() example
; --------------------
; Run this program on the REMOTE computer to 'watch'
; the activity of the SendNetMsg example. Run that
; example on local machine.
;
; This program will tell you when a player involved in
; the game hits a wall ...

; We'll use this instead of JoinHostGame - make it easier


StartNetGame()

; Create a player - a player must be created to


; receive mesages!
playerID=CreateNetPlayer("Shane")

; Loop and get status


While Not KeyHit(1)

; Check to see if we've received a message


If RecvNetMsg() Then

; if we did, let's figure out what type it is


; we know it will be a user message, though
msgType=NetMsgType()

; 1-99 means a user message


If msgType>0 And msgType

; Let's see who the message was from


msgFrom=NetMsgFrom()

; Let's get the message!


msgData$=NetMsgData$()

; Print the message


Print msgData$
Print "(Message was to:"+ NetMsgTo() + ")"
End If
End If
Wend

NetMsgType()
Definition:

Returns the type of message receieved during a network game.

Parameter Description:

None.

Command Description:
First off, this ONLY works when you have joined a network game via StartNetGame or JoinNetGame and you
have created a player via CreateNetPlayer (you must create a player, even if it is just to lurk). You must've
received the message already, determined by the RecvNetMsg() command.

The value returned from this command denotes the message; 1-99 means it is a user message, 100 means a
new player has joined the game, 101 means a player has been deleted from the network game (NetMsgFrom()
returns the player deleted), 102 means the original host has left the game and THIS machine is now the new
host.

If you receive a 200, this means a fatal exception has occurred and you need to exit the game.

You will use NetMsgFrom, NetMsgTo, and NetMsgData$ to get the important information from the message
and act on it.

The example requires that you run it on a remote machine while the local computer runs the example in the
SendNetMsg command.

Example:

; NetMsgType() example
; --------------------
; Run this program on the REMOTE computer to 'watch'
; the activity of the SendNetMsg example. Run that
; example on local machine.
;
; This program will tell you when a player involved in
; the game hits a wall ...

; We'll use this instead of JoinHostGame - make it easier


StartNetGame()

; Create a player - a player must be created to


; receive mesages!
playerID=CreateNetPlayer("Shane")

; Loop and get status


While Not KeyHit(1)

; Check to see if we've received a message


If RecvNetMsg() Then

; if we did, let's figure out what type it is


; we know it will be a user message, though
msgType=NetMsgType()

; 1-99 means a user message


If msgType>0 And msgType

; Let's see who the message was from


msgFrom=NetMsgFrom()

; Let's get the message!


msgData$=NetMsgData$()

; Print the message


Print msgData$
End If
End If
Wend
NetPlayerLocal (playerID)
Definition:

Determines if the player is on the local machine.

Parameter Description:

playerID = a valid player ID number (get from the NetMsgFrom() command)

Command Description:

First off, this ONLY works when you have joined a network game via StartNetGame or JoinNetGame and you
have created a player via CreateNetPlayer (you must create a player, even if it is just to lurk).

Use this command in conjunction with the NetMsgFrom() (to get the player's ID) command to check and see if
the player in question is on the local machine (as opposed to a remote machine). You may wish to act
differently in your program based on whether the message that came in was from a local or remote machine.

You will use NetMsgType(), NetMsgFrom(), and NetMsgTo() to get other important information from the
message and act on it.

The example requires that you run it on a remote machine while the local computer runs the example in the
SendNetMsg command.

Example:

; NetPlayerLocal example
; --------------------
; Run this program on the REMOTE computer to 'watch'
; the activity of the SendNetMsg example. Run that
; example on local machine.
;
; This program will tell you when a player involved in
; the game hits a wall ...

; We'll use this instead of JoinHostGame - make it easier


StartNetGame()

; Create a player - a player must be created to


; receive mesages!
playerID=CreateNetPlayer("Shane")

; Loop and get status


While Not KeyHit(1)

; Check to see if we've received a message


If RecvNetMsg() Then

; if we did, let's figure out what type it is


; we know it will be a user message, though
msgType=NetMsgType()

; 1-99 means a user message


If msgType>0 And msgType

; Let's see who the message was from


msgFrom=NetMsgFrom()

; Let's get the message!


msgData$=NetMsgData$()
; Print the message
Print msgData$
if NetPlayerLocal(NetMsgFrom()) then
print "(This was sent from a local player)"
end if
End If
End If
Wend

NetPlayerName$ (playerID)
Definition:

Returns the actual name of the player in a network game.

Parameter Description:

playerID = a valid player ID number (get from the NetMsgFrom() command

Command Description:

First off, this ONLY works when you have joined a network game via StartNetGame or JoinNetGame and you
have created a player via CreateNetPlayer (you must create a player, even if it is just to lurk).

Use this command in conjunction with the NetMsgFrom() (to get the player's ID) command to derive the
actual name of the player. This command returns a string value.

You will use NetMsgType(), NetMsgFrom(), and NetMsgTo() to get other important information from the
message and act on it.

The example requires that you run it on a remote machine while the local computer runs the example in the
SendNetMsg command.

Example:

; NetPlayerName$() example
; --------------------
; Run this program on the REMOTE computer to 'watch'
; the activity of the SendNetMsg example. Run that
; example on local machine.
;
; This program will tell you when a player involved in
; the game hits a wall ...

; We'll use this instead of JoinHostGame - make it easier


StartNetGame()

; Create a player - a player must be created to


; receive mesages!
playerID=CreateNetPlayer("Shane")

; Loop and get status


While Not KeyHit(1)

; Check to see if we've received a message


If RecvNetMsg() Then

; if we did, let's figure out what type it is


; we know it will be a user message, though
msgType=NetMsgType()
; 1-99 means a user message
If msgType>0 And msgType

; Let's see who the message was from


msgFrom=NetMsgFrom()

; Let's get the message!


msgData$=NetMsgData$()

; Print the message


Print msgData$
Print "(Message was from:"+ NetPlayerName$(NetMsgFrom()) + ")"
End If
End If
Wend

New type_variable
Definition:

Create a new TYPE object in the Type collection.

Parameter Description:

type_variable = the actual Type name, not the custom Type name

Command Description:

If you aren't familiar with the TYPE command, please refer to that before reading about this command.

Creates a NEW object in a Type collection. Each call to this command automatically inserts a new object into
the specified Type collection. Check the example and other Type commands for more information.

Example:

; Define the CHAIR Type

Type CHAIR
Field X
Field Y
Field HEIGHT
End Type

; Create 100 new chairs using FOR ... NEXT using the collection name of ROOM

For tempx = 1 to 10
For tempy = 1 to 10
room.chair = New Chair
room\x = tempx
room\y = tempy
room\height = Rnd(0,10) ; set a random height 0 to 10
Next
Next

Next
Definition:

The closing command of a FOR ... NEXT loop.

Parameter Description:

None

Command Description:

This command closes the FOR ... NEXT loop, causing program execution to start again at the FOR command
unless the loop condition has been met (the last value has been met). Check the example for more info. Note:
Do NOT use the FOR command's variable as a parameter (i.e. NEXT T) as you would in most BASIC languages.
Blitz will automatically match it with the nearest FOR command.

Example:

; Print the values 1 through 10


For t = 1 To 10
Print t
Next
; Print the values 1,3,5,7,9
For t = 1 To 10 Step 2
Print t
Next

NextFile$ (filehandle)
Definition:

Retrieves the next file/folder from a directory opened with the ReadDir command.

Parameter Description:

filehandle = valid filehandle assigned from the ReadDir command

Command Description:

This command will return the NEXT file or folder from the currently open directory (use ReadDir to open the
desired folder for reading). This will return a string containing the folder name or the filename plus extention.
Use FILETYPE to determine if it is a file or folder. See ReadDir and CloseDir for more. You cannot move
'backwards' through a directory, only forward. You might want to parse the contents of a directory into an
array for display, processing, etc.

Example:

; ReadDir/NextFile$/CloseDir example

; Define what folder to start with ...


folder$="C:\"

; Open up the directory, and assign the handle to myDir


myDir=ReadDir(folder$)

; Let's loop forever until we run out of files/folders to list!


Repeat
; Assign the next entry in the folder to file$
file$=NextFile$(myDir)
; If there isn't another one, let's exit this loop
If file$="" Then Exit

; Use FileType to determine if it is a folder (value 2) or a file and print results


If FileType(folder$+"\"+file$) = 2 Then
Print "Folder:" + file$
Else
Print "File:" + file$
End If
Forever

; Properly close the open folder


CloseDir myDir

; We're done!
Print "Done listing files!"

Not
Definition:

Logical operator NOT to test a condition to be false.

Parameter Description:

None.

Command Description:

The NOT operator is used to determine if a condition is FALSE instead of TRUE. This is frequently used in
WHILE loops and IF statements to check for the NON-EXISTANCE of an event or value. We use NOT frequently
in our examples, inside WHILE loops to test if the ESC key has been pressed.

Example:

; NOT example

; Loop until they press ESC


While Not KeyHit(1) ; As long as ESC isn't pressed ...
Print "Press ESC to quit!"
Wend

Null
Definition:

Indicates a null or empty value.

Parameter Description:

None

Command Description:
Designates a null value. Useful for erasing a variable or testing if a variable has a value at all.

Example:

; Null example

strHello$="Hello"

Print strHello$

strHello$=Null

OpenFile (filename$)
Definition:

Opens a file on disk for both reading and writing operations i.e. for update.

Parameter Description:

filename$ = any valid path and filename. The returned value is the filehandle which is used by other file
handling commands.

Command Description:

This command opens the designated file and prepares it to be updated. The file must exists since this function
will not create a new file.

By using FilePos and SeekFile the position within the file that is being read or written can be determined and
also changed. This allows a file to be read and updated without having to make a new copy of the file or
working through the whole file sequentially. This could be useful if you have created a database file and you
want to find and update just a few records within it.

The file handle that is returned is an integer value that the operating system uses to identify which file is to be
read and written to and must be passed to the functions such as ReadInt() and WriteInt().

Note extreme care needs to be exercised when updating files that contain strings since these are not fixed in
length.

Example:

; Changing part of a file using OpenFile, SeekFile and WriteInt

; Open/create a file to Write


fileout = WriteFile("mydata.dat")

; Write the information to the file


WriteInt( fileout, 1 )
WriteInt( fileout, 2 )
WriteInt( fileout, 3 )
WriteInt( fileout, 4 )
WriteInt( fileout, 5 )

; Close the file


CloseFile( fileout )

DisplayFile( "The file as originally written", mydata.dat" )


; Open the file and change the Third Integer
file = OpenFile("mydata.dat")
SeekFile( file, 8 ) ; Move to the third integer in the file
WriteInt( file, 9999 ) ; Replace the original value with 9999
CloseFile( file )

DisplayFile( "The file after being midified", "mydata.dat" )


WaitKey()
; **** Function Definitions follow ****

; Read the file and print it


Function DisplayFile( Tittle$, Filename$ )
Print tittle$
filein = ReadFile( Filename$ )
While Not Eof( filein )
Number = ReadInt( filein )
Print Number
Wend
CloseFile( filein )
Print
End Function

OpenTCPStream (ip$,port)
Definition:

Opens a client TCP stream to the specified server.

Parameter Description:

ip$=Address of stream
port=TCP/IP Port Number

Command Description:

Use this command to open up a TCP/IP stream to the designated server and port. If the open command was
successful, the command returns a stream handle. Otherwise it returns 0.

You can use this for a multitude of different 'internet' options. Obviously to contact a TCP/IP host outside your
own network, you'll need to be connected to the Internet.

The IP address can be in the form of 1.2.3.4 or "www.domain.com".

Example:

; OpenTCPStream/CloseTCPStream Example

Print "Connecting..."
tcp=OpenTCPStream( "www.blitzbasement.com",80 )

If Not tcp Print "Failed.":WaitKey:End

Print "Connected! Sending request..."

WriteLine tcp,"GET http://www.blitzbasement.com HTTP/1.0"


WriteLine tcp,Chr$(10)

If Eof(tcp) Print "Failed.":WaitKey:End

Print "Request sent! Waiting for reply..."


While Not Eof(tcp)
Print ReadLine$( tcp )
Wend

If Eof(tcp)=1 Then Print "Success!" Else Print "Error!"

CloseTCPStream tcp

WaitKey
End

Or
Definition:

Conjunction between two values to derive a boolean value.

Parameter Description:

None

Command Description:

A logical expression to return a boolean TRUE or FALSE comparison of expressions or values. Use this to check
two expressions or more and act upon its return value. See the example.

Example:

; OR Example

myNum1=Rnd(0,10)
myNum2=Rnd(0,10)

If myNum1 = 0 OR myNum2 = 0 then


print "One of my numbers is a Zero"
end if

Origin x,y
Definition:

Allows you to offset all drawing commands from a designated location.

Parameter Description:

x = x offset value
y = y offset value

Command Description:

This command sets a point of origin for all subsequent drawing commands. This can be positive or negative.

Example:

; Origin example
Graphics 800,600,16
; Offset drawing options with origin command -200 in each direction
Origin -200,-200

; Wait for ESC to hit


While Not KeyHit(1)

; Draw an oval - SHOULD be at the exact center, but it isn't!


Oval 400,300,50,50,1
Wend

Oval x,y,width,height[,solid]
Definition:

Draws an oval at the designated location on the screen.

Parameter Description:

x = x coordinate on the screen to draw the oval


y = y coordinate on the screen to draw the oval
width = how wide to make the oval
height = how high to make the oval
[solid] = 1 to make the oval solid

Command Description:

Use this to draw an oval shape at the screen coordinates of your choice. You can make the oval solid or
hollow.

Example:

; Oval example
Graphics 800,600,16

; Wait for ESC to hit


While Not KeyHit(1)
; Set a random color
Color Rnd(255),Rnd(255),Rnd(255)
; Draw a random oval
Oval Rnd(800),Rnd(600),Rnd(100),Rnd(100),Rnd(0,1)
Wend

PauseChannel channel_handle
Definition:

Pauses the playing of a sound channel.

Parameter Description:

channel_handle = variable assigned to the channel when played

Command Description:

When you are playing a sound channel, there may come a time you wish to pause the sound for whatever
reason (like to play another sound effect). This command does this - and the channel can be resumed with the
ResumeChannel command. You can use StopChannel to actually halt the sound. This works with any channel
playback (WAV, MP3, MIDI, etc.).

Example:

; Channel examples

Print "Loading sound ..."


; Load the sample - you'll need to point this to a sound on your computer
; For best results, make it about 5-10 seconds...
sndWave=LoadSound("level1.wav")
; Prepare the sound for looping
LoopSound sndWave

chnWave=PlaySound(sndWave)

Print "Playing sound for 2 seconds ..."


Delay 2000

Print "Pausing sound for 2 seconds ..."


PauseChannel chnWave
Delay 2000

Print "Restarting sound ..."


ResumeChannel chnWave
Delay 2000

Print "Changing Pitch of sound ..."


;StopChannel chnWave
ChannelPitch chnWave, 22000
Delay 2000

Print "Playing new pitched sound ..."


Delay 2000

Print "Left speaker only"


ChannelPan chnWave,-1
Delay 2000

Print "Right speaker only"


ChannelPan chnWave,1
Delay 2000

Print "All done!"


StopChannel chnWave

PeekByte bank,offset
Definition:

Reads a byte from a memory bank.

Parameter Description:

bank = variable containing handle to valid bank


offset = offset in bytes to read the value

Command Description:
This command reads a byte type value from a memory bank created with the CreateBank command. Also see
PokeInt, PokeFloat, PokeByte, and PokeShort. To retrieve from a memory bank, use PeekInt, PeekFloat, and
PeekShort.

Example:

; Bank Commands Example

bnkTest=CreateBank(500)

For t = 1 To 50
PokeByte bnkTest,t,Rnd(255)
PokeInt bnkTest,t+1,Rnd(10000)
PokeShort bnkTest,t+2,Rnd(10000)
PokeFloat bnkTest,t+3,Rnd(-.999,.999)
Next

For t = 1 To 50
Print PeekByte (bnkTest,t)
Print PeekInt (bnkTest,t+1)
Print PeekShort (bnkTest,t+2)
Print PeekFloat (bnkTest,t+3)
Next

Freebank bnkTest

PeekFloat bank,offset
Definition:

Reads a floating point value from a memory bank.

Parameter Description:

bank = variable containing handle to valid bank


offset = offset in bytes to read the value

Command Description:

This command reads a floating point type value from a memory bank created with the CreateBank command.
Also see PokeInt, PokeFloat, PokeByte, and PokeShort. To retrieve from a memory bank, use PeekInt, and
PeekByte, and PeekShort.

Example:

; Bank Commands Example

bnkTest=CreateBank(500)

For t = 1 To 50
PokeByte bnkTest,t,Rnd(255)
PokeInt bnkTest,t+1,Rnd(10000)
PokeShort bnkTest,t+2,Rnd(10000)
PokeFloat bnkTest,t+3,Rnd(-.999,.999)
Next

For t = 1 To 50
Print PeekByte (bnkTest,t)
Print PeekInt (bnkTest,t+1)
Print PeekShort (bnkTest,t+2)
Print PeekFloat (bnkTest,t+3)
Next

Freebank bnkTest

PeekInt bank,offset
Definition:

Reads an integer value from a memory bank.

Parameter Description:

bank = variable containing handle to valid bank


offset = offset in bytes to read the value

Command Description:

This command reads an integer type value from a memory bank created with the CreateBank command. Also
see PokeInt, PokeFloat, PokeByte, and PokeShort. To retrieve from a memory bank, use PeekFloat, and
PeekByte, and PeekShort.

Example:

; Bank Commands Example

bnkTest=CreateBank(500)

For t = 1 To 50
PokeByte bnkTest,t,Rnd(255)
PokeInt bnkTest,t+1,Rnd(10000)
PokeShort bnkTest,t+2,Rnd(10000)
PokeFloat bnkTest,t+3,Rnd(-.999,.999)
Next

For t = 1 To 50
Print PeekByte (bnkTest,t)
Print PeekInt (bnkTest,t+1)
Print PeekShort (bnkTest,t+2)
Print PeekFloat (bnkTest,t+3)
Next

Freebank bnkTest

PeekShort bank,offset
Definition:

Reads a short value from a memory bank.

Parameter Description:

bank = variable containing handle to valid bank


offset = offset in bytes to read the value

Command Description:
This command reads a short type value from a memory bank created with the CreateBank command. Also see
PokeInt, PokeFloat, PokeByte, and PokeShort. To retrieve from a memory bank, use PeekInt, PeekFloat, and
PeekByte.

Example:

; Bank Commands Example

bnkTest=CreateBank(500)

For t = 1 To 50
PokeByte bnkTest,t,Rnd(255)
PokeInt bnkTest,t+1,Rnd(10000)
PokeShort bnkTest,t+2,Rnd(10000)
PokeFloat bnkTest,t+3,Rnd(-.999,.999)
Next

For t = 1 To 50
Print PeekByte (bnkTest,t)
Print PeekInt (bnkTest,t+1)
Print PeekShort (bnkTest,t+2)
Print PeekFloat (bnkTest,t+3)
Next

Freebank bnkTest

Pi
Definition:

Returns the value of Pi

Parameter Description:

None

Command Description:

Returns the value of Pi to 6 digits (3.141592). Needed for geometric math routines.

Example:

; Pi example

Print "The Value of Pi is:" + Pi

PlayCDTrack track,[mode]
Definition:

Plays a CD audio track.

Parameter Description:

track = track number to play


mode = 1; play track once, 2; loop track, 3; play track to end of CD
Command Description:

You can play an audio CD through Blitz Basic with this command. The optional MODE parameter allows
variations of playback. Remember, the playback happens through the CD cable inside the computer that
attaches to the sound card. Many computers (for some reason), don't have this cable inside properly attached.
If this is the case, you will NOT hear CD sound even though you hear other sound effects and music.

You will need to assign the command a channel variable.

Example:

; PlayCDTrack example

; Get a track to play from user


track=Input$("Enter a CD track number to play:")

; Play the track, assign a channel - just play once


chnCD=PlayCDTrack(track,1)

; Figure out what time it is now


oldTime=MilliSecs()
; Play until the channel is over or ESC
While ChannelPlaying(chnCD) And (Not KeyHit(1))
; clear and print the time elapsed
Cls
Locate 0,0
Print "Time Elapsed (sec):" + ((MilliSecs()-oldTime)/1000)
Wend

; Stop the channel


StopChannel chnCD

PlayMusic (filename$)
Definition:

Loads and begins playing a piece of music.

Parameter Description:

filename$= a valid Windows path and filename.

Command Description:

This command will load and play a .WAV. .MID, or .MP3 file (presumably for background or other type music).

You MUST use a channel variable in order to stop or adjust the music playing. You may use StopChannel,
PauseChannel, ResumeChannel, etc. with this command.

Oddly, you can't 'preload' the audio like you can a sound sample via the LoadSound command. Everytime you
call the PlayMusic command, the file is RELOADED and played. Most of us aren't sure why this methodology
was chosen by Blitz, but you will get a hiccup when the hard drive seeks and grabs the music file. In most
cases, this will prevent you from using this command for what I'm sure it was intended for. Instead, you might
want to use the LoopSound command.

Example:

; Load and play the background music


chnBackground=PlayMusic("music\background.wav")

PlaySound sound_variable
Definition:

Plays a sound previously loaded into memory.

Parameter Description:

sound_variable = variable previously assigned with a LoadSound command.

Command Description:

This plays a sound previously loaded and assigned to a variable using the LoadSound command. See example.

You will need to assign a channel variable handle to the sound when you play it. All subsequent sound
handling commands require you use the CHANNEL variable, not the sound variable to control the sound - such
as StopChannel, PauseChannel, ResumeChannel, ChannelPitch, ChannelVolume, ChannelPan, and
ChannelPlaying.

Example:

; Assign a global variable for the sound


Global sndPlayerDie

; Load the sound file into memory

sndPlayerDie=LoadSound("sounds/die.wav")

; Play the sound

chnDie=PlaySound sndPlayerDie

Plot x,y
Definition:

Puts a single pixel on the screen in the current drawing color

Parameter Description:

x= and number from zero to the width of the current graphics mode
y= and number from zero to the height of the current graphics mode

Command Description:

Used to put a pixel on the screen defined by its x, y location in the current drawing color defined by the Color
command

Example:

;Set the color to green


Color 0,255,0
;Draw a dot at location 100,200 with the color green
plot 100,200

PokeByte bank,offset,value
Definition:

Writes a Byte value to a memory bank.

Parameter Description:

bank = variable containing handle to valid bank


offset = offset in bytes to write the value
value = the value to be written

Command Description:

This command writes a byte type value into a memory bank created with the CreateBank command. Also see
PokeInt, PokeFloat, and PokeShort. To retrieve from a memory bank, use PeekInt, PeekFloat, PeekByte, and
PeekShort.

Example:

; Bank Commands Example

bnkTest=CreateBank(500)

For t = 1 To 50
PokeByte bnkTest,t,Rnd(255)
PokeInt bnkTest,t+1,Rnd(10000)
PokeShort bnkTest,t+2,Rnd(10000)
PokeFloat bnkTest,t+3,Rnd(-.999,.999)
Next

For t = 1 To 50
Print PeekByte (bnkTest,t)
Print PeekInt (bnkTest,t+1)
Print PeekShort (bnkTest,t+2)
Print PeekFloat (bnkTest,t+3)
Next

Freebank bnkTest

PokeFloat bank,offset,value
Definition:

Writes a floating point value to a memory bank.

Parameter Description:

bank = variable containing handle to valid bank


offset = offset in bytes to write the value
value = the value to be written

Command Description:
This command writes a floating point type value into a memory bank created with the CreateBank command.
Also see PokeInt, PokeByte, and PokeShort. To retrieve from a memory bank, use PeekInt, PeekFloat,
PeekByte, and PeekShort.

Example:

; Bank Commands Example

bnkTest=CreateBank(500)

For t = 1 To 50
PokeByte bnkTest,t,Rnd(255)
PokeInt bnkTest,t+1,Rnd(10000)
PokeShort bnkTest,t+2,Rnd(10000)
PokeFloat bnkTest,t+3,Rnd(-.999,.999)
Next

For t = 1 To 50
Print PeekByte (bnkTest,t)
Print PeekInt (bnkTest,t+1)
Print PeekShort (bnkTest,t+2)
Print PeekFloat (bnkTest,t+3)
Next

Freebank bnkTest

PokeInt bank,offset,value
Definition:

Writes a Integer value to a memory bank.

Parameter Description:

bank = variable containing handle to valid bank


offset = offset in bytes to write the value
value = the value to be written

Command Description:

This command writes a integer type value into a memory bank created with the CreateBank command. Also
see PokeFloat, PokeByte, and PokeShort. To retrieve from a memory bank, use PeekInt, PeekFloat, PeekByte,
and PeekShort.

Example:

; Bank Commands Example

bnkTest=CreateBank(500)

For t = 1 To 50
PokeByte bnkTest,t,Rnd(255)
PokeInt bnkTest,t+1,Rnd(10000)
PokeShort bnkTest,t+2,Rnd(10000)
PokeFloat bnkTest,t+3,Rnd(-.999,.999)
Next

For t = 1 To 50
Print PeekByte (bnkTest,t)
Print PeekInt (bnkTest,t+1)
Print PeekShort (bnkTest,t+2)
Print PeekFloat (bnkTest,t+3)
Next

Freebank bnkTest

PokeShort bank,offset,value
Definition:

Writes a short value to a memory bank.

Parameter Description:

bank = variable containing handle to valid bank


offset = offset in bytes to write the value
value = the value to be written

Command Description:

This command writes a short type value into a memory bank created with the CreateBank command. Also see
PokeInt, PokeFloat, and PokeByte. To retrieve from a memory bank, use PeekInt, PeekFloat, PeekByte, and
PeekShort.

Example:

; Bank Commands Example

bnkTest=CreateBank(500)

For t = 1 To 50
PokeByte bnkTest,t,Rnd(255)
PokeInt bnkTest,t+1,Rnd(10000)
PokeShort bnkTest,t+2,Rnd(10000)
PokeFloat bnkTest,t+3,Rnd(-.999,.999)
Next

For t = 1 To 50
Print PeekByte (bnkTest,t)
Print PeekInt (bnkTest,t+1)
Print PeekShort (bnkTest,t+2)
Print PeekFloat (bnkTest,t+3)
Next

Freebank bnkTest

Print string$
Definition:

Print a string to the screen.

Parameter Description:

string$ = any valid string


Command Description:

This command will print a string value on the screen (if not in a graphic mode) or on the current drawing
buffer being used by the program. Unlike the Write command, it puts a carriage return/linefeed after the
string.

Example:

; Get the user's name and print a welcome

name$=Input$("What is your name?")


Print "Hello there, " + name$ + "!"

Rand ([low value],high value)


Definition:

Generates a random integer value between the values specified.

Parameter Description:

low value = optional - defaults to 1; lowest number to generate


high value = highest number to generate

Command Description:

Unlike the RND command, this command actually returns only integer values. The low value defaults to 1 if no
value is specified. The high value is the highest number that can be randomly generated.

If you need to generate floating point random numbers, use Rnd.

Example:

; Rand example

; Set the randomizer seed for more true random numbers


SeedRnd (MilliSecs())

; Generate random numbers between 1 and 100


For t = 1 To 20
Print Rand(1,100)
Next

Read variable
Definition:

Get the next set of values from a Data statement.

Parameter Description:

variable = valid variable to match the data type you are reading (integer, string, etc)

Command Description:
This reads the next value in a set of Data statements. This allows you to store large blocks of constant
information (the structure of tile blocks for a game level for example) into easy to maintain Data statements,
then retrieve them for redrawing, etc.

Unlike most BASIC languages, Data statments do not have to be linear and sequential. Through the use of
Labels (aka 'dot variable') you can create 'banks' of Data statments with the unique ability to 'Restore the
Data pointer' to any one of these labels. Each level could have its own label (.level1, .level2, etc). See the
Data statement, Restore command, or .Label command for more information.

Note: You can read multiple values at one time; Read X,Y,Z for example.

Example:

; Sample of read/restore/data/label commands

; Let's put the data pointer to the second data set


Restore seconddata

; Let's print them all to the screen


For t = 1 To 10
Read num ; Get the next data value in the data stack
Print num
Next

; Now for the first set of data


Restore firstdata

; Let's print them all to the screen


For t = 1 To 10
Read num ; Get the next data value in the data stack
Print num
Next

; this is the first set of data


.firstdata
Data 1,2,3,4,5,6,7,8,9,10

; this is the second set of data


.seconddata
Data 11,12,13,14,15,16,17,18,19,20

ReadAvail (filehandle|streamhandle)
Definition:

Returns how many bytes are guaranteed to be successfully read from a stream.

Parameter Description:

filehandle|streamhandle = handle assigned to the file or stream when originally opened.

Command Description:

In the case of file streams, this reflects how much data is internally buffered. In the case of TCP streams, this
reflects how much data has 'arrived'.

Example:

; OpenTCPStream/CloseTCPStream/ReadAvail Example
Print "Connecting..."
tcp=OpenTCPStream( "www.blitzbasement.com",80 )

If Not tcp Print "Failed.":WaitKey:End

Print "Connected! Sending request..."

WriteLine tcp,"GET http://www.blitzbasement.com HTTP/1.0"


WriteLine tcp,Chr$(10)

If Eof(tcp) Print "Failed.":WaitKey:End

Print "Request sent! Waiting for reply..."

While Not Eof(tcp)


Print ReadLine$( tcp )
Print "Bytes available:" + ReadAvail(tcp)
Wend

If Eof(tcp)=1 Then Print "Success!" Else Print "Error!"

CloseTCPStream tcp

WaitKey

ReadByte ( filehandle|stream )
Definition:

Reads a single byte of data from an open file (or stream) and returns it as an integer value between 0 and
255.

Parameter Description:

filehandle|stream = a valid variable set with the OpenFile, ReadFile command, or OpenTCPStream (v1.52+)

Command Description:

Once you've opened a disk file (or stream) for reading, use this command to read a single byte at a time from
the file/stream. Note, a byte is an integer that can take the values 0..255 and occupies 8 bits of storage. Since
characters are stored as byte values this function can be used to read a file one character at a time. Reading
beyond the end of file does not result in an error, but each value read will be zero.

Advanced notes

The number that is stored by WriteByte is actually the least significant byte of an integer so negative numbers
and numbers above 255 will still have a value between 0..255. Unless you understand how 32 bit integers are
stored in 2's compliment notation this will seem strange but it is NOT a bug.

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; Reading and writing a file using ReadByte and WriteByte functions

; Initialise some variables for the example


Byte1% = 10 ; store 10
Byte2% = 100 ; store 100
Byte3% = 255 ; store 255 ( the maximum value that can be stored in a Byte)
Byte4% = 256 ; try to store 256 this will end up as 0 ( i.e. 256 - 256 = 0 )
Byte5% = 257 ; try to store 257 this will end up as 1 ( i.e. 257 - 256 = 1 )
Byte6% = -1 ; try to store -1 this will end up as 255 ( i.e. 256 -1 = 255 )
Byte7% = -2 ; try to store 256 this will end up as 254 ( i.e. 256 - 2 = 254 )
Byte8% = Asc("A") ; Store the ASCII value for the Character "A" ( i.e. 65 )

; Open a file to write to


fileout = WriteFile("mydata.dat ")

; Write the information to the file


WriteByte( fileout, Byte1 )
WriteByte( fileout, Byte2 )
WriteByte( fileout, Byte3 )
WriteByte( fileout, Byte4 )
WriteByte( fileout, Byte5 )
WriteByte( fileout, Byte6 )
WriteByte( fileout, Byte7 )
WriteByte( fileout, Byte8 )

; Close the file


CloseFile( fileout )

; Open the file to Read


filein = ReadFile("mydata.dat")

Read1 = ReadByte( filein )


Read2 = ReadByte( filein )
Read3 = ReadByte( filein )
Read4 = ReadByte( filein )
Read5 = ReadByte( filein )
Read6 = ReadByte( filein )
Read7 = ReadByte( filein )
Read8 = ReadByte( filein )

; Close the file once reading is finished


CloseFile( fileout )

Print "Written - Read"


Write Byte1 + " - " : Print Read1
Write Byte2 + " - " : Print Read2
Write Byte3 + " - " : Print Read3
Write Byte4 + " - " : Print Read4
Write Byte5 + " - " : Print Read5
Write Byte6 + " - " : Print Read6
Write Byte7 + " - " : Print Read7
Write Byte8 + " - " : Print Chr$( Read8 )

WaitKey()

ReadBytes bank,file|stream,offset,count
Definition:

Reads data from a file (or stream) into a memory bank.

Parameter Description:

bank = variable containing handle to valid bank


file = file handle of previously opened file or stream
offset = offset in bytes to write the value
count = how many bytes to write from the offset
Command Description:

You can read the contents of a disk file (or stream) to a memory bank using this command.

Note: The file handle must be opened with OpenFile or OpenTCPStream and subsequently closed with CloseFile
or CloseTCPStream after the reading operations are complete.

Return how many bytes successfully read from a stream.

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; Read/WriteBytes Commands Example

; Create a 50 byte memory bank


bnkTest=CreateBank(500)

; Let's fill the bank with crap


For t = 1 To 50
PokeByte bnkTest,t,Rnd(255)
PokeInt bnkTest,t+1,Rnd(10000)
PokeShort bnkTest,t+2,Rnd(10000)
PokeFloat bnkTest,t+3,Rnd(-.999,.999)
Next

; Open a file to write to


fileBank=WriteFile("test.bnk")
; Write the bank to the file
WriteBytes bnkTest,fileBank,0,50
; Close it
CloseFile fileBank

; Free the bank


FreeBank bnkTest

; Make a new one


bnkTest=CreateBank(500)

; Open the file to read from


fileBank=OpenFile("test.bnk")
; Write the bank to the file
ReadBytes bnkTest,fileBank,0,50
; Close it
CloseFile fileBank

; Write back the results!


For t = 1 To 50
Print PeekByte (bnkTest,t)
Print PeekInt (bnkTest,t+1)
Print PeekShort (bnkTest,t+2)
Print PeekFloat (bnkTest,t+3)
Next

ReadDir (directory)
Definition:

Opens a folder/directory on a device for reading.

Parameter Description:
directory = full path and name of folder/directory to open

Command Description:

In file operations, you will often need to parse through a directory/folder and retrieve unknown filenames and
other folders from it. This command opens a specified folder to begin these operations. The command returns
a file handle which is used by the other commands to perform other services (like most file operators). You
will use the NextFile$ to iterate through each entry (use FILETYPE to see if it is a file or folder). Remember,
once completed, good programming practice dictates that you CloseDir the open folder. The example should
help out alot.

Example:

; ReadDir/NextFile$/CloseDir example

; Define what folder to start with ...


folder$="C:\"

; Open up the directory, and assign the handle to myDir


myDir=ReadDir(folder$)

; Let's loop forever until we run out of files/folders to list!


Repeat
; Assign the next entry in the folder to file$
file$=NextFile$(myDir)

; If there isn't another one, let's exit this loop


If file$="" Then Exit

; Use FileType to determine if it is a folder (value 2) or a file and print results


If FileType(folder$+"\"+file$) = 2 Then
Print "Folder:" + file$
Else
Print "File:" + file$
End If
Forever

; Properly close the open folder


CloseDir myDir

; We're done!
Print "Done listing files!"

ReadFile (filename$)
Definition:

Opens a file on disk for reading operations.

Parameter Description:

filename$ = any valid path and filename. The returned value is the filehandle which is an integer value.

Command Description:

This command opens the designated filename and prepares it to be read from. Use this to read back your own
configuration file, save game data, etc. also useful for reading custom types from a files. The filehandle that is
returned is an integer value that the operating system uses to identify which file is to be read from and must
be passed to the functions such as ReadInt(). If the file could not be opened, for instance, if it does not exists,
then the filehandle is Zero.

Example:

; Reading and writing custom types to files using ReadFile, WriteFile and CloseFile

; Initialise some variables for the example


Type HighScore
Field Name$
Field Score%
Field Level%
End Type

Best.HighScore = New HighScore


Best\Name = "Mark"
Best\Score = 11657
Best\Level = 34

; Open a file to write to


fileout = WriteFile("mydata.dat")

; Write the information to the file


WriteString( fileout, Best\Name )
WriteInt( fileout, Best\Score )
WriteByte( fileout, Best\Level )

; Close the file


CloseFile( fileout )

; Open the file to Read


filein = ReadFile("mydata.dat")

; Lets read the Greatest score from the file


Greatest.HighScore = New HighScore
Greatest\Name$ = ReadString$( filein )
Greatest\Score = ReadInt( filein )
Greatest\Level = ReadByte( filein )

; Close the file once reading is finished


CloseFile( fileout )

Print "High score record read from - mydata.dat "


Print
Write "Name = "
Print Greatest\Name
Write "Score = "
Print Greatest\Score
Write "Level = "
Print Greatest\Level

WaitKey()

ReadFloat (filehandle|stream)
Definition:

Reads a single floating point value from an open file (or stream).

Parameter Description:
filehandle|stream = a valid variable set with the OpenFile, ReadFile command, or OpenTCPStream (v1.52+)
The value returned is a floating point number.

Command Description:

Once you've opened a disk file (or stream) for reading, use this command to read a single floating point
number from the file. Note, each value written uses 4 bytes of space. Reading beyond the end of file does not
result in an error, but each value read will be zero.

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; Reading and writing a file using ReadFloat and WriteFloat functions

; Initialise some variables for the example


Num1# = 10.5 ; store 10.5
Num2# = 365.25 ; store 365.25
Num3# = 32767.123 ; 32767.123 is the largest positive Short Integer Value in BlitzBasic )
Num4# = -32768.123 ; -32768.123 the largest negative Short Integer Value in BlitzBasic )

; Open a file to write to


fileout = WriteFile("mydata.dat")

; Write the information to the file


WriteFloat( fileout, Num1 )
WriteFloat( fileout, Num2 )
WriteFloat( fileout, Num3 )
WriteFloat( fileout, Num4 )

; Close the file


CloseFile( fileout )

; Open the file to Read


filein = ReadFile("mydata.dat")

Read1# = ReadFloat( filein )


Read2# = ReadFloat( filein )
Read3# = ReadFloat( filein )
Read4# = ReadFloat( filein )

; Close the file once reading is finished


CloseFile( fileout )

Print "Floating Point Data Read From File - mydata.dat "


Print Read1
Print Read2
Print Read3
Print Read4

WaitKey()

ReadInt (filehandle|stream)
Definition:

Reads a single 32bit integer value from an open file (or stream) and returns it as an integer value.

Parameter Description:
filehandle|stream = a valid variable set with the OpenFile, ReadFile command, or OpenTCPStream (v1.52+)
The value returned is an integer in the range -2147483648 to 2147483647

Command Description:

Once you've opened a disk file (or stream) for reading, use this command to read a single integer value from
the file. Note, each value written uses 4 bytes of space and is written least significant byte first. Reading
beyond the end of file does not result in an error, but each value read will be zero.

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; Reading and writing a file using ReadInt and WriteInt functions

; Initialise some variables for the example


Int1% = 10 ; store 10
Int2% = 365 ; store 365
Int3% = 2147483647 ; store 2147483647 the largest positive Integer Value in BlitzBasic )
Int4% = - 2147483648 ; store -2147483648 the largest negative Integer Value in BlitzBasic )

; Open a file to write to


fileout = WriteFile("mydata.dat")

; Write the information to the file


WriteInt( fileout, Int1 )
WriteInt( fileout, Int2 )
WriteInt( fileout, Int3 )
WriteInt( fileout, Int4 )

; Close the file


CloseFile( fileout )

; Open the file to Read


filein = ReadFile("mydata.dat")

Read1 = ReadInt( filein )


Read2 = ReadInt( filein )
Read3 = ReadInt( filein )
Read4 = ReadInt( filein )

; Close the file once reading is finished


CloseFile( fileout )

Print "Integer Data Read From File - mydata.dat "


Print Read1
Print Read2
Print Read3
Print Read4

WaitKey()

ReadLine$ (filehandle|stream)
Definition:

Reads a single line of text from an open file (or stream).

Parameter Description:
filehandle|stream = a valid variable set with the OpenFile, ReadFile command, or OpenTCPStream (v1.52+).
The value returned is a text string.

Command Description:

Once you've opened a disk file (or stream) for reading, use this command to read a whole line of text from a
text file or stream. Each line of text is returned as a string variable. This function can be used to read plain
text files.

Characters are read from the input file until an "end-of-line" mark is found. An "end-of-line" can be a single
carriage return (0Dh) or a single linefeed (0Ah) or carriage return followed by a linefeed (0Dh, 0Ah). Reading
beyond the end of file does not result in an error, but each value read will be a zero length string.

ReadLine$ returns all chars except chr$(13)/chr$(10).

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; Reading and writing a file using ReadLine$ and WriteLine functions

; Initialise some variables for the example


String1$ = "Line 1 is short"
String2$ = "Line 2 is a longer line but they can be much longer"
String3$ = "Line 3 is made up "
String4$ = "of two parts joined together."

; Open a file to write to


fileout = WriteFile("mydata.txt")

; Write the information to the file


WriteLine( fileout, String1 )
WriteLine( fileout, String2 )
WriteLine( fileout, String3 + String4)
WriteLine( fileout, "Just to show you don't have to use variables" )

; Close the file


CloseFile( fileout )

; Open the file to Read


filein = ReadFile("mydata.txt")

Read1$ = ReadLine( filein )


Read2$ = ReadLine$( filein )
Read3$ = ReadLine$( filein )
Read4$ = ReadLine$( filein )

; Close the file once reading is finished


CloseFile( fileout )

Print "Lines of text read from file - mydata.txt "


Print
Print Read1
Print Read2
Print Read3
Print Read4

WaitKey()

ReadPixel (x,y,[buffer])
Definition:

Quickly reads the value of a single pixel on the screen.

Parameter Description:

x = x location of the pixel to read


y = y location of the pixel to read
buffer = any valid screen/image buffer (optional)

Command Description:

This command will allow you fast access to a specific pixel in the buffer selected. While this command reads
the pixel quickly (and it can be written back quickly with WritePixel, it is still not fast enough for real-time
screen effects.

You are not required to lock the buffer with LockBuffer and subsequently unlock the buffer with UnlockBuffer.
However, the operations will be a bit faster if you do.

V1.52 and above: It has been necessary to make ReadPixel and ReadPixelFast "alpha-aware".

This means that the high 8 bits of the color returned ReadPixel/ReadPixelFast now contain valid alpha
information.

However, in the case of Blitz2D apps, there is no alpha information in images!

Mark decided that in the abscence of any alpha information, a pixel is assumed to have 'full' alpha.

Therefore, values returned by ReadPixel/ReadPixelFast will now (usually) have their high 8 bits sets. The
exception will be when reading pixels from Blitz3D textures created with an alpha channel.

To get the old behaviour of v1.50 (and below) of ReadPixel/ReadPixelFast, use the following:

rgb=ReadPixel( x,y ) And $FFFFFF

This will 'mask out' the 8 high bits of alpha and return just the red, green and blue components of the pixel.

Example:

; High Speed Graphics Commands

Graphics 640,480,16

; Draw a bunch of crap on the screen


For t= 1 To 1000
Color Rnd(255),Rnd(255),Rnd(255)
Rect Rnd(640),Rnd(480),Rnd(150),Rnd(150),Rnd(1)
Next

Delay 3000

; Copy the top half of the screen over the bottom half
; using fast pixels and locked buffers
LockBuffer FrontBuffer()
For x = 1 To 640
For y = 1 To 240
WritePixelFast x,y+241,ReadPixelFast(x,y)
Next
Next
UnlockBuffer FrontBuffer()

Delay 3000
; Draw the left half of the screen over the right half
; using the slower direct pixel access
For x = 1 To 320
For y = 1 To 480
WritePixel x+320,y,ReadPixel(x,y)
Next
Next

ReadPixelFast (x,y,[buffer])
Definition:

High speed pixel reading from an image buffer.

Parameter Description:

x = x location of the pixel to read


y = y location of the pixel to read
buffer = any valid screen/image buffer (optional)

Command Description:

This command will allow you fast access to a specific pixel in the buffer selected. While this command reads
the pixel quickly (and it can be written back quickly with WritePixelFast, it is still not fast enough for real-time
screen effects.

You are required to lock the buffer with LockBuffer and subsequently unlock the buffer with UnlockBuffer when
the operations are complete before any other graphics commands can be used.

WARNING: You are playing with power. There is nothing keeping you from writing directly to memory off the
screen and TRASHING it. You can crash Blitz using this command.

V1.52 and above: It has been necessary to make ReadPixel and ReadPixelFast "alpha-aware".

This means that the high 8 bits of the color returned ReadPixel/ReadPixelFast now contain valid alpha
information.

However, in the case of Blitz2D apps, there is no alpha information in images!

Mark decided that in the abscence of any alpha information, a pixel is assumed to have 'full' alpha.

Therefore, values returned by ReadPixel/ReadPixelFast will now (usually) have their high 8 bits sets. The
exception will be when reading pixels from Blitz3D textures created with an alpha channel.

To get the old behaviour of v1.50 (and below) of ReadPixel/ReadPixelFast, use the following:

rgb=ReadPixel( x,y ) And $FFFFFF

This will 'mask out' the 8 high bits of alpha and return just the red, green and blue components of the pixel.

Example:

; High Speed Graphics Commands

Graphics 640,480,16

; Draw a bunch of crap on the screen


For t= 1 To 1000
Color Rnd(255),Rnd(255),Rnd(255)
Rect Rnd(640),Rnd(480),Rnd(150),Rnd(150),Rnd(1)
Next

Delay 3000

; Copy the top half of the screen over the bottom half
; using fast pixels and locked buffers
LockBuffer FrontBuffer()
For x = 1 To 640
For y = 1 To 240
WritePixelFast x,y+241,ReadPixelFast(x,y)
Next
Next
UnlockBuffer FrontBuffer()

Delay 3000

; Draw the left half of the screen over the right half
; using the slower direct pixel access
For x = 1 To 320
For y = 1 To 480
WritePixel x+320,y,ReadPixel(x,y)
Next
Next

ReadShort (filehandle|stream)
Definition:

Reads a single short integer value (16 bits) from an open file (or stream) and returns it as an integer value.

Parameter Description:

filehandle|stream = a valid variable set with the OpenFile, ReadFile command, or OpenTCPStream (v1.52+)
The value returned is an integer in the range 0-65535.

Command Description:

Once you've opened a disk file (or stream) for reading, use this command to read a single short integer
(16bit) value from the file. Note, each value written uses 2 bytes of disk space and is written least significant
byte first. Reading beyond the end of file does not result in an error, but each value read will be zero.

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; Reading and writing a file using ReadShort and WriteShort functions

; Initialise some variables for the example


Int1% = 10 ; store 10
Int2% = 365 ; store 365
Int3% = 32767 ; 32767 is the largest positive Short Integer Value in BlitzBasic )
Int4% = -32768 ; -32768 the largest negative Short Integer Value in BlitzBasic )

; Open a file to write to


fileout = WriteFile("mydata.dat")

; Write the information to the file


WriteShort( fileout, Int1 )
WriteShort( fileout, Int2 )
WriteShort( fileout, Int3 )
WriteShort( fileout, Int4 )

; Close the file


CloseFile( fileout )

; Open the file to Read


filein = ReadFile("mydata.dat")

Read1 = ReadShort( filein )


Read2 = ReadShort( filein )
Read3 = ReadShort( filein )
Read4 = ReadShort( filein )

; Close the file once reading is finished


CloseFile( fileout )

Print "Short Integer Data Read From File - mydata.dat "


Print Read1
Print Read2
Print Read3
Print Read4

WaitKey()

ReadString$ (filehandle|stream)
Definition:

Reads a single string variable from an open file (or stream).

Parameter Description:

filehandle|stream = a valid variable set with the OpenFile, ReadFile command, or OpenTCPStream (v1.52+)
The value returned is a text string.

Command Description:

Once you've opened a disk file (or stream) for reading, use this command to read a string variable from the
file.

Each string is stored in the file as a 4 byte (32bit) integer followed by the characters that form the string. The
integer contains the number of characters in the string, i.e. its length. Note, that Carriage Return, Line Feed
and Null characters are NOT use to indicate the end of the string. A file of strings cannot be read like a text
file, since it contains string variables and not text. A null string, i.e. a string of zero length ("") is stored as 4
bytes, an integer count with a value = zero, followed by no Characters. Note strings are not limited to 255
characters as in some languages. Reading beyond the end of file does not result in an error, but each value
read will be a zero length string.

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; Reading and writing a file using ReadString$ and WriteString functions

; Initialise some variables for the example


String1$ = "A short string"
String2$ = "A longer string since these are variables lengths"
String3$ = "This is string3 "
String4$ = "joined to string4"
; Open a file to write to
fileout = WriteFile("mydata.dat")

; Write the information to the file


WriteString( fileout, String1 )
WriteString( fileout, String2 )
WriteString( fileout, String3 + String4)
WriteString( fileout, "Just to show you don't have to use variables" )

; Close the file


CloseFile( fileout )
; Open the file to Read
filein = ReadFile("mydata.dat")

Read1$ = ReadString$( filein )


Read2$ = ReadString$( filein )
Read3$ = ReadString$( filein )
Read4$ = ReadString$( filein )

; Close the file once reading is finished


CloseFile( fileout )

Print "String Variables Read From File - mydata.dat "


Print
Print Read1
Print Read2
Print Read3
Print Read4

WaitKey()

Rect x, y, width, height, solid


Definition:

Draw a rectangle on the screen

Parameter Description:

x = x coordinate to begin drawing the rectangle


y = y coordinate to begin drawing the rectangle
width = how wide to make the rectangle in pixels
height = how tall to make the rectangle in pixels
solid = 0 or False for unfilled and 1 or True for filled

Command Description:

This command will draw a rectangle in the current drawing Color starting at the location specified. The last
parameter determines if the rectangle is filled or just a 'box'.

Example:

; Flip/Backbuffer()/Rect Example

; Set Graphics Mode


Graphics 640,480

; Go double buffering
SetBuffer BackBuffer()
; Setup initial locations for the box
box_x = -20 ; negative so it will start OFF screen
box_y = 100

While Not KeyHit(1)


Cls ; Always clear screen first
Rect box_x,box_y,20,20,1 ; Draw the box in the current x,y location
Flip ; Flip it into view
box_x = box_x + 1 ; Move the box over one pixel
If box_x = 640 Then box_x=-20 ; If it leaves the Right edge, reset its x location
Wend

RectsOverlap (rect1 X,rect1 Y,rect1 Width,rect1 Height,rect2 X,rect2 Y,rect2


Width,rect2 Height)
Definition:

Tests to see if two rectangular areas are overlapping.

Parameter Description:

rect1 X = rectangle 1 x location


rect1 Y = rectangle 1 y location
rect1 Width = rectangle 1 width
rect1 Height = rectangle 1 height
rect2 X = rectangle 2 x location
rect2 Y = rectangle 2 y location
rect2 Width = rectangle 2 width
rect2 Height = rectangle 2 height

Command Description:

This command will take two rectangular locations on the screen and see if they overlap. You will need to know
the x, y, width, and height of both regions to test.

I'm still trying to find a real good logical use for this command with all the other collision commands available
to you like ImagesOverlap, ImagesCollide, ImageRectOverlap, and ImageRectCollide. My guess is that this is
the absolute fastest possible collision method available and useful to those wishing to write their own collision
routines.

Unlike the other collision commands, there is no image to detect a collision with - simply one rectangular
location overlapping another. You could probably use this command instead of the ImageRectOverlap
command, as they are really basically doing the same thing (and I betcha this is faster).

This would be useful for very easy-going 'Monkey Island' games to check the position of your pointer against a
screen location (or 'hot spot') when pixel perfect accuracy (heck, image graphics in general) are not really
needed.

Example:

; RectsOverlap Example
; Flashing graphics warning! Gets hypnotic ...

; Turn on graphics mode


Graphics 640,480,16

; Double buffering, and randomize the randomizer


SetBuffer BackBuffer()
SeedRnd MilliSecs()

; Repeat the loop until ESC pressed


While Not KeyHit(1)

; Generate a random rectangle


rect1X=Rnd(50,610)
rect1Y=Rnd(50,430)
rect1W=20
rect1H=20

; And another
rect2X=Rnd(50,610)
rect2Y=Rnd(50,430)
rect2W=20
rect2H=20
; Clear the screen standard double buffering
Cls
; Draw our rectangle2 in random colors
Color Rnd(255),Rnd(255),Rnd(255)
Rect rect1X,rect1Y,rect1W,rect1H,0
Color Rnd(255),Rnd(255),Rnd(255)
Rect rect2X,rect2Y,rect2W,rect2H,0

; Did they collide? If so, print a message and exit the loop!
If RectsOverlap (rect1X,rect1Y,rect1W,rect1H,rect2X,rect2Y,rect2W,rect2H) Then
Text 0,0, "Our boxes finally collided! Press a mouse button..."
; We do a flip here to ensure the text message gets seen too!
Flip
Exit ; exit the While/Wend loop
End If
; Flip the rects into view, wait 1/10th of a sec, repeat
Flip
Delay 100
Wend
; Wait for a mouse click
WaitMouse()
; End our graphics mode
EndGraphics

RecvNetMsg()
Definition:

Boolean value denotes whether a network message has arrived.

Parameter Description:

None.

Command Description:

First off, this ONLY works when you have joined a network game via StartNetGame or JoinNetGame and you
have created a player via CreateNetPlayer (you must create a player, even if it is just to lurk).

This returns a TRUE value if a message was received, FALSE if none has been received. This will typically go
inside a function that is constantly being checked for message and decode and handle them. You will use
NetMsgType, NetMsgFrom, NetMsgTo, and NetMsgData$ to get the important information from the message
and act on it.
The example requires that you run it on a remote machine while the local computer runs the example in the
SendNetMsg command.

Example:

; RecvNetMsg() example
; --------------------
; Run this program on the REMOTE computer to 'watch'
; the activity of the SendNetMsg example. Run that
; example on local machine.
;
; This program will tell you when a player involved in
; the game hits a wall ...

; We'll use this instead of JoinHostGame - make it easier


StartNetGame()

; Create a player - a player must be created to


; receive mesages!
playerID=CreateNetPlayer("Shane")

; Loop and get status


While Not KeyHit(1)

; Check to see if we've received a message


If RecvNetMsg() Then

; if we did, let's figure out what type it is


; we know it will be a user message, though
msgType=NetMsgType()

; 1-99 means a user message


If msgType>0 And msgType

; Let's see who the message was from


msgFrom=NetMsgFrom()

; Let's get the message!


msgData$=NetMsgData$()

; Print the message


Print msgData$
End If
End If
Wend

RecvUDPMsg( udp_stream )

Parameters:

udp_stream - UDP stream handle

Description:

Receives a UDP message into the specified UDP stream. Standard stream read commands can then be used to
examine the message.

The return value is the integer IP address of the message source, or 0 if no message was available. You can
use UDPMsgPort() to find out the port number of the message source.

Example:

None.

Repeat
Definition:

First command of the REPEAT ... UNTIL loop.

Parameter Description:

None

Command Description:

The REPEAT ... UNTIL loop allows you to perform a series of commands until a specific condition has been met.
This lets the conditional appear after the commands have been executed before checking, not before like the
WHILE ... WEND loop does. In general, use REPEAT ... UNTIL if you know you will have the commands
enclosed between them execute at least once.

Example:

; Repeat until user hits ESC key

Repeat
print "Press ESC to quit this!"
Until KeyHit(1)

Replace$ (string$, find$, replace$)


Definition:

Replace occurances of one string with another within a string.

Parameter Description:

string$ = any valid string variable


find$ = any valid string
replace$ = any valid string

Command Description:

This command will allow you to replace characters within a string with another. Use this to strip or convert
letters out of your strings (like removing spaces or turning them into underscores). Pretty straight forward.

Example:

name$="Bill Wallace"
Print "Your name before replacing: " + name$
Print "Your name with L changed to B: " + Replace$(name$,"l","b")
ResizeBank bankhandle,new_size
Definition:

Resizes a bank.

Parameter Description:

bankhandle = handle assigned to bank when created


new_size = new size of bank in bytes

Command Description:

Resizes a previously created memory bank. Existing bank data is unmodified, but may be moved in memory.
Also see CreateBank, CopyBank, and BankSize.

Example:

; BankSize, ResizeBank, CopyBank Example

; create a bank
bnkTest=CreateBank(5000)

; Fill it with rand Integers


For t = 0 To 4999
PokeByte bnkTest,t,Rand(9)
Next

; Resize the bank


ResizeBank bnkTest,10000

; Copy the first half of the bank to the second half


CopyBank bnkTest,0,bnkTest,5000,5000

; Print final banksize


Print BankSize(bnkTest)

ResizeImage image,width#,height#
Definition:

Resizes an image to a new size using pixel values.

Parameter Description:

image = file handle for previously loaded image


width# = new width in pixels
height# = new height in pixels

Command Description:

Similar to ScaleImage, but uses pixel values instead of percentages. Use this command to resize an image
previously loaded with LoadImage or LoadAnimImage.

This is NOT intended for REAL TIME scaling of images! Precalculate your images before running your program,
or you will likely see massively slow renderings of graphics.
Example:

; ResizeImage example

; Set Graphics Mode


Graphics 800,600,16

; Randomize the random seed


SeedRnd MilliSecs()

; Load an image to tile (your location might vary)


gfxBall=LoadImage("C:\Program Files\Blitz Basic\samples\ball.bmp")

; Size it randomly from 300 to -300 both x and y


ResizeImage gfxBall,Rnd(-300,300),Rnd(-300,300)

; Wait for ESC to hit


While Not KeyHit(1)
DrawImage gfxball,Rnd(800),Rnd(600)
VWait
Wend

Restore label
Definition:

Moves the Data pointer to the selected label.

Parameter Description:

label = any valid and exisiting label

Command Description:

When using Data statements to store large blocks of constants for use with the Read command, it is necessary
to denote the start of the Data with a .Label. The Restore command moves the 'pointer' to the first Data
statement's value following the designated label. You MUST use the Restore label command prior to using the
Read command. This method allows you to store groups of Data statements non-sequentially. Its different (if
you are used to other BASIC languages) but you will find it most flexible. See the example and other
commands related to Data command.

Example:

; Sample of read/restore/data/label commands

; Let's put the data pointer to the second data set


Restore seconddata

; Let's print them all to the screen


For t = 1 To 10
Read num ; Get the next data value in the data stack
Print num
Next

; Now for the first set of data


Restore firstdata

; Let's print them all to the screen


For t = 1 To 10
Read num ; Get the next data value in the data stack
Print num
Next

; this is the first set of data


.firstdata
Data 1,2,3,4,5,6,7,8,9,10

; this is the second set of data


.seconddata
Data 11,12,13,14,15,16,17,18,19,20

ResumeChannel

Parameters:

channel -- a music or sound channel previously allocated via LoadSound, PlayMusic, etc.

Description:

ResumeChannel is used to continue the playing of a sound sample or music track on the given channel after
you have temporarily halted playback on that channel (via PauseChannel).

Example (using ResumeChannel):

Graphics 640, 480, 0, 2

musicchannel = PlayMusic ("oohyeahbaby.mp3") ; Replace with a music file on your hard drive!

Repeat

Print "Press a key to pause the music..."


WaitKey

PauseChannel musicchannel

Print "Press a key to continue the music..."


WaitKey

ResumeChannel musicchannel

Until KeyHit (1)

End

Return value
Definition:

Immediately exits a function with an optional return value or resumes execution from a subroutine called with
Gosub.

Parameter Description:

value = TRUE or FALSE

Command Description:
When called inside a FUNCTION structure, the RETURN command immediately returns from the function back
to the calling code. An optional value may be returned. See FUNCTION for more information. Remember, after
a Return, the remaining code of the Function is not executed. See example. It also returns execution from a
subroutine called with the Gosub command.

Example:

; RETURN example

; Set result to the return value of the function 'testme'


result=testme(Rnd(0,10));

; The program effectively ends here.

; The actual function


Function testme(test);

; If the random number passed = 0


If test=0 Then
Print "Value was 0"
Return False ; The Function ends immediately
Else
Print "The value was greater than 0"
Return True ; The Function ends immediately
End If
Print "This line never gets printed!"
End Function

Right$ (string$, length)


Definition:

Return a specified number of characters from the rightmost side of a string.

Parameter Description:

string$ = any valid string variable


length = the number of characters on the right to return

Command Description:

You can retrieve a certain number of characters from the rightmost side of a string. See the example.

Example:

name$="Bill Wallace"
Print "The last 4 letters of your name are: " + Right$(name$,4)

Rnd (start#,end#)
Definition:

Returns a random number.

Parameter Description:
start# = Lowest value to generate
end# = Highest value to generate

Command Description:

This returns either a floating point or integer number of a random value falling between the start and end
number. It returns an integer if assiged to an integer variable, and it returns a floating point value if assiged
to a floating number variable. The start and end values are inclusive. Be sure to use the SeedRnd command to
avoid generating the same random numbers every time the program is run.

Example:

y=Rnd(0,10) ; Set y to a random integer between 0 and 10


y#=Rnd(0,5) ; Set y floating value between 0.000000 and 10.000000

RotateImage image,value#
Definition:

Rotates the image counter-clockwise a specific angle.

Parameter Description:

image = variable containing the image handle


value# = floating number from 0 to 350 degrees

Command Description:

I'm going to start this description off with:

This command is not fast enough to render rotations in real time!

Now, the purpose of this command is to rotate an image a specified number of degrees. Since it is slow, you
will need to pre-calculate rotated images with this command. This means, before the program actually displays
the images you rotate, you will want to rotate them ahead of time.

This command automatically dithers/anti-aliases the rotated graphic image, so it might mess with your
transparency. To avoid this issue, use the TFormFilter command. This will render the rotated images with bi-
linear filtering.

I'm going to end this command with:

This command is not fast enough to render rotations in real time!

Example:

; RotateImage/TFormFilter Example

; Turn on graphics mode


Graphics 640,480,16

; Change the 0 to a 1 to see the difference


; between filter on and off.
TFormFilter 0

; Create new empty graphic to store our circle in


gfxBox=CreateImage(50,50)
; Draw the box image
; Set drawing operations to point to our new empty graphic
SetBuffer ImageBuffer(gfxBox)
Color 255,0,0
; Note the extra space between the box and the edge of the graphic
Rect 10,10,30,30,1
SetBuffer FrontBuffer()

While Not KeyHit(1)


; Make a copy of the image so we are always using a fresh one each time
; we rotate it.
gfxTemp=CopyImage(gfxBox)
; Rotate it a random value and draw it at a random location
RotateImage gfxTemp,Rnd(360)
DrawImage gfxTemp,Rnd(640),Rnd(480)
Wend

RSet$ (string$, length)


Definition:

Pads a string with spaces to a specified value, right aligning the string.

Parameter Description:

string$ = any valid string or string variable


length = how long you want the new string to be (including padding)

Command Description:

If you have a string that is say, 10 letters long, but you want to make it a full 25 letters, padding the rest of
the string with spaces, this command will do so, leaving the original string value right justified. You could use
this to pad your high score names to make sure all are the same width in characters.

Example:

name$="Shane R. Monroe"
Print "New Padded Name: '" + RSet$(name$,40) + "'"

RuntimeError message$
Definition:

Pops up an error dialog box with a specified message.

Parameter Description:

message$ = Any valid string

Command Description:

When doing your own error trapping, use this command to pop up a fatal error and close the program. You
can specify the error message that is displayed.

Example:
;There was a problem - raise an error and quit

RuntimeError "Installation corrupted. Please reinstall."

Sar repetitions
Definition:

Performs binary shift right.

Parameter Description:

repetitions = number of shifts to make right

Command Description:

This performs a left binary shift on the value the specified number of times. This basically is a faster method of
dividing the value exponentially. By shifting right once, you are dividing the value by 2. By shifting right twice,
you divide by 4, etc.

Sar command varies from Shr whereas it fills blank bits shifted with copies of the sign bit, 0 for positive
numbers and 1 for negative.
The usefulness of this command is basically faster math execution. Also see Shl.

Example:

; shl, shr, sar examples

value = 100

; multiple x 2
Print "Shift 1 bit left; Value = " + value Shl 1
; multiple x 4
Print "Shift 2 bits left; Value = " + value Shl 2
; multiple x 16
Print "Shift 4 bits left; Value = " + value Shl 4
; divide by 2
Print "Shift 1 bit right; Value = " + value Shr 1
; divide by 4
Print "Shift 2 bits right; Value = " + value Shr 2
; divide by 16
Print "Shift 4 bits right; Value = " + value Shr 4

Print "Shift by SAR 4 times = " + value Sar 4

WaitKey()

SaveBuffer (buffer,filename$)
Definition:

Saves the selected video buffer to a bitmap file.

Parameter Description:

buffer = The buffer to save; FrontBuffer() or BackBuffer()


filename$ = valid Windows path/filename

Command Description:

Typically, this is used to take a screen snapshot. This will save the screen buffer you specify to a .bmp file you
specify. Remember, use the proper name for the buffer you wish to save; FrontBuffer() for the current visible
screen, and BackBuffer() for the back or invisible drawing buffer. The filename must be valid Windows
filename syntax.

Example:

; Save the screen when player pushes F10

If KeyHit(10) Then
SaveBuffer(FrontBuffer(),"screenshot.bmp")
End If

SaveImage (image,bmpfile$,[frame] )
Definition:

Saves an image to hard drive as a .bmp file.

Parameter Description:

image = variable handle to the image to save


bmpfile$ = string with full path and filename to save to
frame = optional; which frame of the image to save

Command Description:

Saves an image or one of its frames to hard drive. You will need an existing image to save off. This returns a 1
if the save was successful, 0 if not.

Example:

; SaveImage example

; Set Graphics Mode


Graphics 800,600,16

; Load an image to tile (your location might vary)


gfxBall=LoadImage("C:\Program Files\Blitz Basic\samples\ball.bmp")

; Save the image to the c: drive ...


ok=SaveImage (gfxBall,"c:\newball.bmp")

; Print results
If ok=1 Then
Print "Save successful!"
Else
Print "There was an error saving!"
End If

; Wait for ESC to hit


While Not KeyHit(1)
Wend
ScaleImage image,xscale#,yscale#
Definition:

Scales an image to a new size using percentages.

Parameter Description:

image = file handle variable to a previously loaded image


xscale# = the amount to scale the image horizontally
yscale# = the amount to scale the image vertically

Command Description:

Use this command to rescale an image to a new size using a floating point percentage (1.0 = 100%, 2.0 =
200%, etc). Using a negative value perform image flipping. You must've previously loaded the image with
LoadImage or LoadAnimImage.

This is NOT intended for REAL TIME scaling of images! Precalculate your images before running your program,
or you will likely see massively slow renderings of graphics.

Example:

; ScaleImage example

; Set Graphics Mode


Graphics 800,600,16

; Randomize the random seed


SeedRnd MilliSecs()

; Load an image to tile (your location might vary)


gfxBall=LoadImage("C:\Program Files\Blitz Basic\samples\ball.bmp")

; Scale it randomly from 50% to 150% both x and y


ScaleImage gfxBall,Rnd(-2.0,2.0),Rnd(-2.0,2.0)

; Wait for ESC to hit


While Not KeyHit(1)
DrawImage gfxball,Rnd(800),Rnd(600)
VWait
Wend

ScanCodes
Definition:

A complete listing of scancodes.

Parameter Description:

None.

Command Description:

This isn't a command at all, but rather a complete listing of key scancodes for use with the KeyHit and
KeyDown commands.
Example:

KEYBOARD KEY SCANCODE COMMENTS


ESCAPE 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
0 11
Minus (-) 12 On Main Keyboard
Equals (=) 13
Backspace 14 Backspace key
Tab 15
Q 16
W 17
E 18
R 19
T 20
Y 21
U 22
I 23
O 24
P 25
Left Bracket ([) 26
Right Bracket (]) 27
Return/Enter 28 Return/Enter on Main Keyboard
Left Control 29
A 30
S 31
D 32
F 33
G 34
H 35
J 36
K 37
L 38
Semi-Colon (;) 39
Apostrophe (') 40
Grave 41 Accent Grave
Left Shift 42
Backslash (\) 43
Z 44
X 45
C 46
V 47
B 48
N 49
M 50
Comma (,) 51
Period (.) 52 On Main keyboard
Slash (/) 53 On Main Keyboard
Right Shift 54
Multiply (*) 55 On Numeric Keypad
Left Alt/Menu 56
Space 57
Capital 58
F1 59
F2 60
F3 61
F4 62
F5 63
F6 64
F7 65
F8 66
F9 67
F10 68
NumLock 69
Scroll Lock 70
NumPad 7 71
NumPad 8 72
NumPad 9 73
Subtract (-) 74 On Numeric Keypad
NumPad 4 75
NumPad 5 76
NumPad 6 77
Add (+) 78 On Numeric Keypad
NumPad 1 79
NumPad 2 80
NumPad 3 81
NumPad 0 82
Decimal (.) 83 On Numeric Keypad
OEM_102 86 On UK/Germany Keyboards
F11 87
F12 88
F13 100 (NEC PC98)
F14 101 (NEC PC98)
F15 102 (NEC PC98)
Kana 112 Japanese Keyboard
ABNT_C1 115 /? on Portugese (Brazilian) keyboards
Convert 121 Japanese Keyboard
NoConvert 123 Japanese Keyboard
Yen 125 Japanese Keyboard
ABNT_C2 126 Numpad . on Portugese (Brazilian) keyboards
Equals 141 = on numeric keypad (NEC PC98)
PrevTrack 144 Previous Track (DIK_CIRCUMFLEX on Japanese keyboard)
AT 145 (NEC PC98)
Colon (:) 146 (NEC PC98)
Underline 147 (NEC PC98)
Kanji 148 Japanese Keyboard
Stop 149 (NEC PC98)
AX 150 Japan AX
Unlabeled 151 (J3100)
Next Track 153 Next Track
Enter 156 ENTER on Numeric Keypad
Right Control 157
Mute 160 Mute
Calculator 161 Calculator
Play/Pause 162 Play/Pause
Media Stop 164 Media Stop
Volume Down 174 Volume -
Volume Up 176 Volume +
Web Home 178 Web Home
Comma (,) 179 On Numeric Keypad (NEX PC98)
Divide (/) 181 On Numeric Keypad
SysReq 183
Right Alt/Menu 184 Right Alt
Pause 197 Pause
Home 199 Home on Arrow Pad
Up 200 Up Arrow on Arrow Keypad
Page Up/Prior 201 Page Up on Arrow Keypad
Left 203 Left Arrow on Arrow Keypad
Right 205 Right Arrow on Arrow Keypad
End 207 End Key on Arrow Keypad
Down 208 Down Key on Arrow Keypad
Next 209 Next Key on Arrow Keypad
Insert 210 Insert Key on Arrow Keypad
Delete 211 Delete Key on Arrow Keypad
Left Windows 219 Left Windows Key
Right Windows 220 Right Windows Key
Apps 221 Apps Menu Key
Power 222 System Power
Sleep 223 System Sleep
Wake 227 System Wake
Web Search 229
Web Favorites 230
Web Refresh 231
Web Stop 232
Web Forward 233
Web Back 234
My Computer 235
Mail 236
Media Select 237

ScanLine()
Definition:

Returns the scanline location of the drawing operation.

Parameter Description:

None.

Command Description:

If for some reason you need to know the current scanline location of the drawing system, here is how you get
it.

Example:

; ScanLine() Example

While Not KeyHit(1)


Print ScanLine()
Wend

SeedRnd seed
Definition:

Sets the random number generator with a seed value.

Parameter Description:

seed = valid integer number

Command Description:

Computer random number generators are not truly random. They generate numbers based on a seed value
(an integer number). If you 'seed' the random number generator with the same seed, it will always generate
the same set of numbers. Use this command to ensure you get a good set of numbers. Usually you set the
seed value to a timer or system clock value to ensure that each time the program is run, a new value is
seeded. Look at the example for normal usage of this command.

Example:

SeedRnd Millisecs() ; Seed the randomizer with the current system time in milliseconds.

SeekFile (filehandle, offset)


Definition:

Moves the current pointer inside an open file to a new location.

Parameter Description:

filehandle = the variable returned by the Readfile, WriteFile or OpenFile when the file was opened. The value
returned is the offset from the start of the file. ( 0 = Start of the file )

Command Description:

This command allows the position in a file to be changed. This allows random access to data within files and
can be used with files opened by ReadFile, WriteFile and OpenFile. Note, the offset is the number of bytes from
the start of the file, where the first byte is at offset 0. It is important to take account of the size of the data
elements in your file.

For instance Integers are 4 bytes long so the first integer in the file is at offset 0 and the second at offset 4. If
you write Custom Data types out then you must work out haw many bytes each takes so that you can move
about the file correctly. Seeking beyond the end of a file does not generate an error but the data is not read or
written to the file, and may course unknown side effects.

By using FilePos and SeekFile the position within the file that is being read or written can be determined and
also changed. This allows a file to be read and updated without having to make a new copy of the file or
working through the whole file sequentially. This could be useful if you have created a database file and you
want to find and update just a few records within it. It is also possible to create an index file that contains
pointers to where each record starts in a data file.

To calculate an offset you need to know how long each data element is; Offset = Wanted_Element *
size_of_element - size_of_element

For example a file of integers which are 4 bytes long is calculated by:

The 7th integer is at offset 7 * 4 - 4 i.e. 24

Note, extreme care needs to be exercised when updating files that contain strings since these are not fixed in
length.

Example:

; Changing part of a file using OpenFile, SeekFile, FilePos

; Open/create a file to Write


fileout = WriteFile("mydata.dat")

; Write the information to the file


WriteInt( fileout, 100 )
WriteInt( fileout, 200 )
WriteInt( fileout, 300 )
WriteInt( fileout, 400 )
WriteInt( fileout, 500 )

; Close the file


CloseFile( fileout )

DisplayFile( "The file as originally written", mydata.dat" )

Print "Data read in random order"


; Open the file to read just the 4th and 2nd elements from

file = OpenFile("mydata.dat")

; read and print the 4th integer ie 4*4-4 = 12 byte from the start of the file
SeekFile( file, 12 ) ; Move to the found location
Number = ReadInt( file )
Print Number

; read and print the 2th integer ie 2*4-4 = 4 bytes from the start of the file
SeekFile( file, 4 ) ; Move to the found location
Number = ReadInt( file )
Print Number

CloseFile( file )

Waitkey()
End ; End of program

; **** Function Definitions follow ****


; Read the file and print it
Function DisplayFile( Tittle$, Filename$ )
Print tittle$
file = ReadFile( Filename$ )
While Not Eof( file )
Number = ReadInt( file )
Print Number
Wend
CloseFile( file )
Print
End Function

Select variable
Definition:

Executes commands based on the value of a provided variable.

Parameter Description:

variable - any valid variable

Command Description:

This command allows you to set up a selection structure that, based on the value of the variable you feed it,
will execute different commands in different CASEs. You can also specify a DEFAULT set of commands to
happen if NONE of the CASEs are met. The selection structure is ended with an END SELECT command.

This selection structure removes the need for large nested IF/THEN condition checking. See the example for
more.

Example:
; SELECT/CASE/DEFAULT/END SELECT Example

; Assign a random number 1-10


mission=Rnd(1,10)

; Start the selection process based on the value of 'mission' variable


Select mission

; Is mission = 1?
Case 1
Print "Your mission is to get the plutonium and get out alive!"

; Is mission = 2?
Case 2
Print "Your mission is to destroy all enemies!"

; Is mission = 3?
Case 3
Print "Your mission is to steal the enemy building plans!"

; What do do if none of the cases match the value of mission


Default
Print "Missions 4-10 are not available yet!"

; End the selection process


End Select

SendNetMsg type,data$,from,to,reliable
Definition:

Sends a message during a network game.

Parameter Description:

type = value 1-99


data$ = string containing message to send
from = player ID of the sender
to = player ID of the recipient (0=broadcast)
reliable = flag for sending message reliably

Command Description:

First off, this ONLY works when you have joined a network game via StartNetGame or JoinNetGame and you
have created a player via CreateNetPlayer (you must create a player, even if it is just to lurk).

This is probably the most complicated of the networking commands. This what you use to actually send a
message to one or all of the players on the network game. The other players will use RecvNetMsg() to
intercept your message.
The TYPE parameter is a number from 1 to 99. These values are denoted as 'user messages'.

The Data$ parameter is the actual string that contains the message you want to send. Helpful to know that in
order to keep traffic low, you will want to combine details of a message into a single message instead of
sending multiple messages with a single element. For example, you might want to send X, Y, and FRAME in a
single string like "200,100,4" and parse it out at the recipient's end.

FROM is the player's ID that is sending the message. This is the value returned from the CreateNetPlayer()
command.
TO is the player's ID you wish to send the message to. A default value of 0 will broadcast to ALL players.

The RELIABLE flag will put a priority on the message and it will ensure there is no packet loss in the delivery.
However, it is at least 3 times slower than a regular non-reliable message.

The example requires that you run it on the local machine while the remote computer runs the example in the
RecvNetMsg() command.

Example:

; SendNetMsg example
; ------------------
; Run this example on the local computer
; run the example for RecvNetMsg() on a remote computer

; Graphics mode with double buffering


Graphics 640,480,16
SetBuffer BackBuffer()

; Create a network game with NO requester


joinStatus=HostNetGame("ShaneGame")

; A type to hold all the player's information


Type multi
Field x
Field y
Field id
Field name$
Field xspeed
Field boxColor
End Type

; make sure the game started ok...


If joinStatus=2 Then
Print "Hosted game started... "
Else
Print "Hosted game could not be started!"
End
End If

; Create 5 local players using TYPEs


For t = 1 To 5
; New type instance
player.multi = New Multi
; Assign the ID field with the created player ID and name him
player\ID=CreateNetPlayer("Player" + t)

; if the player was created ok ... assign some random parameters


If player\ID <> 0 Then
player\name$="Player" + t
player\x = Rand(640)
player\y = Rand(480)
player\boxColor = Rand(255)
player\xspeed = Rand(1,5)
; Print some text results
Print "Player " + t + " has joined the game with ID=" + player\ID
Else
Print "The player couldn't join! Aborting!"
End If
Next

; We've got them all! Wait for a key


Print "All local players are joined! Press a key ..."
WaitKey()

; Loop this routine


While Not KeyHit(1)
Cls
; for each of the players, update their locations on the screen
For player = Each multi
Color player\boxColor,player\boxColor,player\boxColor
Rect player\x,player\y,10,10,1
Text player\x-10,player\y-15,player\name$
player\x = player\x + player\xspeed
If player\x > 640 Or player\x < 0 Then
player\xspeed=-player\xspeed
message$="Player ID #" + player\ID + " hit a wall!"
; Send a broadcast message if a player rebounds off the wall
; this message will show up on the remote machine
SendNetMsg Rand(1,99),message$,player\id,0
End If
Next
Flip
Wend
End

SendUDPMsg udp_stream,dest_ip[,dest_port]

Parameters:

udp_stream - UDP stream handle


dest_ip - destination IP address
dest_port (optional) - destination port number

Description:

Transmits all the data written to the UDP stream to the specified IP address and port. Data is written using the
standard stream commands. If no destination port is specified, the port number used to create the UDP
Stream is used.

Example:

None.

SetBuffer buffer
Definition:

Used to set the current drawing buffer.

Parameter Description:

Buffers can either be the FrontBuffer(), BackBuffer() or an ImageBuffer() Default buffer is the FrontBuffer

Command Description:

Use this command to set the current drawing buffer. If not used the default buffer, FrontBuffer() is used.
SetBuffer also resets the origin to 0,0 and the Viewpoint to the width and height of the buffer.
Example:

SetBuffer FrontBuffer() ;Sets FrontBuffer as the current drawing buffer

SetFont fonthandle
Definition:

Sets a previously loaded font active for writing operations.

Parameter Description:

fontname = string containing font name


height = font height desired
bold = set to TRUE to load font as BOLD
italic = set to TRUE to load font as ITALIC
underlined set to TRUE to load font as UNDERLINED

Command Description:

This activates a TrueType font previously loaded into memory (though the LoadFont command) for future use
with printing commands such as Text.

Note: Blitz doesn't work with SYMBOL fonts, like Webdings and WingDings.

Be sure to free the memory used by the font went you are done using the FreeFont command.

Example:

; LoadFont/SetFont/FreeFont example

; enable graphics mode


Graphics 800,600,16

; Set global on font variables


Global fntArial,fntArialB,fntArialI,fntArialU

;Load fonts to a file handle variables


fntArial=LoadFont("Arial",24,False,False,False)
fntArialB=LoadFont("Arial",18,True,False,False)
fntArialI=LoadFont("Arial",32,False,True,False)
fntArialU=LoadFont("Arial",14,False,False,True)

; set the font and print text


SetFont fntArial
Text 400,0,"This is just plain Arial 24 point",True,False

SetFont fntArialB
Text 400,30,"This is bold Arial 18 point",True,False

SetFont fntArialI
Text 400,60,"This is italic Arial 32 point",True,False

SetFont fntArialU
Text 400,90,"This is underlined Arial 14 point",True,False

; Standard 'wait for ESC' from user


While Not KeyHit(1)
Wend
; Clear all the fonts from memory!
FreeFont fntArial
FreeFont fntArialB
FreeFont fntArialI
FreeFont fntArialU

SetGfxDriver index
Definition:

Set the graphics driver for use with graphics commands.

Parameter Description:

index = index number obtained with CountGfxDrivers command

Command Description:

Some computers may have more than one video card and/or video driver installed (a good example is a
computer system with a primary video card and a Voodoo2 or other pass-through card).

Once you know how many drivers there are using the CountGfxDrivers(), you can iterate through them with
GfxDriverName$ and display them for the user to choose from. Once the user has chosen (or you decide), you
can set the graphics driver with this command.

Normally, this won't be necessary with 2D programming.

Example:

; GfxDriver Examples

; Count how many drivers there are


totalDrivers=CountGfxDrivers()
Print "Choose a driver to use:"

; Go through them all and print their names (most people will have only 1)
For t = 1 To totalDrivers
Print t+") " + GfxDriverName$(t)
Next

; Let the user choose one


driver=Input("Enter Selection:")

; Set the driver!


SetGfxDriver driver
Print "Your driver has been selected!"

Sgn (number)
Definition:

Returns the sign of the number argument.

Parameter Description:

number=float or integer
Command Description:

This function is used to determine whether a number or value is greater than 0, equal to 0 or less than 0.
Note: non-integer values return the sign to 7 signigicant figures. (e.g. -1.000000)

Example:

Print Sgn(10) ; prints 1


Print Sgn(5.5) ; prints 1.000000
Print Sgn(0) ; prints 0
Print Sgn(0.0) ; prints 0.000000
Print Sgn(-5.5) ; prints -1.000000
Print Sgn(-10) ; prints -1

Shl repetitions
Definition:

Performs binary shift left.

Parameter Description:

repetitions = number of shifts to make left

Command Description:

This performs a left binary shift on the value the specified number of times. This basically is a faster method of
multiplying the value exponentially. By shifting left once, you are multiplying the value by 2. By shifting left
twice, you multiple by 4, etc.

The usefulness of this command is basically faster math execution.

Example:

; shl, shr, sar examples

value = 100

; multiple x 2
Print "Shift 1 bit left; Value = " + value Shl 1
; multiple x 4
Print "Shift 2 bits left; Value = " + value Shl 2
; multiple x 16
Print "Shift 4 bits left; Value = " + value Shl 4
; divide by 2
Print "Shift 1 bit right; Value = " + value Shr 1
; divide by 4
Print "Shift 2 bits right; Value = " + value Shr 2
; divide by 16
Print "Shift 4 bits right; Value = " + value Shr 4

Print "Shift by SAR 4 times = " + value Sar 4

WaitKey()

ShowPointer
Parameters:

n/a

Description:

ShowPointer is for use in windowed display modes, and simply shows the Windows pointer after it's been
hidden (via HidePointer). It has no effect in full-screen modes.

Example:

Graphics 640, 480, 0, 2

HidePointer

Print "Move pointer over window and press a key..."


WaitKey

ShowPointer

Delay 1000

Shr repetitions
Definition:

Performs binary shift right.

Parameter Description:

repetitions = number of shifts to make right

Command Description:

This performs a left binary shift on the value the specified number of times. This basically is a faster method of
dividing the value exponentially. By shifting right once, you are dividing the value by 2. By shifting right twice,
you divide by 4, etc.

The usefulness of this command is basically faster math execution.

Example:

; shl, shr, sar examples

value = 100

; multiple x 2
Print "Shift 1 bit left; Value = " + value Shl 1
; multiple x 4
Print "Shift 2 bits left; Value = " + value Shl 2
; multiple x 16
Print "Shift 4 bits left; Value = " + value Shl 4
; divide by 2
Print "Shift 1 bit right; Value = " + value Shr 1
; divide by 4
Print "Shift 2 bits right; Value = " + value Shr 2
; divide by 16
Print "Shift 4 bits right; Value = " + value Shr 4

Print "Shift by SAR 4 times = " + value Sar 4


WaitKey()

Sin (Number)
Definition:

The Sin command, or Sinus, is a trigonometry function, that returns a number between -1 and 1. This value
represents the "Y" coordinate of the point a

Parameter Description:

number=float or integer representing a value in degree

Command Description:

This command is used for translating angle values to coordinates, but there are a few things you have to take
into account when doing it. First of all the Sin() command assumes the point you want is at radius 1 (pixel),
next it uses a circle where 0 degrees is due EAST and increases in a counterclockwise direction, then you've
got to take into account the the Y axis on a computer screen is up-side-down compared to a normal
mathematical coordinate system.

See also ASin, Cos, ACos, Tan, Atan, ATan2

Example:

Graphics 640,480; Change to graphics mode, nothing tricky yet.


Origin 320,240 ; Move the point of orign for all drawing commands to the middle of the screen.

For degrees=0 To 359; Step though all the degrees in a circle (360 in all)
Delay(5); Wait 5 milli secsonds.

; The next line calculates the Y coordinate of the point of the circle using the Sin
; command, and multiplies it by 100 (to get a larger radius, try and change it).
y=Sin(degrees)*100

y=-y ; Invert Y coordinate to represent it properly on screen.

; The next line calculates the X coordinate of the point of the circle using the Cos,
; command, and multiplies it by 100 (to get a larger radius, try and change it).
x=Cos(degrees)*100

Rect x,y,1,1 ; Draw the current point on the circle.

Next ; Give us another angle

MouseWait ; Wait for the mouse.


End ; Terminate the program.

SoundPan sound_variable,pan#
Definition:

Pans the sound effect right, center, or left.

Parameter Description:
sound_variable = any valid sound variable previously created with the LoadSound command.
pan# = floating point number from -1 (left) to 0 (center) to 1 (right)

Command Description:

Use this command to pan your sound effect between the left and right speakers (or restore the panning to the
center). Use this for cool panning stereo sounds during your game.

Example:

; Load sound sample


sndDeath=LoadSound("audio\death.wav")

; Pan sound effect half to the left


SoundPan sndDeath,-.5

; Play sound
PlaySound sndDeath

SoundPitch sound_variable, hertz


Definition:

Alter the pitch of a sound.

Parameter Description:

sound_variable = any valid sound variable previously created with the LoadSound command.

hertz = valid playback hertz speed (up to 44000 hertz).

Command Description:

Alters the pitch of a sound previously loaded with the LoadSound command. By changing the pitch, you can
often reuse sounds for different uses or to simulate a 'counting up/down' sound. To make the sound 'higher
pitched', increase the hertz. Conversely, decreasing the hertz will 'lower' the pitch. Note: this is in relation to
the original hertz of the sound.

Example:

; Load the sound (11,000 hertz)

snd1Up = LoadSound("audio\oneup.wav")

; Play the sound normally


PlaySound snd1Up

; Change the pitch UP and play it


SoundPitch snd1Up, 22000
PlaySound snd1Up

; Change the pitch down and play it


SoundPitch snd1Up, 8000
PlaySound snd1Up
SoundVolume sound_variable,volume#
Definition:

Alter the volume level of a sound effect.

Parameter Description:

sound_variable = any valid sound variable previously created with the LoadSound command.
volume# = floating point number from 0 (silence) to 1 (full volume)

Command Description:

Alter the playback volume of your sound effect with this command. This command uses a floating point
number from 0 to 1 to control the volume level.

Please see ChannelVolume for more options!

Example:

; Load sound sample


sndDeath=LoadSound("audio\death.wav")

; Change volume level to half


SoundVolume sndDeath,.5

; Play sound
PlaySound sndDeath

Sqr (float)
Definition:

Returns the square root of a given value.

Parameter Description:

float = any floating point number (integers are converted on the fly)

Command Description:

This command will return the square root of a specified value. The value returned is a floating point number.

Example:

; sqr# example

value=25

print "The square root of our value is: " + sqr#(value)


waitkey()

StartNetGame()
Definition:
Starts a network game.

Parameter Description:

None.

Command Description:

Displays a Windows dialog with option to join or start a new multiplayer network game, via modem, serial
connection or TCP/IP (Internet).

Note: This command must be started before any other network commands, otherwise they will fail.

A return value of 0 indicates failure, 1 means a game was joined and 2 means a game was created and is
being hosted on the local machine.

Example:

newGame = StartNetGame()
; Check the status of the new game.
If newGame = 0 Then
print "Could not start or join net game."
ElseIf newGame = 1
print "Successfully joined the network game."
ElseIf newGame = 2
print "A new network game was started."
EndIf

Step
Definition:

Set an increment for the FOR ... NEXT loop.

Parameter Description:

None

Command Description:

Use this to tell your FOR ... NEXT loop to increment a certain value each pass through the loop. STEP 1 is
assumed and need not be declared. STEP 2 would skip every other value, STEP 3 would skip every third value,
etc.

Example:

; Print 1 through 100, by tens

For t = 1 To 100 Step 10


Print t
Next

Stop
Definition:
Halts program execution during debugging.

Parameter Description:

None

Command Description:

If running the program in debug mode, it this command halts the program and returns you to the editor where
you can then step through your code, view variables, etc.

Example:

; Halt the program and go to the editor/debugger

Stop

StopChannel channel_handle
Definition:

Stops a playing sound channel.

Parameter Description:

channel_handle = variable assigned to the channel when played

Command Description:

This command replaced StopSound in the latter versions of Blitz Basic.

Once you have a sound playing, and a channel variable attached to it, you use this command to stop the
sound. This works for all sound channel types, including MP3, WAV, MIDI, and CD track playback.

Example:

; Channel examples

Print "Loading sound ..."


; Load the sample - you'll need to point this to a sound on your computer
; For best results, make it about 5-10 seconds...
sndWave=LoadSound("level1.wav")
; Prepare the sound for looping
LoopSound sndWave

chnWave=PlaySound(sndWave)

Print "Playing sound for 2 seconds ..."


Delay 2000

Print "Pausing sound for 2 seconds ..."


PauseChannel chnWave
Delay 2000

Print "Restarting sound ..."


ResumeChannel chnWave
Delay 2000
Print "Changing Pitch of sound ..."
;StopChannel chnWave
ChannelPitch chnWave, 22000
Delay 2000

Print "Playing new pitched sound ..."


Delay 2000

Print "Left speaker only"


ChannelPan chnWave,-1
Delay 2000

Print "Right speaker only"


ChannelPan chnWave,1
Delay 2000

Print "All done!"


StopChannel chnWave

StopNetGame
Definition:

Stops a network game in progress.

Parameter Description:

None.

Command Description:

Use this command to terminate the network game currently in progress (started with the StartNetGame()
command). If possible, the hosting session will transfer to another machine connected to the network game.

Example:

; stopNetGame() example

newGame = StartNetGame()
; Check the status of the new game.
If newGame = 0 Then
print "Could not start or join net game."
ElseIf newGame = 1
print "Successfully joined the network game."
ElseIf newGame = 2
print "A new network game was started."
EndIf
waitkey()
StopNetGame()
print "The Network game was stopped."

Str variable/value
Definition:

Convert numeric value to a string value.

Parameter Description:
variable/value = numeric value or variable

Command Description:

Use this command to transform an numeric value to a string value for use with string commands. Blitz prints
numeric values just fine, but should you want to do functions like LEFT$, you'll need to convert your numeric
variable to a string variable. Note: during the conversion, all 6 decimal places will be represented on floating
point number conversions.

Example:

; STR example

num#=2.5
mynum$=str num#

Print mynum$

String$ (string$, integer)


Definition:

Returns a designated string a designated number of times.

Parameter Description:

string$ = any valid string or string variable


integer = the number of times to repeat the string

Command Description:

This makes a string filled with the specified occurances of the designated string. In other words, you could use
this command to write the same string over and over again. See the example.

Example:

name$="Shane"
' Write the name string 10 times
Print String$(name$,10)

StringHeight (string)
Definition:

Returns the height (in pixels) of a given string.

Parameter Description:

string = any valid string or string variable

Command Description:

This will return the size, in pixels, the height of the indicated string. This is useful for determining screen
layout, scrolling of text, and more. This is calculated based on the size of the currently loaded font.

Example:

; StringWidth/Height Example

a$="Hello Shane!"
Print "A$=" + a$
Print "This string is "+ StringWidth(a$) + " pixels wide and"
Print "it is " + StringHeight(a$) + " tall, based on the current font!"

StringWidth (string)
Definition:

Returns the width (in pixels) of a given string.

Parameter Description:

string = any valid string or string variable

Command Description:

This will return the size, in pixels, the width of the indicated string. This is useful for determining screen
layout, scrolling of text, and more. This is calculated based on the size of the currently loaded font.

Example:

; StringWidth/Height Example

a$="Hello Shane!"
Print "A$=" + a$
Print "This string is "+ StringWidth(a$) + " pixels wide and"
Print "it is " + StringHeight(a$) + " tall, based on the current font!"

SystemProperty

Parameters:

property$ - system property information required (valid strings listed below)

Description:

SystemProperty () returns the location of a standard system folder, which can be different on every computer.
Note that it's not a good idea to play around in a user's Windows or System folder!

Valid parameters are:

"tempdir" - Temp folder


"systemdir" - System folder
"windowsdir" - Windows folder
"appdir" - Program Files folder
Example:

Print "System folder location: " + SystemProperty ("systemdir")


Print "Windows folder location: " + SystemProperty ("windowsdir")
Print "Temp folder: " + SystemProperty ("tempdir")
Print "Program was run from " + SystemProperty ("appdir")

Tan (number)
Definition:

Returns the tangent of an angle.

Parameter Description:

number=float or integer representing a value in degrees

Command Description:

Tan takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side
opposite the angle divided by the length of the side adjacent to the angle.

This is useful for artillery sort of games where your bullets will fire from a barrel at a certain angle. You can
use the Tan value in your power/angle formula to help determine the trajectory of the shot.

Example:

; tan example

angle1=25
angle2=45

print "The ratio of angle 1 is: " + tan(angle1)


print "The ratio of angle 2 is: " + tan(angle2)
waitkey()

TCPStreamIP( tcp_stream )

Parameters:

tcp_stream - TCP stream handle

Description:

Returns the integer IP address of the specified tcp_stream. The address returned is always that of the client
machine.

Example:

None.

TCPStreamPort( tcp_stream )

Parameters:
tcp_stream - TCP stream handle

Description:

Returns the port number of the specified TCP stream. The port number returned is always that of the client
machine.

Example:

None.

TCPTimeouts read_millis,accept_millis

Parameters:

read_millis - milliseconds value


accept_millis - milliseconds value

Description:

read_millis allows you to control how long reading data into a TCP stream can take before causing an error. By
default, this is set to 10,000 (10 seconds). This means that if data takes longer than 10 seconds to arrive, an
error occurs and the stream can not be used any more.

accept_millis allows you to control how the AcceptTCPStream() function will wait for a new connection. By
default, this value is 0, so AcceptTCPStream() will return immediately if there is no new connection available.

Example:

None.

<command><parameter>

Definition:

<definitition>

Parameter Description:

<param description>

Command Description:

<description>

Example:

<example>

Text x,y,string$,[center x],[center y]


Definition:
Print text to the graphic screen at the designated coordinates.

Parameter Description:

x = starting x coordinate to print text


y = starting 4 coordinate to print text
string$ = string/text to print
center x = optional; true = center horizontally
center y = optional; true = center vertically

Command Description:

Prints a string at the designated screen coordinates. You can center the text on the coordiates by setting
center x/center y to TRUE. This draws the text in the current drawing color.

Note: Printing a space with text will NOT render a block - a space is an empty value. So printing " " will not
make a box appear.

Example:

; Text example

; enable graphics mode


Graphics 800,600,16

; wait for ESC key before ending


While Not KeyHit(1)
;print the text, centered horizontally at x=400, y=0
Text 400,0,"Hello There!",True,False
Wend

TFormFilter enable
Definition:

Toggles bilinear filtering on convoluted images.

Parameter Description:

enable = 0 to turn off filtering; 1 to turn it on

Command Description:

This command will enable or disable bi-linear filtering on images that are convoluted (altered) by commands
like TFormImage and RotateImage.

This filtering allows the convoluted graphics to have smoother, more aliased edges. This also makes the
operations slower. The bi-linear filtering can also create non-transparent edges what will mess with your
transparency. Experiment for the best results.

Try changing the example to see the difference.

Example:

; RotateImage/TFormFilter Example

; Turn on graphics mode


Graphics 640,480,16
; Remove the line below to see the difference
; between filter on and off.
TFormFilter 0

; Create new empty graphic to store our circle in


gfxBox=CreateImage(50,50)

; Draw the box image


; Set drawing operations to point to our new empty graphic
SetBuffer ImageBuffer(gfxBox)
Color 255,0,0
; Note the extra space between the box and the edge of the graphic
Rect 10,10,30,30,1
SetBuffer FrontBuffer()

While Not KeyHit(1)


; Make a copy of the image so we are always using a fresh one each time
; we rotate it.
gfxTemp=CopyImage(gfxBox)
; Rotate it a random value and draw it at a random location
RotateImage gfxTemp,Rnd(360)
DrawImage gfxTemp,Rnd(640),Rnd(480)
Wend

TFormImage image,a#,b#,c#,d#

Parameters:

image - image handle


a# - 1,1 element of 2x2 matrix
b# - 2,1 element of 2x2 matrix
c# - 1,2 element of 2x2 matrix
d# - 2,2 element of 2x2 matrix

Description:

Transforms an image based on a 2x2 matrix.

The only real use for this command not available via ScaleImage or RotateImage is that you can use it to
shear an image.

Example:

None.

Then
Definition:

Part of the IF conditional structure

Parameter Description:

None.
Command Description:

Used in an IF statement to denote the end of the conditional to be checked. Famous for its participation in the
IF ... THEN structure. See example and IF statement for more information.

Example:

; IF THEN Example

; Input the user's name


name$=Input$("What is your name? ")

; Doesn't the person's name equal SHANE?


If name$ = "Shane" Then

Print "You are recognized, Shane! Welcome!"

Else

Print "Sorry, you don't belong here!"

; End of the condition checking


End If

TileBlock image [,x,y,frame]


Definition:

Tile an image without transparency.

Parameter Description:

image = file handle variable holding the loaded image


x = x coordinate offset(optional)
y = y coordinate offset (optional)
frame = frame of the image to use (optional)

Command Description:

Similar to TileImage but ignores transparency. Use this to tile an entire or portion of the screen with a single
repetative image.

Example:

; TileBlock example
Graphics 800,600,16

; Load an image to tile (your location might vary)


gfxBall=LoadImage("C:\Program Files\Blitz Basic\samples\ball.bmp")

; Tile the graphic without transparency


TileBlock gfxBall

; Wait for ESC to hit


While Not KeyHit(1)
Wend
TileImage handle,[x],[y],[frames]
Definition:

Tiles the screen with an image (or its frames) of your choice.

Parameter Description:

handle= variable holding the image's handle


x=starting x location of the tile; assumed 0
y=starting y location of the tile; assumed 0
frames=the frame of the image to tile; optional with imagestrip

Command Description:

If you want to make a starfield or other easy tiled background, this is YOUR command. All you have to do is
specify the image handle (an image loaded with the LoadImage or LoadAnimImage command). Optionally, you
can specify a starting x and y location, as well as an optional frame. You can milk some serious parallax
effects with a simple imagestrip with a couple of various starfields and the TileImage command.

Example:

; CreateImage/TileImage/ImageBuffer example

; Again, we'll use globals even tho we don't need them here
; One variable for the graphic we'll create, one for a timer
Global gfxStarfield, tmrScreen

; Declare graphic mode


Graphics 640,480,16

; Create a blank image that is 320 pixels wide and 32 high with 10 frames of 32x32
gfxStarfield=CreateImage(32,32,10)

; loop through each frame of the graphic we just made


For t = 0 To 9
; Set the drawing buffer to the graphic frame so we can write on it
SetBuffer ImageBuffer(gfxStarfield,t)
; put 50 stars in the frame at random locations
For y = 1 To 50
Plot Rnd(32),Rnd(32)
Next
Next

; Double buffer mode for smooth screen drawing


SetBuffer BackBuffer()

; Loop until ESC is pressed


While Not KeyHit(1)

; Only update the screen every 300 milliseconds. Change 300 for faster or
; slower screen updates
If MilliSecs() > tmrScreen+300 Then
Cls ; clear the screen

; Tile the screen with a random frame from our new graphic starting at
; x=0 and y=0 location.
TileImage gfxStarfield,0,0,Rnd(9)
Flip ; Flip the screen into view
tmrScreen=MilliSecs() ; reset the time
End If
Wend
To
Definition:

Dictates the range of values for a FOR ... NEXT loop.

Parameter Description:

See example

Command Description:

Use the TO command to tell your FOR ... NEXT loop which numbers the variable should be assign to during the
loop. If you count down instead of up, you must use a negative STEP value. The values must be integer
values. See example.

Example:

; Print numbers 10 to 1

For t = 10 to 1 Step -1
Print t
Next

TotalVidMem

Parameters:

n/a

Description:

TotalVidMem () simply returns the total available memory on a graphics card, in bytes. Note that to retrieve
the currently available number of bytes, you should use AvailVidMem ().

Example:

Print "Total graphics memory available: " + TotalVidMem () + " bytes."


; NOTE: To retrieve the *available* graphics memory, use AvailVidMem ()!

Trim$ (string$)
Definition:

Removes leading and trailing spaces from a string.

Parameter Description:

string$ = any valid string or string variable

Command Description:

Use this command to remove that nasty space at the beginning and ending of a string.
Example:

name$=" Shane R. Monroe "


Print "Your name before trimming is: '" + name$ "' ..."
Print "Your name trimmed is: '" + Trim$(name$) + "' ..."

True
Definition:

A boolean expression used in comparisons. Actually returns a value of 1.

Parameter Description:

None.

Command Description:

TRUE is a keyword to denote a positive result in a conditional statement. Often times, TRUE is implied and
doesn't need to be directly referenced. TRUE can also be used as a RETURN value from a FUNCTION. See the
example.

Example:

; TRUE example

; Assign test a random number of 0 or 1


test= Rnd(0,1)

; TRUE is implied; This statement REALLY means: if test=1 is TRUE then proceed
If test=1 Then
Print "Test was valued at 1"
End If

; Let's set test to be true


test=True

; Pointlessly test it
If test=True Then
Print "Test is true"
End If

Type variable
Definition:

Define an object with a collection of variables.

Parameter Description:

variable = any legal variable name

Command Description:
If you know C prgramming, a TYPE is basically a STRUCT in Blitz Basic. If you don't know C, read on!

TYPE is your best friend. It is used to create a 'collection' of objects that share the same parameters and need
to be interated through quickly and easily.

Think about SPACE INVADERS. There are many aliens on the screen at one time. Each of these aliens have a
few variables that they all need: x and y coordinates plus a variable to control which graphic to display (legs
out or legs in). Now, we could make hundreds of variables like invader1x, invader1y, invader2x, invader2y,
etc. to control all the aliens, but that wouldn't make much sense would it? You could use an array to track
them; invader(number,x,y,graphic), and the loop through them with a FOR ... NEXT loop but that is a lot of
work! The TYPE variable collection was created to handle just this sort of need.

TYPE defines an object collection. Each object in that collection inherits its own copy of the variables defined
by the TYPE's FIELD command. Each variable of each object in the collection can be read individually and can
be easily iterated through quickly. Use the FIELD command to assign the variables you want between the TYPE
and END TYPE commands.

If it helps, think of a TYPE collection as a database. Each object is a record of the database, and every variable
is a field of the record. Using commands like BEFORE, AFTER, and FOR ... EACH, you can move change the
pointer of the 'database' to point to a different record and retrieve/set the variable 'field' values.

Not a database guru? Need another example? Okay. Let's say you are setting up an auditorium for a speech or
event and you are putting up hundreds of chairs for the spectators. The chairs have to be in a certain place on
the floor, and some will need to be raised up a bit higher than others (visiting dignitaries, the mayor is
coming, etc.). So being the computer genius you are, you start figuring out how you can layout the chairs with
the least amount of effort. You realize that the floor is checkered, so its really a huge grid! This will make it
easy! You just need to number the floor on a piece of graph paper and put into the grid how high each chair
should be, based on where the boss told you the important people are to sit. So, for each chair, you will have
a row and column on the graph paper (x and y location) and a level to adjust the chair to (height). Good, we
are organized. Now, even though we have it all on paper, we still have to do the work of placing all the chairs.
After you are done, let's say your boss walks up to you and says "they aren't centered right .. move'em all
over 1 square". Ah crap! You have them all perfect, and even though it is a simple thing to move a chair one
square to the right (after all, their order and height won't change) - you still have to move each and every
chair! Should would be nice if you could just wave your hand and say "For each chair in the room, add 1
square to its x location" and have it just magically happen. Alas, in the real world, get busy - you've got a lot
of chairs to move!

In Blitz, you could have set up a TYPE called CHAIR, set the TYPE's FIELDS as X, Y, and HEIGHT. You would
then create as many chairs as you need with the NEW command (each time you call NEW, it makes a new
chair, with its OWN X, Y, and HEIGHT variables) and assign them the X, Y, and HEIGHT values you decide
upon. In our example above, when the boss told you to move the chairs over 1 box, you probably groaned
inside. That's a lot of work! In Blitz, we could use four lines of code to adjust all our CHAIR objects to the new
position (using FOR ... EACH commands).

Still lost? Its okay - TYPEs are hard to get a grasp on. Look at the example and we'll try to show you how
types work in a practical environment. I recommend looking at other people's code too, to help you get a
handle on them. Once you do, you will know why C people are crazy for STRUCTs and why almost all Blitz
programs use them.

Example:

; Define the CHAIR Type

Type CHAIR
Field X
Field Y
Field HEIGHT
End Type

; Create 100 new chairs using FOR ... NEXT using the collection name of ROOM

For tempx = 1 to 10
For tempy = 1 to 10
room.chair = New Chair
room\x = tempx
room\y = tempy
room\height = Rnd(0,10) ; set a random height 0 to 10
Next
Next

; Move them all over 1 (like the description example)

For room.chair = Each chair


room\x = room\x + 1
Next

UDPMsgIP( udp_stream )

Parameters:

udp_stream - UDP stream handle

Description:

Returns the integer IP address of the sender of the last UDP message received. This value is also returned by
RecvUDPMsg().

Example:

None.

UDPMsgPort( udp_stream )

Parameters:

udp_stream - UDP stream handle

Description:

Returns the port of the sender of the last UDP message received.

Example:

None.

UDPStreamIP( udp_stream )

Parameters:

udp_stream - UDP stream handle

Description:
Returns the integer IP address of the specified udp_stream. Currently, this always returns 0.

Example:

None.

UDPStreamPort( udp_stream )

Parameters:

udp_stream - UDP stream handle

Description:

Returns the port number of the specified UDP stream. This can be useful if you've created the UDP stream
without specifying a port number.

Example:

None.

UDPTimeouts recv_millis

Parameters:

recv_millis - milliseconds value

Description:

recv_millis allows you to control how long the RecvUDPMsg() function will wait for a new message. By default,
this is set to 0, meaning RecvUDPMsg() will return immediately if there is no message to be received.

Example:

None.

UnlockBuffer buffer
Definition:

Unlocks the buffer previously locked for high speed pixel operations.

Parameter Description:

buffer = any valid screen/image buffer (optional)

Command Description:

After you use LockBuffer on a buffer, the only graphics commands you can use are the read/write pixel
commands ReadPixel, WritePixel, ReadPixelFast, and WritePixelFast. You must use this command before using
other graphics commands.

The buffer parameter isn't required. If omitted, the default buffer set with SetBuffer will be used.

See the other commands for more information.

Example:

; High Speed Graphics Commands

Graphics 640,480,16

; Draw a bunch of crap on the screen


For t= 1 To 1000
Color Rnd(255),Rnd(255),Rnd(255)
Rect Rnd(640),Rnd(480),Rnd(150),Rnd(150),Rnd(1)
Next

Delay 3000

; Copy the top half of the screen over the bottom half
; using fast pixels and locked buffers
For x = 1 To 640
For y = 1 To 240
LockBuffer FrontBuffer()
WritePixelFast x,y+241,ReadPixelFast(x,y)
UnlockBuffer FrontBuffer()
Next
Next

Delay 3000

; Draw the left half of the screen over the right half
; using the slower direct pixel access
For x = 1 To 320
For y = 1 To 480
WritePixel x+320,y,ReadPixel(x,y)
Next
Next

Until condition
Definition:

The closing command of the REPEAT ... UNTIL loop.

Parameter Description:

condition = any valid expression (see example)

Command Description:

This portion of the REPEAT ... UNTIL loop dictates what condition must be met before the loop stops execution.
All commands between the two commands will be executed endlessly until the UNTIL condition is met.

Example:

; Repeat until user hits ESC key


Repeat
print "Press ESC to quit this!"
Until KeyHit(1)

Upper$ (string$)
Definition:

Converts a string to all upper case.

Parameter Description:

string$ = any valid string or string variable

Command Description:

This command takes the given string and converts it entirely to upper case.

Example:

name$="Shane R. Monroe"
print "Your name all in upper case is: " + upper$(name$)

Viewport x, y, width, height


Definition:

Restricts the drawing commands to a specified area of the screen.

Parameter Description:

x = the topmost left corner to start the port x coordinate


y = the topmost left corner to start the port y coordinate
width = how wide the port is (in pixels)
height = how tall the port is (in pixels)

Command Description:

There are MANY MANY times you want to draw graphics (aliens, ships, etc) ONLY on a certain area of the
screen while leaving the other areas alone. This is often referred to as 'windowing' or 'portaling' or 'clipping' an
area. Usually, you will perform all your drawing operations first (background, controls, etc), then section off
the restricted area of the screen with VIEWPORT to do drawing in that area. There are a million uses for this;
overhead map radar screens, Ultima style display windows, onscreen scrollers, etc. This is a bit more complex
than most graphic commands, so be sure you have a good handle on it before trying to use it. The biggest tip
I can give you about this command is: REMEMBER TO CLEAR THE VIEWPORT WHEN YOU ARE DONE! Do this
by setting the viewport to include the whole screen (i.e. Viewport 0,0,640,480 if your game was in 640x480).
Look carefully at the example. Remember, the second set of numbers isn't the ENDING location of the port -
rather the SIZE of the port starting at the first coordinates.

Example:

; ViewPort Example

; Set Up Graphics Mode


Graphics 800,600

; Set up Double Buffering


SetBuffer BackBuffer()

; Set viewport starting at 100,100 and make it 200,200 pixels in size


Viewport 100,100,200,200

; Infinately draw random rectangles with random colors


While Not KeyHit(1)
Cls ; Clear screen in 'blitting' technique
For t = 1 To 100 ; Do 100 rectangles each time
Color Rnd(255),Rnd(255),Rnd(255) ; Random color
Rect Rnd(800),Rnd(600),Rnd(300),Rnd(300),Rnd(0,1) ; Random sized and located box, some filled
Next ; repeat that drawing loop
Flip ; Flip to the back buffer
Wend

VWait [frames]
Definition:

Waits for one or more vertical blanks to happen before continuing the program.

Parameter Description:

[frames] = optional number of frames to wait

Command Description:

There are times when you can draw too fast, and your drawing operations happen so fast that you get
undesireable effects. This command forces Blitz to wait until the drawing scan line reaches the bottom of the
screen before proceeding. Try the example with and without the VWAIT command.

Example:

; Vwait example
Graphics 800,600,16

; Wait for ESC to hit


While Not KeyHit(1)
; Set a random color
Color Rnd(255),Rnd(255),Rnd(255)
; Draw a random line
Line Rnd(800),Rnd(600),Rnd(800),Rnd(600)
; Wait For a vertical blank to happen before looping
VWait
Wend

WaitJoy ([port])
Definition:

Halts program execution until a joystick button is pressed and returns its button code.

Parameter Description:
port = joystick port to check

Command Description:

This command makes your program halt until a jpystick button is pressed on the joystick. Used alone, it
simply halts and waits for a button press. It can also be used to assign the pressed button's code value to a
variable. See example.

In MOST CASES, you are not going to want to use this command because chances are likely you are going to
want things on the screen still happening while awaiting the button press. In that situation, you'll use a WHILE
... WEND awaiting a JoyHit value - refreshing your screen each loop.

As with any joystick command, you MUST have a DirectX compatible joystick plugged in and properly
configured within Windows for it to work. See your joystick documentation for more information.

Example:

; WaitJoy() sample

Print "Press a joystick button to continue."

button=WaitJoy()

Print "The joystick button code of the button you pressed was: " + button
Print "Now press a button to quit."

WaitJoy()

End

WaitKey()
Definition:

Halts program execution until a key is pressed and returns its ASCII code.

Parameter Description:

None.

Command Description:

This command makes your program halt until a key is pressed on the keyboard. Used alone, it simply halts
and waits for a key press. It can also be used to assign the pressed key's ASCII value to a variable. See
example.

In MOST CASES, you are not going to want to use this command because chances are likely you are going to
want things on the screen still happening while awaiting the keypress. In that situation, you'll use a WHILE ...
WEND awaiting a KeyHit value - refreshing your screen each loop.

Example:

; WaitKey() sample

Print "Press any key to continue."

key=WaitKey()
Print "The ASCII code of the key you pressed was: " + key
Print "Now press a key to quit."

WaitKey()

End

WaitMouse()
Definition:

Halts program execution until a mouse button is pressed and returns its button code.

Parameter Description:

None.

Command Description:

This command makes your program halt until a mouse button is pressed on the mouse. Used alone, it simply
halts and waits for a button press. It can also be used to assign the pressed button's code value to a variable.
See example.

In MOST CASES, you are not going to want to use this command because chances are likely you are going to
want things on the screen still happening while awaiting the button press. In that situation, you'll use a WHILE
... WEND awaiting a MouseHit value - refreshing your screen each loop.

Example:

; WaitMouse() sample

Print "Press a mouse button to continue."

button=WaitMouse()

Print "The mouse button code of the button you pressed was: " + button
Print "Now press a button to quit."

WaitMouse()

End

WaitTimer (timer_variable)
Definition:

Pauses execution until the requested timer meets its value.

Parameter Description:

timer = any valid timer variable created with the CreateTimer command.

Command Description:

Use this in conjunction with the CreateTimer command. This command will halt execution until the timer
reaches its value. This is useful to control the execution speed of your program. Check out the CreateTime
command for more.

Example:

; Create the timer to track speed


frameTimer=CreateTimer(60)

; Your main screen draw loop


While Not KeyHit(1)
WaitTimer(frameTimer) ; Pause until the timer reaches 60
Cls
; Draw your screen stuff
Flip
Wend

Wend
Definition:

The closing command of a WHILE/WEND loop.

Parameter Description:

None.

Command Description:

This is the command that tells program execution to branch to the beginning of the WHILE/WEND loop at the
WHILE command. See the WHILE command for complete details.

Example:

; While/Wend Example

; The loop condition is at the TOP of the loop


While Not KeyHit(1) ; As long as the user hasn't hit ESC yet ...
Print "Press Esc to end this mess!" ; Print this
Wend ; Go back to the start of the WHILE loop

While condition
Definition:

Begins a WHILE/WEND conditional loop.

Parameter Description:

condition = any valid conditional statement

Command Description:

The WHILE/WEND loop is used when you wish to execute a series of commands multiple times based on
whether a condition is true or not. This is similar to the REPEAT/UNTIL loop, except the condition checking is
at the beginning of the loop, instead of at the end. Usually you'll use WHILE/WEND when you aren't sure
whether or not the looped commands will even need to be executed once, since you can actually stop the loop
before any commands are executed if the condition check fails. If you need to execute the commands in the
loop at least once before checking a condition, use REPEAT/UNTIL. See example.

Example:

; While/Wend Example

; The loop condition is at the TOP of the loop


While Not KeyHit(1) ; As long as the user hasn't hit ESC yet ...
Print "Press Esc to end this mess!" ; Print this
Wend ; Go back to the start of the WHILE loop

Write string$
Definition:

Writes a string to the current screen or graphic buffer.

Parameter Description:

string$ = any valid string

Command Description:

This command will write a string value to the screen (if not in a graphic mode) or to the current drawing buffer
being used by the program. This command doesn't put a carriage return/linefeed at the end of the line (see
the Print command for that feature).

Example:

; Get the user's name and print a welcome

name$=Input$("What is your name?")


Write "Hello there, " + name$ + "!"

WriteByte (filehandle|stream, mybyte)


Definition:

Writes a single byte of data to an open file (or stream).

Parameter Description:

filehandle|stream = a valid variable set with the OpenFile, ReadFile command, or OpenTCPStream (v1.52+)
mybyte = can be an Integer or a floating point number, but only values between 0 and 255 will be stored
faithfully.

Command Description:

Once you've opened a disk file (or stream) for reading, use this command to write a single byte at a time to
the file/stream. Note, a byte is an integer that can take the values 0..255 and occupies 8 bits of storage. Since
characters are stored as byte values this function can be used to create a text file one character at a time.

Advanced notes:
The number that is stored by WriteByte is actually the least significant byte of an integer so negative numbers
and numbers above 255 will still have a value between 0..255. Unless you understand how 32 bit integers are
stored in 2's compliment notation this will seem strange but it is NOT a bug.

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; Reading and Writing a file using ReadByte and WriteByte functions

; Initialise some variables for the example


Byte1% = 10 ; store 10
Byte2% = 100 ; store 100
Byte3% = 255 ; store 255 ( the maximum value that can be stored in a Byte )
Byte4% = 256 ; try to store 256 this will end up as 0 ( i.e. 256 - 256 = 0 )
Byte5% = 257 ; try to store 257 this will end up as 1 ( i.e. 257 - 256 = 1 )
Byte6% = -1 ; try to store -1 this will end up as 255 ( i.e. 256 -1 = 255 )
Byte7% = -2 ; try to store 256 this will end up as 254 ( i.e. 256 - 2 = 254 )
Byte8% = Asc("A") ; Store the ASCII value for the Character "A" ( i.e. 65 )

; Open a file to write to


fileout = WriteFile("mydata.dat ")

; Write the information to the file


WriteByte( fileout, Byte1 )
WriteByte( fileout, Byte2 )
WriteByte( fileout, Byte3 )
WriteByte( fileout, Byte4 )
WriteByte( fileout, Byte5 )
WriteByte( fileout, Byte6 )
WriteByte( fileout, Byte7 )
WriteByte( fileout, Byte8 )

; Close the file


CloseFile( fileout )

; Open the file to Read


filein = ReadFile("mydata.dat")

Read1 = ReadByte( filein )


Read2 = ReadByte( filein )
Read3 = ReadByte( filein )
Read4 = ReadByte( filein )
Read5 = ReadByte( filein )
Read6 = ReadByte( filein )
Read7 = ReadByte( filein )
Read8 = ReadByte( filein )

; Close the file once reading is finished


CloseFile( fileout )

Print "Written - Read"


Write Byte1 + " - " : Print Read1
Write Byte2 + " - " : Print Read2
Write Byte3 + " - " : Print Read3
Write Byte4 + " - " : Print Read4
Write Byte5 + " - " : Print Read5
Write Byte6 + " - " : Print Read6
Write Byte7 + " - " : Print Read7
Write Byte8 + " - " : Print Chr$( Read8 )

WaitKey()
WriteBytes bank,filehandle|stream,offset,count
Definition:

Write data from a memory bank to a file (or stream).

Parameter Description:

bank = variable containing handle to valid bank


filehandle|stream = a valid variable set with the WriteFile or OpenTCPStream (v1.52+)
offset = offset in bytes to write the value
count = how many bytes to write from the offset

Command Description:

You can write the contents of a memory bank to a file on disk (or stream) using this command.

Note: The file handle must be opened with WriteFile or OpenTCPStream and subsequently closed with
CloseFile or CloseTCPStream after the writing operations are complete.
Return how many bytes successfully written to a stream.

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; Read/WriteBytes Commands Example

; Create a 50 byte memory bank


bnkTest=CreateBank(500)

; Let's fill the bank with crap


For t = 1 To 50
PokeByte bnkTest,t,Rnd(255)
PokeInt bnkTest,t+1,Rnd(10000)
PokeShort bnkTest,t+2,Rnd(10000)
PokeFloat bnkTest,t+3,Rnd(-.999,.999)
Next

; Open a file to write to


fileBank=WriteFile("test.bnk")
; Write the bank to the file
WriteBytes bnkTest,fileBank,0,50
; Close it
CloseFile fileBank

; Free the bank


FreeBank bnkTest

; Make a new one


bnkTest=CreateBank(500)

; Open the file to read from


fileBank=OpenFile("test.bnk")
; Write the bank to the file
ReadBytes bnkTest,fileBank,0,50
; Close it
CloseFile fileBank

; Write back the results!


For t = 1 To 50
Print PeekByte (bnkTest,t)
Print PeekInt (bnkTest,t+1)
Print PeekShort (bnkTest,t+2)
Print PeekFloat (bnkTest,t+3)
Next

WriteFile (filename$)
Definition:

Opens a file on disk for writing operations.

Parameter Description:

filename$ = any valid path and filename. The returned value is the filehandle which is an integer value.

Command Description:

This command opens the designated filename and prepares it to be written to. Use this to write your own
configuration file, save game data, etc. also useful for saving custom types to files. The filehandle that is
returned is an integer value that the operating system uses to identify which file is to be written to and must
be passed to the functions such as WriteInt(). If the file could not be opened then the filehandle is Zero.

Example:

; Reading and writing custom types to files using ReadFile, WriteFile and CloseFile

; Initialise some variables for the example


Type HighScore
Field Name$
Field Score%
Field Level%
End Type

Best.HighScore = New HighScore


Best\Name = "Mark"
Best\Score = 11657
Best\Level = 34

; Open a file to write to


fileout = WriteFile("mydata.dat")

; Write the information to the file


WriteString( fileout, Best\Name )
WriteInt( fileout, Best\Score )
WriteByte( fileout, Best\Level )

; Close the file


CloseFile( fileout )

; Open the file to Read


filein = ReadFile("mydata.dat")

; Lets read the Greatest score from the file


Greatest.HighScore = New HighScore
Greatest\Name$ = ReadString$( filein )
Greatest\Score = ReadInt( filein )
Greatest\Level = ReadByte( filein )

; Close the file once reading is finished


CloseFile( fileout )

Print "High score record read from - mydata.dat "


Print
Write "Name = "
Print Greatest\Name
Write "Score = "
Print Greatest\Score
Write "Level = "
Print Greatest\Level

WaitKey()

WriteFloat (filehandle|stream, myFloat)


Definition:

Writes a single floating point value to an open file (or stream).

Parameter Description:

filehandle|stream = a valid variable set with the OpenFile, WriteFile command, or OpenTCPStream (v1.52+)
myFloat = a floating point variable

Command Description:

Once you've opened a disk file (or stream) for writing, use this command to write a single floating point
number to the file. Note, each value written uses 4 bytes.

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; Reading and writing a file using ReadFloat and WriteFloat functions

; Initialise some variables for the example


Num1# = 10.5 ; store 10.5
Num2# = 365.25 ; store 365.25
Num3# = 32767.123 ; 32767.123 is the largest positive Short Integer Value in BlitzBasic )
Num4# = -32768.123 ; -32768.123 the largest negative Short Integer Value in BlitzBasic )

; Open a file to write to


fileout = WriteFile("mydata.dat")

; Write the information to the file


WriteFloat( fileout, Num1 )
WriteFloat( fileout, Num2 )
WriteFloat( fileout, Num3 )
WriteFloat( fileout, Num4 )

; Close the file


CloseFile( fileout )

; Open the file to Read


filein = ReadFile("mydata.dat")

Read1# = ReadFloat( filein )


Read2# = ReadFloat( filein )
Read3# = ReadFloat( filein )
Read4# = ReadFloat( filein )
; Close the file once reading is finished
CloseFile( fileout )

Print "Floating Point Data Read From File - mydata.dat "


Print Read1
Print Read2
Print Read3
Print Read4

WaitKey()

WriteInt (filehandle|stream, myinteger)


Definition:

Write a single 32bit integer value to an open file (or stream).

Parameter Description:

filehandle|stream = a valid variable set with the OpenFile, WriteFile command, or OpenTCPStream (v1.52+)
myinteger = an integer variable (a floating point number can be used but this will be converted to an integer
before saving so only the integer part will be saved)

Command Description:

Once you've opened a disk file (or stream) for writing, use this command to write a single integer value to the
file. Note, each value written uses 4 bytes and is written least significant byte first. The range of the value
saved is -2147483648 to 2147483647

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; Reading and writing a file using ReadInt and WriteInt functions

; Initialise some variables for the example


Int1% = 10 ; store 10
Int2% = 365 ; store 365
Int3% = 2147483647; store 2147483647 the largest positive Integer Value in BlitzBasic )
Int4% = - 2147483648 ; store -2147483648 the largest negative Integer Value in BlitzBasic )

; Open a file to write to


fileout = WriteFile("mydata.dat")

; Write the information to the file


WriteInt( fileout, Int1 )
WriteInt( fileout, Int2 )
WriteInt( fileout, Int3 )
WriteInt( fileout, Int4 )

; Close the file


CloseFile( fileout )

; Open the file to Read


filein = ReadFile("mydata.dat")

Read1 = ReadInt( filein )


Read2 = ReadInt( filein )
Read3 = ReadInt( filein )
Read4 = ReadInt( filein )

; Close the file once reading is finished


CloseFile( fileout )

Print "Integer Data Read From File - mydata.dat "


Print Read1
Print Read2
Print Read3
Print Read4

WaitKey()

WriteLine$ (filehandle|stream, string$)


Definition:

Writes a single line of text to an open file (or stream).

Parameter Description:

filehandle|stream = a valid variable set with the OpenFile, WriteFile command, or OpenTCPStream (v1.52+).
The value returned is a text string.
string$ = valid string value.

Command Description:

Once you've opened a disk file (or stream) for writing, use this command to right a whole line of text to the
file. Each line of text is automatically terminated with an "end-of-line" mark, consisting of a Carriage Return
character followed by a LineFeed character. (i.e. 0Dh, 0Ah ) This function can be used to make plain text files.

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; Reading and writing a file using ReadLine$ and WriteLine functions

; Initialise some variables for the example


String1$ = "Line 1 is short"
String2$ = "Line 2 is a longer line but they can be much longer"
String3$ = "Line 3 is made up "
String4$ = "of two parts joined together."

; Open a file to write to


fileout = WriteFile("mydata.txt")

; Write the information to the file


WriteLine( fileout, String1 )
WriteLine( fileout, String2 )
WriteLine( fileout, String3 + String4)
WriteLine( fileout, "Just to show you don't have to use variables" )

; Close the file


CloseFile( fileout )

; Open the file to Read


filein = ReadFile("mydata.txt")

Read1$ = ReadLine( filein )


Read2$ = ReadLine$( filein )
Read3$ = ReadLine$( filein )
Read4$ = ReadLine$( filein )

; Close the file once reading is finished


CloseFile( fileout )

Print "Lines of text read from file - mydata.txt "


Print
Print Read1
Print Read2
Print Read3
Print Read4

WaitKey()

WritePixel x,y,rgb,[buffer]
Definition:

Quickly writes a pixel to an image buffer.

Parameter Description:

x = x location of the pixel to read


y = y location of the pixel to read
rgb = rgb pixel value to write
buffer = any valid screen/image buffer (optional)

Command Description:

This command will allow you fast access to a specific pixel in the buffer selected. While the ReadPixel
command reads the pixel quickly (and you write it back with this command), it is still not fast enough for real-
time screen effects.

You are not required to lock the buffer with LockBuffer and subsequently unlock the buffer with UnlockBuffer.
However, the operations will be a bit faster if you do.

Example:

; High Speed Graphics Commands

Graphics 640,480,16

; Draw a bunch of crap on the screen


For t= 1 To 1000
Color Rnd(255),Rnd(255),Rnd(255)
Rect Rnd(640),Rnd(480),Rnd(150),Rnd(150),Rnd(1)
Next

Delay 3000

; Copy the top half of the screen over the bottom half
; using fast pixels and locked buffers
LockBuffer FrontBuffer()
For x = 1 To 640
For y = 1 To 240
WritePixelFast x,y+241,ReadPixelFast(x,y)
Next
Next
UnlockBuffer FrontBuffer()
Delay 3000

; Draw the left half of the screen over the right half
; using the slower direct pixel access
For x = 1 To 320
For y = 1 To 480
WritePixel x+320,y,ReadPixel(x,y)
Next
Next

WritePixelFast x,y,rgb,[buffer]
Definition:

High speed pixel writing to an image buffer.

Parameter Description:

x = x location of the pixel to read


y = y location of the pixel to read
rgb = rgb pixel value to write
buffer = any valid screen/image buffer (optional)

Command Description:

This command will allow you fast access to a specific pixel in the buffer selected. While the ReadPixelFast
command reads the pixel quickly (and it is written back quickly with this command, it is still not fast enough
for real-time screen effects.

You are required to lock the buffer with LockBuffer and subsequently unlock the buffer with UnlockBuffer when
the operations are complete before any other graphics commands can be used.

WARNING: You are playing with power. There is nothing keeping you from writing directly to memory off the
screen and TRASHING it. You can crash Blitz using this command.

Example:

; High Speed Graphics Commands

Graphics 640,480,16

; Draw a bunch of crap on the screen


For t= 1 To 1000
Color Rnd(255),Rnd(255),Rnd(255)
Rect Rnd(640),Rnd(480),Rnd(150),Rnd(150),Rnd(1)
Next

Delay 3000

; Copy the top half of the screen over the bottom half
; using fast pixels and locked buffers
LockBuffer FrontBuffer()
For x = 1 To 640
For y = 1 To 240
WritePixelFast x,y+241,ReadPixelFast(x,y)
Next
Next
UnlockBuffer FrontBuffer()
Delay 3000

; Draw the left half of the screen over the right half
; using the slower direct pixel access
For x = 1 To 320
For y = 1 To 480
WritePixel x+320,y,ReadPixel(x,y)
Next
Next

WriteShort (filehandle|stream, myinteger)


Definition:

Write a single short integer value (16 bits) to an open file (or stream).

Parameter Description:

filehandle|stream = a valid variable set with the OpenFile, WriteFile command, or OpenTCPStream (v1.52+)
myinteger = an integer variable (a floating point number can be used but this will be converted to an integer
before saving so only the integer part will be saved)

Command Description:

Once you've opened a disk file (or stream) for writing, use this command to write a single short integer (16
bit) value to the file. Note, each value written uses 2 bytes and is written least significant byte first. The range
of the value saved is 0-65535

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; Reading and writing a file using ReadShort and WriteShort functions

; Initialise some variables for the example


Int1% = 10 ; store 10
Int2% = 365 ; store 365
Int3% = 32767 ; 32767 is the largest positive Short Integer Value in BlitzBasic )
Int4% = -32768 ; -32768 the largest negative Short Integer Value in BlitzBasic )

; Open a file to write to


fileout = WriteFile("mydata.dat")

; Write the information to the file


WriteShort( fileout, Int1 )
WriteShort( fileout, Int2 )
WriteShort( fileout, Int3 )
WriteShort( fileout, Int4 )

; Close the file


CloseFile( fileout )

; Open the file to Read


filein = ReadFile("mydata.dat")

Read1 = ReadShort( filein )


Read2 = ReadShort( filein )
Read3 = ReadShort( filein )
Read4 = ReadShort( filein )
; Close the file once reading is finished
CloseFile( fileout )

Print "Short Integer Data Read From File - mydata.dat "


Print Read1
Print Read2
Print Read3
Print Read4

WaitKey()

WriteString$ (filehandle|stream, mystring)


Definition:

Writes a single string variable to an open file (or stream).

Parameter Description:

filehandle|stream = a valid variable set with the OpenFile, WriteFile command, or OpenTCPStream (v1.52+)
mystring = any string variable or text contained between quotes.

Command Description:

Once you've opened a disk file (or stream) for writing, use this command to write a string variable to the file.

Each string is stored in the file as a 4 byte (32bit) integer followed by the characters that form the string. The
integer contains the number of characters in the string, i.e. its length. Note, that Carriage Return, Line Feed
and Null characters are NOT use to indicate the end of the string. A file of strings cannot be read like a text
file, since it contains string variables and not text. A null string, i.e. a string of zero length ("") is stored as 4
bytes, an integer count with a value = zero, followed by no Characters. Note strings are not limited to 255
characters as in some languages. Reading beyond the end of file does not result in an error, but each value
read will be a zero length string.

Streams can only be used in Blitz Basic v1.52 or greater.

Example:

; Reading and writing a file using ReadString$ and WriteString functions

; Initialise some variables for the example


String1$ = "A short string"
String2$ = "A longer string since these are variables lengths"
String3$ = "This is string3 "
String4$ = "joined to string4"

; Open a file to write to


fileout = WriteFile("mydata.dat")

; Write the information to the file


WriteString( fileout, String1 )
WriteString( fileout, String2 )
WriteString( fileout, String3 + String4)
WriteString( fileout, "Just to show you don't have to use variables" )

; Close the file


CloseFile( fileout )

; Open the file to Read


filein = ReadFile("mydata.dat")
Read1$ = ReadString$( filein )
Read2$ = ReadString$( filein )
Read3$ = ReadString$( filein )
Read4$ = ReadString$( filein )

; Close the file once reading is finished


CloseFile( fileout )

Print "String Variables Read From File - mydata.dat "


Print
Print Read1
Print Read2
Print Read3
Print Read4

WaitKey()

Xor
Definition:

Performs a bit level Exclusive OR between two values.

Parameter Description:

None.

Command Description:

Often used for lightweight (meaning worthless ;) encryption, this will take two values and perform an
exclusive OR with each bit following the basic rules of XOR. The result can be XORed with one of the original
numbers to reveal the other number. See the example for more.

Example:

num=%11110000111100001111000011110000 ; Define a bit pattern which is easy to recognize

bitmask=Rnd(-2147483648,2147483647) ; Define a RANDOM Xor 32bit wide bitmask

; This line prints the binary and decimal numbers before the Xor
Print "Binary number is: "+Bin$(num)+" ("+num+")"

; This line prints the binary and decimal numbers of the Xor bitmask
Print "Xor bitmask is: "+Bin$(bitmask)+" ("+bitmask+")"

Print "------------------------------------------------------------------"

; This line Xor's the number with the bitmask


xres=num Xor bitmask

; This line prints the binary and decimal numbers after the Xor
Print "Xor result is: "+Bin$(xres)+" ("+xres+")"
Print "------------------------------------------------------------------"

; This line Xor's the Xor result with the bitmask again
xres=xres Xor bitmask
; This line prints the binary and decimal numbers after the second Xor. NOTE: This number is identical to the
original number
Print "Result Xor'ed again: "+Bin$(xres)+" ("+xres+")"
WaitMouse ; Wait for the mouse before ending.
INSTRUCCIONES 3D
Welcome to Blitz3D
"The Ultimate 3D Creation Language"

By Paul Gerfen
(c) Copyright 2001 Paul Gerfen
http://www.gamecoding.co.uk

Hi Guys, Paul here from Gamecoding.. recently I was asked to come up with a selection of
tutorials for complete beginners. Seeing as I'm mostly a 2D games programmer - I too
could be considered as a total beginner.

B3D is an incredibly powerful language, but believe me - by the time you have worked your
way through these mini tutorials, you will have the basic 3D knowledge to realize your
dreams and start to create your own projects.

Updates to these tutorials as well as extra notes, can be found on my website


www.gamecoding.co.uk or at the official blitz website, www.blitzbasic.com

Background
Let's begin by running through what we have, and more importantly what we shall need:

No doubt you've already had a run through the demos that accompany Blitz3D, and are
very keen to get stuck in and produce the next big "Quakey-Game". Unfortunately and this
stage all we are going to do is start with the very basic's and work our way through all the
main functions of B3D before we even think of moving on to advanced topics.

Hopefully you have a little experience of Blitz Basic programming (or for that matter any
Basic language would help), Let's take a look at 3D before we delve in…

As your probably use to with other basic languages you have a set of co-ordinates, X (Left &
Right) and Y (Up and Down). With 3D we have an extra coordinate to consider "Z", This
gives us depth into the screen. For example if we were standing at a river throwing a rock
as far as we can into it, what would be happening is:

As the stone leaves our hand it firstly moves away from us, and then gains height. What is
happening here is that the Z coordinate is increasing as the stone moves away from us,
while the Y coordinate gains height. Of course the stone will eventually fall to the ground
(decrease in Y).

Its important to try and visualize these 3 axes, as we shall see a 3d world is based entirely
on them.

Let's start by running through some of the major parts of Blitz3D before we start to get our
hands dirty on some actual code.

Entities
The basic building blocks of all Blitz3D programs.

Cameras

Well, we all need to see what's going on !

Planes

Nope, not the flying kind with wings and engines...

Meshes

Perhaps you'd like to make your own objects from scratch.

Terrains

Rolling Hills and Landscapes, in less time it takes to put the kettle on.

MultiTexturing

Why have a plain object when you can give it a coat of many colours.

Read through some of the info ?, I hope so.. Lets dig deep and start to produce our first
B3D program.
My aim to take you step by step through the very basic's. You can run the source code that
goes with each chapter by either CUT & PASTING from the tutorials themselves, or by
loading the accompanying files from the B3D CD. (Recommended!)

The Tutorials
You will need the sourcecode files and object files to run these snippets. These can be found
on the Blitz3D CD (or in the zip accompanying the Blitz Trial), I would advise opening up the
sourcecode projects and switching between Blitz and this tutorial. (As this will hopefully
explain the code and various instructions in more detail)

Setting Up

Everything you will need to know about writing a B3D program.

Movement & Rotation

Time to display a shape on the screen and start to give it some movement.

Camera Movement

There's more to B3D than just a static camera.

Object Animation
Time to make our object come alive.

Texturing

Let's make the object more lifelike, by giving it a coat of paint.

Lighting

B3D supports more than one type of lighting, here we take a brief look at the 3 main types
available to us.

Collision Detection

So what does happen when two worlds collide ?

Vertexes

What happens when you smash your object up into separate pieces, and then tear each part
up ?

Introduction to Entities
Everything going on in a Blitz3D program takes place within a 3D world, which is populated
by 'entities'.

Entities come in many flavors, and each kind of entity performs a certain, specialized task,
but all entities have a few things in common, the most important of which are:

All entities have a position, a rotation and a size, and can be moved, rotated and scaled at
will.

All entities have an optional 'parent' entity. If an entity has a parent, then it becomes
'attached' to the parent and will move, rotate and scale whenever the parent does.

Now, lets have a quick look at the kind of entities that can be used in the 3D world:

Cameras
Camera entities allows you to 'see' what's going on in the world. If you don't create at least
one camera, you wont be able to see anything! Cameras also control where on the screen
3D rendering occurs, and provide atmospheric fog effects.

Lights
Light entities provide illumination for the 3D world. Without any lights, you will still see
what's happening in the world thanks to 'ambient light'. Amibent light is light that is
'everywhere at once', and illuminates everything equally. However, since ambient light has
no position or direction, you wont get nice shading effects, and everything will look very
flat.
Meshes
Mesh entities provide a way to add actual, physical items to the world. Meshes are made up
of triangles, and each triangle can be colored or textured in a variety of ways. The most
common way of adding a mesh to the world is to load it from a file produced by a 3D
modelling program, but you can also create your own meshes.

Pivots
Pivot entities don't actually do a lot! Their main purpose in life is to provide a parent for
other entities. This can be useful for many reasons. For example, by attaching a bunch of
meshes to a pivot, you can move all the meshes at once simply by moving the pivot!

Sprites
Sprite entities are flat, 2D entities most commonly used for particle effects, like explosions,
smoke and fire. Sprites automatically face the camera, regardless of the angle you view
them from, so are often textured with a 'spherical' style texture.

Planes
Plane entities are infinitely large, flat surfaces that can be used for a variety of effects such
as ground and water. Since planes are entities, they can also be moved and rotated, which
means you can also use them for sky and cloud effects.

Terrains
Terrain entities are used to create very large landscapes. They are constructed of a grid of
triangles, and are rendered using a technique that draws an approximation of the terrain
using a limited number of triangles. This is necessary for very large terrains that may
contains millions of triangles - which would not only be far too slow for realtime rendering,
but would also take up way too much memory!

These entities form the backbone of any B3D program, it really is worth spending the time
getting to know the various instructions associated with them. As we shall see - by using
different parameters and the special additional commands for controlling or altering their
behavour, we can adapt an entity to our liking. Even if it means defining a special FX that
Blitz, with its present command set cannot do !.

Introduction to Camera Entities


Cameras allow you to see what's going on in the 3D world. Without at least one camera,
nothing that may be happening in the world will be rendered to the screen.

Cameras also control a number of other effects, including rendering range, zoom and fog.

Creating Cameras
To create a camera, simply use the CreateCamera command:
;create a new camera!
camera=CreateCamera()

Camera Viewport
A camera needs to know where on screen its view of the world is to be rendered. This area
of the screen is known as the camera viewport. By default, a new camera's viewport is set
to the entire screen.

To change the camera viewport use the CameraViewport command:

;Draw to top left corner of the screen


CameraViewport camera,0,0,GraphicsWidth()/2,GraphicsHeight()/2

Camera Range
Camera range determines how far into the distance a camera can 'see'. You specify 2 values
for camera range - a near value and a far value. All rendering is clipped to this range.

Its a good idea to try and keep the near value as high as possible, while keeping the far
value as low as possible. This helps to minimize z-buffer problems like 'jaggies'. By default,
the near value for a new camera is 1, and the far value is 1000.

To change the camera range, use the CameraRange command:

;Sets the near range to 5 and the far range to 5000


CameraRange camera,5,5000

Camera Zoom
Changing a cameras zoom allows you to 'zoom-in' or 'zoom-out' of the action in the world.
The default zoom value for a new camera is 1. Zoom values greater than 1 will cause a
'zoom-in' effect, while zoom values less than 1 will cause a 'zoom-out'. Zoom values should
never be set at 0 or less!

The CameraZoom command controls camera zoom:

;Zoom-in a bit!
CameraZoom camera,1.5

Fog Effects
Blitz3D allows you to setup fog effects independently for each camera. This can be useful for
limiting what a certain camera can see. For example, a racing game might use a camera for
its rearview mirror. However, you might want to limit what is visible in the rearview mirror
in order to keep the game running fast.

To setup a simple fog effect for a camera, you might use something like this:

;Sets the color of fog for this camera


CameraFogColor camera,0,128,255

;Sets the near/far range of fog for this camera


CameraFogRange camera,1,1000

;Sets the fog mode for this camera.


CameraFogMode camera,1

Often, the fog range and camera range will be the same. However, by increasing the near
value of fog, you can control how 'thick' fog appears to be. Smaller fog near values will
result in a thicker fog effect, since the fog will start nearer to the camera.

Unfortunately, fog is not well supported on all graphics cards. While all cards can perform
some kind of fog effect, the quality varies a lot. For this reason, its a good idea to make fog
optional in your Blitz3D games.

Introduction to Planes
Planes are a simple way to add large, flat surfaces to the world. Planes are useful for such
things as ground, sea, sky, clouds and so on. Just about every 3d game will use planes in
some way or another.

Creating Planes
How do you create a plane ? - Easy, just use the CreatePlane instruction:

;create a simple plane.


plane=CreatePlane()

Manipulating planes
By default, a new Plane is positioned at 0,0,0 and faces upwards. However, you may want
the plane to face a different direction, or to be moved up or down. To do this, you just need
to use the standard entity commands.

For example, you might want to use a plane for a layer-of-clouds type effect. In this case,
just rotate and position the plane as necessary:
;create clouds plane.
plane=CreatePlane()

;rotate plane so it faces downwards.


RotateEntity clouds,0,0,180

;and position it up in the sky!


PositionEntity clouds,0,100,0

So now we have a plane that is going to represent the sky, how can we make it look
realistic ?

The easy answer would be to Texture it !, as you shall see later on in these tutorials -
Blitz3D has ALL the answers.

If you take a careful look at most of todays top titles you will notice that most of the sky
scenes contain more than one layer. Usually this consists of 2 - sometimes even 3 planes.
The very top plane contains static objects such as the Sun, while the plane infront has a
cloud layer. This can be achieved by using the BRUSHFX instuction (to make the texture
slightly see-through) -in conjunction with an animated texture, that is slowly wrap-scrolling.
(And YES, B3D can do this effect with ease!)

Introduction to Meshes
Meshes are the entities you will most frequently be working with - unless you're writing
something weird (please do...)!

Meshes are made up of vertices and triangles, and can be either loaded from files (perhaps
the result of a 3d modeler program), or built 'by hand'. (assembled from within a B3d
program in realtime)

Loading Meshes
There are 2 commands provided for loading meshes from files - 'LoadMesh' and
'LoadAnimMesh', both of which load a '.X' or '.3DS' file and return an entity. So what's the
difference ?

Models stored in files are usually made up of several 'parts'. In the case of a character
model, these parts may represent arms, legs etc.

In addition, files also contain animation information with the 'LoadAnimMesh' command. The
entity returned will actually be the parent entity of the whole bunch of child 'parts'.

Therefore, 'LoadAnimMesh' really loads in several meshes !

If you don't need to animate a model, you can use 'LoadMesh' instead. This will 'collapse' all
the parts in a mesh and return a single, combined mesh. The collapsed mesh will look the
same as a mesh loaded with LoadAnimMesh, only you wont be able to animate it, and it
wont have any child meshes.
Why bother with LoadMesh at all ? SPEED! - It's faster for B3D to deal with a single mesh
than with multiple meshes, so if you're not planning to animate or doing anything tricky
with a mesh, use LoadMesh.

Creating Meshes
Before looking closely at creating meshes, you'll need to know about 'Brushes' in Blitz3D. A
brush is a collection of properties used when rendering triangles. These properties are:

• Colour - The colour a triangle is rendered in. (see BrushColor)


• Texture - From 0 to 8 texture maps that are used to render a triangle. (see
BrushTexture)
• Alpha - How transparent a triangle is. Alpha can range from 0 (completely
transparent) to 1 (completely opaque). (see BrushAlpha)
• Shininess - How 'shiny' a triangle is. This value can range from 0 (not shiny) to 1
(really shiny!). (see BrushShininess)
• Blend - The blend mode used to render a triangle. Blend mode describes how a
triangle is combined with what's already on the screen. (see BrushBlend)
• FX - Optional special effects for rendering. (see BrushFX)

To create a brush, you use the CreateBrush command:

;create a brush.
brush=CreateBrush()

Once we have a brush, we can set its properties:

;a red brush.
BrushColor brush,255,255,0

a shiny red brush.


BrushShininess brush,1

So what has all this got to do with meshes ?

Well, when I said meshes are made up of vertices and triangles, I sort of lied !. Meshes are
actually made of 'surfaces', and surfaces are made up of vertices and triangles !.

When a surface is created, you provide it with a brush that controls how all the triangles in
the surface are rendered.

So, a quick overview:

• A mesh is made up of any number of surfaces.


• Each surface in a mesh contains any number of vertices and triangles.
• All triangles in a surface are rendered using a common brush.

Lets dive on in and create a simple mesh:


brush=CreateBrush() ; create a brush
BrushColor brush,255,0,0 ; a red brush

mesh=CreateMesh() ; create a mesh


surf=CreateSurface( mesh,brush) ; create a (red) surface

AddVertex surf,-1,1,0 ; Now, we add 4 vertices...


AddVertex surf,1,1,0
AddVertex surf,1-,1,0
AddVertex surf,-1,-1,0

AddTriangle surf,0,1,2 ; and 2 triangles...


AddTriangle surf,0,2,3

UpdateNormals mesh

This code will create a simple red square mesh entity.

So what's with the weird 'UpdateNormals' command at the end ?. Well, in order for a mesh
to be correctly lit, its 'vertex normals' must be calculated. Without going into the gory
details, the UpdateNormals command will do this for you. If you are aware of how normals
work, you can actually set your own vertex normals using the VertexNormal command. If
not, just remember to stick an 'UpdateNormals' command at the end of any mesh
modifications you do, or else your meshes will not be correctly lit.

Note that you can create any number of surfaces you want. So, the same mesh can contain
many differently coloured/textured/whatever triangles !.

Why bother with surfaces at all ?, Why not just create a bunch of separate meshes, each
with its own rendering properties and skip all this surface nonsense ?. Well, again it comes
down to SPEED !. It's faster for Blitz3D to handle multiple surfaces - which can NOT be
moved or rotated as entities can - than it would be to handle multiple meshes.

Modifying Meshes
Once you've created a mesh, there are various commands available for modifying the mesh
in realtime. This can be used to create a range of impressive special effects such as waving
flags, rippling water and so on.

These commands are:

• VertexCoords - Changes the coordinates of a vertex.


• VertexColor - Changes the colour of a vertex.
• VertexTexCoords - Changes the texture mapping coordinates of a vertex.
• VertexNormal - Changes the normal of a vertex.

For more info on how to use these commands, take a look at the Vertex tutorial further on
down the line.

Introduction to Terrains
Terrain entities are used to draw very large landscapes made up of many, many triangles -
even up to a million or more!

To actually draw this many triangles would be a very slow process, so terrains use a
technique known as 'dynamic level of detail' to speed things up.

This basically means that instead of drawing all of the triangles in a terrain, a smaller
number of triangles is used to render an approximation of the terrain.

Terrains have a few limitations:

• The vertices of a terrain are laid out in a square grid pattern, with the same number
of vertices along each edge of the grid.
• Only the height of a vertex may be modified.
• The size of a terrain must be a 'power of 2' value, eg: 2,4,8,16,32...

Creating Terrains
You can create terrains either by loading in a heightmap image, or by creating an 'empty'
terrain and setting the height of each vertex yourself.

A heightmap image is simply a grayscale image, where black pixels represent 'low' vertices,
and white pixels represent 'high' vertices. A heightmap image must be of a valid terrain size
- ie: square, and a power of 2 wide/high.

When a terrain is created, its width and depth are the same as the size of the terrain, and
its height is 1. For example, if you create a terrain using:

terrain=CreateTerrain( 32 )

The terrain will extend from 0 to 32 along the x and z axis', and from 0 to 1 along the y
axis.

However, you are free to position and scale the terrain as you see fit using entity
manipulation commands such as ScaleEntity, PositionEntity. For example:

;terrain is 32 x 1 x 32
terrain=CreateTerrain( 32 )

;terrain is now 320 x 100 x 320


ScaleEntity terrain,10,100,10

;and centred (on x/z axis') at 0,0,0


PositionEntity terrain,-160,0,-160

Terrrain Detail Level


You can directly control how many triangles are used to approximate a terrain using the
TerrainDetail command.

Using less triangles will naturally result in better speed, but beware that below a certain
threshold your terrain will start to behave very strangely!

For example, if you ask Blitz3D to render a detailed 1,000,000 triangle terrain using only
100 triangles, chances are it just wont be able to do a decent job.

This usually leads to a phenomenon known as 'pop-in', where Blitz3D just isn't able to make
its mind about about how to draw the terrain, and you end up with vertices abruptly
changing position, or 'popping', when the camera view changes.

So what number of triangles should be used? Well, this is definitely a 'trial and error' kind of
thing and depends on a number of factors:

• The variation in the terrain - ie: how 'bumpy' it is.


• The scale of the terrain - ie: how much of it is visible to the camera.
• The range of the camera.

You can reduce the number of triangles needed to represent a terrain using the following
tricks:

• 'Blur' or smooth out the terrain. For example, if you're using a heightmap image, just
apply a 'blur' filter or equivalent to the heightmap.
• Increase the scale of the terrain so less of it is visible to the camera.
• Decrease the camera range, again meaning less of the terrain is visible to the camera.

If all of this sounds a bit wishy-washy, well, it is!

Generating nice looking terrain with minimum pop-in is as much an artform as it is a


science.

Blitz3D also provides a technique called 'vertex morphing' to help reduce pop-in. Vertex
morphing involves Blitz3D automatically smoothing out the terrain a little to reduce pop-in.
The TerrainDetail command is also used to enable vertex morphing.

Modifying Terrain
The ModifyTerrain command is used to change the height of a terrain vertex, for example:

;create a terrain of size 32.


terrain=CreateTerrain( 32 )

;push the centre vertex up half-way.


ModifyTerrain terrain,16,16,.5

The parameters used with ModifyTerrain must be given in 'terrain coordinates'. This
means that the x and z values should always be from 0 to the size of the terrain, and the
height value should always be from 0 to 1. In other words, any scale, position or rotation
applied to the terrain will be ignored.

Texturing Terrains
By default the terrain you create will be just a plain colour, but by using the EntityTexture command it is possible
to apply a texture brush to the whole landscape. Unfortunately at this time, it is not possible to texture different parts
of the terrain with different textures. But fear not !, remember a brush can have 8 multitextures applied to it. By
carefully building up these textures - it is possible to have different texturemaps applied onto the same landscape.

Introduction to Texturing
Textures are probably the coolest thing to happen to 3D graphics since polygons!

Textures are special images which are drawn on top of polygons in order to give them
added detail.

Textures can be either created 'from scratch' or loaded from an image file.

Just like ordinary Blitz2D images, textures are made up of pixels. These pixels can be
accessed using x,y coordinates just like images - only, in a slightly different way.

Instead of x,y values ranging from 0 up to the size of the texture, x,y values for textures
range from 0 to 1. This means the texture pixel at location .5,.5 is always in the center of
the texture. This is possibly a little confusing at first, but it actually turns out to be very
convenient as you don't have to keep track of how big your textures are!

Texture Flags
When a texture is created, a 'texture flags' value is provided to indicate what type of
texture you're after.

Here are the legal texture flags values:

1: Texture has color information.


2: Texture has alpha information.
4: Texture is a masked texture. This means that black pixels are transparent.
8: Texture is mipmapped.
16: Texture is horizontally clamped.
32: Texture is vertically clamped.
64: Texture is a spherical environment map.

Texture flags can be added together to combine the effect of separate flags. For example, a
texture flags value of '3' indicates you want a texture with both color PLUS alpha
information.

If neither the color, alpha or mask flags are used, then the texture is created in a special
format that allows you to draw to it using standard Blitz2D or even Blitz3D commands! A
texture created this way will have color information, but may or may not have alpha
information (this depends on what graphics card you're using!), so its really safest to
assume it has no alpha information.

If the masked flag is used, the color and alpha flags are ignored.
The clamped flags allow you to control whether the texture 'wraps' or not. By default,
textures will 'wrap' or 'repeat' if drawn on large triangles. However, you can prevent this by
using the clamped flags.

Finally, the spherical environment map flag provides a dead easy way to do cool 'reflective'
type effects. Try it!

Creating Textures
You can either create a texture and draw to it by hand, or load a texture from an image file.

Loading a texture from a file is easy:

texture=LoadTexture( "mytexture.jpg",3 )

Note the texture flags value of '3'. This indicates we want the texture to contain both color
and alpha information.

However, the JPG file format does not support alpha information! In this case, Blitz3D will
create its own alpha values based on the color values in the texture.

However, both the PNG and TGA file formats do support alpha information, and Blitz3D will
use this information if present.

To create a texture by hand, use the CreateTexture command.

;create a 256x256 texture


texture=CreateTexture( 256,256,0 )

;retrieve its width


width=TextureWidth( texture )

;retrieve its height


height=TextureHeight( texture )

Why are we retrieving the texture size when we've already told Blitz3D how big we want the
texture?

Well, this is because all 3D graphics cards have limits on the size of texture they can
handle. Typically, texture width and height should be a power of 2 value (eg:
1,2,4,8,16,32,64,128,256,512,1024...) and in some cases - 3DFX cards being the main
culprit here - must be no larger than 256 by 256.

There are also rumours out there that some cards can only handle square textures -
although here at Blitz Research we are yet to run into any such beast!

A texture size where width and height are both power of 2 values and <= 256 is pretty
much guaranteed to be supported by your card - but it never hurts to check!
In the event that you specify a texture size not supported by your graphics card, Blitz3D will
pick the nearest useful size instead.

Also note that we are using a texture flags value of 0. This is because we probably want to
draw something to the texture, and to be able to use graphics commands on a texture you
should not specify the color, alpha or masked texture flags.

OK, now we've created our texture we should probably draw something on it:

;set drawing buffer to the texture


SetBuffer TextureBuffer( texture )

;set cls color to red


ClsColor 255,0,0

;clear the texture to red


Cls

;set drawing color to blue


Color 0,0,255

;draw a blue oval.


Oval 0,0,width,height

;back to the back buffer...


SetBuffer BackBuffer()

Finally, once you've finished with a texture, use FreeTexture to release it.

Animating Textures
ScaleTexture, RotateTexture and PositionTexture can all be used to animate textures.
For example, to cause a texture to scroll, you might use something like...

texture_x#=texture_x#+.1 ;add .1 to texture x position.


PositionTexture texture,texture_x#,0 ;position the texture.

...in your main loop. You can dynamically scale and rotate textures in a similar way.

Multitexturing
Blitz3D allows you to draw up to 8 textures to a single triangle, a technique known as
'multitexturing'.

A common use for multitexturing is 'light mapping', a technique where a texture


containing lighting information is combined with a texture containing color information to
provide lighting effects.

When you use the EntityTexture or BrushTexture commands, an optional 'index'


parameter allows you to control which of the 8 textures you are setting.

By default, multiple textures are combined using multiplication which achieves a lighting
type effect. However, the TextureBlend command allows you to perform other operations
such as alpha-blend and add on multiple textures.

Setting Up Setting Up

Aim: To setup a simple B3D program


Skill level: Beginner
Files Needed: settingup.bb

Blitz3D sits on top of the regular Blitz, instead of learning a totally new set of commands we
can use the same programming techniques as we would with a any Blitz 2D program.
(which is very handy if you have used Blitz before)

Let's take a look at our first program, before we go any further.

Graphics3D 800,600

SetBuffer BackBuffer()

camera=CreateCamera()
CameraViewport camera,0,0,800,600

light=CreateLight()

cube=CreateCube()
PositionEntity cube,0,0,5

While Not KeyHit(1)

TurnEntity cube,.1,.2,.3

UpdateWorld
RenderWorld

Text 320,500,"First Blitz3D Program"

Flip

Wend
End

Run the program above if you haven't already, hopefully you'll be confronted with a
spinning 3D Cube and a short message. Not bad for only 15 lines of code !!!

So what's happening here ? - lets go through it…


Graphics3D 800,600

Perhaps the most important line of the whole program, this instruction is responsible for
initializing the 3d graphics card. As you've probably guessed I'm setting up the screen with
the res of 800x600. If you have any problems running the programs then change the values
of this command. (as not all graphics cards will be able to use the same res)

SetBuffer BackBuffer()

This command is the same as the original Blitz buffer instruction as we use in all our Blitz
programs.

camera=CreateCamera()
CameraViewport camera,0,0,800,600

These two camera instructions firstly create a standard camera, then setup the variables to
respond to the graphics mode we are in.
Why do we need a camera ?, well the standard camera is what we can see. We could have
multiple cameras setup in our program and switch between them. For example we could
have one setup to follow a character in our program and one that remains static pointing at
something. (for instance as a close circuit TV camera)

light=CreateLight()

We shed some light on our little scene by defining a standard light, by default B3D will
already give us a light (so there's no real need for this instruction) - its just good practise to
set things up properly.

cube=CreateCube()
PositionEntity cube,0,0,5

To make our little cube, instead of using a 3d modeller program - I've cheated and used the
B3D autocreate command to give us a cube.

NOTE: Blitz3D contains a whole host of built in ready-to-use shapes such as Cube, Sphere,
Cylinder and Cone. (See doc's for details)

PositionEntity cube,0,0,5

Now we have cube we need to position it, by using the POSITIONENTITY command. As you
can see we positioned the CUBE, but we could also use the command to move anything -
including the camera. The coordinates are in the format of X,Y and Z. Remember using
negative coordinates will move the shape in the opposite direction, for example:
PositionEntity cube,3,-2,7 is really moving the cube 3 units to the right, 2 units up and 7
units into the screen. (away from us)

I expect you will use this command mostly in the beginning sections of your programs to
move everything in position.

While Not KeyHit(1)


The start of our main programming loop, It's good manners to use a loop like this that will
quit out when the ESC key is pressed. How many times have you run a program only to find
that the only way of quitting out is to restart the computer ?

TurnEntity cube,0.1,0.2,0.3

There's going to be at least 2 commands that your program will rely heavily on, and this is
one of them. This little beauty of an instruction turns the cube by the amount giving in the
X,Y and Z amounts. In this case X=.1 of a unit, Y=.2 and Z=.3 - as before you use negative
commands to spin in the other direction. (and of course you can use the instruction to spin
anything, rather than just a shape - such as the camera)

One important thing to remember is that although it rotates the object, the axis rotate with
it. For example you designed a rocket pointing up and then rotated it until it was pointing
downwards, if you then move the shape in the Y plane (up & down) down would become up
!!. It will make sense once you've played around with the examples...

UpdateWorld
RenderWorld

The UPDATEWORLD command is responsible for updating the coordinates of the entities in
our world that may have moved from their last position. (such as moving, rotating and
scaling objects) - and controlling any collisions that may have been setup. Without using
this instruction, your world would be a very static place. Lastly we use RENDERWORLD to
display the scene into our double buffer ready for us to flip into sight with the FLIP
instruction.

Text 320,500,"First Blitz3D Program"


Flip
Wend
End

This last section of code firstly prints a message to the screen, (which must be done every
update in the loop as the buffer is cleared every time the loop repeats). This is a good time
to do any other drawing to the screen such as using commands from the original 2d version
of blitz. (such as scores or special effects). Now we flip the buffer onto the screen using the
old FLIP instruction. The WEND command marks the end of our repeating loop, lastly we
come to the END, which as we already know quits the program. (so we must have pressed
the ESC key to reach this part in our program)

That's it, we have successfully reached the end of our first program
Tutorial 2 - Movement & Rotation

Movement & Movement

Rotation
Aim: Move an object around 3d space
Skill level: Beginner
Files Needed: movement.bb / rocket.3ds
Lets start to get things moving, in this tutorial we will be loading an object which I made up
in 3D Studio. Granted its not wonderful and looks more like a candle than a state-of-the-art
rocket, but it will do us.

Let's take a look through the full source, feel free to run it and have a play !.

NOTE: You will need to have the object ROCKET.3DS in the same directory as the
sourcecode for Blitz to find it

You can move the rocket forwards with the UP cursor, and rotate it with the LEFT and
RIGHT cursor keys.

Graphics3D 800,600

SetBuffer BackBuffer()

camera=CreateCamera()
CameraViewport camera,0,0,800,600

light=CreateLight()

rocket=LoadMesh( "rocket.3ds" )
PositionEntity rocket,0,0,7

While Not KeyHit(1)

If KeyDown(200) Then
MoveEntity rocket,0,0.05,0
EndIf

If KeyDown(203) Then
TurnEntity rocket,0,0,1.0
EndIf

If KeyDown(205) Then
TurnEntity rocket,0,0,-1.0
EndIf

UpdateWorld
RenderWorld

Text 320,500,"Movement & Rotation"

Flip

Wend
End

I won't explain every line of code, just the new commands which we have yet to use. First
up is:

rocket=LoadMesh("rocket.3ds")
As you can probably guess, this line of code will load a 3d model called ROCKET.3DS into a
handle variable called 'rocket'.

What's a handle variable ?, its exactly the same type of label we use in normal blitz for
initializing sprites. (It holds the address in memory of where the data is stored), in this case
the variable rocket points to the location of where the model is stored.

If KeyDown(200) Then
MoveEntity rocket,0,0.05,0
EndIf

These 3 lines tell us that if you are pressing the UP cursor move the object 'ROCKET' in the
Y axis 0.05 units upwards.

Let's take a more indepth look at this, remember my rocket is pointing up - so to start with
I want my rocket to travel upwards - hence why I am increasing the Y coordinate.
(remember in 3D a positive Y means up - not down like in normal coordinate systems, such
as plotting sprites in standard Blitz)

If my rocket was a car, that was designed to be facing towards the right - then I would
want my car to travel to the right of the screen, (it goes forwards) - so I would be
increasing the X coordinate. It's very important to get this right at the beginning of your
program, or your shape could start moving in the wrong direction to what you want it to.

If KeyDown(203) Then
TurnEntity rocket,0,0,1.0
EndIf

If KeyDown(205) Then
TurnEntity rocket,0,0,-1.0
EndIf

It should be quite obvious to you that these lines control the rotation of our rocket. If you
press the LEFT cursor - turn the rocket 1.0 unit clockwise, whereas pressing the RIGHT
cursor results in turning -1.0 units anti clockwise.

So how comes the shape still moves forward even though we are no longer pointing up ? ..
well.. you've got to thank Mr Sibly for giving us the very easy TurnEntity command !. You
see as we turn the object, the axis move with it. If we rotate the shape 90 degrees, the Y
axis is now pointing where the X axis should be. Don't worry why or how.. just be thankful
you don't have to work out any nasty calculations to do it.

Just incase you where wondering, you can rotate the shape without the axis moving by
using the RotateEntity command. This would be used mainly for placement of objects in
your world - for example, if I designed the rocket on its side. I would firstly rotate it till its
standing upright with the Rotate command - then I could use the turn command to move it.

And that's about it really.. The only way of getting to know this command, (which will
probably be your most widely used command) - is to experiment. Try getting the rocket to
rotate in other directions !!

remember here's the format you use:


TurnEntity [what object it is],
X [amount to rotate about the X axis],
Y [amount to rotate about the Y axis],
Z [amount to rotate about the Z axis]

NOTE: Blitz3D also contains a command for scaling an object, (see the doc's for info on
SCALEENTITY) - if for instance we designed it too small we could increase it on-the-fly, or
shrink it if its too large. If you choose to use a multitude of different 3d Packages to design
your objects with, then you will need to use this command quite a lot. 3D Studio for
instance, likes to scale your object much larger than other packages.

Tutorial 3 - Camera Movement

Camera Movement Camera

Aim: Move the camera around 3d space


Skill level: Beginner
Files Needed: camera.bb / house.3ds

So far we have just used a static camera, which just sits there - pointing at the screen. But
in the real world of PC games - we will want it to follow the main character around, (if a
third person view is required - such as Tomb Raider) or perhaps give us a more personal
view such as a first person view (used in Quake or Unreal).

Take a good look at Mr Sibly's 'Marko' demo for a great example of an intelligent camera.
The code to control your camera can be just as complicated as the main game code... if you
want it to be !

Let's have a look at a basic example:

Graphics3D 800,600

SetBuffer BackBuffer()

camera=CreateCamera()
CameraViewport camera,0,0,800,600

light=CreateLight()

house=LoadMesh( "house.3ds" )
RotateEntity house,0,90,0

While Not KeyHit(1)

If KeyDown(200) Then
MoveEntity camera,0,0,1
EndIf

If KeyDown(208) Then
MoveEntity camera,0,0,-1
EndIf

If KeyDown(203) Then
TurnEntity camera,0,1.0,0
EndIf

If KeyDown(205) Then
TurnEntity camera,0,-1.0,0
EndIf

UpdateWorld
RenderWorld

Text 335,500,"Camera Movement"

Flip

Wend
End

Using the cursor keys you can explore the environment, The UP & DOWN cursors moving
forward and back in space - the LEFT & RIGHT cursors panning the camera around on the
spot.

There's not really much more to it, we have already covered movement and rotation in the
previous tutorial. The only difference here is that we are moving forward into the screen.
Just as we moved the shape, we use the same MoveEntity and TurnEntity commands to
move the camera, That's what makes B3D such a great language to learn !.
Instead of having to remember loads of different commands for objects, cameras and lights
- we just use the same instructions.

Perhaps you want to make the view bob up and down, such as the walking motion in Quake
or Doom.. easy enough, just create a loop that moves the height of the camera up and
down. I'll leave the actual coding part up to you !.

By Default Blitz3D will stop drawing an object if it is too far away from the camera, this is
known as the CAMERA RANGE. Anything past its region will not be drawn. This is very
handy if we have alot on screen, anything far into the distance will not show - meaning that
we gain some extra processing time.

BUT WAIT... Blitz3D can also give us a fog effect !. We've all seen games that use it,
(Unreal or example). The further the object is away from the camera the less we can see it.
For more info on these functions see the doc's under Camera Commands. Used correctly,
the fog commands can give a 3D world something of a sinister lifelike look !.

Tutorial 3 - Object Animation

Object Animation Animation

Aim: To animate an object


Skill level: Intermediate
Files Needed: animation.bb / gargoyle.md2
So far we have just used static objects, its Time to liven up our 3d world and think about
animation. Blitz will load in animated meshes from a variety of sources, including X. format
(DirectX), MD2 (used by the Quake 2 engine) and lastly 3DS (3D Studio).

How do you draw and animate an object ?, although B3D has a few commands for building
shapes such as the cube and sphere instructions - really we need to use a 3d modeller
program to create our object.

Most 3d packages will export/import just about every format you are going to ever need,
personally I like to work with the Directx format (X). What modeller you choose to use
really depends on your preference, Truespace (www.caligari.com), Rhino 3D
(www.rhino3d.com) and Canvas 3d (www.amegia.com) - all support X format without any
problems.

Recently I've been using the AC3D modeller for my modelling needs, since its simple but
powerful. You can download a fully working trial version from official website -
(www.comp.lancs.ac.uk/computing/users/andy/ac3d.html), but of course designing an
object that has realistic movement really is an art form all in itself. Most of us including me
- are going to find it a struggle, luckily places such as 3dcafe (www.3dcafe.com) contain
hundreds of ready made free models for us to use.

Time for the source:

Graphics3D 800,600

SetBuffer BackBuffer()

camera=CreateCamera()
CameraViewport camera,0,0,800,600

light=CreateLight()

man=LoadMD2( "gargoyle.md2" )
PositionEntity man,0,-35,600
RotateEntity man,0,180,0

AnimateMD2 man,1,.1,32,46

While Not KeyHit(1)

If dist
If dist=970 AnimateMD2 man,1,.05,0,31

dist=dist+1

UpdateWorld
RenderWorld

Text 320,500,"An Animated MD2 Demo"


Flip

Wend
End

So whats going on ?

man=LoadMD2( "gargoyle.md2" )
PositionEntity man,0,-35,600
RotateEntity man,0,-90,0

Here, I've used the LoadMD2 command to load an MD2 animated object into the pointer
handle 'man'. MD2 models can be found just about anywhere on the net, they are the staple
diet of Quake 2 - So as you'd expect there's thousands of ready made objects with
animation out there just waiting to be included in your epic. (Although be careful to read
any copyright messages that may be attached to them).

Unless you plan on using MD2 models all the time, I expect you will be using the
LOADMESH command which does exactly the same thing as the LOADMD2 instruction. (but
allows loading of X and 3DS animations)

We wont be going into any of the details that involve creating animations from a modeller,
but if your interested I'm sure whatever product you use will contain some sort of tutorial
for creating animations. (You should be able to find some tutorials for 3d modelling from my
Gamecoding website very soon)

The frames of animation (keyframes) are loaded in with the model, all we have to do is tell
B3D where to start - and where to end !. Before we look at this in action, you will notice
that I've positioned and rotated the object to a new starting point. Originally the character
was designed facing Right, so we need to rotate it by 90 degrees - so it faces us. (I did this
by using the RotateEntity command)

AnimateMD2 man,1,.1,32,46

This instruction informs B3D that we want the object 'man' to animate in a loop (so the
walking frames can restart), at a speed of .1 of a unit, starting at frame 32 - and ending in
frame 46

When we have set the command up, every update (depending on the animation speed you
have selected) the animation will run by itself without us having to do any more to it.

If we were using a regular animated object (X or 3DS format) - we would use the ANIMATE
instruction, which works exactly like the ANIMATEMD2 command I've used here in this
example.

As you can see by looking through the source, I've setup a loop that continues to move the
shape forwards until the counter is equal to 970. (using the MOVEENTITY command)

After that the animation is reset to display the standing stance animation.. (frames 0-31).
Why not alter the program to include rotation, so that the character can move about freely.
Although I've setup the animation to loop, we can of course just have it run through the
animation loop once if we had wanted to it. To do this you just change the MODE flag in the
Animate instruction. Here's the instruction in full:

Animate [entity name], [mode 0,1,2 or 3], [speed], [frame to begin at], [frame to end at]

in the case of MD2's you'd use the instruction:

AnimateMD2 [entity name], [mode 0, 1,2 or 3], [speed], [frame to begin at], [frame to end at]

Just incase your interested, here's a rundown of all the mode switches we can use:
(Remember we used the loop anim mode)

0: Stop Anim
1: Loop Anim
2: Ping-Pong Anim
3: One-Shot Anim

NOTE: To play an anim backwards use a negative speed value

B3D thankfully makes animation very easy, it really is just a case of setting up whatever we
need the anim to do first using the various flags in the ANIMATION instruction before
setting it running. However to make the animation look convincing you need to get the
timing right. How many times have you looked at a game only to see the main hero
character float-walking over the floor rather than connecting with it ?.

But that's half the fun of it !, as you'll see a little effort can really make a big difference.

B3D contains a large array of animation commands that will suit every purpose you will ever
need, but tucked away in the depths you'll find a couple of incredible commands that can
morph animation frames from one animation to another. For instance, an object of a man
running can switch smoothly to an anim of him standing still. If you run this example a few
times and watch the point that the object comes to a halt you'll notice the jump. But, by
using these commands we could smooth out the change so it would be unnoticeable.
Although I wont be using these commands in this tutorial, I may add a new tutorial on the
subject very soon.

So what are you waiting for !, go and design the next Quake !!

Tutorial 4 - Texturing

Texturing Texturing

Aim: How to texture an object


Skill level: Intermediate
Files Needed: texture.bb / blitztexture.bmp

For our objects to look more realistic we really need to texture them, but what is texture
mapping ?
Think if it as a way of adding extra details to an object. For example... You design an
ordinary white cube, doesn't look much does it ?

But add a texturemap to it, and suddenly you have a BORG cube !.
Textures are bitmap pictures that have been designed with a paint program (that can save
BMP format files.)

Another example... If you designed a basic model of a creature, using a texturemap you
could add all the external features - such as clothes and facial expressions.

Although B3D has alot of commands to manage multiple textures and special effects, for
now we shall just be using the very basic EntityTexture command.
Of course we could save ourselves alot of time by designing our objects and applying the
textures to them directly from a 3d modelling program, but that would make this tutorial a
waste of time !.

So why would we want to apply a texture in realtime ?, well for starters a new texture may
be put onto the object at any time. Take a wall, shoot it ! - now for things to look realistic in
our 3d world, we would like to have somekind of indication that it was shot. We could do
this by loading a texture of a bullet hole directly onto the wall. Every 3d game currently on
the market uses texture trickery in some form or another, as your experience grows - so
will your imagination !. Why have a flat river, when you could use texturemaps to give the
impression of ripples or waves.

B3D has so many lovely features for us to use including the new ANIMATED textures
command, we will be using this later on !. (Quake I/II/III used this trick to give us the
impression of moving water)

Let's look at this in practice:

Graphics3D 800,600

SetBuffer BackBuffer()

camera=CreateCamera()
CameraViewport camera,0,0,800,600

light=CreateLight()

cube=CreateCube()
PositionEntity cube,0,0,5

texture=LoadTexture("blitztexture.bmp")
EntityTexture cube,texture

While Not KeyHit(1)

TurnEntity cube,0.1,0.2,0.3

UpdateWorld
RenderWorld

Text 340,500,"Texturing Demo"


Flip

Wend
End

As you can see, a texture can make all the difference to a very basic object.

The only 2 lines of code we don't already know are:

texture=LoadTexture("blitztexture.bmp")
EntityTexture cube,texture

Two nice and friendly commands, the first loads a texturemap into memory - with the
pointer variable 'texture' pointing to it.

Once we have successfully loaded the texture, we assign it to the object using the
EntityTexture command. (here we are assigning the variable pointer TEXTURE to the cube
we defined earlier)

You could if you wanted load the picture file BLITZTEXTURE.BMP into MS Paint and make
some changes.. if you wanted to !

And that's all there is to it, but a quick word of advice: If your object isn't textured as it
should, always check that the texturemaps are in the right directory. It's all to easy to
spend half the day trying to work out a texturing problem, only to find that you moved the
program to another directory without dragging the associated texture files with it.

Tutorial 5 - Lighting

Lighting Lighting

Aim: Lighting a scene


Skill level: Intermediate
Files Needed: lights.bb

So we can now move objects (and ourselves) around, texture objects, animate... so what
shall we look at now ?

How about lighting, used correctly we can make great use of it to really give our little world
ambiance.

By default B3D will already give us a light in our scene, pointing directly into the screen.
Think of it as a torch stuck on top of the camera, pointing at whatever we can see.

Sourcecode time:

Graphics3D 800,600
SetBuffer BackBuffer()

camera=CreateCamera()
CameraViewport camera,0,0,800,600

AmbientLight 0,0,0

;cube 1
cube=CreateCube()
PositionEntity cube,0,0,5

light=CreateLight(3)
LightColor light,100,20,30
LightConeAngles light,0,45
PositionEntity light,0,0,0.5
LightRange light,8
PointEntity light,cube

;cube 2
cube2=CopyEntity(cube)
PositionEntity cube2,-5,0,8

light2=CreateLight(3)
LightColor light2,40,150,60
LightConeAngles light2,0,45
PositionEntity light2,-5,0,4.5
LightRange light2,8
PointEntity light2,cube2

;cube 3
cube3=CopyEntity(cube)
PositionEntity cube3,5,0,8

light3=CreateLight(3)
LightColor light3,70,80,190
LightConeAngles light3,0,45
PositionEntity light3,5,0,4.5
LightRange light3,8
PointEntity light3,cube3

While Not KeyHit(1)

TurnEntity cube,0.1,0.2,0.3
TurnEntity cube2,0.3,0.2,0.1
TurnEntity cube3,0.3,0.2,0.1

UpdateWorld
RenderWorld

Text 310,500,"Coloured Lighting Demo"

Flip

Wend
End
There's quite a few new commands to look at here.

Remember that torch I spoke about, well the first new command we will learn is strictly for
changing the colour of the beam. (so to speak)

AmbientLight 0,0,0

This sets the light to black, so that any additional lights we use will show up with full effect.
First thing to remember when using this command is that the colour values range from 0 to
255, and we have 3 separate colour shades to think of RED, GREEN & BLUE. (the same as a
TV)

By changing these values we can just about get any colour we want, such as setting them
all to 255 will result in the colour white. It's usually easier to work out the values you will
need from a paint program such as Paintshop Pro.

light=CreateLight(3)

B3D at present lets us use three different types of lighting. As with the ANMATE instruction
these are selected with flags, these are:

1: AREALIGHT - Which will light the whole surrounding area around it.
2: POINTLIGHT - A directional light that can light a specific area
3: SPOTLIGHT - Very similar to POINT, but can give off more light on a subject area than using
POINTLIGHT.

For this demo I chose to use SPOTLIGHT.

LightColor light,100,20,30

Same as the AMBIENTLIGHT instruction, this command lets us select the colour of the light.
Here I've set it up so that RED=100, GREEN=20 and BLUE=30 - which gives us a nice
reddish glow.

LightConeAngles light,0,45

We use this instruction to control the angle of light that comes from our spotlight. In this
case I've set it up to 45 degrees, In-other-words.. The light has a radius of 45 degrees, any
part of the object that is outside of this will not be lit.

PositionEntity light,0,0,0.5

We move the light into position.

LightRange light,8

This controls the distance of the light, I set it at 8 units.. If I wanted the light to shine
further into the distance then I would increase this value.

PointEntity light,cube
This command will point the light at our cube object. No matter where are light is positioned
it will point towards the cube. But if you then move the object or light - you will have to
repoint it with this command.

Something else you should think about is whether the light and object can see each other.
(the LIGHTRANGE instruction)

I won't go into details with the rest of the program as you should be able to work out what
is happening without any additional help.

Where's the fancy lensflare commands, I can hear you cry. Well at present B3D doesn't
have any readymade, built-in commands - so its really up to you the programmer - to come
up with these effects. And believe me it is possible with a little careful effort. I've seen some
of the Beta Testers come up with lighting effects that would equal Unreal !. But then this is
a subject for another tutorial...

Tutorial 6 - Collisions

Collision Detection Movement

Aim: To detect a collision between 2 objects


Skill level: Intermediate
Files Needed: collision.bb

In this example I shall be using 2 ready-made entity objects, a Sphere and a Box.

Hopefully The program will display a message once the sphere comes into contact with the
box. Run the program first to fully understand what is happening before delving into the
sourcecode below.

Graphics3D 800,600

Const CUBE_COL=1
Const SPHERE_COL=2

SetBuffer BackBuffer()

camera=CreateCamera()
CameraViewport camera,0,0,800,600
PositionEntity camera,0,0,-5

light=CreatLight()

cube=CreateCube()
PositionEntity cube,-5,0,5
EntityColor cube,70,80,190
EntityType cube,CUBE_COL

sphere=CreateSphere(12)
PositionEntity sphere,5,0,5
EntityColor sphere,170,80,90
EntityType sphere,SPHERE_COL

Collisions SPHERE_COL,CUBE_COL,3,1

While Not KeyHit(1)

MoveEntity sphere,-0.02,0,0

UpdateWorld
RenderWorld

If EntityCollided(sphere,CUBE_COL) Then
Text 370,80,"Collided !!!"
EndIf

Text 335,500,"Collision Detection"


Flip

Wend

End

Being able to check for collisions is perhaps the most major part of any game. After all,
without collision detection what's to stop Mario falling through the floor, or the bullets from
Max Payne's gun doing its damage. We need it - whether we want it or not !.

If you look carefully through the above example you will notice quite a few new commands.
Let's briefly run through the entire program before we look at these.

Firstly we create 2 objects - a Cube and a Sphere.., then we setup the collision so that B3D
will check these objects every time the UPDATEWORLD instruction is called.

Slowly we move the Sphere towards the Cube, until they collide.. after that, we print up the
collision message on the screen to signal that we have collided.

So what do these new instructions do:

Const CUBE_COL=1
Const SPHERE_COL=2

Ok, its not an instruction, but just something I've strung together for this example. When
programming always try and make things as easy as possible - It will certainly help when it
comes to debugging. (working out any problems)

The Collision instructions we have to setup rely on variables, but rather than just using
numbers - I'll use the CONSTANT variables I've setup to represent them.

So in the above two lines, I can use the variable names CUBE_COL every time I want to use
a 1 - and SPHERE_COL instead of 2. Although of course I could just use the numbers with
the instructions, as you'll see it will help us out.

EntityType cube,CUBE_COL
After we've setup the basic entity object, we need to setup a collision variable for it. We do
this by assigning a number to the entity, As you can see to do this we use the ENTITYTYPE
command. Here I've set the entity cube to have a value of 1. (remember the CONST
variable is set to 1)

EntityType sphere,SPHERE_COL

As before, we setup the sphere collision variable to have a value of 2.

AN IMPORTANT NOTE TO REMEMBER !

Every entity DOES NOT have to have a separate collision variable number. For example say
we created a 3d maze game, that had 10 objects for the sides of the maze. We would want
to check if we have collided with a wall, it wouldn't matter which wall.. just a wall. So every
wall object(entity) would have the same collision variable.
I would use the code:

Const WALL=1
EntityType wall1,WALL
EntityType wall2,WALL... etc

Later on when we check for a collision we would just say, is there a collision with the wall ?.
Nice and Easy isnt it ?

Collisions SPHERE_COL,CUBE_COL,3,1

Now the fun begins, this is the main instruction that informs B3D which objects to check for
collisions and what action it should take.

The first part of the line "Collisions SPHERE_COL,CUBE_COL,3,1", is saying that we want
a check to take place between the collision markers 1 and 2. (Remember the Sphere is 1
and the Cube is 2)

If we had more entities with the same collision marker value, then of course these too
would be included.

"Collisions SPHERE_COL,CUBE_COL,3,1" - The first value (3), represents the type of


collision that we want B3D to perform, in this case we are using mode '3' - which is a
Sphere-to-Box collision.

B3D has 3 different types of collisions we can perform, these are:

1 = Sphere-to-Sphere
2 = Sphere-to-Polygon
3 = Sphere-to-Box

Now we come to the last value, "Collisions SPHERE_COL,CUBE_COL,3,1". This is the


response value, it signals what B3D should do when a collision has taken place. I used the
value 1 which is used for a dead stop. (when it collides with something, don't let it move
any closer to it)

As before there are 3 mode types we can use:


1 = Stop
2 = Slide1 - Full sliding collision
3 = Slide2 - Takes into consideration the angle of slopes

Even though in my program I am moving the sphere into the box with the MOVEENTITY
command, when it collides (because I've used the STOP mode).. the entity will NOT move
through it.

We have one more command to look at, that's the collision check instruction itself
"EntityCollided".

If EntityCollided(sphere,CUBE_COL) then
Text 370,80,"Collided !!!"
EndIf

As you can can probably guess, this instruction (imbedded in an IF statement) - is checking
the entity SPHERE for a collision with the collision marker 1 (the cube).

If it has collided then print the message to signal a collision !.

Ok, we have now run through the entire program - but did it make much sense to you ?, To
begin with I couldn't grasp it at all !. The best way to understand the various collision
instructions is to experiment yourself with the different mode settings. Eventually (if you
haven't understood fully by now).. you will realize just how easy and powerful they can be.

Tutorial 8 - Vertexes

Vertexes Movement

Aim: To edit a meshes vertexes in Real-time


Skill level: Intermediate
Files Needed: vertex.bb / plane.3ds

If you've already read the section on Meshes beforehand then hopefully you'll know most of
what we will be doing already in this tutorial, if not - go away and read it first !.

let's recap:

• Each MESH (a 3d object), is made up of SURFACES.


• Each SURFACE has a BRUSH.
• Each BRUSH can be assigned 8 different texturemaps.
(which can be overlaid on each other to create new effects)
• Each SURFACE is made up of TRIANGLES.
• Each TRIANGLE is made up of 3 VERTEXES.

So, armed with that info - you should know what makes a 3d object tick !. Lets take a flat
square as an example, it is made up of 4 vertexes and 2 triangles. What we are planning of
doing is to take 2 of those vertexes and change their coordinates.
Infact as mentioned in the Introduction to Meshes, we can even change the colour of the
vertexes in realtime too. Run the example - what you can hopefully see is a square object
(which is slowly spinning on the Z plane), being pulled out of shape in 2 corners - while
every-so-often the colours change.

It's a very easy effect to create, I wont go into great detail about how/why the program
works - but here's a quick rundown if your interested:

We setup the variable 'COUNTER', which does exactly that.. to be used as a counter. Every
time the program runs through its main loop, it is incremented. Based on what value the
counter is equal to, corresponds to what direction we should pull the vertexes. If the
counter reaches 1000 then change the colour of each vertex to a random selection, before
resetting the counter value.

Let's take a look:

Graphics3D 800,600

SetBuffer BackBuffer()

camera=CreateCamera()
CameraViewport camera,0,0,800,600

light=CreateLight()

plane=LoadMesh("plane.3ds")
PositionEntity plane,0,0,25
EntityFX plane,2

surface=GetSurface(plane,CountSurfaces(plane))

VertexColor surface,0,255,0,0
VertexColor surface,1,0,255,0
VertexColor surface,2,0,0,255
VertexColor surface,3,255,0,255

While Not KeyHit(1)

TurnEntity plane,0,0,.3

counter=counter+1

If counter<500 Then
x1#=-.01
y1#=-.01
x2#=+.01
EndIf

If counter>499 Then
x1#=+.01
y1#=+.01
x2#=-.01
EndIf
xx#=VertexX(surface,0)
yy#=VertexY(surface,0)
zz#=VertexZ(surface,0)

VertexCoords surface,0,xx+x1,yy+y1,zz

xx#=VertexX(surface,2)
yy#=VertexY(surface,2)
zz#=VertexZ(surface,2)

VertexCoords surface,2,xx+x2,yy+y1,zz

If counter=1000 Then
counter=0
VertexColor surface,0,Rnd#(0,255),Rnd#(0,255),Rnd#(0,255)
VertexColor surface,1,Rnd#(0,255),Rnd#(0,255),Rnd#(0,255)
VertexColor surface,2,Rnd#(0,255),Rnd#(0,255),Rnd#(0,255)
VertexColor surface,3,Rnd#(0,255),Rnd#(0,255),Rnd#(0,255)
EndIf

UpdateWorld
RenderWorld

Text 350,500,"Vertex Control"

Flip

Wend
End

So how do we get at the vertexes of the object ?

Well for starters we load the object with the LoadMesh command, the object we are loading
is of course called Plane.3ds.

EntityFX plane,2

Now here's a new command we haven't seen before !, this command is really more of mode
switch than anything else. But setting values we can access the entity in different ways. the
mode value '2' is to able vertex colouring on the whole entity, by default this is turned off.

Here's those mode settings:

1 = Full-Bright
2 = Use Vertex Colours
4 = Flatshading
8 = Disable Fog

There is another command very similar to EntitiyFX called BRUSHFX. This uses the same
mode settings, but instead of changing the whole entity will work on a single brush.
(remember a mesh has surfaces, with brushes applied to them)

surface=GetSurface(plane,CountSurfaces(plane))
In order to get at the vertexes we must first unlock them, we do this by creating a pointer
variable that holds the memory address to the surfaces on the mesh.

Calm down !, we don't have to get our hands dirty calling with lots of nasty math's - instead
we just use the GETSURFACE command, which likes us to pass firstly the mesh name - and
secondly the amount of surfaces it has. As you can see I've cheated and used the
COUNTSURFACES command to do this for me.

VertexColor surface,0,255,0,0
VertexColor surface,1,0,255,0
VertexColor surface,2,0,0,255
VertexColor surface,3,255,0,255

Before going into the main loop, I've set the colour of each vertex to a different colour. This
gives us a nice rainbow effect !. As you can see we pass the pointer variable SURFACE to
the VERTEXCOLOR command, as well as the vertex number (0-3, since our object only has
4 points) - followed by the colour values for the Red, Green and Blue shades. (must be in
the range of 0 (Dark) through to 255 (Light))

xx#=VertexX(surface,0)
yy#=VertexY(surface,0)
zz#=VertexZ(surface,0)

Since I want the coordinates of the mesh to change all the time, I cant set it with a value
that doesn't change. Every update I've got to get the current coordinates and slightly
update them (by adding an offset to the X and Y coords).

I do this by firstly, getting the current X,Y and Z vertex coords - using the various get
vertex commands.

VertexX(surface,0) - gives us access to the X coordinate of the object surface, at vertex 0.

Just as, VertexY(surface,99) - would give us access to the Y coodinate of vertex 99 !!!.

VertexCoords surface,0,xx+x1,yy+y1,zz

As you've probably worked out by now, this is the main instruction for changing the actual
Vertex positions. It needs to be called with the Surface pointer value, followed by the new
values for the X, Y and Z positions.

And that's all there is to it !!

But why would you want to change the coordinates ?

All games will alter their objects, its just a case of working out how, and where they do it.
Imagine you've just written a driving simulation.. wouldn't it be nice when you crash the car
to reflect the damage ?. Perhaps crumple that fender.. or crack that window.

Just like a certain other car game currently in the charts, they use exactly the same
method. You gotta hand it to B3D - You want it.. it's there, now go and use it wisely !.
AddAnimSeq ( entity,length)

Parameters:

entity - entity handle


length -

Description:

Creates an animation sequence for an entity. This must be done before any animation keys set by SetAnimKey
can be used in an actual animation.

Returns the animation sequence number added.

Example:

None.

AddMesh source_mesh,dest_mesh

Parameters:

source_mesh - source mesh handle


dest_mesh - destination mesh handle

Description:

Adds the source mesh to the destination mesh.

Example:

None.

AddTriangle ( surface,v0,v1,v2 )

Parameters:

surface - surface handle


v0 - index number of first vertex of triangle
v1 - index number of second vertex of triangle
v2 - index number of third vertex of triangle

Description:

Adds a triangle to a surface and returns the triangle's index number, starting from 0.

The v0, v1 and v2 parameters are the index numbers of the vertices created using AddVertex.

Depending on how the vertices are arranged, then the triangle will only be visible from a certain side. Imagine
that a triangle's vertex points are like dot-to-dot pattern, each numbered v0, v1, v2. If these dots, starting
from v0, through to V2, form a clockwise pattern relative to the viewer, then the triangle will be visible. If
these dots form an anti-clockwise pattern relative to the viewer, then the triangle will not be visible.

The reason for having one-sided triangles is that it reduces the amount of triangles that need to be rendered
when one side faces the side of an object which won't be seen (such as the inside of a snooker ball). However,
if you wish for a triangle to be two-sided, then you can either create two triangles, using the same set of
vertex numbers for both but assigning them in opposite orders, or you can use CopyEntity and FlipMesh
together.

Example:

None.

AddVertex ( surface,x#,y#,z#[,u#][,v#][,w#] )

Parameters:

surface - surface handle


x# - x coordinate of vertex
y# - y coordinate of vertex
z# - z coordinate of vertex
u# (optional) - u texture coordinate of vertex
v# (optional) - v texture coordinate of vertex
w# (optional) - w texture coordinate of vertex - not used, included for future expansion

Description:

Adds a vertex to the specified surface and returns the vertices' index number, starting from 0.

x,y,z are the geometric coordinates of the vertex, and u,v,w are texture mapping coordinates.

A vertex is a point in 3D space which is used to connect edges of a triangle together. Without any vertices,
you can't have any triangles. At least three vertices are needed to create one triangle; one for each corner.

The optional u,v parameters allow you to specify texture coordinates for a vertex, which will determine how
any triangle created using those vertices will be texture mapped.

This works on the following basis: the bottom left of an image has the uv coordinates 0,0. The bottom right
has coordinates 0,1, top left 0,1 and top right 1,1. Now, depending on what uv coordinate you assign to the
vertex, this will represent a point on the image. For example, a coordinate of 0.5,0.5 would represent the
centre of the image.

So now imagine you have a normal equilateral triangle. By assigning the bottom left vertex a uv coordinate of
0,0, then bottom right a coordinate of 1,0 and the top centre 0.5,1, this will texture map the triangle with an
image that fits it.

Example:

None.

AlignToVector entity,vector_x#,vector_y#,vector_z#,axis

Parameters:

entity - entity handle


vector_x# - vector x
vector_y# - vector y
vector_z# - vector z

axis - axis of entity that will be aligned to vector


1: x-axis
2: y-axis
3: z-axis

Description:

Aligns an entity axis to a vector.

Example:

None.

AmbientLight red#,green#,blue#

Parameters:

red# - red ambient light value


green# - green ambient light value
blue# - blue ambient light value

Description:

Sets the ambient lighting colour.

The green, red and blue values should be in the range 0-255. The default ambient light colour is 255,255,255.

Ambient light is a light source that affects all points on a 3D object equally. So with ambient light only, all 3D
objects will appear flat, as there will be no shading.

Ambient light is useful for providing a certain level of light, before adding other lights to provide a realistic
lighting effect.

An ambient light level of 0,0,0 will result in no ambient light being displayed.

Example:

; AmbientLight Example
; --------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

sphere=CreateSphere( 32 )
PositionEntity sphere,-2,0,5

cone=CreateCone( 32 )
PositionEntity cone,2,0,5

; Set initial ambient light colour values


red#=127
green#=127
blue#=127

While Not KeyDown( 1 )

; Change red, green, blue values depending on key pressed


If KeyDown( 2 )=True And red#>0 Then red#=red#-1
If KeyDown( 3 )=True And red#<255 Then red#=red#+1
If KeyDown( 4 )=True And green#>0 Then green#=green#-1
If KeyDown( 5 )=True And green#<255 Then green#=green#+1
If KeyDown( 6 )=True And blue#>0 Then blue#=blue#-1
If KeyDown( 7 )=True And blue#<255 Then blue#=blue#+1

; Set ambient light using red, green, blue values


AmbientLight red#,green#,blue#

RenderWorld

Text 0,0,"Press keys 1-6 to change AmbientLight red#,green#,blue# values


Text 0,20,"Ambient Red: "+red#
Text 0,40,"Ambient Green: "+green#
Text 0,60,"Ambient Blue: "+blue#

Flip

Wend

End

Animate entity,[,mode][,speed#][,sequence][,transition#]

Parameters:

entity - entity handle

mode (optional) - mode of animation.


0: stop animation
1: loop animation (default)
2: ping-pong animation
3: one-shot animation

speed# (optional) - speed of animation. Defaults to 1.


sequence (optional) - specifies which sequence of animation frames to play. Defaults to 0.
transition# (optional) - used to tween between an entities current position rotation and the first frame of
animation. Defaults to 0.

Description:

Animates an entity.

More info about the optional parameters:

speed# - a negative speed will play the animation backwards.

sequence - Initially, an entity loaded with LoadAnimMesh will have a single animation sequence. More
sequences can be added using either LoadAnimSeq or AddAnimSeq. Animation sequences are numbered
0,1,2...etc.

transition# - A value of 0 will cause an instant 'leap' to the first frame, while values greater than 0 will cause a
smooth transition.

Example:

None.

AnimateMD2 md2[,mode][,speed#][,first_frame][,last_frame]

Parameters:

md2 - md2 handle

mode (optional) - mode of animation


0: stop animation
1: loop animation (default)
2: ping-pong animation
3: one-shot animation

speed# (optional) - speed of animation. Defaults to 1.


first_frame (optional) - first frame of animation. Defaults to 1.
last_frame# (optional) - last frame of animation. Defaults to last frame of all md2 animations.

Description:

Starts an md2 entity animating.

The md2 will actually move from one frame to the next when UpdateWorld is called, usually once per main
loop.

Example:

; AnimateMD2 Example
; ------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

; Load md2
gargoyle=LoadMD2( "media/gargoyle/gargoyle.md2" )

; Load md2 texture


garg_tex=LoadTexture( "media/gargoyle/gargoyle.bmp" )

; Apply md2 texture to md2


EntityTexture gargoyle,garg_tex

; Animate md2
AnimateMD2 gargoyle,1,0.1,32,46

PositionEntity gargoyle,0,-45,100
RotateEntity gargoyle,0,180,0

While Not KeyDown( 1 )


UpdateWorld
RenderWorld
Flip
Wend

End

Animating ( entity )

Parameters:

entity - entity handle

Description:

Returns true if the specified entity is currently animating.

Example:

None.

AnimLength ( entity )

Parameters:

entity - entity handle

Description:

Returns the length of the specified entity's current animation sequence.

Example:

None.

AnimSeq ( entity )

Parameters:

entity - entity handle

Description:

Returns the specified entity's current animation sequence.

Example:

None.
AnimTime# ( entity )

Parameters:

entity - entity handle

Description:

Returns the current animation time of an entity.

Example:

None.

Antialias enable

Parameters:

enable - true to enable fullscreen antialiasing, false to disable. Defaults to false.

Description:

Enables or disables fullscreen antialiasing.

Fullscreen antialiasing is a technique used to smooth out the entire screen, so that jagged lines are made less
noticeable.

Some 3D cards have built-in support for fullscreen antialiasing, which should allow you to enable the effect
without much slowdown. However, for cards without built-in support for fullscreen antialiasing, enabling the
effect may cause severe slowdown.

Example:

; AntiAlias Example
; -----------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

sphere=CreateSphere()
PositionEntity sphere,0,0,2

While Not KeyDown( 1 )

; Toggle antialias enable value between true and false when spacebar is pressed
If KeyHit( 57 )=True Then enable=1-enable

; Enable/disable antialiasing
AntiAlias enable
RenderWorld

Text 0,0,"Press spacebar to toggle between AntiAlias True/False"


If enable=False Then Text 0,20,"AntiAlias False" Else Text 0,20,"AntiAlias True"

Flip

Wend

End

BrushAlpha brush,alpha#

Parameters:

brush - brush handle


alpha# - alpha level of brush

Description:

Sets the alpha level of a brush.

The alpha# value should be in the range 0-1. The default brush alpha setting is 1.

The alpha level is how transparent an entity is. A value of 1 will mean the entity is non-transparent, i.e.
opaque. A value of 0 will mean the entity is completely transparent, i.e. invisible. Values between 0 and 1 will
cause varying amount of transparency accordingly, useful for imitating the look of objects such as glass and
ice.

An BrushAlpha value of 0 is especially useful as Blitz3D will not render entities with such a value, but will still
involve the entities in collision tests. This is unlike HideEntity, which doesn't involve entities in collisions.

Example:

None.

BrushBlend brush,blend

Parameters:

brush - brush handle


blend -
1: alpha
2: multiply (default)
3: add

Description:

Sets the blending mode for a brush.

Example:

None.
BrushColor brush,red#,green#,blue#

Parameters:

brush - brush handle


red# - brush red value
green# - brush green value
blue# - brush blue value

Description:

Sets the colour of a brush.

The green, red and blue values should be in the range 0-255. The default brush color is 255,255,255.

Please note that if EntityFX or BrushFX flag 2 is being used, brush colour will have no effect and vertex colours
will be used instead.

Example:

; BrushColor Example
; ------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

cube=CreateCube()
PositionEntity cube,0,0,5

; Create brush
brush=CreateBrush()

; Set brush color


BrushColor brush,0,0,255

; Paint mesh with brush


PaintMesh cube,brush

While Not KeyDown( 1 )

pitch#=0
yaw#=0
roll#=0

If KeyDown( 208 )=True Then pitch#=-1


If KeyDown( 200 )=True Then pitch#=1
If KeyDown( 203 )=True Then yaw#=-1
If KeyDown( 205 )=True Then yaw#=1
If KeyDown( 45 )=True Then roll#=-1
If KeyDown( 44 )=True Then roll#=1

TurnEntity cube,pitch#,yaw#,roll#

RenderWorld
Flip

Wend

End

BrushFX brush,fx

Parameters:

brush - brush handle

fx -
1: full-bright
2: use vertex colors instead of brush color
4: flatshaded
8: disable fog

Description:

Sets miscellaneous effects for a brush.

Flags can be added to combine two or more effects. For example, specifying a flag of 3 (1+2) will result in a
full-bright and vertex-coloured brush.

Example:

<example>

BrushShininess brush,shininess#

Parameters:

brush - brush handle


shininess# - shininess of brush

Description:

Sets the specular shininess of a brush.

The shininess# value should be in the range 0-1. The default shininess setting is 0.

Shininess is how much brighter certain areas of an object will appear to be when a light is shone directly at
them.

Setting a shininess value of 1 for a medium to high poly sphere, combined with the creation of a light shining
in the direction of it, will give it the appearance of a shiny snooker ball.

Example:

None.
BrushTexture brush,texture[,frame][,index]

Parameters:

brush - brush handle


texture - texture handle
frame (optional) - texture frame. Defaults to 0.
index (optional) - texture index. Defaults to 0.

Description:

Assigns a texture to a brush.

The optional frame parameter specifies which animation frame, if any exist, should be assigned to the brush.

The optional index parameter specifies texture layer that the texture should be assigned to. Brushes have up
to four texture layers, 0-3 inclusive.

Example:

; CreateBrush Example
; -------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

cube=CreateCube()
PositionEntity cube,0,0,5

; Load texture
tex=LoadTexture( "media/b3dlogo.jpg" )

; Create brush
brush=CreateBrush()

; Apply texture to brush


BrushTexture brush,tex

; Paint mesh with brush


PaintMesh cube,brush

While Not KeyDown( 1 )

pitch#=0
yaw#=0
roll#=0

If KeyDown( 208 )=True Then pitch#=-1


If KeyDown( 200 )=True Then pitch#=1
If KeyDown( 203 )=True Then yaw#=-1
If KeyDown( 205 )=True Then yaw#=1
If KeyDown( 45 )=True Then roll#=-1
If KeyDown( 44 )=True Then roll#=1

TurnEntity cube,pitch#,yaw#,roll#
RenderWorld
Flip

Wend

End

CameraClsColor camera,red#,green#,blue#

Parameters:

camera - camera handle


red# - red value of camera background color
green# - green value of camera background color
blue# - blue value of camera background color

Description:

Sets camera background color. Defaults to 0,0,0.

Example:

None.

CameraClsMode camera,cls_color,cls_zbuffer

Parameters:

camera - camera handle


cls_color - true to clear the color buffer, false not to
cls_zbuffer - true to clear the z-buffer, false not to

Description:

Sets camera clear mode.

Example:

None.

CameraFogColor camera,red#,green#,blue#

Parameters:

camera - camera handle


red# - red value of value
green# - green value of fog
blue# - blue value of fog

Description:
Sets camera fog color.

Example:

plane=CreatePlane()
grass_tex=LoadTexture( "media/mossyground.bmp" )
EntityTexture plane,grass_tex

; Set camera fog to 1 (linear fog)


CameraFogMode camera,1

; Set camera fog range


CameraFogRange camera,1,10

; Set initial fog colour values


red#=0
green#=0
blue#=0

While Not KeyDown( 1 )

; Change red, green, blue values depending on key pressed


If KeyDown( 2 )=True And red#>0 Then red#=red#-1
If KeyDown( 3 )=True And red#<255 Then red#=red#+1
If KeyDown( 4 )=True And green#>0 Then green#=green#-1
If KeyDown( 5 )=True And green#<255 Then green#=green#+1
If KeyDown( 6 )=True And blue#>0 Then blue#=blue#-1
If KeyDown( 7 )=True And blue#<255 Then blue#=blue#+1

; Set camera fog color using red, green, blue values


CameraFogColor camera,red#,green#,blue#

If KeyDown( 205 )=True Then TurnEntity camera,0,-1,0


If KeyDown( 203 )=True Then TurnEntity camera,0,1,0
If KeyDown( 208 )=True Then MoveEntity camera,0,0,-0.05
If KeyDown( 200 )=True Then MoveEntity camera,0,0,0.05

RenderWorld

Text 0,0,"Use cursor keys to move about the infinite plane"


Text 0,20,"Press keys 1-6 to change CameraFogColor red#,green#,blue# values
Text 0,40,"Fog Red: "+red#
Text 0,60,"Fog Green: "+green#
Text 0,80,"Fog Blue: "+blue#

Flip

Wend

End

CameraFogMode camera,mode

Parameters:

camera - sets camera fog mode


mode - fog mode
0: no fog
1: linear fog
Description:

Sets the camera fog mode.

This will enable/disable fogging, a technique used to gradually fade out graphics the further they are away
from the camera. The can be used to avoid 'pop-up', the moment at which 3D objects suddenly appear on the
horizon.

The default fog color is black and the default fog range is 1-1000, although these can be changed by using
CameraFogColor and CameraFogRange respectively.

Each camera can have its own fog mode, for multiple on-screen fog effects.

Example:

; CameraFogMode Example
; ---------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
PositionEntity camera,0,1,0
CameraFogRange camera,1,10

light=CreateLight()
RotateEntity light,90,0,0

plane=CreatePlane()
grass_tex=LoadTexture( "media/mossyground.bmp" )
EntityTexture plane,grass_tex

While Not KeyDown( 1 )

; Toggle camera fog mode between 0 and 1 when spacebar is pressed


If KeyHit( 57 )=True Then fog_mode=1-fog_mode : CameraFogMode camera,fog_mode

If KeyDown( 205 )=True Then TurnEntity camera,0,-1,0


If KeyDown( 203 )=True Then TurnEntity camera,0,1,0
If KeyDown( 208 )=True Then MoveEntity camera,0,0,-0.05
If KeyDown( 200 )=True Then MoveEntity camera,0,0,0.05

RenderWorld

Text 0,0,"Use cursor keys to move about the infinite plane"


Text 0,20,"Press spacebar to toggle between CameraFogMode 0/1"
If fog_mode=False Then Text 0,40,"CameraFogMode 0" Else Text 0,40,"CameraFogMode 1"

Flip

Wend

End

CameraFogRange camera,near#,far#

Parameters:

camera - camera handle


near# - distance in front of camera that fog starts
far# - distance in front of camera that fog ends

Description:

Sets camera fog range.

The near parameter specifies at what distance in front of the camera that the fogging effect will start; all 3D
object before this point will not be faded.

The far parameter specifies at what distance in front of the camera that the fogging effect will end; all 3D
objects beyond this point will be completely faded out.

Example:

; CameraFogRange Example
; ----------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
PositionEntity camera,0,1,0

light=CreateLight()
RotateEntity light,90,0,0

plane=CreatePlane()
grass_tex=LoadTexture( "media/mossyground.bmp" )
EntityTexture plane,grass_tex

; Set camera fog to 1 (linear fog)


CameraFogMode camera,1

; Set intial fog range value


fog_range=10

While Not KeyDown( 1 )

; If square brackets keys pressed then change fog range value


If KeyDown( 26 )=True Then fog_range=fog_range-1
If KeyDown( 27 )=True Then fog_range=fog_range+1

; Set camera fog range


CameraFogRange camera,1,fog_range

If KeyDown( 205 )=True Then TurnEntity camera,0,-1,0


If KeyDown( 203 )=True Then TurnEntity camera,0,1,0
If KeyDown( 208 )=True Then MoveEntity camera,0,0,-0.05
If KeyDown( 200 )=True Then MoveEntity camera,0,0,0.05

RenderWorld

Text 0,0,"Use cursor keys to move about the infinite plane"


Text 0,20,"Press [ or ] to change CameraFogRange value"
Text 0,40,"CameraFogRange camera,1,"+fog_range

Flip

Wend

End
CameraPick ( camera,viewport_x#,viewport_y# )

Parameters:

camera - camera handle


viewport_x# - 2D viewport coordinate
viewport_z# - 2D viewport coordinate

Description:

Picks the entity positioned at the specified viewport coordinates.

Returns the entity picked, or 0 if none there.

An entity must have its EntityPickMode set to a non-0 value value to be 'pickable'.

Example:

None.

CameraProject camera,x#,y#,z#

Parameters:

camera - camera handle


x# - world coordinate x
y# - world coordinate y
z# - world coordinate z

Description:

Projects the world coordinates x,y,z on to the 2D screen.

Example:

None.

CameraRange camera,near#,far#

Parameters:

camera - camera handle


near - distance in front of camera that 3D objects start being drawn
far - distance in front of camera that 3D object stop being drawn

Description:

Sets camera range.

Try and keep the ratio of far/near as small as possible for optimal z-buffer performance. Defaults to 1,1000.
Example:

None.

CameraViewport camera,x,y,width,height

Parameters:

camera - camera handle


x - x coordinate of top left hand corner of viewport
y - y coordinate of top left hand corner of viewport
width - width of viewport
height - height of viewport

Description:

Sets the camera viewport position and size.

The camera viewport is the area of the 2D screen that the 3D graphics as viewed by the camera are displayed
in.

Setting the camera viewport allows you to achieve spilt-screen and rear-view mirror effects.

Example:

; CameraViewport Example
; ----------------------

Graphics3D 640,480
SetBuffer BackBuffer()

; Create first camera


cam1=CreateCamera()

; Set the first camera's viewport so that it fills the top half of the camera
CameraViewport cam1,0,0,GraphicsWidth(),GraphicsHeight()/2

; Create second camera


cam2=CreateCamera()

; Set the second camera's viewport so that it fills the bottom half of the camera
CameraViewport cam2,0,GraphicsHeight()/2,GraphicsWidth(),GraphicsHeight()/2

light=CreateLight()
RotateEntity light,90,0,0

plane=CreatePlane()
grass_tex=LoadTexture( "media/mossyground.bmp" )
EntityTexture plane,grass_tex
PositionEntity plane,0,-1,0

While Not KeyDown( 1 )

If KeyDown( 205 )=True Then TurnEntity cam1,0,-1,0


If KeyDown( 203 )=True Then TurnEntity cam1,0,1,0
If KeyDown( 208 )=True Then MoveEntity cam1,0,0,-0.05
If KeyDown( 200 )=True Then MoveEntity cam1,0,0,0.05

RenderWorld
Text 0,0,"Use cursor keys to move the first camera about the infinite plane"

Flip

Wend

End

CameraZoom camera,zoom#

Parameters:

camera - camera handle


zoom# - zoom factor of camera

Description:

Sets zoom factor for a camera. Defaults to 1.

Example:

None.

CaptureWorld

Parameters:

None.

Description:

Takes a snapshot of the position and orientation of each entity in the world.

This snapshot can then be used with RenderWorld to render entities at a point somewhere between their
captured position and their current position. See RenderWorld for more about how and why this is done.

Example:

None.

ClearCollisions

Parameters:

None.

Description:

Clears the collision information list.


Whenever you use the Collisions command to enable collisions between two different entity types, information
is added to the collision list. This command clears that list, so that no collisions will be detected until the
Collisions command is used again.

The command will not clear entity collision information. For example, entity radius, type etc.

Example:

; ClearCollisions Example
; -----------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

sphere=CreateSphere( 32 )
PositionEntity sphere,-2,0,5

cone=CreateCone( 32 )
EntityType cone,type_cone
PositionEntity cone,2,0,5

; Set collision type values


type_sphere=1
type_cone=2

; Set up sphere collision data


EntityRadius sphere,1
EntityType sphere,type_sphere

; Set up cone collision data


EntityType cone,type_cone

; Enable collisions between type_sphere and type_cone, with sphere->polygon method and slide response
Collisions type_sphere,type_cone,2,2

While Not KeyDown( 1 )

x#=0
y#=0
z#=0

If KeyDown( 203 )=True Then x#=-0.1


If KeyDown( 205 )=True Then x#=0.1
If KeyDown( 208 )=True Then y#=-0.1
If KeyDown( 200 )=True Then y#=0.1
If KeyDown( 44 )=True Then z#=-0.1
If KeyDown( 30 )=True Then z#=0.1

MoveEntity sphere,x#,y#,z#

; If spacebar pressed then clear collisions


If KeyHit( 57 )=True Then ClearCollisions

; Perform collision checking


UpdateWorld

RenderWorld

Text 0,0,"Use cursor/A/Z keys to move sphere"


Text 0,20,"Press spacebar to use ClearCollisions command"

Flip

Wend

End

ClearSurface surface,[clear_verts][,clear_triangles]

Parameters:

surface - surface handle


clear_verts (optional) - true to remove all vertices from the specified surface, false not to. Defaults to true.
clear_triangles (optional) - true to remove all triangles from the specified surface, false not to. Defaults to
true.

Description:

Removes all vertices and/or triangles from a surface.

This is useful for deleting sections of mesh. The results will be instantly visible.

After deleting a surface, you may wish to create it again but with a slightly different polygon count for dynamic
level of detail (LOD).

Example:

None.

ClearTextureFilters

Parameters:

None.

Description:

Clears the current texture filter list.

Example:

None.

ClearWorld [entities][,brushes][,textures]

Parameters:

None.
Description:

Clears a world of all entities, brushes and/or textures.

This is useful for when a game level may have finished and you wish to free everything up in preparation for
loading new entities/brushes/textures without having to free every entity/brush/texture individually.

See also: FreeEntity, FreeBrush, FreeTexture.

Example:

None.

CollisionEntity ( entity,index )

Parameters:

entity - entity handle


index - index of collision

Description:

Returns the other entity involved in a particular collision. should be in the range 1...CountCollisions( entity ),
inclusive.

Example:

None.

CollisionNX# ( entity,index )

Parameters:

entity - entity handle


index - index of collision

Description:

Returns the x component of the normal of a particular collision.

should be in the range 1...CountCollisions( entity ) inclusive.

See also: CollisionNY, CollisionNZ.

Example:

None.

CollisionNY# ( entity,index )
Parameters:

entity - entity handle


index - index of collision

Description:

Returns the y component of the normal of a particular collision.

should be in the range 1...CountCollisions( entity ) inclusive.

See also: CollisionNX, CollisionNZ.

Example:

None.

CollisionNZ# ( entity,index )

Parameters:

entity - entity handle


index - index of collision

Description:

Returns the z component of the normal of a particular collision.

should be in the range 1...CountCollisions( entity ) inclusive.

See also: CollisionNX, CollisionNY.

Example:

None.

Collisions src_type,dest_type,method,response

Parameters:

src_type - entity type to be checked for collisions.


dest_type - entity type to be collided with.

method - collision detection method.


1: sphere-to-sphere collisions
2: sphere-to-polygon collisions
3: sphere-to-box collisions

response - what the source entity does when a collision occurs.


1: stop
2: slide1 - full sliding collision
3: slide2 - prevent entities from sliding down slopes
Description:

Enables collisions between two different entity types.

Entity types are just numbers you assign to an entity using EntityType. Blitz uses then uses the entity types to
check for collisions between all the entities that have those entity types.

Blitz has many ways of checking for collisions, as denoted by the method parameter. However, collision
checking is always sphere to something. In order for Blitz to know what size a source entity is, you must first
assign an entity radius to all source entities using EntityRadius.

In the case of a collision detection method of 1 being selected (sphere-to-sphere), then the destination entities
concerned will need to have an EntityRadius assigned to them too. In the case of method being 2 being
selected (sphere-to-box), then the destination entities will need to have an EntityBox assigned to them.
Method No.2 (sphere-to-polygon) requires nothing to be assigned to the destination entities.

Not only does Blitz check for collisions, but it acts upon them when it detects them too, as denoted by the
response parameter. You have three options in this situation. You can either choose to make the source entity
stop, slide or only slide upwards.

All collision checking occurs, and collision responses are acted out, when UpdateWorld is called.

Finally, every time the Collision command is used, collision information is added to the collision information
list. This can be cleared at any time using the ClearCollisions command.

Example:

; Collisions Example
; ------------------

Graphics3D 640,480
SetBuffer BackBuffer()

; Set collision type values


type_character=1
type_scenery=2

camera=CreateCamera()
RotateEntity camera,45,0,0
PositionEntity camera,0,15,-10

light=CreateLight()
RotateEntity light,45,0,0

; Create sphere 'character'


sphere=CreateSphere( 32 )
EntityRadius sphere,1
EntityType sphere,type_character
PositionEntity sphere,0,7,0

; Create cube 'scenery'


cube=CreateCube()
EntityRadius cube,1
EntityType cube,type_scenery
PositionEntity cube,0,-5,0
EntityColor cube,127,0,0
ScaleEntity cube,10,10,10

; Create cylinder 'scenery'


cylinder=CreateCylinder( 32 )
ScaleEntity cylinder,2,2,2
EntityColor cylinder,255,0,0
EntityType cylinder,type_scenery
PositionEntity cylinder,-4,7,-4

; Create cone 'scenery'


cone=CreateCone( 32 )
ScaleEntity cone,2,2,2
EntityColor cone,255,0,0
EntityType cone,type_scenery
PositionEntity cone,4,7,-4

; Create prism 'scenery'


prism=CreateCylinder( 3 )
ScaleEntity prism,2,2,2
EntityColor prism,255,0,0
EntityType prism,type_scenery
PositionEntity prism,-4,7,4
RotateEntity prism,0,180,0

; Create pyramid 'scenery'


pyramid=CreateCone( 4 )
ScaleEntity pyramid,2,2,2
EntityColor pyramid,255,0,0
EntityType pyramid,type_scenery
RotateEntity pyramid,0,45,0
PositionEntity pyramid,4,7,4

; Set collision method and response values


method=2
response=2

method_info$="sphere-to-polygon"
response_info$="slide1"

While Not KeyDown( 1 )

x#=0
y#=0
z#=0

If KeyDown( 203 )=True Then x#=-0.1


If KeyDown( 205 )=True Then x#=0.1
If KeyDown( 208 )=True Then z#=-0.1
If KeyDown( 200 )=True Then z#=0.1

MoveEntity sphere,x#,y#,z#
MoveEntity sphere,0,-0.02,0

; Change collision method


If KeyHit(50)=True
method=method+1
If method=4 Then method=1
If method=1 Then method_info$="sphere-to-sphere"
If method=2 Then method_info$="sphere-to-polygon"
If method=3 Then method_info$="sphere-to-box"
EndIf

; Change collision response


If KeyHit(19)=True
response=response+1
If response=4 Then response=1
If response=1 Then response_info$="stop"
If response=2 Then response_info$="slide1"
If response=3 Then response_info$="slide2"
EndIf
; Enable Collions between type_character and type_scenery
Collisions type_character,type_scenery,method,response

; Perform collision checking


UpdateWorld

RenderWorld

Text 0,0,"Use cursor keys to move sphere"


Text 0,20,"Press M to change collision Method (currently: "+method_info$+")"
Text 0,40,"Press R to change collision Response (currently: "+response_info$+")"
Text 0,60,"Collisions type_character,type_scenery,"+method+","+response

Flip

Wend

End

CollisionSurface ( entity,index )

Parameters:

entity - entity handle


index - index of collision

Description:

Returns the index number of the surface belonging to the specified entity that was closest to the point of a
particular collision.

should be in the range 1...CountCollisions( entity ), inclusive.

Example:

None.

CollisionTime ( entity,index )

Parameters:

entity - entity handle


index - index of collision

Description:

Returns the time taken to calculate a particular collision.

should be in the range 1...CountCollisions( entity ) inclusive.

Example:

None.
CollisionTriangle ( entity,index )

Parameters:

entity - entity handle


index - index of collision

Description:

Returns the index number of the triangle belonging to the specified entity that was closest to the point of a
particular collision.

should be in the range 1...CountCollisions( entity ), inclusive.

Example:

None.

CollisionX# ( entity,index )

Parameters:

entity - entity handle


index - index of collision

Description:

Returns the world x coordinate of a particular collision.

should be in the range 1...CountCollisions( entity ) inclusive.

See also: CollisionY, CollisionZ.

Example:

None.

CollisionY# ( entity,index )

Parameters:

entity - entity handle


index - index of collision

Description:

Returns the world y coordinate of a particular collision.

should be in the range 1...CountCollisions( entity ) inclusive.


See also: CollisionX, CollisionZ.

Example:

None.

CollisionZ# ( entity,index )

Parameters:

entity - entity handle


index - index of collision

Description:

Returns the world z coordinate of a particular collision.

should be in the range 1...CountCollisions( entity ) inclusive.

See also: CollisionX, CollisionZ.

Example:

None.

CopyEntity ( entity[,parent] )

Parameters:

entity - entity handle


parent (optional) - parent entity of copied entity

Description:

Creates a copy of an entity and returns the copied entity's handle.

If a parent entity is specified, then the copied entity will be created at the parent entity's position. Otherwise,
it will be created at 0,0,0.

Example:

None.

CountChildren ( entity )

Parameters:

entity - entity handle


Description:

Returns the number of children of an entity.

Example:

None.

CountCollisions ( entity )

Parameters:

entity - entity handle

Description:

Returns how many collisions an entity was involved in during the last UpdateWorld.

Example:

None.

CountSurfaces ( mesh )

Parameters:

mesh - mesh handle

Description:

Returns the number of surfaces in a mesh.

Surfaces are sections of mesh. A mesh may contain only one section, or very many.

See also: GetSurface.

Example:

None.

CountTriangles ( surface )

Parameters:

surface - surface handle

Description:

Returns the number of triangles in a surface.


Example:

None.

CountVertices ( surface )

Parameters:

surface - surface handle

Description:

Returns the number of vertices in a surface.

Example:

None.

CreateBrush ( [red#][,green#][,blue#] )

Parameters:

red# (optional) - brush red value


green# (optional) - brush green value
blue# (optional) - brush blue value

Description:

Creates a brush and returns a brush handle.

The optional green, red and blue values allow you to set the colour of the brush. Values should be in the range
0-255. If omitted the values default to 255.

A brush is a collection of properties such as Colour, Alpha, Shininess, Texture etc that are all stored as part of
the brush. Then, all these properties can be applied to an entity, mesh or surface at once just by using
PaintEntity, PaintMesh or PaintSurface.

When creating your own mesh, if you wish for certain surfaces to look differently from one another, then you
will need to use brushes to paint individual surfaces. Using commands such as EntityColor, EntityAlpha will
apply the effect to all surfaces at once, which may not be what you wish to achieve.

See also: LoadBrush.

Example:

; CreateBrush Example
; -------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

cube=CreateCube()
PositionEntity cube,0,0,5

; Load texture
tex=LoadTexture("../media/b3dlogo.jpg")

; Create brush
brush=CreateBrush()

; Apply texture to brush


BrushTexture brush,tex

; And some shininess


BrushShininess brush,1

; Paint mesh with brush


PaintMesh cube,brush

While Not KeyDown( 1 )

pitch#=0
yaw#=0
roll#=0

If KeyDown( 208 )=True Then pitch#=-1


If KeyDown( 200 )=True Then pitch#=1
If KeyDown( 203 )=True Then yaw#=-1
If KeyDown( 205 )=True Then yaw#=1
If KeyDown( 45 )=True Then roll#=-1
If KeyDown( 44 )=True Then roll#=1

TurnEntity cube,pitch#,yaw#,roll#

RenderWorld
Flip

Wend

End

CreateCamera ( [parent] )

Parameters:

parent (optional) - parent entity of camera

Description:

Creates a camera entity and returns its handle.

Without at least one camera, you won't be able to see anything in your 3D world. With more than one camera,
you will be to achieve effect such as split-screen modes and rear-view mirrors.

A camera can only render to the backbuffer. If you wish to display 3D graphics on an image or a texture then
copy the contents of the backbuffer to the appropriate buffer.

The optional parent parameter allow you to specify a parent entity for the camera so that when the parent is
moved the child camera will move with it. However, this relationship is one way; applying movement
commands to the child will not affect the parent.

Specifying a parent entity will still result in the camera being created at position 0,0,0 rather than at the
parent entity's position.

Example:

; CreateCamera Example
; --------------------

Graphics3D 640,480
SetBuffer BackBuffer()

; Create camera
camera=CreateCamera()

light=CreateLight()

cone=CreateCone()
PositionEntity cone,0,0,5

While Not KeyDown( 1 )


RenderWorld
Flip
Wend

End

CreateCone ( [segments][,parent][,solid] )

Parameters:

segments (optional) - cone detail. Defaults to 8.


parent (optional) - parent entity of cone
solid (optional) - true for a cone with a base, false for a cone without a base. Defaults to true.

Description:

Creates a cone mesh/entity and returns its handle.

The cone will be centred at 0,0,0 and the base of the cone will have a radius of 1.

The segments value must be in the range 3-100 inclusive, although this is only checked in debug mode. A
common mistake is to leave debug mode off and specify the parent parameter (usually an eight digit memory
address) in the place of the segments value. As the amount of polygons used to create a cone is exponentially
proportional to the segments value, this will result in Blitz trying to create a cone with unimaginable amounts
of polygons! Depending on how unlucky you are, your computer will then crash.

Example segments values (solid=true):


4: 6 polygons - a pyramid
8: 14 polygons - bare minimum amount of polygons for a cone
16: 30 polygons - smooth cone at medium-high distances
32: 62 polygons - smooth cone at close distances

The optional parent parameter allow you to specify a parent entity for the cone so that when the parent is
moved the child cone will move with it. However, this relationship is one way; applying movement commands
to the child will not affect the parent.

Specifying a parent entity will still result in the cone being created at position 0,0,0 rather than at the parent
entity's position.

See also: CreateCube, CreateSphere, CreateCylinder.

Example:

; CreateCone Example
; ------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

; Create cone
cone=CreateCone()

PositionEntity cone,0,0,5

While Not KeyDown( 1 )


RenderWorld
Flip
Wend

End

CreateCube( [parent] )

Parameters:

parent (optional) - parent entity of cube

Description:

Creates a cube mesh/entity and returns its handle.

The cube will extend from -1,-1,-1 to +1,+1,+1.

The optional parent parameter allow you to specify a parent entity for the cube so that when the parent is
moved the child cube will move with it. However, this relationship is one way; applying movement commands
to the child will not affect the parent.

Specifying a parent entity will still result in the cube being created at position 0,0,0 rather than at the parent
entity's position.

See also: CreateSphere, CreateCylinder, CreateCone.

Example:

; CreateCube Example
; ------------------
Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

; Create cube
cube=CreateCube()

PositionEntity cube,0,0,5

While Not KeyDown( 1 )


RenderWorld
Flip
Wend

End

CreateCylinder ( [segments][,parent][,solid] )

Parameters:

segments (optional) - cylinder detail. Defaults to 8.


parent (optional) - parent entity of cylinder
solid (optional) - true for a cylinder, false for a tube. Defaults to true.

Description:

Creates a cylinder mesh/entity and returns its handle.

The cylinder will be centred at 0,0,0 and will have a radius of 1.

The segments value must be in the range 3-100 inclusive, although this is only checked in debug mode. A
common mistake is to leave debug mode off and specify the parent parameter (usually an eight digit memory
address) in the place of the segments value. As the amount of polygons used to create a cylinder is
exponentially proportional to the segments value, this will result in Blitz trying to create a cylinder with
unimaginable amounts of polygons! Depending on how unlucky you are, your computer may then crash.

Example segments values (solid=true):


3: 8 polygons - a prism
8: 28 polygons - bare minimum amount of polygons for a cylinder
16: 60 polygons - smooth cylinder at medium-high distances
32: 124 polygons - smooth cylinder at close distances

The optional parent parameter allow you to specify a parent entity for the cylinder so that when the parent is
moved the child cylinder will move with it. However, this relationship is one way; applying movement
commands to the child will not affect the parent.

Specifying a parent entity will still result in the cylinder being created at position 0,0,0 rather than at the
parent entity's position.

See also: CreateCube, CreateSphere, CreateCone.

Example:
; CreateCylinder Example
; ----------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

; Create cylinder
cylinder=CreateCylinder()

PositionEntity cylinder,0,0,5

While Not KeyDown( 1 )


RenderWorld
Flip
Wend

End

CreateLight ( [type][,parent] )

Parameters:

type (optional) - type of light


1: directional
2: point
3: spot

parent (optional) - parent entity of light

Description:

Creates a light.

Lights work by affecting the colour of all vertices within the light's range. You need at to create at least one
light if you wish to use 3D graphics otherwise everything will appear flat.

The optional type parameter allows you to specify the type of light you wish to create. A value of 1 creates a
directional light. This works similar to a sun shining on a house. All walls facing a certain direction are lit the
same. How much they are lit by depends on the angle of the light reaching them.

A value of 2 creates a point light. This works a little bit like a light bulb in a house, starting from a central
point and gradually fading outwards.

A value of 3 creates a spot light. This is a cone of light. This works similar to shining a torch in a house. It
starts with an inner angle of light, and then extends towards an outer angle of light.

The optional parent parameter allow you to specify a parent entity for the light so that when the parent is
moved the child light will move with it. However, this relationship is one way; applying movement commands
to the child will not affect the parent.

Specifying a parent entity will still result in the light being created at position 0,0,0 rather than at the parent
entity's position.

Example:
None.

CreateListener ( parent[,rolloff_factor#][,doppler_scale#][,distance_scale#] )

Parameters:

parent - parent entity of listener. A parent entity, typically a camera, must be specified to 'carry' the listener
around.
rolloff_factor# (optional) - the rate at which volume diminishes with distance. Defaults to 1.
doppler_scale# (optional) - the severity of the doppler effect. Defaults to 1.
distance_scale# (optional) - artificially scales distances. Defaults to 1.

Description:

Creates a listener entity and returns its handle. Currently, only a single listener is supported.

Example:

None.

CreateMesh ( [parent] )

Parameters:

parent (optional) - parent entity of mesh

Description:

Creates a mesh and returns a mesh handle.

Example:

None.

CreateMirror ( [parent] )

Parameters:

parent - parent entity of mirror

Description:

Creates a mirror entity and returns its handle.

A mirror entity is basically a flat, infinite 'ground'. This ground is invisible, except it reflects anything above it,
below it. It is useful for games where you want have the effect of a shiny floor showing a reflection. For a true
shiny floor efffect, try combining a mirror entity with a textured plane entity that has an alpha level of 0.5.

The optional parent parameter allow you to specify a parent entity for the mirror so that when the parent is
moved the child mirror will move with it. However, this relationship is one way; applying movement
commands to the child will not affect the parent.

Specifying a parent entity will still result in the mirror being created at position 0,0,0 rather than at the parent
entity's position.

See also: CreatePlane.

Example:

; CreateMirror Example
; --------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
PositionEntity camera,0,1,-5

light=CreateLight()
RotateEntity light,90,0,0

; Create cone
cone=CreateCone(32)
PositionEntity cone,0,2,0

; Create plane
plane=CreatePlane()
grass_tex=LoadTexture( "media/chorme-2.bmp" )
EntityTexture plane,grass_tex
EntityAlpha plane,0.5

; Create mirror
mirror=CreateMirror()

While Not KeyDown( 1 )

If KeyDown( 203 )=True Then MoveEntity cone,-0.1,0,0


If KeyDown( 205 )=True Then MoveEntity cone,0.1,0,0
If KeyDown( 208 )=True Then MoveEntity cone,0,-0.1,0
If KeyDown( 200 )=True Then MoveEntity cone,0,0.1,0
If KeyDown( 44 )=True Then MoveEntity cone,0,0,-0.1
If KeyDown( 30 )=True Then MoveEntity cone,0,0,0.1

RenderWorld

Text 0,0,"Use cursor/A/Z keys to move cone above infinite mirror"

Flip

Wend

End

CreatePivot ( [parent] )

Parameters:

parent (optional) - parent entity of pivot


Description:

Creates a pivot entity.

A pivot entity is an invisible point in 3D space that's main use is to act as a parent entity to other entities. The
pivot can then be used to control lots of entities at once, or act as new centre of rotation for other entities.

To enforce this relationship; use EntityParent or make use of the optional parent entity parameter available
with all entity load/creation commands.

Indeed, this parameter is also available with the CreatePivot command if you wish for the pivot to have a
parent entity itself.

Example:

None.

CreatePlane ( [sub_divs][,parent] )

Parameters:

sub_divs - sub divisions of plane


parent (optional) - parent entity of plane

Description:

Creates a plane entity and returns its handle.

A plane entity is basically a flat, infinite 'ground'. It is useful for outdoor games where you never want the
player to see/reach the edge of the game world.

The optional sub_divs parameter specified how sub divisions of polygons the plane will have. Although a plane
is flat and so adding extra polygons will not make it smoother, adding more polygons will allow more vertices
to be lit for more detailed lighting effects.

The optional parent parameter allow you to specify a parent entity for the plane so that when the parent is
moved the child plane will move with it. However, this relationship is one way; applying movement commands
to the child will not affect the parent.

Specifying a parent entity will still result in the plane being created at position 0,0,0 rather than at the parent
entity's position.

See also: CreateMirror.

Example:

; CreatePlane Example
; -------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
PositionEntity camera,0,1,0

light=CreateLight()
RotateEntity light,90,0,0
; Create plane
plane=CreatePlane()

grass_tex=LoadTexture( "media/mossyground.bmp" )

EntityTexture plane,grass_tex

While Not KeyDown( 1 )

If KeyDown( 205 )=True Then TurnEntity camera,0,-1,0


If KeyDown( 203 )=True Then TurnEntity camera,0,1,0
If KeyDown( 208 )=True Then MoveEntity camera,0,0,-0.05
If KeyDown( 200 )=True Then MoveEntity camera,0,0,0.05

RenderWorld

Text 0,0,"Use cursor keys to move about the infinite plane"

Flip

Wend

End

CreateSphere ( [segments][,parent] )

Parameters:

segments (optional) - sphere detail. Defaults to 8.


parent (optional) - parent entity of sphere

Description:

Creates a sphere mesh/entity and returns its handle.

The sphere will be centred at 0,0,0 and will have a radius of 1.

The segments value must be in the range 2-100 inclusive, although this is only checked in debug mode. A
common mistake is to leave debug mode off and specify the parent parameter (usually an eight digit memory
address) in the place of the segments value. As the amount of polygons used to create a sphere is
exponentially proportional to the segments value, this will result in Blitz trying to create a sphere with
unimaginable amounts of polygons! Depending on how unlucky you are, your computer will then crash.

Example segments values:


8: 224 polygons - bare minimum amount of polygons for a sphere
16: 960 polygons - smooth looking sphere at medium-high distances
32: 3968 polygons - smooth sphere at close distances

The optional parent parameter allow you to specify a parent entity for the sphere so that when the parent is
moved the child sphere will move with it. However, this relationship is one way; applying movement
commands to the child will not affect the parent.

Specifying a parent entity will still result in the sphere being created at position 0,0,0 rather than at the parent
entity's position.

See also: CreateCube, CreateCylinder, CreateCone.


Example:

; CreateSphere Example
; --------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

; Create sphere
sphere=CreateSphere()

PositionEntity sphere,0,0,5

While Not KeyDown( 1 )


RenderWorld
Flip
Wend

End

CreateSprite ( [parent] )

Parameters:

parent (optional) - parent entity of sprite

Description:

Creates a sprite entity and returns its handle.

The sprite will be positioned at 0,0,0 and extend from 1,-1 to +1,+1.

A sprite entity is a flat, square (which can be made rectangular by scaling it) 3D object.

Sprites have two real strengths. The first is that they consist of only two polygons; meaning you can use many
of them at once. This makes them ideal for particle effects and 2D-using-3D games where you want lots of
sprites on-screen at once.

Secondly, sprites can be assigned a view mode using SpriteViewMode. By default this view mode is set to 1,
which means the sprite will always face the camera. So no matter what the orientation of the camera is
relative to the sprite, you will never actually notice that they are flat; by giving them a spherical texture, you
can make them appear to look no different than a normal sphere.

The optional parent parameter allow you to specify a parent entity for the sprite so that when the parent is
moved the child sprite will move with it. However, this relationship is one way; applying movement commands
to the child will not affect the parent.

Specifying a parent entity will still result in the sprite being created at position 0,0,0 rather than at the parent
entity's position.

See also: LoadSprite.

Example:
None.

CreateSurface ( mesh[,brush] )

Parameters:

mesh - mesh handle


brush (optional) - brush handle

Description:

Creates a surface attached to a mesh and returns the surface's handle.

Surfaces are sections of mesh which are then used to attach triangles to. You must have at least one surface
per mesh in order to create a visible mesh, however you can use as many as you like. Splitting a mesh up into
lots of sections allows you to affect those sections individually, which can be a lot more useful than if all the
surfaces are combined into just one.

Example:

None.

CreateTerrain ( grid_size[,parent] )

Parameters:

grid_size - no of grid squares along each side of terrain, and must be a power of 2
parent (optional) - parent entity of terrain

Description:

Creates a terrain entity and returns its handle.

The terrain extends from 0,0,0 to grid_size,1,grid_size.

A terrain is a special type of polygon object that uses real-time level of detail (LOD) to display landscapes
which should theoretically consist of over a million polygons with only a few thousand. The way it does this is
by constantly rearranging a certain amount of polygons to display high levels of detail close to the viewer and
low levels further away.

This constant rearrangement of polygons is noticeable however, and is an well-known side-effect of all LOD
landscapes. This 'pop-in' effect can be reduced though in lots of ways, as the other terrain help files will go on
to explain.

The optional parent parameter allow you to specify a parent entity for the terrain so that when the parent is
moved the child terrain will move with it. However, this relationship is one way; applying movement
commands to the child will not affect the parent.

Specifying a parent entity will still result in the terrain being created at position 0,0,0 rather than at the parent
entity's position.

See also: LoadTerrain.

Example:
; CreateTerrain Example
; ---------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
PositionEntity camera,0,1,0

light=CreateLight()
RotateEntity light,90,0,0

; Create terrain
terrain=CreateTerrain(128)

; Texture terrain
grass_tex=LoadTexture( "media/mossyground.bmp" )
EntityTexture terrain,grass_tex

While Not KeyDown( 1 )

If KeyDown( 205 )=True Then TurnEntity camera,0,-1,0


If KeyDown( 203 )=True Then TurnEntity camera,0,1,0
If KeyDown( 208 )=True Then MoveEntity camera,0,0,-0.05
If KeyDown( 200 )=True Then MoveEntity camera,0,0,0.05

RenderWorld

Text 0,0,"Use cursor keys to move about the terrain"

Flip

Wend

End

CreateTexture ( width,height[,flags][,frames] )

Parameters:

width - width of texture


height - height of texture

flags (optional) - texture flag


1: Color
2: Alpha
4: Masked
8: Mipmapped
16: Clamp U
32: Clamp V
64: Spherical reflection map

frames (optional) - no of frames texture will have

Description:

Creates a texture and returns its handle.

Width and height are the size of the texture. Note that the actual texture size may be different from the width
and height requested, as different types of 3D hardware support different sizes of texture.

The optional flags parameter allows you to apply certain effects to the texture. Flags can be added to combine
two or more effects, eg. 3 (1+2) = texture with color and alpha maps.

Here are quick descriptions of the flags:


1: Color - color map, what you see is what you get.
2: Alpha - alpha map. If an image contains an alpha map, this will be used to make certain areas of the
texture transparent. Otherwise, the color map will be used as an alpha map. With alpha maps, the dark areas
always equal hihg-transparency, light areas equal low-transparency.
4: Masked - all areas of a texture coloured 0,0,0 will not be drawn to the screen.
8: Mipmapped - low detail versions of the texture will be used at high distance. Results in a smooth, blurred
look.
16: Clamp u - clamp u texture co-ordinates. Prevents texture wrapping.
32: Clamp v - clamp v texture co-ordiantes. Prevents texture wrapping.
64: Spherical reflection map - environment mapping, for that shiny, teapot look.

Once you have created a texture, use SetBuffer TextureBuffer to draw to it. However, to display 2D graphics
on a texture, it is usually quicker to draw to an image and then copy it to the texturebuffer, and to display 3D
graphics on a texture, your only option is to copy from the backbuffer to the texturebuffer.

See also: LoadTexture, LoadAnimTexture.

Example:

; CreateTexture Example
; ---------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

cube=CreateCube()
PositionEntity cube,0,0,5

; Create texture of size 256x256


tex=CreateTexture(256,256)

; Set buffer - texture buffer


SetBuffer TextureBuffer(tex)

; Clear texture buffer with background white color


ClsColor 255,255,255
Cls

; Draw text on texture


font=LoadFont("arial",24)
SetFont font
Color 0,0,0
Text 0,0,"This texture"
Text 0,40,"was created using" : Color 0,0,255
Text 0,80,"CreateTexture()" : Color 0,0,0
Text 0,120,"and drawn to using" : Color 0,0,255
Text 0,160,"SetBuffer TextureBuffer()"

; Texture cube with texture


EntityTexture cube,tex
; Set buffer - backbuffer
SetBuffer BackBuffer()

While Not KeyDown( 1 )

pitch#=0
yaw#=0
roll#=0

If KeyDown( 208 )=True Then pitch#=-1


If KeyDown( 200 )=True Then pitch#=1
If KeyDown( 203 )=True Then yaw#=-1
If KeyDown( 205 )=True Then yaw#=1
If KeyDown( 45 )=True Then roll#=-1
If KeyDown( 44 )=True Then roll#=1

TurnEntity cube,pitch#,yaw#,roll#

RenderWorld
Flip

Wend

End

Dither enable

Parameters:

enable - true to enable dithering, false to disable. Defaults to true.

Description:

Enables or disables hardware dithering.

Hardware dithering is useful when running games in 16-bit colour mode. Due to the fact that 16-bit mode
offers less colours than the human eye can distinguish, separate bands of colour are often noticeable on
shaded objects. However, hardware dithering will dither the entire screen to give the impression that more
colours are being used than is actually the case, and generally looks a lot better.

Due to the fact that 24-bit and 32-bit offer more colours as the human eye can distinguish, hardware dithering
is made pretty much redundant in those modes.

Example:

; Dither Example
; --------------

Graphics3D 640,480,16
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

; Rotate light so that it creates maximum shading effect on sphere


RotateEntity light,90,0,0

sphere=CreateSphere( 32 )
PositionEntity sphere,0,0,2
While Not KeyDown( 1 )

; Toggle dither enable value between true and false when spacebar is pressed
If KeyHit( 57 )=True Then enable=1-enable

; Enable/disable hardware dithering


Dither enable

RenderWorld

Text 0,0,"Press spacebar to toggle between Dither True/False"


If enable=False Then Text 0,20,"Dither False" Else Text 0,20,"Dither True"

Flip

Wend

End

EmitSound sound,entity

Parameters:

sound - sound handle


entity - entity handle

Description:

Emits a sound attached to the specified entity and returns a sound channel.

The sound must have been loaded using Load3DSound for 3D effects.

Example:

None.

EntityAlpha entity,alpha#

Parameters:

entity - entity handle


alpha# - alpha level of entity

Description:

Sets the entity alpha level of an entity.

The alpha# value should be in the range 0-1. The default entity alpha setting is 1.

The alpha level is how transparent an entity is. A value of 1 will mean the entity is non-transparent, i.e.
opaque. A value of 0 will mean the entity is completely transparent, i.e. invisible. Values between 0 and 1 will
cause varying amount of transparency accordingly, useful for imitating the look of objects such as glass and
ice.

An EntityAlpha value of 0 is especially useful as Blitz3D will not render entities with such a value, but will still
involve the entities in collision tests. This is unlike HideEntity, which doesn't involve entities in collisions.

Example:

None.

EntityAnimating ( entity )

Parameters:

entity - entity handle

Description:

Returns true if entity is currently animating.

Example:

None.

EntityAnimTime# ( entity )

Parameters:

entity - entity handle

Description:

Returns the current animation time of an entity.

Example:

None.

EntityAutoFade entity,near#,far#

Parameters:

entity - entity handle


near# - distance in front of the camera at which entity's will start being faded
far# - distance in front of the camera at which entity's will stop being faded (and will be invisible)

Description:

Enables auto fading for an entity. This will cause an entity's alpha level to be adjusted at distances between
near and far to create a 'fade-in' effect.
Example:

None.

EntityBlend entity,blend

Parameters:

entity - entity handle

blend - blend mode of entity


0: disable texture
1: alpha
2: multiply (default)
3: add

Description:

Sets the blending mode of an entity.

Example:

None.

EntityBox entity,x#,y#,z#,width#,height#,depth#

Parameters:

entity - entity handle#


x# - x position of entity's collision box
y# - y position of entity's collision box
z# - z position of entity's collision box
width# - width of entity's collision box
height# - height of entity's collision box
depth# - depth of entity's collision box

Description:

Sets the dimensions of an entity's collision box.

Example:

None.

EntityCollided ( entity,type )

Parameters:

entity - entity handle


type - type of entity
Description:

Returns true if an entity collided with any other entity of the specified type.

Example:

None.

EntityColor entity,red#,green#,blue#

Parameters:

entity - entity handle


red# - red value of entity
green# - green value of entity
blue# - blue value of entity

Description:

Sets the color of an entity.

The green, red and blue values should be in the range 0-255. The default entity color is 255,255,255.

Example:

; EntityColor Example
; -------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

cube=CreateCube()
PositionEntity cube,0,0,5

; Set initial entity color values


red#=255
green#=255
blue#=255

While Not KeyDown( 1 )

; Change red, green, blue values depending on key pressed


If KeyDown( 2 )=True And red#>0 Then red#=red#-1
If KeyDown( 3 )=True And red#<255 Then red#=red#+1
If KeyDown( 4 )=True And green#>0 Then green#=green#-1
If KeyDown( 5 )=True And green#<255 Then green#=green#+1
If KeyDown( 6 )=True And blue#>0 Then blue#=blue#-1
If KeyDown( 7 )=True And blue#<255 Then blue#=blue#+1

; Set entity color using red, green, blue values


EntityColor cube,red#,green#,blue#

TurnEntity cube,0.1,0.1,0.1
RenderWorld

Text 0,0,"Press keys 1-6 to change EntityColor red#,green#,blue# values


Text 0,20,"Entity Red: "+red#
Text 0,40,"Entity Green: "+green#
Text 0,60,"Entity Blue: "+blue#

Flip

Wend

End

EntityDistance# ( src_entity,dest_entity)

Parameters:

src_entity - source entity handle


dest_entity - destination entity handle

Description:

Returns the distance between src_entity and dest_entity.

Example:

None.

EntityFX entity,fx

Parameters:

entity - entity handle

fx -
1: full-bright
2: use vertex colors instead of brush color
4: flatshaded
8: disable fog

Description:

Sets miscellaneous effects for an entity.

Flags can be added to combine two or more effects. For example, specifying a flag of 3 (1+2) will result in a
full-bright and vertex-coloured brush.

Example:

None.
EntityInView ( entity,camera )

Parameters:

entity - entity handle


camera - camera handle

Description:

Returns true if the specified entity is visible to the specified camera.

If the entity is a mesh, its bounding box will be checked for visibility.

For all other types of entities, only their centre position will be checked.

Example:

None.

EntityName$ ( entity )

Parameters:

entity - entity handle

Description:

Returns the name of an entity. An entity's name may be set in a modelling program, or manually set using
NameEntity.

Example:

None.

EntityOrder entity,order

Parameters:

entity - entity handle


order - order that entity will be drawn in

Description:

Sets the drawing order for an entity.

An order value of 0 will mean the entity is drawn normally. A value greater than 0 will mean that entity is
drawn first, behind everything else. A value less than 0 will mean the entity is drawn last, in front of
everything else.

Setting an entity's order to non-0 also disables z-buffering for the entity, so should be only used for simple,
convex entities like skyboxes, sprites etc.
EntityOrder affects the specified entity but none of its child entities, if any exist.

Example:

None.

EntityParent entity,parent[,global]

Parameters:

entity - entity handle


parent - parent entity handle
global (optional) - true for the child entity to retain its global position and orientation. Defaults to true.

Description:

Attaches an entity to a parent.

Parent may be 0, in which case the entity will have no parent.

Example:

None.

EntityPick ( entity,range# )

Parameters:

entity - entity handle


range# - range of pick area around entity

Description:

Returns the nearest entity 'ahead' of the specified entity. An entity must have a non-zero EntityPickMode to be
pickable.

Example:

None.

EntityPickMode entity,pick_geometry,obscurer

Parameters:

entity - entity handle

pick_geometry - type of geometry used for picking:


0: Unpickable (default)
1: Sphere (EntityRadius is used)
2: Polygon
3: Box (EntityBox is used)

obscurer - true to determine that the entity 'obscures' other entities during an EntityVisible call.

Description:

Sets the pick mode for an entity.

Example:

None.

EntityPitch# ( entity[,global] )

Parameters:

entity - name of entity that will have pitch angle returned


global (optional) - true if the pitch angle returned should be relative to 0 rather than a parent entity's pitch
angle. False by default.

Description:

Returns the pitch angle of an entity.

The pitch angle is also the x angle of an entity.

Example:

; EntityPitch Example
; -------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

cone=CreateCone( 32 )
PositionEntity cone,0,0,5

While Not KeyDown( 1 )

pitch#=0
yaw#=0
roll#=0

If KeyDown( 208 )=True Then pitch#=-1


If KeyDown( 200 )=True Then pitch#=1
If KeyDown( 203 )=True Then yaw#=-1
If KeyDown( 205 )=True Then yaw#=1
If KeyDown( 45 )=True Then roll#=-1
If KeyDown( 44 )=True Then roll#=1

TurnEntity cone,pitch#,yaw#,roll#

RenderWorld
Text 0,0,"Use cursor/Z/X keys to turn cone"

; Return entity pitch angle of cone


Text 0,20,"Pitch: "+EntityPitch#( cone )

Flip

Wend

End

EntityRadius entity,radius#

Parameters:

entity - entity handle


radius# - radius of entity's collision sphere

Description:

Sets the radius of an entity's collision sphere.

An entity radius should be set for all entities involved in spherical collisions, which is all source entities (as
collisions are always sphere-to-something), and whatever destination entities are involved in sphere-to-sphere
collisions (collision method No.1).

Example:

; EntityRadius Example
; --------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

sphere=CreateSphere( 32 )
PositionEntity sphere,-2,0,5

cone=CreateCone( 32 )
EntityType cone,type_cone
PositionEntity cone,2,0,5

; Set collision type values


type_sphere=1
type_cone=2

; Set sphere radius value


sphere_radius#=1

; Set sphere and cone entity types


EntityType sphere,type_sphere
EntityType cone,type_cone

; Enable collisions between type_sphere and type_cone, with sphere->polygon method and slide response
Collisions type_sphere,type_cone,2,2

While Not KeyDown( 1 )


x#=0
y#=0
z#=0

If KeyDown( 203 )=True Then x#=-0.1


If KeyDown( 205 )=True Then x#=0.1
If KeyDown( 208 )=True Then y#=-0.1
If KeyDown( 200 )=True Then y#=0.1
If KeyDown( 44 )=True Then z#=-0.1
If KeyDown( 30 )=True Then z#=0.1

MoveEntity sphere,x#,y#,z#

; If square brackets keys pressed then change sphere radius value


If KeyDown( 26 )=True Then sphere_radius#=sphere_radius#-0.1
If KeyDown( 27 )=True Then sphere_radius#=sphere_radius#+0.1

; Set entity radius of sphere


EntityRadius sphere,sphere_radius#

; Perform collision checking


UpdateWorld

RenderWorld

Text 0,0,"Use cursor/A/Z keys to move sphere"


Text 0,20,"Press [ or ] to change EntityRadius value"
Text 0,40,"EntityRadius sphere,"+sphere_radius

Flip

Wend

End

EntityRoll# ( entity[,global] )

Parameters:

entity - name of entity that will have roll angle returned


global (optional) - true if the roll angle returned should be relative to 0 rather than a parent entity's roll angle.
False by default.

Description:

Returns the roll angle of an entity.

The roll angle is also the z angle of an entity.

Example:

; EntityRoll Example
; -------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

cone=CreateCone( 32 )
PositionEntity cone,0,0,5

While Not KeyDown( 1 )

pitch#=0
yaw#=0
roll#=0

If KeyDown( 208 )=True Then pitch#=-1


If KeyDown( 200 )=True Then pitch#=1
If KeyDown( 203 )=True Then yaw#=-1
If KeyDown( 205 )=True Then yaw#=1
If KeyDown( 45 )=True Then roll#=-1
If KeyDown( 44 )=True Then roll#=1

TurnEntity cone,pitch#,yaw#,roll#

RenderWorld

Text 0,0,"Use cursor/Z/X keys to turn cone"

; Return entity roll angle of cone


Text 0,20,"Roll: "+EntityRoll#( cone )

Flip

Wend

End

EntityShininess entity,shininess#

Parameters:

entity - entity handle


shininess# - shininess of entity

Description:

Sets the specular shininess of an entity.

The shininess# value should be in the range 0-1. The default shininess setting is 0.

Shininess is how much brighter certain areas of an object will appear to be when a light is shone directly at
them.

Setting a shininess value of 1 for a medium to high poly sphere, combined with the creation of a light shining
in the direction of it, will give it the appearance of a shiny snooker ball.

Example:

None.
EntityTexture entity,texture[,frame][,index]

Parameters:

entity - entity handle


texture - texture handle
frame (optional) - frame of texture
index (optional) - index of layer to be textured.

Description:

Sets the texture of an entity.

The optional frame parameter specifies which texture animation frame, if any exist, should be used as the
texture. Defaults to 0.

The optional index parameter specifies which texture layer the texture should use. There are four available
texture layers, 0-3 inclusive. Defaults to 0.

Example:

; EntityTexture Example
; ---------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

cube=CreateCube()
PositionEntity cube,0,0,5

; Load texture
tex=LoadTexture( "media/b3dlogo.jpg" )

; Texture entity
EntityTexture cube,tex

While Not KeyDown( 1 )

pitch#=0
yaw#=0
roll#=0

If KeyDown( 208 )=True Then pitch#=-1


If KeyDown( 200 )=True Then pitch#=1
If KeyDown( 203 )=True Then yaw#=-1
If KeyDown( 205 )=True Then yaw#=1
If KeyDown( 45 )=True Then roll#=-1
If KeyDown( 44 )=True Then roll#=1

TurnEntity cube,pitch#,yaw#,roll#

RenderWorld
Flip

Wend
End

EntityType entity,collision_type[,recursive]

Parameters:

entity - entity handle


collision_type - collision type of entity
recursive (optional) - true to apply collision type to entity's children. Defaults to false.

Description:

Sets the collision type for an entity.

Example:

None.

EntityVisible ( src_entity,dest_entity )

Parameters:

src_entity - source entity handle


dest_entity - destination entity handle

Description:

Returns true if src_entity and dest_entity can 'see' each other.

Example:

None.

EntityX# ( entity[,global] )

Parameters:

entity - name of entity that will have x-coordinate returned


global (optional) - true if the x-coordinate returned should be relative to 0,0,0 rather than a parent entity's
position. False by default.

Description:

Returns the x-coordinate of an entity.

Example:

; EntityX Example
; ---------------
Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

cone=CreateCone( 32 )
PositionEntity cone,0,0,10

While Not KeyDown( 1 )

x#=0
y#=0
z#=0

If KeyDown(203)=True Then x#=-0.1


If KeyDown(205)=True Then x#=0.1
If KeyDown(208)=True Then y#=-0.1
If KeyDown(200)=True Then y#=0.1
If KeyDown(44)=True Then z#=-0.1
If KeyDown(30)=True Then z#=0.1

MoveEntity cone,x#,y#,z#

RenderWorld

Text 0,0,"Use cursor/A/Z keys to move cone"

; Return entity x position of cone


Text 0,20,"X Position: "+EntityX#( cone )

Flip

Wend

End

EntityY# ( entity[,global] )

Parameters:

entity - name of entity that will have y-coordinate returned


global (optional) - true if the y-coordinate returned should be relative to 0,0,0 rather than a parent entity's
position. False by default.

Description:

Returns the y-coordinate of an entity.

Example:

; EntityY Example
; ---------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

cone=CreateCone( 32 )
PositionEntity cone,0,0,10

While Not KeyDown( 1 )

x#=0
y#=0
z#=0

If KeyDown(203)=True Then x#=-0.1


If KeyDown(205)=True Then x#=0.1
If KeyDown(208)=True Then y#=-0.1
If KeyDown(200)=True Then y#=0.1
If KeyDown(44)=True Then z#=-0.1
If KeyDown(30)=True Then z#=0.1

MoveEntity cone,x#,y#,z#

RenderWorld

Text 0,0,"Use cursor/A/Z keys to move cone"

; Return entity y position of cone


Text 0,20,"Y Position: "+EntityY#( cone )

Flip

Wend

End

EntityYaw# ( entity[,global] )

Parameters:

entity - name of entity that will have yaw angle returned


global (optional) - true if the yaw angle returned should be relative to 0 rather than a parent entity's yaw
angle. False by default.

Description:

Returns the yaw angle of an entity.

The yaw angle is also the y angle of an entity.

Example:

; EntityYaw Example
; -----------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

cone=CreateCone( 32 )
PositionEntity cone,0,0,5

While Not KeyDown( 1 )

pitch#=0
yaw#=0
roll#=0

If KeyDown( 208 )=True Then pitch#=-1


If KeyDown( 200 )=True Then pitch#=1
If KeyDown( 203 )=True Then yaw#=-1
If KeyDown( 205 )=True Then yaw#=1
If KeyDown( 45 )=True Then roll#=-1
If KeyDown( 44 )=True Then roll#=1

TurnEntity cone,pitch#,yaw#,roll#

RenderWorld

Text 0,0,"Use cursor/Z/X keys to turn cone"

; Return entity yaw angle of cone


Text 0,20,"Yaw: "+EntityYaw#( cone )

Flip

Wend

End

EntityZ# ( entity[,global] )

Parameters:

entity - name of entity that will have z-coordinate returned


global (optional) - true if the z-coordinate returned should be relative to 0,0,0 rather than a parent entity's
position. False by default.

Description:

Returns the z-coordinate of an entity.

Example:

; EntityZ Example
; ---------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

cone=CreateCone( 32 )
PositionEntity cone,0,0,10

While Not KeyDown( 1 )

x#=0
y#=0
z#=0

If KeyDown(203)=True Then x#=-0.1


If KeyDown(205)=True Then x#=0.1
If KeyDown(208)=True Then y#=-0.1
If KeyDown(200)=True Then y#=0.1
If KeyDown(44)=True Then z#=-0.1
If KeyDown(30)=True Then z#=0.1

MoveEntity cone,x#,y#,z#

RenderWorld

Text 0,0,"Use cursor/A/Z keys to move cone"

; Return entity z position of cone


Text 0,20,"Z Position: "+EntityZ#( cone )

Flip

Wend

End

FindChild ( entity,child_name$ )

Parameters:

entity - entity handle


child_name$ - child name to find within entity

Description:

Returns the first child of the specified entity with name matching child_name$.

Example:

None.

FindSurface ( mesh,brush)

Parameters:

mesh - mesh handle


brush - brush handle

Description:

Attempts to find a surface attached to the specified mesh and created with the specified brush. Returns the
surface handle if found or 0 if not.

See also: CountSurfaces, GetSurface.


Example:

None.

FitMesh mesh,x#,y#,z#,width#,height#,depth#[,uniform]

Parameters:

mesh - mesh handle


x# - x position of mesh
y# - y position of mesh
z# - z position of mesh
width# - width of mesh
height# - height of mesh
depth# - depth of mesh
uniform (optional) - if true, the mesh will be scaled by the same amounts in x, y and z, so will not be
distorted. Defaults to false.

Description:

Scales and translates all vertices of a mesh so that the mesh occupies the specified box.

Example:

None.

FlipMesh mesh

Parameters:

mesh - mesh handle

Description:

Flips all the triangles in a mesh.

This is useful for a couple of reasons. Firstly though, it is important to understand a little bit of the theory
behind 3D graphics. A 3D triangle is represented by three points; only when these points are presented to the
viewer in a clockwise-fashion is the triangle visible. So really, triangles only have one side.

Normally, for example in the case of a sphere, a model's triangles face the inside of the model, so it doesn't
matter that you can't see them. However, what about if you wanted to use the sphere as a huge sky for your
world, i.e. so you only needed to see the inside? In this case you would just use FlipMesh.

Another use for FlipMesh is to make objects two-sided, so you can see them from the inside and outside if you
can't already. In this case, you can copy the original mesh using CopyEntity, specifying the original mesh as
the parent, and flip it using FlipMesh. You will now have two meshes occupying the same space - this will
make it double-sided, but beware, it will also double the polygon count!

The above technique is worth trying when an external modelling program has exported a model in such a way
that some of the triangles appear to be missing.

Example:
; FlipMesh Example
; ----------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

; Create sphere
sphere=CreateSphere()

; Scale sphere
ScaleEntity sphere,100,100,100

; Texture sphere with sky texture


sky_tex=LoadTexture("../media/sky.bmp")
EntityTexture sphere,sky_tex

; Flip mesh so we can see the inside of it


FlipMesh sphere

Color 0,0,0

While Not KeyDown( 1 )


RenderWorld
Text 0,0,"You are viewing a flipped sphere mesh - makes a great sky!"
Flip
Wend

End

FreeBrush brush

Parameters:

brush - brush handle

Description:

Frees up a brush.

Example:

None.

FreeEntity entity

Parameters:

entity - entity handle

Description:

Frees up an entity.
Example:

None.

FreeTexture texture

Parameters:

texture - texture handle

Description:

Frees up a texture. This will allow the memory that it occupied before to be used for other purposes.

Freeing a texture means you will not be able to use it again; however, entities already textured with it will not
lose the texture.

Example:

; FreeTexture Example
; -------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

cube=CreateCube()
PositionEntity cube,0,0,5

; Load texture
tex=LoadTexture("../media/b3dlogo.jpg")

; Texture cube with texture


EntityTexture cube,tex

While Not KeyDown( 1 )

; If spacebar pressed then free texture


If KeyHit( 57 )=True Then FreeTexture tex

pitch#=0
yaw#=0
roll#=0

If KeyDown( 208 )=True Then pitch#=-1


If KeyDown( 200 )=True Then pitch#=1
If KeyDown( 203 )=True Then yaw#=-1
If KeyDown( 205 )=True Then yaw#=1
If KeyDown( 45 )=True Then roll#=-1
If KeyDown( 44 )=True Then roll#=1

TurnEntity cube,pitch#,yaw#,roll#

RenderWorld
Text 0,0,"Press spacebar to free texture"
Text 0,20,"As you can see this will not effect already textured entities"
Flip

Wend

End

GetChild (entity,index)

Parameters:

entity - entity handle


index - index of child entity. Should be in the range 1...CountChildren( entity ) inclusive.

Description:

Returns a child of an entity.

Example:

None.

GetEntityType ( entity )

Parameters:

entity - entity handle

Description:

Returns the collision type of an entity.

Example:

None.

GetParent ( entity )

Parameters:

entity - entity handle

Description:

Returns an entity's parent.

Example:

None.
GetSurface ( mesh, index )

Parameters:

mesh - mesh handle


index - index of surface

Description:

Returns the handle of the surface attached to the specified mesh and with the specified index number.

should be in the range 1...CountSurfaces( mesh ), inclusive.

You need to 'get a surface', i.e. get its handle, in order to be able to then use that particular surface with other
commands.

See also: CountSurfaces.

Example:

None.

GfxDriver3D

Parameters:

driver -- display driver number to check, from 1 to CountGfxDrivers ()

Description:

GfxDriver3D returns True if the specified graphics driver is 3D-capable.

GfxDriver3D is generally used after obtaining a list of available graphics drivers from a user's system via
CountGfxDrivers (). You apply this to each driver in turn (or a selected driver) to see if it is 3D-capable. If this
returns False, the driver can not perform 3D operations.

On systems with more than one display driver, you can use this to check each for 3D capability before
choosing one via the SetGfxDriver command.

Example:

For a = 1 To CountGfxDrivers ()
If GfxDriver3D (a)
Print GfxDriverName (a) + " is 3D-capable"
Else
Print GfxDriverName (a) + " is NOT 3D-capable"
EndIf
Delay 100
Next

GfxMode3D
Parameters:

mode - graphics mode number from 1 - CountGfxModes ()

Description:

GfxMode3D returns True if the specified graphics mode is 3D-capable.

GfxMode3D is generally used after obtaining a list of available display modes from a user's system via
CountGfxModes (). You apply this to each mode in turn (or a selected mode) to see if you can enter 3D mode.
If this returns False, calling Graphics3D () with this mode's details will fail!

If you don't wish to perform this check, the only Graphics3D call you can make with a guarantee of working on
99% of 3D graphics cards is 'Graphics3D 640, 480'. However, see GfxModeExists' gfx3d parameter for another
method of performing this check.

Example:

For a = 1 To CountGfxModes ()
If GfxMode3D (a)
Print "Mode " + a + " is 3D-capable"
Else
Print "Mode " + a + " is NOT 3D-capable"
EndIf
Delay 100
Next

GfxModeExists

Parameters:

width - the width of the display mode you want to check for
height - the height of the display mode you want to check for
depth - the depth of the display mode you want to check for
gfx3d - optional parameter to check if mode is 3D-capable (defaults to 0 for backwards compatibility)

Description:

GfxModeExists is a sadly under-used command which will allow you to check if a given display mode exists on
your player's graphics card before calling the Graphics or Graphics3D commands. Note that supplying the
optional gfx3d parameter will also check if the specified mode is 3D-capable.

GfxModeExists will return True if a display mode fitting the given parameters is available, and False if the
specified mode is not available. If it returns False, a game should either use a different mode or exit politely
(eg. RuntimeError "I have been lazy and hard-coded my game to use a particular display mode which your
system doesn't have. I should really use CountGfxModes and GfxModeWidth/Height/Depth to find out what
your system can do. Oh, well, this saved 10 minutes out of my life!"... note subtle sarcastic hint!).

Example:

If GfxModeExists (2500, 2500, 64)


Graphics 2500, 2500, 64
Else
RuntimeError "Domestic PC display hardware isn't yet capable of silly resolutions like 2500 x 2500 x 64-bit!"
EndIf
Graphics3D

Parameters:

width - width of screen resolution


height - height of screen resolution
depth (optional) - colour depth of screen. Defaults to highest colour depth available.

mode (optional) - mode of display. Defaults to 0.


0: windowed (if possible) in debug mode, fullscreen in non-debug mode
1: fullscreen always
2. windowed always
3: windowed/scaled always

Description:

Sets 3D Graphics mode. This command must be executed before any other 3D command, otherwise programs
will return an error.

Width and height set the resolution of the screen and common values are 640,480 and 800,600. The
resolution must be compatible with the 3D card and monitor being used.

Depth sets the colour mode of the screen. If this value is omitted or set to 0, then the highest available colour
depth available will be used. Other values usually available are 16, 24 and 32. 16-bit colour mode displays the
least amount of colours, 65536. 24-bit and 32-bit colour modes display over 16 million colours and as a result
offer a better quality picture, although may result in slower programs than 16-bit.

Example:

; Graphics3D Example
; ------------------

; Sets 3D graphics mode


Graphics3D 640,480,16,0
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

cone=CreateCone( 32 )
PositionEntity cone,0,0,5

While Not KeyDown( 1 )


RenderWorld
Flip
Wend

End

HandleSprite sprite,x_handle#,y_handle#

Parameters:

sprite - sprite handle. Not to be confused with HandleSprite - ie. the handle used to position the sprite, rather
than the sprite's actual handle

Description:
Sets a sprite handle. Defaults to 0,0,0.

A sprite extends from 1,-1 to +1,+1.

Example:

None.

HideEntity entity

Parameters:

entity - entity handle

Description:

Hides an entity, so that it is no longer visible, and is no longer involved in collisions.

The main purpose of hide entity is to allow you to create entities at the beginning of a program, hide them,
then copy them and show as necessary in the main game. This is more efficient than creating entities mid-
game.

If you wish to hide an entity so that it is no longer visible but still involved in collisions, then use EntityAlpha 0
instead. This will make an entity completely transparent.

HideEntity affects the specified entity and all of its child entities, if any exist.

Example:

None.

HWMultiTex enable

Parameters:

enable - true to enable hardware multitexturing, false to disable. Defaults to true.

Description:

Enables or disables hardware multitexturing.

Multitexturing is a technique used to display more than one texture on an object at once. Sometimes, 3D
hardware has built-in support for this, so that using two textures or more per object will not be any slower
than using just one.

However, some cards have problems dealing with hardware multitexturing, and for these situations you have
the option of disabling it.

When hardware texturing isn't being used, Blitz3D will use its own software technique, which involves
duplicating objects that just have one texture each.

Example:
None.

LightColor light,red#,green#,blue#

Parameters:

light - light handle


red# - red value of light
green# - green value of light
blue# - blue value of light

Description:

Sets the color of a light.

An r,g,b value of 255,255,255 will brighten anything the light shines on.

An r,g,b value of 0,0,0 will have no affect on anything it shines on.

An r,g,b value of -255,-255,-255 will darken anything it shines on. This is known as 'negative lighting', and is
useful for shadow effects.

Example:

None.

LightConeAngles light,inner_angle#,outer_angle#

Parameters:

light - light handle


inner_angle# - inner angle of cone
outer_angle# - outer angle of cone

Description:

Sets the 'cone' angle for a spotlight.

The default light cone angles setting is 0,90.

Example:

None.

LightMesh mesh,red#,green#,blue#[,range#][,light_x#][,light_y#][,light_z#]

Parameters:

mesh - mesh handle


red# - mesh red value
green# - mesh green value
blue# - mesh blue value
range# (optional) - light range
light_x# (optional) - light x position
light_y# (optional) - light y position
light_z# (optional) - light z position

Description:

Performs a 'fake' lighting operation on a mesh.

Example:

None.

LightRange light,range#

Parameters:

light - light handle


range - range of light

Description:

Sets the range of a light.

The range of a light is how far it reaches. Everything outside the range of the light will not be affected by it.

The value is very approximate, and should be experimented with for best results.

Example:

None.

LinePick ( x#,y#,z#,dx#,dy#,dz#[,radius#] )

Parameters:

x# - x coordinate of start of line pick


y# - y coordinate of start of line pick
z# - z coordinate of start of line pick
dx# - distance x of line pick
dy# - distance y of line pick
dz# - distance z of line pick
radius (optional) - radius of line pick

Description:

Returns the first entity between x,y,z to x+dx,y+dy,z+dz.

Example:

None.
Load3DSound ( file$ )

Parameters:

file$ - filename of sound file to be loaded and used as 3D sound

Description:

Loads a sound and returns its handle for use with EmitSound.

Example:

None.

LoadAnimMesh ( file$[,parent] )

Parameters:

file$ - mesh filename


parent - parent entity of mesh

Description:

Loads a mesh from a .x or .3ds file and returns a mesh handle.

Any hierarchy and animation information in the file is retained (if present in the file!).

Example:

None.

LoadAnimSeq ( entity,filename$ )

Parameters:

entity - entity handle


filename$ - filename of animated 3D object

Description:

Appends an animation sequence from a file to an entity.

Returns the animation sequence number added.

Example:

None.
LoadAnimTexture (
file$,flags,frame_width,frame_height,first_frame,frame_count )

Parameters:

file$ - name of file with animation frames laid out in left-right, top-to-bottom order

flags - texture flag:


1: Color
2: Alpha
4: Masked
8: Mipmapped
16: Clamp U
32: Clamp V
64: Spherical reflection map

frame_width - width of each animation frame


frame_height - height of each animation frame
first_frame - the first frame to be used as an animation frame.
frame_count - the amount of frames to be used

Description:

Loads a sequence of animation frames into a texture.

See also: CreateTexture, LoadTexture.

Example:

None.

LoadBrush ( file$[,flags][,u_scale][,v_scale]

Parameters:

file$ - filename
flags - brush flags

flags (optional) - flags can be added to combine effects:


1: Color
2: Alpha
4: Masked
8: Mipmapped
16: Clamp U
32: Clamp V
64: Spherical reflection map

u_scale - brush u_scale


v_scale - brush v_scale

Description:

Creates a brush, assigns a texture to it, and returns a brush handle.

Example:
None.

LoaderMatrix file_extension$,xx#,xy#,xz#,yx#,yy#,yz#,zx#,zy#,zz#

Parameters:

file extension$ - file extension of 3d file, e.g. ".x",".3ds"


xx# - 1,1 element of 3x3 matrix
xy# - 2,1 element of 3x3 matrix
xz# - 3,1 element of 3x3 matrix
yx# - 1,2 element of 3x3 matrix
yy# - 2,2 element of 3x3 matrix
yz# - 3,2 element of 3x3 matrix
zx# - 1,3 element of 3x3 matrix
zy# - 2,3 element of 3x3 matrix
zz# - 3,3 element of 3x3 matrix

Description:

Sets a matrix for 3d files loaded with the specified file extension.

This can be used to change coordinate systems when loading.

By default, the following loader matrices are used:

LoaderMatrix "x",1,0,0,0,1,0,0,0,1 ; no change in coord system


LoaderMatrix "3ds",1,0,0,0,0,1,0,1,0 ; swap y/z axis'

You can use LoaderMatrix to flip meshes/animations if necessary, eg:

LoaderMatrix "x",-1,0,0,0,1,0,0,0,1 ; flip x-cords for ".x" files


LoaderMatrix "3ds",-1,0,0,0,0,-1,0,1,0 ; swap y/z, negate x/z for ".3ds" files

Example:

None.

LoadMD2 ( md2_file$[,parent] )

Parameters:

md2_file$ - filename of md2


parent (optional) - parent entity of md2

Description:

Loads an md2 entity and returns its handle.

An md2's texture has to be loaded and applied to the md2 separately, otherwise the md2 will appear
untextured.

Md2's have their own set of animation commands, and will not work with normal animation commands.

The optional parent parameter allow you to specify a parent entity for the md2 so that when the parent is
moved the child md2 will move with it. However, this relationship is one way; applying movement commands
to the child will not affect the parent.

Specifying a parent entity will still result in the md2 being created at position 0,0,0 rather than at the parent
entity's position.

Example:

; LoadMD2 Example
; ---------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

; Load md2
gargoyle=LoadMD2( "media/gargoyle/gargoyle.md2" )

; Load md2 texture


garg_tex=LoadTexture( "media/gargoyle/gargoyle.bmp" )

; Apply md2 texture to md2


EntityTexture gargoyle,garg_tex

PositionEntity gargoyle,0,-45,100
RotateEntity gargoyle,0,180,0

While Not KeyDown( 1 )


RenderWorld
Flip
Wend

End

LoadMesh ( file$[,parent] )

Parameters:

file$ - filename of mesh


parent (optional) - parent entity of mesh

Description:

Loads a mesh from a .x or .3ds file and returns the mesh's handle.

Any hierarchy and animation information in the file will be ignored. Use LoadAnimMesh to maintain hierarchy
and animation information.

The optional parent parameter allow you to specify a parent entity for the mesh so that when the parent is
moved the child mesh will move with it. However, this relationship is one way; applying movement commands
to the child will not affect the parent.

Specifying a parent entity will still result in the mesh being created at position 0,0,0 rather than at the parent
entity's position.

See also: LoadAnimMesh.

Example:

; LoadMesh Example
; ----------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

; Load mesh
drum=LoadMesh("media/oil-drum/oildrum.3ds")

PositionEntity drum,0,0,MeshDepth(drum)*2

While Not KeyDown( 1 )


RenderWorld
Flip
Wend

End

LoadSprite ( tex_file$[,tex_flag][,parent] )

Parameters:

text_file$ - filename of image file to be used as sprite

tex_flag (optional) - texture flag:


1: Color
2: Alpha
4: Masked
8: Mipmapped
16: Clamp U
32: Clamp V
64: Spherical reflection map

parent - parent of entity

Description:

Creates a sprite entity, and assigns a texture to it.

See also: CreateSprite, SpriteViewMode.

Example:

None.
LoadTerrain ( file$[,parent] )

Parameters:

file$ - filename of image file to be used as height map


parent (optional) - parent entity of terrain

Description:

Loads a terrain from an image file and returns the terrain's handle. The image's red channel is used to
determine heights. Terrain is initially the same width and depth as the image, and 1 high.

Tips on generating nice terrain:

* Smooth or blur the height map


* Reduce the y scale of the terrain
* Increase the x/z scale of the terrain
* Reduce the camera range

When texturing an entity, a texture with a scale of 1,1,1 (default) will be the same size as one of the terrain's
grid squares. A texture that is scaled to the same size as the size of the bitmap used to load it or the no. of
grid square used to create it, will be the same size as the terrain.

The optional parent parameter allow you to specify a parent entity for the terrain so that when the parent is
moved the child terrain will move with it. However, this relationship is one way; applying movement
commands to the child will not affect the parent.

Specifying a parent entity will still result in the terrain being created at position 0,0,0 rather than at the parent
entity's position.

See also: CreateTerrain.

Example:

SetBuffer BackBuffer()

camera=CreateCamera()
PositionEntity camera,1,1,1

light=CreateLight()
RotateEntity light,90,0,0

; Load terrain
terrain=LoadTerrain( "media/height_map.bmp" )

; Set terrain detail, enable vertex morphing


TerrainDetail terrain,4000,True

; Scale terrain
ScaleEntity terrain,1,50,1

; Texture terrain
grass_tex=LoadTexture( "media/mossyground.bmp" )
EntityTexture terrain,grass_tex,0,1

While Not KeyDown( 1 )

If KeyDown( 203 )=True Then x#=x#-0.1


If KeyDown( 205 )=True Then x#=x#+0.1
If KeyDown( 208 )=True Then y#=y#-0.1
If KeyDown( 200 )=True Then y#=y#+0.1
If KeyDown( 44 )=True Then z#=z#-0.1
If KeyDown( 30 )=True Then z#=z#+0.1

If KeyDown( 205 )=True Then TurnEntity camera,0,-1,0


If KeyDown( 203 )=True Then TurnEntity camera,0,1,0
If KeyDown( 208 )=True Then MoveEntity camera,0,0,-0.1
If KeyDown( 200 )=True Then MoveEntity camera,0,0,0.1

x#=EntityX(camera)
y#=EntityY(camera)
z#=EntityZ(camera)

terra_y#=TerrainY(terrain,x#,y#,z#)+5

PositionEntity camera,x#,terra_y#,z#

RenderWorld

Text 0,0,"Use cursor keys to move about the terrain"

Flip

Wend

End

LoadTexture ( file$[,flags] )

Parameters:

file$ - filename of image file to be used as texture

flags (optional) - texture flag:


1: Color
2: Alpha
4: Masked
8: Mipmapped
16: Clamp U
32: Clamp V
64: Spherical reflection map

Description:

Load a texture from an image file and returns the texture's handle.

The optional flags parameter allows you to apply certain effects to the texture. Flags can be added to combine
two or more effects, e.g. 3 (1+2) = texture with colour and alpha maps.

Here are quick descriptions of the flags:


1: Color - colour map, what you see is what you get.
2: Alpha - alpha map. If an image contains an alpha map, this will be used to make certain areas of the
texture transparent. Otherwise, the colour map will be used as an alpha map. With alpha maps, the dark areas
always equal hihg-transparency, light areas equal low-transparency.
4: Masked - all areas of a texture coloured 0,0,0 will not be drawn to the screen.
8: Mipmapped - low detail versions of the texture will be used at high distance. Results in a smooth, blurred
look.
16: Clamp u - clamp u texture co-ordinates. Prevents texture wrapping.
32: Clamp v - clamp v texture co-ordinates. Prevents texture wrapping.
64: Spherical reflection map - environment mapping, for that shiny, teapot look.
Something to consider when applying texture flags to loaded textures is that the texture may have already
had certain flags applied to it via the TextureFilter command. The default for the TextureFilter command is 9
(1+8), which is a coloured, mipmapped texture. This cannot be overridden via the flags parameter of
LoadTexture command - if you wish for the filters to be removed you will need to use the ClearTextureFilters
command.

See also: CreateTexture, LoadAnimTexture.

Example:

; LoadTexture Example
; -------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

cube=CreateCube()
PositionEntity cube,0,0,5

; Load texture
tex=LoadTexture("../media/b3dlogo.jpg")

; Texture cube with texture


EntityTexture cube,tex

While Not KeyDown( 1 )

pitch#=0
yaw#=0
roll#=0

If KeyDown( 208 )=True Then pitch#=-1


If KeyDown( 200 )=True Then pitch#=1
If KeyDown( 203 )=True Then yaw#=-1
If KeyDown( 205 )=True Then yaw#=1
If KeyDown( 45 )=True Then roll#=-1
If KeyDown( 44 )=True Then roll#=1

TurnEntity cube,pitch#,yaw#,roll#

RenderWorld
Flip

Wend

End

Command Reference

There is a help page for every command. These can be accessed by clicking the appropriate
command name in the left-hand frame. Many commands have their own example too.
If you spot any mistakes in the documentation then please post a quick description of the error on
the Bug Reports forum at www.blitzbasic.co.nz. This will allow the authors of the documentation to
correct the error in time for the next release of the docs.

Docs Version: 1.62

MD2Animating ( md2 )

Parameters:

md2 - md2 handle

Description:

Returns 1 (true) if md2 is currently animating, 0 (false) if not.

Example:

; MD2Animating Example
; --------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

; Load md2
gargoyle=LoadMD2( "media/gargoyle/gargoyle.md2")

; Load md2 texture


garg_tex=LoadTexture( "media/gargoyle/gargoyle.bmp" )

; Apply md2 texture to md2


EntityTexture gargoyle,garg_tex

PositionEntity gargoyle,0,-45,100
RotateEntity gargoyle,0,180,0

While Not KeyDown( 1 )

; Toggle animation stop/start when spacebar pressed


If KeyHit( 57 )=True start=1-start : AnimateMD2 gargoyle,start,0.1,32,46

UpdateWorld
RenderWorld

Text 0,0,"Press spacebar to stop/start md2 animation"

; Output current md2 animation status to screen


Text 0,20,"MD2Animating: "+MD2Animating( gargoyle )

Flip

Wend

End
MD2AnimLength ( md2 )

Parameters:

md2 - md2 handle

Description:

Returns the animation length of an md2 model.

The animation length is the total amount of animation frames that consist within the md2 file.

Example:

; MD2AnimLength Example
; ---------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

; Load md2
gargoyle=LoadMD2( "media/gargoyle/gargoyle.md2")

; Load md2 texture


garg_tex=LoadTexture( "media/gargoyle/gargoyle.bmp" )

; Apply md2 texture to md2


EntityTexture gargoyle,garg_tex

PositionEntity gargoyle,0,-45,100
RotateEntity gargoyle,0,180,0

While Not KeyDown( 1 )

RenderWorld

; Output animation length to screen


Text 0,0,"MD2AnimLength: "+MD2AnimLength( gargoyle )

Flip

Wend

End

MD2AnimTime ( md2 )

Parameters:

md2 - md2 handle

Description:
Returns the animation time of an md2 model.

The animation time is the exact moment that the md2 is at with regards its frames of animation. For example,
if the md2 at a certain moment in time is moving between the third and fourth frames, then MD2AnimTime
will return a number in the region 3-4.

Example:

; MD2AnimTime Example
; -------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

; Load md2
gargoyle=LoadMD2( "media/gargoyle/gargoyle.md2")

; Load md2 texture


garg_tex=LoadTexture( "media/gargoyle/gargoyle.bmp" )

; Apply md2 texture to md2


EntityTexture gargoyle,garg_tex

; Animate md2
AnimateMD2 gargoyle,1,0.1,32,46

PositionEntity gargoyle,0,-45,100
RotateEntity gargoyle,0,180,0

While Not KeyDown( 1 )

UpdateWorld
RenderWorld

; Output current animation frame to screen


Text 0,0,"MD2AnimTime: "+MD2AnimTime( gargoyle )

Flip

Wend

End

MeshDepth# (mesh)

Parameters:

mesh - mesh handle

Description:

Returns the depth of a mesh.

See also: MeshWidth, MeshHeight.


Example:

None.

MeshesIntersect (mesh_a,mesh_b )

Parameters:

mesh_a - mesh_a handle


mesh_b - mesh_b handle

Description:

Returns true if the specified meshes are currently intersecting.

This is a fairly slow routine - use with discretion...

This command is currently the only polygon->polygon collision checking routine available in Blitz3D.

Example:

; MeshesIntersect Example
; -----------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

drum=LoadMesh("media/oil-drum/oildrum.3ds")
PositionEntity drum,-20,0,100

crate=LoadMesh("media/wood-crate/wcrate1.3ds")
PositionEntity crate,20,0,100

While Not KeyDown( 1 )

TurnEntity drum,1,1,1
TurnEntity crate,-1,-1,-1

RenderWorld

; Test to see if drum and crate meshes are intersecting; if so then display message to confirm this
If MeshesIntersect(drum,crate)=True Then Text 0,0,"Meshes are intersecting!"

Flip

Wend

End

MeshHeight# (mesh )
Parameters:

mesh - mesh handle

Description:

Returns the height of a mesh.

See also: MeshWidth, MeshDepth.

Example:

None.

MeshWidth# (mesh)

Parameters:

mesh - mesh handle

Description:

Returns the width of a mesh.

See also: MeshHeight, MeshDepth.

Example:

None.

ModifyTerrain terrain,grid_x,grid_z,height#[,realtime]

Parameters:

terrain - terrain handle


grid_x - grid x coordinate of terrain
grid_y - grid y coordinate of terrain
height# - height of point on terrain. Should be in the range 0-1.
realtime (optional) - true to modify terrain immediately. False to modify terrain when RenderWorld in next
called. Defaults to false.

Description:

Sets the height of a point on a terrain.

Example:

None.

MoveEntity entity,x#,y#,z#
Parameters:

entity - name of entity to be moved


x# - x amount that entity will be moved by
y# - y amount that entity will be moved by
z# - z amount that entity will be moved by

Description:

Moves an entity relative to its current position and orientation.

What this means is that an entity will move in whatever direction it is facing. So for example if you have an
game character is upright when first loaded into Blitz3D and it remains upright (i.e. turns left or right only),
then moving it by a z amount will always see it move forward or backward, moving it by a y amount will
always see it move up or down, and moving it by an x amount will always see it strafe.

See also: TranslateEntity, PositionEntity.

Example:

; MoveEntity Example
; ------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

cone=CreateCone( 32 )

; Move cone in front of camera, so we can see it to begin with


MoveEntity cone,0,0,10

While Not KeyDown( 1 )

; Reset movement values - otherwise, the cone will not stop!


x#=0
y#=0
z#=0

; Change rotation values depending on the key pressed


If KeyDown( 203 )=True Then x#=-0.1
If KeyDown( 205 )=True Then x#=0.1
If KeyDown( 208 )=True Then y#=-0.1
If KeyDown( 200 )=True Then y#=0.1
If KeyDown( 44 )=True Then z#=-0.1
If KeyDown( 30 )=True Then z#=0.1

; Move cone using movement values


MoveEntity cone,x#,y#,z#

; If spacebar pressed then rotate cone by random amount


If KeyHit( 57 )=True Then RotateEntity cone,Rnd( 0,360 ),Rnd( 0,360 ),Rnd( 0,360 )

RenderWorld

Text 0,0,"Use cursor/A/Z keys to move cone, spacebar to rotate cone by random amount"
Text 0,20,"X Movement: "+x#
Text 0,40,"Y Movement: "+y#
Text 0,60,"Z Movement: "+z#
Flip

Wend

End

NameEntity entity,name$

Parameters:

entity - entity handle


name$ - name of entity

Description:

Sets an entity's name.

Example:

None.

PaintEntity entity,brush

Parameters:

entity - entity handle


brush - brush handle

Description:

Paints a entity with a brush.

The reason for using PaintEntity to apply specific properties to a entity using a brush rather than just using
EntityTexture, EntityColor, EntityShininess etc, is that you can pre-define one brush, and then paint entities
over and over again using just the one command rather than lots of separate ones.

Example:

None.

PaintMesh mesh,brush

Parameters:

mesh - mesh handle


brush - brush handle

Description:

Paints a mesh with a brush.


This has the effect of instantly altering the visible appearance of the mesh, assuming the brush's properties
are different to what was was applied to the surface before.

The reason for using PaintMesh to apply specific properties to a mesh using a brush rather than just using
EntityTexture, EntityColor, EntityShininess etc, is that you can pre-define one brush, and then paint meshes
over and over again using just the one command rather than lots of separate ones.

See also: PaintEntity, PaintSurface.

Example:

; PaintMesh Example
; -----------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

cube=CreateCube()
PositionEntity cube,0,0,5

; Load texture
tex=LoadTexture("../media/b3dlogo.jpg")

; Create brush
brush=CreateBrush()

; Apply texture to brush


BrushTexture brush,tex

; And some other effects


BrushColor brush,0,0,255
BrushShininess brush,1

; Paint mesh with brush


PaintMesh cube,brush

While Not KeyDown( 1 )

pitch#=0
yaw#=0
roll#=0

If KeyDown( 208 )=True Then pitch#=-1


If KeyDown( 200 )=True Then pitch#=1
If KeyDown( 203 )=True Then yaw#=-1
If KeyDown( 205 )=True Then yaw#=1
If KeyDown( 45 )=True Then roll#=-1
If KeyDown( 44 )=True Then roll#=1

TurnEntity cube,pitch#,yaw#,roll#

RenderWorld
Flip

Wend
End

PaintSurface surface,brush

Parameters:

surface - surface handle


brush - brush handle

Description:

Paints a surface with a brush.

This has the effect of instantly altering the visible appearance of that particular surface, i.e. section of mesh,
assuming the brush's properties are different to what was was applied to the surface before.

See also: PaintEntity, PaintMesh.

Example:

None.

PickedEntity ( )

Parameters:

None.

Description:

Returns the entity ‘picked’ by the most recently executed Pick command. This might have been CameraPick,
EntityPick or LinePick.

Returns 0 if no entity was picked.

Example:

None.

PickedNX ( )

Parameters:

None.

Description:

Returns the x component of the normal of the most recently executed Pick command. This might have been
CameraPick, EntityPick or LinePick.
Example:

None.

PickedNY ( )

Parameters:

None.

Description:

Returns the y component of the normal of the most recently executed Pick command. This might have been
CameraPick, EntityPick or LinePick.

Example:

None.

PickedNZ ( )

Parameters:

None.

Description:

Returns the z component of the normal of the most recently executed Pick command. This might have been
CameraPick, EntityPick or LinePick.

Example:

None.

PickedSurface ( )

Parameters:

None.

Description:

Returns the index number of the surface that was ‘picked’ by the most recently executed Pick command. This
might have been CameraPick, EntityPick or LinePick.

Example:

None.
PickedTime ( )

Parameters:

None.

Description:

Returns the time taken to calculate the most recently executed Pick command. This might have been
CameraPick, EntityPick or LinePick.

Example:

None.

PickedTriangle ( )

Parameters:

None.

Description:

Returns the index number of the triangle that was ‘picked’ by the most recently executed Pick command. This
might have been CameraPick, EntityPick or LinePick.

Example:

None.

PickedX# ( )

Parameters:

None.

Description:

Returns the world x coordinate of the most recently executed Pick command. This might have been
CameraPick, EntityPick or LinePick.

The coordinate represents the exact point of where something was picked.

See also: PickedY, PickedZ.

Example:

None.
PickedY# ( )

Parameters:

None.

Description:

Returns the world y coordinate of the most recently executed Pick command. This might have been
CameraPick, EntityPick or LinePick.

The coordinate represents the exact point of where something was picked.

See also: PickedX, PickedZ.

Example:

None.

PickedZ# ( )

Parameters:

None.

Description:

Returns the world z coordinate of the most recently executed Pick command. This might have been
CameraPick, EntityPick or LinePick.

The coordinate represents the exact point of where something was picked.

See also: PickedX, PickedY.

Example:

None.

PointEntity entity,target[,roll#]

Parameters:

entity - entity handle


target - target entity handle
roll# (optional) - roll angle of entity

Description:

Points one entity at another.

The optional roll parameter allows you to specify a roll angle as pointing an entity only sets pitch and yaw
angles.

If you wish for an entity to point at a certain position rather than another entity, simply create a pivot entity at
your desired position, point the entity at this and then free the pivot.

Example:

None.

PositionEntity entity,x#,y#,z#,[,global]

Parameters:

entity - name of entity to be positioned


x# - x co-ordinate that entity will be positioned at
y# - y co-ordinate that entity will be positioned at
z# - z co-ordinate that entity will be positioned at
global (optional) - true if the position should be relative to 0,0,0 rather than a parent entity's position. False
by default.

Description:

Positions an entity at an absolute position in 3D space.

Entities are positioned using an x,y,z coordinate system. x, y and z each have their own axis, and each axis
has its own set of values. By specifying a value for each axis, you can position an entity anywhere in 3D
space. 0,0,0 is the centre of 3D space, and if the camera is pointing in the default positive z direction, then
positioning an entity with a z value of above 0 will make it appear in front of the camera, whereas a negative z
value would see it disappear behind the camera. Changing the x value would see it moving sideways, and
changing the y value would see it moving up/down.

Of course, the direction in which entities appear to move is relative to the position and orientation of the
camera.

See also: MoveEntity, TranslateEntity.

Example:

; PositionEntity Example
; ----------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

cone=CreateCone( 32 )

; Set position values so that cone is positioned in front of camera, so we can see it to begin with
x#=0
y#=0
z#=10

While Not KeyDown( 1 )

; Change position values depending on key pressed


If KeyDown( 203 )=True Then x#=x#-0.1
If KeyDown( 205 )=True Then x#=x#+0.1
If KeyDown( 208 )=True Then y#=y#-0.1
If KeyDown( 200 )=True Then y#=y#+0.1
If KeyDown( 44 )=True Then z#=z#-0.1
If KeyDown( 30 )=True Then z#=z#+0.1

; Position cone using position values


PositionEntity cone,x#,y#,z#

RenderWorld

Text 0,0,"Use cursor/A/Z keys to change cone position"


Text 0,20,"X Position: "+x#
Text 0,40,"Y Position: "+y#
Text 0,60,"Z Position: "+z#

Flip

Wend

End

PositionMesh mesh,x#,y#,z#

Parameters:

mesh - mesh handle


x# - x position of mesh
y# - y position of mesh
z# - z position of mesh

Description:

Moves all vertices of a mesh.

Example:

None.

PositionTexture texture,u_position#,v_position#

Parameters:

texture - texture handle


u_position# - u position of texture
v_position# - v position of texture

Description:

Positions a texture at an absolute position.

This will have an immediate effect on all instances of the texture being used.

Positioning a texture is useful for performing scrolling texture effects, such as for water etc.
Example:

; PositionTexture Example
; -----------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

cube=CreateCube()
PositionEntity cube,0,0,5

; Load texture
tex=LoadTexture( "media/b3dlogo.jpg" )

; Texture cube
EntityTexture cube,tex

; Set initial uv position values


u_position#=1
v_position#=1

While Not KeyDown( 1 )

; Change uv position values depending on key pressed


If KeyDown( 208 )=True Then u_position#=u_position#-0.01
If KeyDown( 200 )=True Then u_position#=u_position#+0.01
If KeyDown( 203 )=True Then v_position#=v_position#-0.01
If KeyDown( 205 )=True Then v_position#=v_position#+0.01

; Position texture
PositionTexture tex,u_position#,v_position#

TurnEntity cube,0.1,0.1,0.1

RenderWorld

Text 0,0,"Use cursor keys to change uv position values"


Text 0,20,"u_position#="+u_position#
Text 0,40,"v_position#="+v_position#

Flip

Wend

End

ProjectedX# ( )

Parameters:

None.

Description:

Returns the viewport x coordinate of the most recently executed CameraProject.


Example:

None.

ProjectedY# ( )

Parameters:

None.

Description:

Returns the viewport y coordinate of the most recently executed CameraProject.

Example:

None.

ProjectedZ# ( )

Parameters:

None.

Description:

Returns the viewport z coordinate of the most recently executed CameraProject.

Example:

None.

RenderWorld [tween#]

Parameters:

tween# - defaults to 1.

Description:

Renders all entities in the world.

The optional tween parameter can be used to render entities at a point somewhere between their captured
position and their current position. A tween value of 0 will render entities at their captured position, a tween
value of 1 will render entities at their current position. Other values may be used for interpolation. Defaults to
1.

Tweening is a technique used to allow games to have their game logic updated a fixed amount of times, e.g.
30, while having Blitz3D interpolate between these game logic updates to render as many frames per second
as it can, e.g. 60+, with each frame different to the last.

This results in a game which only has to have its game logic updated at half the rate of the renders per
second, freeing up CPU time, while at the same time having the game run as smooth as possible on anybody's
machine.

Render tweening is quite an advanced technique, and it is not necessary to use it, so don't worry if you don't
quite understand it. See the castle demo included in the mak (nickname of Mark Sibly, author of Blitz3D)
directory of the Blitz3D samples section for a demonstration of render tweening.

Example:

None.

ResetEntity entity

Parameters:

entity - entity handle

Description:

Resets the collision state of an entity.

Example:

None.

RotateEntity entity,pitch#,yaw#,roll#,[,global]

Parameters:

entity - name of the entity to be rotated


pitch# - angle in degrees of pitch rotation
yaw# - angle in degrees of yaw rotation
roll# - angle in degrees of roll rotation
global (optional) - true if the angle rotated should be relative to 0,0,0 rather than a parent entity's orientation.
False by default.

Description:

Rotates an entity so that it is at an absolute orientation.

Pitch is the same as the x angle of an entity, and is equivalent to tilting forward/backwards.

Yaw is the same as the y angle of an entity, and is equivalent to turning left/right.

Roll is the same as the z angle of an entity, and is equivalent to tilting left/right.

See also: TurnEntity.

Example:
; RotateEntity Example
; --------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

cone=CreateCone( 32 )
PositionEntity cone,0,0,5

While Not KeyDown( 1 )

; Change rotation values depending on the key pressed


If KeyDown( 208 )=True Then pitch#=pitch#-1
If KeyDown( 200 )=True Then pitch#=pitch#+1
If KeyDown( 203 )=True Then yaw#=yaw#-1
If KeyDown( 205 )=True Then yaw#=yaw#+1
If KeyDown( 45 )=True Then roll#=roll#-1
If KeyDown( 44 )=True Then roll#=roll#+1

; Rotate cone using rotation values


RotateEntity cone,pitch#,yaw#,roll#

RenderWorld

Text 0,0,"Use cursor/Z/X keys to change cone rotation"


Text 0,20,"Pitch: "+pitch#
Text 0,40,"Yaw : "+yaw#
Text 0,60,"Roll : "+roll#

Flip

Wend

End

RotateMesh mesh,pitch#,yaw#,roll#

Parameters:

mesh - mesh handle


pitch# - pitch of mesh
yaw# - yaw of mesh
roll# - roll of mesh

Description:

Rotates all vertices of a mesh by the specified rotation.

Example:

None.

RotateSprite sprite,angle#
Parameters:

sprite - sprite handle


angle# - absolute angle of sprite rotation

Description:

Rotates a sprite.

Example:

None.

RotateTexture texture,angle#

Parameters:

texture - texture handle


angle# - absolute angle of texture rotation

Description:

Rotates a texture.

This will have an immediate effect on all instances of the texture being used.

Rotating a texture is useful for performing swirling texture effects, such as for smoke etc.

Example:

; RotateTexture Example
; ---------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

cube=CreateCube()
PositionEntity cube,0,0,5

; Load texture
tex=LoadTexture( "media/b3dlogo.jpg" )

; Texture cube
EntityTexture cube,tex

; Set initial texture angle value


angle#=1

While Not KeyDown( 1 )

; Change texture angle value depending on key pressed


If KeyDown( 205 )=True Then angle#=angle#-1
If KeyDown( 203 )=True Then angle#=angle#+1

; Rotate texture
RotateTexture tex,angle#

TurnEntity cube,0.1,0.1,0.1

RenderWorld

Text 0,0,"Use left and right cursor keys to change texture angle value"
Text 0,20,"angle#="+angle#

Flip

Wend

End

ScaleEntity entity,x_scale#,y_scale#,z_scalel#,[,global]

Parameters:

entity - name of the entity to be scaled


x_scale# - x size of entity
y_scale# - y size of entity
z_scale# - z size of entity
global (optional) -

Description:

Scales an entity so that it is of an absolute size.

Scale values of 1,1,1 are the default size when creating/loading entities.

Scale values of 2,2,2 will double the size of an entity.

Scale values of 0,0,0 will make an entity disappear.

Scale values of less than 0,0,0 will invert an entity and make it bigger.

Example:

; ScaleEntity Example
; -------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

cone=CreateCone( 32 )
PositionEntity cone,0,0,5

; Set scale values so that cone is default size to begin with


x_scale#=1
y_scale#=1
z_scale#=1
While Not KeyDown( 1 )

; Change scale values depending on the key pressed


If KeyDown( 203 )=True Then x_scale#=x_scale#-0.1
If KeyDown( 205 )=True Then x_scale#=x_scale#+0.1
If KeyDown( 208 )=True Then y_scale#=y_scale#-0.1
If KeyDown( 200 )=True Then y_scale#=y_scale#+0.1
If KeyDown( 44 )=True Then z_scale#=z_scale#-0.1
If KeyDown( 30 )=True Then z_scale#=z_scale#+0.1

; Scale cone using scale values


ScaleEntity cone,x_scale#,y_scale#,z_scale#

RenderWorld

Text 0,0,"Use cursor/A/Z keys to scale cone"


Text 0,20,"X Scale: "+x_scale#
Text 0,40,"Y Scale: "+y_scale#
Text 0,60,"Z Scale: "+z_scale#

Flip

Wend

End

ScaleMesh mesh,x_scale#,y_scale#,z_scale#

Parameters:

mesh - mesh handle


x_scale# - x scale of mesh
y_scale# - y scale of mesh
z_scale# - z scale of mesh

Description:

Scales all vertices of a mesh by the specified scaling factors.

Example:

None.

ScaleSprite sprite,x_scale#,y_scale#

Parameters:

sprite - sprite handle


x_scale# - x scale of sprite
y scale# - y scale of sprite

Description:

Scales a sprite.
Example:

None.

ScaleTexture texture,u_scale#,v_scale#

Parameters:

texture - name of texture


u_scale# - u scale
v_scale# - v scale

Description:

Scales a texture by an absolute amount.

This will have an immediate effect on all instances of the texture being used.

Example:

; ScaleTexture Example
; --------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

cube=CreateCube()
PositionEntity cube,0,0,5

; Load texture
tex=LoadTexture( "media/b3dlogo.jpg" )

; Texture cube
EntityTexture cube,tex

; Set initial uv scale values


u_scale#=1
v_scale#=1

While Not KeyDown( 1 )

; Change uv scale values depending on key pressed


If KeyDown( 208 )=True Then u_scale#=u_scale#-0.01
If KeyDown( 200 )=True Then u_scale#=u_scale#+0.01
If KeyDown( 203 )=True Then v_scale#=v_scale#-0.01
If KeyDown( 205 )=True Then v_scale#=v_scale#+0.01

; Scale texture
ScaleTexture tex,u_scale#,v_scale#

TurnEntity cube,0.1,0.1,0.1

RenderWorld
Text 0,0,"Use cursor keys to change uv scale values"
Text 0,20,"u_scale#="+u_scale#
Text 0,40,"v_scale#="+v_scale#

Flip

Wend

End

SetAnimKey entity,frame[,pos_key][,rot_key][,scale_key]

Parameters:

entity - entity handle


frame - frame of animation to be used as anim key
pos_key (optional) - true to include entity position information when setting key. Defaults to true.
rot_key (optional) - true to include entity rotation information when setting key. Defaults to true.
scale_key (optional) - true to include entity scale information when setting key. Defaults to true.

Description:

Sets an animation key for the specified entity at the specified frame.

Example:

None.

ShowEntity entity

Parameters:

entity - entity handle

Description:

Shows an entity. Very much the opposite of HideEntity.

Once an entity has been hidden using HideEntity, use show entity to make it visible and involved in collisions
again.

Entities are shown by default after creating/loading them, so you should only need to use ShowEntity after
using HideEntity.

ShowEntity affects the specified entity and all of its child entities, if any exist.

Example:

None.

SpriteViewMode sprite,view_mode
Parameters:

sprite - sprite handle

view_mode - view_mode of sprite


1: fixed (sprite always faces camera)
2: free (sprite is independent of camera)
3: upright (sprite always faces camera, but tilts with camera)

Description:

Sets the viewmode of a sprite.

Example:

None.

<command>

Parameters:

<param description>

Description:

<description>

Example:

<example>

TerrainDetail terrain,detail_level[,vertex_morph]

Parameters:

terrain - terrain handle


detail_level - detail level of terrain
vertex_morph (optional) - true to enable vertex morphing of terrain. Defaults to false.

Description:

Sets the detail level for a terrain. This is the number of triangles used to represent the terrain. A typical value
is 2000.

The optional vertex_morph parameter specifies whether to enable vertex morphing. It is recommended you
set this to true, as it will reduce the visibility of LOD 'pop-in'.

Example:

; TerrainDetail Example
; ---------------------
Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
PositionEntity camera,1,1,1

light=CreateLight()
RotateEntity light,90,0,0

; Load terrain
terrain=LoadTerrain( "media/height_map.bmp" )

; Scale terrain
ScaleEntity terrain,1,50,1

; Texture terrain
grass_tex=LoadTexture( "media/mossyground.bmp" )
EntityTexture terrain,grass_tex,0,1

; Set terrain detail value


terra_detail=4000

; Set vertex morph value


vertex_morph=True

While Not KeyDown( 1 )

; Change terrain detail value depending on key pressed


If KeyDown(26) Then terra_detail=terra_detail-10
If KeyDown(27) Then terra_detail=terra_detail+10

; Toggle vertex morphing on/off when spacebar is pressed


If KeyHit(57)=True Then vertex_morph=1-vertex_morph

; Set terrain detail, vertex morphing


TerrainDetail terrain,terra_detail,vertex_morph

If KeyDown( 203 )=True Then x#=x#-0.1


If KeyDown( 205 )=True Then x#=x#+0.1
If KeyDown( 208 )=True Then y#=y#-0.1
If KeyDown( 200 )=True Then y#=y#+0.1
If KeyDown( 44 )=True Then z#=z#-0.1
If KeyDown( 30 )=True Then z#=z#+0.1

If KeyDown( 205 )=True Then TurnEntity camera,0,-1,0


If KeyDown( 203 )=True Then TurnEntity camera,0,1,0
If KeyDown( 208 )=True Then MoveEntity camera,0,0,-0.1
If KeyDown( 200 )=True Then MoveEntity camera,0,0,0.1

x#=EntityX(camera)
y#=EntityY(camera)
z#=EntityZ(camera)

terra_y#=TerrainY(terrain,x#,y#,z#)+5

PositionEntity camera,x#,terra_y#,z#

RenderWorld

Text 0,0,"Use cursor keys to move about the terrain"


Text 0,20,"Use [ and ] keys to change terrain detail level"
Text 0,40,"Press spacebar to enable/disable vertex morphing"
Text 0,60,"Terrain Detail: "+terra_detail
If vertex morph=True Then Text 0,80,"Vertex Morphing: True" Else Text 0,80,"Vertex Morphing: False"
Flip

Wend

End

TerrainHeight# ( terrain,grid_x,grid_z )

Parameters:

terrain - terrain handle


grid_x - grid x coordinate of terrain
grid_z - grid z coordinate of terrain

Description:

Returns the height of the terrain at terrain grid coordinates x,z. The value returned is in the range 0 to 1.

See also: TerrainY.

Example:

None.

TerrainShading terrain,enable

Parameters:

terrain - terrain handle


enable - true to enable terrain shading, false to to disable it.

Description:

Enables or disables terrain shading.

Shaded terrains are a little slower than non-shaded terrains, and in some instances can increase the visibility
of LOD 'pop-in'. However, the option is there to have shaded terrains if you wish to do so.

Terrain shading is disabled by default.

Example:

; TerrainShading Example
; ----------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
PositionEntity camera,1,1,1

light=CreateLight()
RotateEntity light,45,0,0
; Load terrain
terrain=LoadTerrain( "media/height_map.bmp" )

; Set terrain detail, enable vertex morphing


TerrainDetail terrain,4000,True

; Scale terrain
ScaleEntity terrain,1,50,1

; Texture terrain
grass_tex=LoadTexture( "media/mossyground.bmp" )
EntityTexture terrain,grass_tex,0,1

While Not KeyDown( 1 )

; Toggle terrain shading value between 0 and 1 when spacebar is pressed


If KeyHit(57)=True Then terra_shade=1-terra_shade

; Enable/disable terrain shading


TerrainShading terrain,terra_shade

If KeyDown( 203 )=True Then x#=x#-0.1


If KeyDown( 205 )=True Then x#=x#+0.1
If KeyDown( 208 )=True Then y#=y#-0.1
If KeyDown( 200 )=True Then y#=y#+0.1
If KeyDown( 44 )=True Then z#=z#-0.1
If KeyDown( 30 )=True Then z#=z#+0.1

If KeyDown( 205 )=True Then TurnEntity camera,0,-1,0


If KeyDown( 203 )=True Then TurnEntity camera,0,1,0
If KeyDown( 208 )=True Then MoveEntity camera,0,0,-0.1
If KeyDown( 200 )=True Then MoveEntity camera,0,0,0.1

x#=EntityX(camera)
y#=EntityY(camera)
z#=EntityZ(camera)

terra_y#=TerrainY(terrain,x#,y#,z#)+5

PositionEntity camera,x#,terra_y#,z#

RenderWorld

Text 0,0,"Use cursor keys to move about the terrain"


Text 0,20,"Press spacebar to toggle between TerrainShading True/False"
If terra_shade=True Then Text 0,40,"TerrainShading: True" Else Text 0,40,"TerrainShading: False"

Flip

Wend

End

TerrainSize ( terrain )

Parameters:

terrain - terrain handle


Description:

Returns the grid size used to create a terrain.

Example:

; TerrainSize Example
; -------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
PositionEntity camera,1,1,1

light=CreateLight()
RotateEntity light,90,0,0

; Load terrain
terrain=LoadTerrain( "media/height_map.bmp" )

; Set terrain detail, enable vertex morphing


TerrainDetail terrain,4000,True

; Scale terrain
ScaleEntity terrain,1,50,1

; Texture terrain
grass_tex=LoadTexture( "media/mossyground.bmp" )
EntityTexture terrain,grass_tex,0,1

While Not KeyDown( 1 )

If KeyDown( 203 )=True Then x#=x#-0.1


If KeyDown( 205 )=True Then x#=x#+0.1
If KeyDown( 208 )=True Then y#=y#-0.1
If KeyDown( 200 )=True Then y#=y#+0.1
If KeyDown( 44 )=True Then z#=z#-0.1
If KeyDown( 30 )=True Then z#=z#+0.1

If KeyDown( 205 )=True Then TurnEntity camera,0,-1,0


If KeyDown( 203 )=True Then TurnEntity camera,0,1,0
If KeyDown( 208 )=True Then MoveEntity camera,0,0,-0.1
If KeyDown( 200 )=True Then MoveEntity camera,0,0,0.1

x#=EntityX(camera)
y#=EntityY(camera)
z#=EntityZ(camera)

terra_y#=TerrainY(terrain,x#,y#,z#)+5

PositionEntity camera,x#,terra_y#,z#

RenderWorld

Text 0,0,"Use cursor keys to move about the terrain"

; Output terrain size to screen


Text 0,20,"Terrain Size: "+TerrainSize(terrain)

Flip

Wend
End

TerrainX# (terrain,x#,y#,z# )

Parameters:

terrain - terrain handle


x# - world x coordinate
y# - world y coordinate
z# - world z coordinate

Description:

Returns the interpolated x coordinate on a terrain.

See also: TerrainY, TerrainZ.

Example:

; TerrainX Example
; ----------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
PositionEntity camera,1,1,1

light=CreateLight()
RotateEntity light,90,0,0

; Load terrain
terrain=LoadTerrain( "media/height_map.bmp" )

; Scale terrain
ScaleEntity terrain,1,50,1

; Texture terrain
grass_tex=LoadTexture( "media/mossyground.bmp" )
EntityTexture terrain,grass_tex,0,1

; Set terrain detail, enable vertex morphing


TerrainDetail terrain,4000,True

While Not KeyDown( 1 )

If KeyDown( 203 )=True Then x#=x#-0.1


If KeyDown( 205 )=True Then x#=x#+0.1
If KeyDown( 208 )=True Then y#=y#-0.1
If KeyDown( 200 )=True Then y#=y#+0.1
If KeyDown( 44 )=True Then z#=z#-0.1
If KeyDown( 30 )=True Then z#=z#+0.1

If KeyDown( 205 )=True Then TurnEntity camera,0,-1,0


If KeyDown( 203 )=True Then TurnEntity camera,0,1,0
If KeyDown( 208 )=True Then MoveEntity camera,0,0,-0.1
If KeyDown( 200 )=True Then MoveEntity camera,0,0,0.1
x#=EntityX(camera)
y#=EntityY(camera)
z#=EntityZ(camera)

terra_y#=TerrainY(terrain,x#,y#,z#)+5

PositionEntity camera,x#,terra_y#,z#

RenderWorld

Text 0,0,"Use cursor keys to move about the terrain"

; Output TerrainX value to screen


Text 0,20,"TerrainX: "+TerrainX(terrain,x#,terra_y#,z#)

Flip

Wend

End

TerrainY# (terrain,x#,y#,z# )

Parameters:

terrain - terrain handle


x# - world x coordinate
y# - world y coordinate
z# - world z coordinate

Description:

Returns the interpolated y coordinate on a terrain.

Gets the ground's height, basically.

See also: TerrainX, TerrainZ, TerrainHeight.

Example:

; TerrainY Example
; ----------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
PositionEntity camera,1,1,1

light=CreateLight()
RotateEntity light,90,0,0

; Load terrain
terrain=LoadTerrain( "media/height_map.bmp" )

; Scale terrain
ScaleEntity terrain,1,50,1

; Texture terrain
grass_tex=LoadTexture( "media/mossyground.bmp" )
EntityTexture terrain,grass_tex,0,1

; Set terrain detail, enable vertex morphing


TerrainDetail terrain,4000,True

While Not KeyDown( 1 )

If KeyDown( 203 )=True Then x#=x#-0.1


If KeyDown( 205 )=True Then x#=x#+0.1
If KeyDown( 208 )=True Then y#=y#-0.1
If KeyDown( 200 )=True Then y#=y#+0.1
If KeyDown( 44 )=True Then z#=z#-0.1
If KeyDown( 30 )=True Then z#=z#+0.1

If KeyDown( 205 )=True Then TurnEntity camera,0,-1,0


If KeyDown( 203 )=True Then TurnEntity camera,0,1,0
If KeyDown( 208 )=True Then MoveEntity camera,0,0,-0.1
If KeyDown( 200 )=True Then MoveEntity camera,0,0,0.1

x#=EntityX(camera)
y#=EntityY(camera)
z#=EntityZ(camera)

terra_y#=TerrainY(terrain,x#,y#,z#)

PositionEntity camera,x#,terra_y#+5,z#

RenderWorld

Text 0,0,"Use cursor keys to move about the terrain"

; Output TerrainY value to screen


Text 0,20,"TerrainY: "+terra_y#

Flip

Wend

End

TerrainZ# (terrain,x#,y#,z# )

Parameters:

terrain - terrain handle


x# - world x coordinate
y# - world y coordinate
z# - world z coordinate

Description:

Returns the interpolated z coordinate on a terrain.

See also: TerrainX, TerrainY.

Example:

; TerrainZ Example
; ----------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
PositionEntity camera,1,1,1

light=CreateLight()
RotateEntity light,90,0,0

; Load terrain
terrain=LoadTerrain( "media/height_map.bmp" )

; Scale terrain
ScaleEntity terrain,1,50,1

; Texture terrain
grass_tex=LoadTexture( "media/mossyground.bmp" )
EntityTexture terrain,grass_tex,0,1

; Set terrain detail, enable vertex morphing


TerrainDetail terrain,4000,True

While Not KeyDown( 1 )

If KeyDown( 203 )=True Then x#=x#-0.1


If KeyDown( 205 )=True Then x#=x#+0.1
If KeyDown( 208 )=True Then y#=y#-0.1
If KeyDown( 200 )=True Then y#=y#+0.1
If KeyDown( 44 )=True Then z#=z#-0.1
If KeyDown( 30 )=True Then z#=z#+0.1

If KeyDown( 205 )=True Then TurnEntity camera,0,-1,0


If KeyDown( 203 )=True Then TurnEntity camera,0,1,0
If KeyDown( 208 )=True Then MoveEntity camera,0,0,-0.1
If KeyDown( 200 )=True Then MoveEntity camera,0,0,0.1

x#=EntityX(camera)
y#=EntityY(camera)
z#=EntityZ(camera)

terra_y#=TerrainY(terrain,x#,y#,z#)+5

PositionEntity camera,x#,terra_y#,z#

RenderWorld

Text 0,0,"Use cursor keys to move about the terrain"

; Output TerrainZ value to screen


Text 0,20,"TerrainZ: "+TerrainZ(terrain,x#,terra_y#,z#)

Flip

Wend

End

TextureBlend texture,blend
Parameters:

texture - name of texture

blend - blend mode of texture


0: disable texture
1: alpha
2: multiply (default)
3: add

Description:

Set the blending mode for a texture.

This is used with multitexturing to control how the texture is combined with other textures.

Example:

None.

TextureBuffer ( texture[,frame] )

Parameters:

texture - texture handle


frame (optional) - texture frame

Description:

Returns the handle of a texture's drawing buffer.

This can be used with SetBuffer to perform 2D drawing operations to the texture, although it's usually faster
to draw to an image, and then copy the image buffer across to the texture buffer using CopyRect.

You cannot render 3D to a texture buffer; 3D can only be rendered to the back buffer. To display 3D graphics
on a texture, use CopyRect to copy the contents of the back buffer to a texture buffer.

Example:

; TextureBuffer Example
; ---------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

cube=CreateCube()
PositionEntity cube,0,0,5

; Create texture of size 256x256


tex=CreateTexture(256,256)

; Set buffer - texture buffer


SetBuffer TextureBuffer(tex)

; Clear texture buffer with background white color


ClsColor 255,255,255
Cls

; Draw text on texture


font=LoadFont("arial",24)
SetFont font
Color 0,0,0
Text 0,0,"This texture"
Text 0,40,"was created using" : Color 0,0,255
Text 0,80,"CreateTexture()" : Color 0,0,0
Text 0,120,"and drawn to using" : Color 0,0,255
Text 0,160,"SetBuffer TextureBuffer()"

; Texture cube with texture


EntityTexture cube,tex

; Set buffer - backbuffer


SetBuffer BackBuffer()

While Not KeyDown( 1 )

pitch#=0
yaw#=0
roll#=0

If KeyDown( 208 )=True Then pitch#=-1


If KeyDown( 200 )=True Then pitch#=1
If KeyDown( 203 )=True Then yaw#=-1
If KeyDown( 205 )=True Then yaw#=1
If KeyDown( 45 )=True Then roll#=-1
If KeyDown( 44 )=True Then roll#=1

TurnEntity cube,pitch#,yaw#,roll#

RenderWorld
Flip

Wend

End

TextureCoords texture,coords

Parameters:

texture - name of texture


coords -
0: UV coordinates are from first UV set in vertices (default)
1: UV coordinates are from second UV set in vertices

Description:

Sets the texture coordinate mode for a texture.

This determines where the UV values used to look up a texture come from.
Example:

None.

TextureFilter match_text$,flags

Parameters:

match_text$ - text that, if found in texture filename, will activate certain filters
flags - filter flags

Description:

Adds a texture filter. Any textures loaded that contain the text specified by match_text$ will have the provided
flags added.

This is mostly of use when loading a mesh.

By default, the following texture filter is used:

TextureFilter "",1+8

This means that all loaded textures will have color and be mipmapped by default.

Example:

None.

TextureHeight ( texture )

Parameters:

texture - texture handle

Description:

Returns the height of a texture.

Example:

None.

TextureWidth (texture )

Parameters:

texture - texture handle

Description:
Returns the width of a texture.

Example:

None.

TFormedX

Parameters:

None.

Description:

Returns the x component of the last TFormPoint, TFormVector or TFormNormal operation.

Example:

None.

TFormedY

Parameters:

None.

Description:

Returns the y component of the last TFormPoint, TFormVector or TFormNormal operation.

Example:

None.

TFormedZ

Parameters:

None.

Description:

Returns the z component of the last TFormPoint, TFormVector or TFormNormal operation.

Example:

None.

TFormNormal x#,y#,z#,src_entity,dest_entity
Parameters:

x# - x component of normal on which to perform transformation


y# - y component of normal on which to perform transformation
z# - z component of normal on which to perform transformation
src_entity - source entity local space to transform normal from
dest_entity - destination entity local space to transform normal to

Description:

Transforms a normal in src_entity local space to dest_entity local space.

If either src_entity or dest_entity is 0, then global space is used.

The results of the transformation can be retrieved using the TFormedX, TFormedY and TFormedZ commands.

Example:

None.

TFormPoint x#,y#,z#,src_entity,dest_entity

Parameters:

x# - x coordinate of point on which to perform transformation


y# - y coordinate of point on which to perform transformation
z# - z coordinate of point on which to perform transformation
src_entity - source entity local space to transform point from
dest_entity - destination entity local space to transform point to

Description:

Transforms a point in src_entity local space to dest_entity local space.

If either src_entity or dest_entity is 0, then global space is used.

The results of the transformation can be retrieved using the TFormedX, TFormedY and TFormedZ commands.

Example:

None.

TFormVector x#,y#,z#,src_entity,dest_entity

Parameters:

x# - x component of vector on which to perform transformation


y# - y component of vector on which to perform transformation
z# - z component of vector on which to perform transformation
src_entity - source entity local space to transform vector from
dest_entity - destination entity local space to transform vector to

Description:
Transforms a vector in src_entity local space to dest_entity local space.

If either src_entity or dest_entity is 0, then global space is used.

The results of the transformation can be retrieved using the TFormedX, TFormedY and TFormedZ commands.

Example:

None.

TranslateEntity entity,x#,y#,z#,[,global]

Parameters:

entity - name of entity to be translated


x# - x amount that entity will be translated by
y# - y amount that entity will be translated by
z# - z amount that entity will be translated by
global (optional) -

Description:

Translates an entity relative to its current position and not its orientation.

What this means is that an entity will move in a certain direction despite where it may be facing. Imagine that
you have a game character that you want to make jump in the air at the same time as doing a triple
somersault. Translating the character by a positive y amount will mean the character will always travel directly
up in their air, regardless of where it may be facing due to the somersault action.

See also: MoveEntity, PositionEntity.

Example:

; TranslateEntity Example
; -----------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

cone=CreateCone( 32 )

; Rotate cone by random amount to demonstrate that TranslateEntity is independent of entity orientation
RotateEntity cone,Rnd( 0,360 ),Rnd( 0,360 ),Rnd( 0,360 )

; Translate cone in front of camera, so we can see it to begin with


TranslateEntity cone,0,0,10

While Not KeyDown( 1 )

; Reset translation values - otherwise, the cone will not stop!


x#=0
y#=0
z#=0

; Change translation values depending on the key pressed


If KeyDown( 203 )=True Then x#=-0.1
If KeyDown( 205 )=True Then x#=0.1
If KeyDown( 208 )=True Then y#=-0.1
If KeyDown( 200 )=True Then y#=0.1
If KeyDown( 44 )=True Then z#=-0.1
If KeyDown( 30 )=True Then z#=0.1

; Translate sphere using translation values


TranslateEntity cone,x#,y#,z#

; If spacebar pressed then rotate cone by random amount


If KeyHit( 57 )=True Then RotateEntity cone,Rnd( 0,360 ),Rnd( 0,360 ),Rnd( 0,360 )

RenderWorld

Text 0,0,"Use cursor/A/Z keys to translate cone, spacebar to rotate cone by random amount"
Text 0,20,"X Translation: "+x#
Text 0,40,"Y Translation: "+y#
Text 0,60,"Z Translation: "+z#

Flip

Wend

End

TriangleVertex ( surface,triangle_index,corner )

Parameters:

surface - surface handle


triangle_index - triangle index
corner - corner of triangle. Should be 0, 1 or 2.

Description:

Returns the vertex of a triangle corner.

Example:

None.

TurnEntity entity,pitch#,yaw#,roll#,[,global]

Parameters:

entity - name of entity to be rotated


pitch# - angle in degrees that entity will be pitched
yaw# - angle in degrees that entity will be yawed
roll# - angle in degrees that entity will be rolled
global (optional) -

Description:

Turns an entity relative to its current orientation.


Pitch is the same as the x angle of an entity, and is equivalent to tilting forward/backwards.

Yaw is the same as the y angle of an entity, and is equivalent to turning left/right.

Roll is the same as the z angle of an entity, and is equivalent to tilting left/right.

See also: RotateEntity.

Example:

; TurnEntity Example
; ------------------

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
light=CreateLight()

cone=CreateCone( 32 )
PositionEntity cone,0,0,5

While Not KeyDown( 1 )

; Reset turn values - otherwise, the cone will not stop turning!
pitch#=0
yaw#=0
roll#=0

; Change movement values depending on the key pressed


If KeyDown( 208 )=True Then pitch#=-1
If KeyDown( 200 )=True Then pitch#=1
If KeyDown( 203 )=True Then yaw#=-1
If KeyDown( 205 )=True Then yaw#=1
If KeyDown( 45 )=True Then roll#=-1
If KeyDown( 44 )=True Then roll#=1

; Move sphere using movement values


TurnEntity cone,pitch#,yaw#,roll#

RenderWorld

Text 0,0,"Use cursor/Z/X keys to turn cone"


Text 0,20,"Pitch: "+pitch#
Text 0,40,"Yaw: "+yaw#
Text 0,60,"Roll: "+roll#

Flip

Wend

End

UpdateNormals mesh

Parameters:

mesh - mesh handle


Description:

Recalculates all normals in a mesh. This is necessary for correct lighting if you have not set surface normals
using 'VertexNormals' commands.

Example:

None.

UpdateWorld [anim_speed#]

Parameters:

anim_speed# (optional) - a master control for animation speed. Defaults to 1.

Description:

Animates all entities in the world, and performs collision checking.

The optional anim_speed# parameter allows you affect the animation speed of all entities at once. A value of 1
will animate entities at their usual animation speed, a value of 2 will animate entities at double their animation
speed, and so on.

For best results use this command once per main loop, just before calling RenderWorld.

Example:

None.

VertexBlue# ( surface,index )

Parameters:

surface - surface handle


index - index of vertex

Description:

Returns the blue component of a vertices color.

Example:

None.

VertexColor surface,index,red#,green#,blue#

Parameters:

surface - surface handle


index - index of vertex
red# - red value of vertex
green# - green value of vertex
blue# - blue value of vertex

Description:

Sets the color of an existing vertex.

Example:

None.

VertexCoords surface,index,x#,y#,z#

Parameters:

surface - surface handle


index - index of vertex
x# - x position of vertex
y# - y position of vertex
z# - z position of vertex

Description:

Sets the geometric coordinates of an existing vertex.

This is the command used to perform what is commonly referred to as 'dynamic mesh deformation'. It will
reposition a vertex so that all the triangle edges connected to it, will move also. This will give the effect of
parts of the mesh suddenly deforming.

Example:

None.

VertexGreen# ( surface,index )

Parameters:

surface - surface handle


index - index of vertex

Description:

Returns the green component of a vertices color.

Example:

None.

VertexNormal surface,index,nx#,ny#,nz#
Parameters:

surface - surface handle


index - index of vertex
nx# - normal x of vertex
ny# - normal y of vertex
nz# - normal z of vertex

Description:

Sets the normal of an existing vertex.

Example:

None.

VertexNX# ( surface,index )

Parameters:

surface - surface handle


index - index of vertex

Description:

Returns the x component of a vertices normal.

Example:

None.

VertexNY# ( surface,index )

Parameters:

surface - surface handle


index - index of vertex

Description:

Returns the y component of a vertices normal.

Example:

None.

VertexNZ# ( surface,index )

Parameters:
surface - surface handle
index - index of vertex

Description:

Returns the z component of a vertices normal.

Example:

None.

VertexRed# ( surface,index )

Parameters:

surface - surface handle


index - index of vertex

Description:

Returns the red component of a vertices color.

Example:

None.

VertexTexCoords surface,index,u#,v#[,w#][,coord_set]

Parameters:

surface - surface handle


index - index of surface
u# - u# coordinate of vertex
v# - v# coordinate of vertex
w# (optional) - w# coordinate of vertex
coord_set (optional) - co_oord set. Should be set to 0 or 1.

Description:

Sets the texture coordinates of an existing vertex.

Example:

None.

VertexU# ( surface,index )

Parameters:
surface - surface handle
index - index of vertex

Description:

Returns the texture u coordinate of a vertex.

Example:

None.

VertexV# ( surface,index )

Parameters:

surface - surface handle


index - index of vertex

Description:

Returns the texture v coordinate of a vertex.

Example:

None.

VertexW# ( surface,index )

Parameters:

surface - surface handle


index - index of vertex

Description:

Returns the texture w coordinate of a vertex.

Example:

None.

VertexX# ( surface,index )

Parameters:

surface - surface handle


index - index of vertex

Description:
Returns the x coordinate of a vertex.

Example:

None.

VertexY# ( surface,index )

Parameters:

surface - surface handle


index - index of vertex

Description:

Returns the y coordinate of a vertex.

Example:

None.

VertexZ ( surface,index )

Parameters:

surface - surface handle


index - index of vertex

Description:

Returns the z coordinate of a vertex.

Example:

None.

Wbuffer enable

Parameters:

enable - true to enable w-buffering rendering, false to disable. Defaults to true for 16-bit colour mode, false
for 24-bit and 32-bit.

Description:

Enables or disables w-buffering.

W-buffering is a technique used to draw 3D object in order of their depth - i.e. the ones furthest away from
the camera first, then the ones closer to the camera, and so on.
Normally, z-buffering is used to perform such a technique, but a z-buffer can be slightly inaccurate in 16-bit
colour mode, for which the level of precision is less than in 24-bit or 32-bit colour modes. This means that in
some situations, objects will appear to overlap each other when they shouldn't and so on.

To compensate for this, you can use w-buffering. This is a slightly more accurate technique than z-buffering,
although it may be less compatible on some set-ups than z-buffering.

Example:

None.

Windowed3D

Parameters:

n/a

Description:

Windowed3D () returns True if a graphics card is capable of rendering 3D graphics modes in a window on the
desktop.

Certain graphics cards will only allow specific 3D colour depths (eg. Voodoo3 supports only 16-bit 3D modes
and Matrox only supports 16 and 32-bit 3D modes but allows 24-bit 2D modes to be set). If the user's desktop
is set to a depth unsupported in 3D, Windowed3D will return False.

Example:

If Windowed3D ()
Graphics3D 640, 480, 0, 2
Print "Windowed mode!"
Else
Graphics3D 640, 480, 0, 1
Print "Full screen modes only!"
EndIf

MouseWait
End

Wireframe enable

Parameters:

enable - true to enable wireframe rendering, false to disable. Defaults to false.

Description:

Enables or disables wireframe rendering.

This will show the outline of each polygon on the screen, with no shaded-in areas.

Wireframe should only be used for debugging purposes, as driver support is patchy. For the same reason, no
support is offered for the wireframe rendering of individual polygon entities.
Example:

; Wireframe Example
; -----------------

Graphics3D 640,480,16
SetBuffer BackBuffer()

camera=CreateCamera()

light=CreateLight()
RotateEntity light,90,0,0

sphere=CreateSphere( 32 )
PositionEntity sphere,0,0,2

While Not KeyDown( 1 )

; Toggle wireframe enable value between true and false when spacebar is pressed
If KeyHit( 57 )=True Then enable=1-enable

; Enable/disable wireframe rendering


WireFrame enable

RenderWorld

Text 0,0,"Press spacebar to toggle between Wireframe True/False"


If enable=False Then Text 0,20,"Wireframe False" Else Text 0,20,"Wireframe True"

Flip

Wend

End

You might also like