# Usage
## Command line
Usage: DOjS.EXE [-r] [-l] [-s] [-f] [-a] <script> [script parameters]
    -r             : Do not invoke the editor, just run the script.
    -l             : Use 50-line mode in the editor.
    -w <width>     : Screen width: 320 or 640, Default: 640.
    -b <bpp>       : Bit per pixel:8, 16, 24, 32. Default: 32.
    -s             : No wave sound.
    -f             : No FM sound.
    -a             : Disable alpha (speeds up rendering).
    -x             : Allow raw disk write (CAUTION!)

## Editor keys
    F1        : Open/Close help
    SHIFT-F1  : Function context help
    F3        : Save script
    F4        : Run script
    F7        : Find text
    F9        : Show/Close logfile
    F10       : Quit

    Shift-F4       : Truncate logfile and run script
    Shift-F7       : Find again
    CTRL-D         : Delete current line
    SHIFT+Movement : Select text, releasing SHIFT deselects
    CTRL-C         : Copy selection
    CTRL-X         : Cut selection
    CTRL-V         : Paste
    CTRL-LEFT      : Previous word
    CTRL-RIGHT     : Next word
    CTRL/PAGE-UP   : One page up
    CTRL/PAGE-DOWN : One page down
    HOME           : Go to start of line
    END            : Go to end of line
    CTRL-HOME      : Go to start of line
    CTRL-END       : Go to end of line
    TAB            : Insert spaces until next TAB-stop at cursor
    SHIFT-TAB      : Reduce indentation of line

    TAB size is 4.
    The help viewer will remember the current position.

    The logfile can be truncated by pressing DEL in the log viewer.

## Scripts and resources
Scripts, as well as resources can either be stored in the file system or in ZIP files. To load data from a zip file the format is <ZIP filename>=<ZIP entry name> (e.g. data.zip=mypic.bmp). DOjS can be started with a script, a script in a ZIP file or no parameters. If the script was loaded from a ZIP file the running script can obtain resources from the same ZIP file by using ZipPrefix() to obtain paths refering to that ZIP. If the script was not started from a ZIP ZipPrefix() just passes through the file name (thus loading the file from HDD). If no arameters are supplied DOjS will first try to load <name of the EXE>.ZIP=MAIN.JS and then JSBOOT.ZIP=MAIN.JS.
Examples:
* DOJS.EXE -r script.js will start script.js from the HDD, ZipPrefix("pic.bmp") will yield pic.bmp.
* DOJS.EXE -r data.zip=script.js will start script.js from the ZIP file data.zip, ZipPrefix("pic.bmp") will yield data.zip=pic.bmp.
* HURTZ.EXE DOjS was renamed to HURTZ.EXE. It will start MAIN.JS from the ZIP file HURTZ.ZIP, ZipPrefix("pic.bmp") will yield HURTZ.ZIP=pic.bmp.
* DOJS.EXE The script was added to JSBOOT.ZIP. DOjS will start MAIN.JS from the ZIP file JSBOOT.ZIP, ZipPrefix("pic.bmp") will yield JSBOOT.ZIP=pic.bmp.

# JS API description
A very minimal API documentation.

## Script format
Scripts need to provide three functions: Setup(), Loop() and Input(). Scripts are loaded and executed top-own. After that Setup() is called once and then Loop() repeatedly. Input() is called whenever mouse of keyboard input happens.

### Setup()
This function is called once at startup. It can initialize variables, setup hardware, etc.

### Loop()
This function is called after setup repeatedly until Stop() is called. After calling Stop() the program ends when Loop() exits.

### Input(event: {x:number, y:number, flags:number, buttons:number, key:number, kbstat:number, dtime:number})
This function is called whenever mouse/keyboard input happens. The parameter is an event object with the following fields: {x:number, y:number, flags:number, buttons:number, key:number, kbstat:number, dtime:number}. The definitions for the flags and key field can be found in jsboot/func.js.

## File
### f = new File(filename:string, mode:string)
Open a file, for file modes see jsboot/file.js. Files can only either be read or written, never both. Writing to a closed file throws an exception.

### f.ReadByte():number
### f.ReadBytes():number[]
### f.ReadLine():string
Read a single/multiple byte(s)/line from file. The maximum line length is 4096 byte.

### f.WriteByte(ch:number)
### f.WriteString(txt:string)
### f.WriteLine(txt:string)
Write a byte/string/NEWLINE terminated string to a file.

### f.Close()
Close the file.

### f.GetSize():number
Get file size.

## Color
See jsboot/color.js for predefined EGA colors. Use NO_COLOR for the transparent color.

### Color(red:number, green:number, blue:number[, alpha:number]):number
Create a RGBA color.

### HSBColor(hue:number, bright:number, sat:number[, alpha:number]):number
Create a HSBA color.

### GetRed(c:number):number
### GetGreen(c:number):number
### GetBlue(c:number):number
### GetAlpha(c:number):number
get the R/G/B/A part of a color.

## Bitmap
### bm = new Bitmap(filename:string)
Load a BMP or PNG image.

### bm = new Bitmap(width:number, height:number)
Create empty Bitmap of given size.

### bm = new Bitmap(x:number, y:number, width:number, height:number)
Create Bitmap from current screen.

### bm = new Bitmap(x:number, y:number, width:number, height:number, buffer:number)
Create Bitmap from 3dfx buffer.

### bm = new Bitmap(data:number[], width:number, height:number)
Create Bitmap of given size from 32bit (ARGB) integer arrays.

### bm.filename
Name of the file.

### bm.width
Width in pixels

### bm.height
Height in pixels

### bm.Draw(x:number, y:number)
Draw the image to the canvas at given coordinates.

### bm.DrawAdvanced(srcX:number, srcY:number, srcW:number, srcH:number, destX:number, destY:number, destW:number, destH:number)
Draw scaled image.

### bm.DrawTrans(x:number, y:number)
Draw the image to the canvas at given coordinates using RGBA transparency.

### bm.GetPixel(x:number, y:number):Color
get the color of an image pixel.

### bm.SaveBmpImage(fname:string)
### bm.SavePcxImage(fname:string)
### bm.SaveTgaImage(fname:string)
### bm.SavePngImage(fname:string)
Save Bitmap to file.

## Font
See jsboot/font.js for direction and alignment values.

### f = new Font(filename:string)
Load a .FNT file for GRX.

### f.filename
Name of the file.

### f.height
Font height.

### f.DrawStringLeft(x:number, y:number, text:string, foreground:Color, background: Color)
### f.DrawStringCenter(x:number, y:number, text:string, foreground:Color, background: Color)
### f.DrawStringRight(x:number, y:number, text:string, foreground:Color, background: Color)
Draw a string to the canvas.

### f.StringWidth(text:string):number
Calculate string width for this font.

### f.StringHeight(text:string):number
Calculate string height for this font.

## Midi
### mid = new Midi(filename:string)
Load a midi file.

### mid.Play()
Play the midi file.

### mid.filename
Name of the file.

### mid.length
Get file playtime.

### MidiIsPlaying():boolean
Check if the file is still playing

### MidiPause()
### MidiResume()
### MidiStop()
Pause/resume/stop playing midi.

### MidiGetPos():number
### MidiGetTime():number
Get current play position (in seconds).

### MidiOut(data:number[])
Send MIDI commands to output.

## Sample
### snd = new Sample(filename:string)
Load a WAV-file.

### snd.filename
Name of the file.

### snd.length
Sound length.

### snd.frequency
Sound frequency.

### snd.Play(volume:number, panning:number, loop:boolean)
Play the WAV.

### snd.Stop()
Stop the sound.

### snd.Get(idx:number):number
Get sample value at index.

### VoiceGetPosition(voc:number):number
Get current play position for given voice.

### SoundInputSource(src:number)
Select sound input source.

### SoundStartInput(rate, bits, stereo)
Start sound recording with given parameters.

### SoundStopInput()
Stop sound recording.

### ReadSoundInput():number[]
Get the actuall sound data.

## Drawing functions

### SetRenderBitmap(bm:Bitmap)
Set the current render destination. Empty or null for screen bitmap.

### SizeX():number
get the width of the drawing area.

### SizeY():number
get the height of the drawing area.

### ClearScreen(c:Color)
clear the screen with given color.

### Plot(x:number, y:number, c:Color)
draw a point.

### Line(x1:number, y1:number, x2:number, y2:number, c:Color)
draw a line.

### Box(x1:number, y1:number, x2:number, y2:number, c:Color)
draw a box.

### Circle(x1:number, y1:number, r:number, c:Color)
draw a circle.

### Ellipse(xc:number, yc:number, xa:number, ya:number, c:Color)
draw an ellipse.

### CircleArc(x:number, y:number, r:number, start:number, end:number, style:number, c:Color):{"centerX":XXX,"centerY":XXX,"endX":XXX,"endY":XXX,"startX":XXX,"startY":XXX}
Draw a circle arc. Returns an object with coordinates of the drawn arc: {"centerX":XXX,"centerY":XXX,"endX":XXX,"endY":XXX,"startX":XXX,"startY":XXX}.

### CustomLine(x1:number, y1:number, x2:number, y2:number, w:number, c:Color)
draw a line with given width.

### CustomCircle(x1:number, y1:number, r:number, w:number, c:Color)
draw a circle with given width.

### CustomEllipse(xc:number, yc:number, xa:number, ya:number, w:number, c:Color)
draw an ellipse with given width.

### CustomCircleArc(x:number, y:number, r:number, start:number, end:number, style:number, w:number, c:Color):{"centerX":XXX,"centerY":XXX,"endX":XXX,"endY":XXX,"startX":XXX,"startY":XXX}
Draw a circle arc with given width. Returns an object with coordinates of the drawn arc: {"centerX":XXX,"centerY":XXX,"endX":XXX,"endY":XXX,"startX":XXX,"startY":XXX}.

### FilledBox(x1:number, y1:number, x2:number, y2:number, c:Color)
draw a filled box.

### FilledCircle(x1:number, y1:number, r:number, c:Color)
draw a filled circle.

### FilledEllipse(xc:number, yc:number, xa:number, ya:number, c:Color)
draw an ellipse.

### FilledPolygon([[x1, x2], [..], [xN, yN]], c:Color)
draw a filled polygon.

### FloodFill(x:number, y:number, border:Color, c:Color)
do a flood fill.

### GetPixel(x:number, y:number):Color
get color of on-screen pixel.

### DrawArray(dat:number[], x:number, y:number, width:number, height:number)
draw 32bit ARGB array to screen.

### TextXY(x:number, y:number, text:string, fg:Color, bg:Color)
Draw a text with the default font.

### TransparencyEnabled(b:boolean)
Enable/disable transparency.

### SaveBmpImage(fname:string)
### SavePcxImage(fname:string)
### SaveTgaImage(fname:string)
### SavePngImage(fname:string)
Save current screen to file.

## Keyboard/Mouse Input
### MouseSetSpeed(spmul:number, spdiv:number)
set mouse speed

### MouseSetLimits(x1:number, y1:number, x2:number, y2:number)
set mouse limits

## MouseSetCursorMode(mode:int, ...)
change mode of the cursor.

### MouseShowCursor(b:boolean)
show hide mouse cursor

### MouseWarp(x:number, y:number)
move mouse cursor

## Other functions/properties
### SOUND_AVAILABLE: boolean
true if WAV sound is available.

### MOUSE_AVAILABLE: boolean
true if mouse is available.

### IPX_AVAILABLE: boolean
true if networking is available.

### global: object
The global context.

### ARGS: string[]
The command line parameters including script name.

### Print(a, ...)
Write data to JSLOG.TXT logfile.

### Println(a, ...)
Write data to JSLOG.TXT logfile.

### Stop()
DOjS will exit after the current call to Loop().

### Sleep(ms:number)
Sleep for the given number of ms.

### MsecTime():number
Get ms timestamp.

### Read(filename:string):string
Load the contents of a file into a string.

### ReadZIP(filename:string, entry:string):string
Load the contents of a ZIP file entry into a string.

### List(dname:string):[f1:string, f1:string, ...]
Get directory listing.

### Stat(name:string):{"atime":string,"blksize":number,"ctime":string,"drive":string,"is_blockdev":bool,"is_chardev":bool,"is_directory":bool,"is_regular":bool,"mtime":string,"nlink":number,"size":number}
Get information about a file/directory.

### MakeDir(name:string)
Create directory.

### RmFile(name:string)
### RmDir(name:string)
Delete file/directory.

### Rename(from:string, to:string)
Rename file/directory.

### MemoryInfo():{"used":XXX, "available":XXX}
Get memory statistics.

### Gc(info:boolean)
Run garbage collector, print statistics to logfile if info==true.

### SetFramerate(rate:number)
Set maximum frame rate. If Loop() takes longer than 1/rate seconds then the framerate will not be reached.

### GetFramerate():number
Current frame rate.

### SetExitKey(key:number)
Change the exit key from ESCAPE to any other keycode from jsboot/func.js.

### CharCode(c:string)
Can be used to obtain the key code for SetExitKey() for a character, e.g. SetExitKey(CharCode('q')).

### Require(filename:string):module
Used to load a module. The functions exported from this module can be accessed using the returned value.

### Include(filename:string)
Used to load a module. The functions exported from this module will be put into the global context.

### ZipPrefix(fname:string):string
Prefix a filename with the ZIP file the started script came from.

### RandomInt(min:number, max:number):number
Get random integer between min and max.

### POST(n:number)
Write n to IO-port 0x80 to be displayed by a POST-card.

### System(cmd:string):number
Execute DOS command 'cmd'.

### OutPortByte(port:number, val:number)
### OutPortWord(port:number, val:number)
### OutPortLong(port:number, val:number)
Write byte/word/long to given IO-port.

### InPortByte(port:number):number
### InPortWord(port:number):number
### InPortLong(port:number):number
Read byte/word/long from given IO-port.

### BytesToString(data:number[]):string
Convert byte array to ASCII string. The string is terminated at the first NULL byte or at array length (whichever comes first).

### StringToBytes(string):number[]
Convert ASCII string to byte array.

### NamedFunction(func_param, func_src, func_source_filename):function
This works like Function(), but it only takes one parameter and the source of the parsed string can be provided.

## IPX networking
DOjS supports IPX networking. Node addresses are arrays of 6 numbers between 0-255. Default socket number and broadcast address definitions can be found in jsboot/ipx.js.

### IpxSocketOpen(num:number)
Open an IPX socket.

### IpxSocketClose()
Close IPX socket (if any).

### IpxSend(data:string, dest:array[6:number])
Send packet via IPX. Max length 79 byte.

### IpxCheckPacket():boolean
Check for packet in receive buffer.

### IpxGetPacket():{data:string, source:array[6:number]}
Get packet from receive buffer (or NULL).

### IpxGetLocalAddress():array[6:number]
Get the local address.

## 3D rendering
Please see the HTML help for details.

### CreateScene(nedge:number, npoly:number)
Allocates memory for a scene.

### ScenePolygon3D(type:POLYTYPE, texture:Bitmap, v:V3D[])
Puts a polygon in the rendering list.

### RenderScene()
Renders all the specified ScenePolygon3D()'s on the current bitmap.

### ClearScene()
Initializes a scene.

### DestroyScene()
Deallocate memory previously allocated by CreateScene.

### SetSceneGap(gap:number)
Set scene gap.

### Polygon3D(type:POLYTYPE, texture:Bitmap, v:V3D[])
Draw 3d polygons using the specified rendering mode.

### Triangle3D(type:POLYTYPE, texture:Bitmap, v1:V3D, v2:V3D, v3:V3D)
Draw 3d triangles, using vertices.

### Quad3D(type:POLYTYPE, texture:Bitmap, v1:V3D, v2:V3D, v3:V3D, v4:V3D)
Draw 3d quads using vertex.

### Clip3D(type:POLYTYPE, min_z:number, max_z:number, v:V3D[])
Clips the polygon given in v'.

## ZBuffer
### zbuf = new ZBuffer()
Create ZBuffer for the current rendering Bitmap.

### zbuf = new ZBuffer(bm:Bitmap)
Create ZBuffer for the given Bitmap.

### zb.width
Width of ZBuffer

### zb.height
Height of ZBuffer

### zb.Set()
Set this ZBuffer as current rendering ZBuffer.

### zb.Clear(z)
Clear ZBuffer with given z value.

## 3dfx/Glide
The API is only documented in the HTML API-doc.

## COMPort
### GetSerialPorts():number[]
Get available serial ports and their addresses

### com = new COMPort(port:number, baud:number, bits:number, parity:number, stop:number, flow:number[, addr:number, irq:number])
Open/create new COM port.

### com.Close()
close port.

### com.FlushInput()
flush receive buffer.

### com.FlushOutput()
 flush send buffer.

### com.IsOutputEmpty():boolean
### com.IsOutputFull():boolean
check state of send buffer.

### com.IsInputEmpty():boolean
### com.IsInputFull():boolean
check state of receive buffer.

### com.WriteByte(number)
### com.WriteString(string):number
Write a byte/string to a COM port.

### com.ReadByte():number
### com.ReadBuffer():string
Read a single byte/the buffer from COM port.

## LPT
### GetParallelPorts():number[]
Get available parallel ports and their addresses

### LPTRawData(port:number, data:number)
read/write data to LPT data register.

### LPTRawStatus(port:number)
read status register of LPT port.

### LPTRawControl(port:number, bits:number)
write bits to LPT control register.

### LPTReset(port:number)
reset parallel port.

### LPTSend(port:number, data:string)
send data to parallel port.

### LPTStatus(port:number)
read parallel port status.

## TCP/IP
### GetLocalIpAddress():number[]
Get the local IP address.

### GetNetworkMask():number[]
Get the netmask.

### Resolve(hostname:string):number[]
Resolve an IP address using DNS.

### ResolveIp(ip:number[]):string
Reverse lookup IP address using DNS.

### GetHostname():string
Get hostname.

### GetDomainname():string
Get domainname.

### http_get(url:string, head:string[]):HTTPResult
Do a HTTP GET request and return the answer as array.

### http_string_content(res:HTTPResult):string
Convert the data array returned by http_get() into a string.

### http_ok(res:HTTPResult):bool
Check if a HTTP request succeeded.

### http_headers(res:HTTPResult):Object
Extract all response headers.

## Sockets
### socket = Socket(host:IpAddres|string, rport:number, [lport:number])
Create a TCP client socket (outgoing connection).

### socket = UdpSocket(host:IpAddres|string, rport:number, [lport:number])
Create a UDP socket.

### socket = ServerSocket(host:IpAddres|string, lport:number)
Create a server socket.

### socket.Close([doFlush:boolean = false])
close the socket.

### socket.WaitFlush()
wait until all written data is flushed.

### socket.WaitInput([timeout:number = 1])
wait on socket for incoming data with timeout.

### socket.ReadByte():number
return the next byte from the socket as number.

### socket.WriteByte(ch:number)
write a byte to a socket.

### socket.WriteBytes(data:number[])
send binary data.

### socket.WriteString(data:string)
send string

### socket.Mode(mode:number)
Set binary or ascii mode for UDP/TCP sockets.

### socket.Flush([flushWait:boolean = false])
Send pending TCP data.

### socket.NoFlush()
Sets non-flush mode on next TCP write.

### socket.FlushNext()
Causes next transmission to have a flush (PUSH bit set).

### socket.DataReady():number
returns number of bytes waiting to be read.

### socket.Established():bool
check if the socket connection is established.

### socket.GetRemoteHost():number[]
get the remote host ip

### socket.GetLocalPort():number
get the local port number

### socket.GetRemotePort():number
get the remote port number

### socket.ReadLine():string
return the next line from the socket as string (blocks until CR/NL).

### socket.ReadString(len:number):string
return data as string (blocks until 'len' was read).

### socket.ReadBytes(len:number):number[]
return data as array of numbers (blocks until 'len' was read).

## ZIP Files
### zip = new Zip(filename:string, mode:string, [compression:number])
Open a ZIP.

### zip.Close()
Close the zip.

### zip.NumEntries():number
Get number of entries in ZIP

### zip.GetEntries():Array
Get entry listing.
[
  [name, is_directory, size, crc32],
  ...
]

### zip.AddFile(entry_path:string, hdd_path:string)
Add file to ZIP.

### zip.ExtractFile(entry_path:string, hdd_path:string)
Extract file from ZIP.

### zip.ReadBytes(entry_name:string):number[]
Return the bytes from the zip entry as number array.

### zip.WriteBytes(entry_name:string, data:number[])
Write a bytes to a zip entry.

## raw disk access
RawWrite() only works when DOjS was started with "-x"

### GetNumberOfFDD():number
get number of FDDs

### GetNumberOfHDD():number
get number of HDDs

### GetDiskStatus():number
query the disk status

### GetRawSectorSize(drive:number):number
get number of sectors for a drive.

### RawRead(disk:number, sector:number):number[]
read a sector from a disk.

### RawWrite(disk:number, sector:number, data:number[])
write a sector to disk
