Difference between revisions of "Oolite JavaScript Reference: Global"

From Elite Wiki
(Added formatCredits() and formatInteger())
m (Added link)
 
(38 intermediate revisions by 9 users not shown)
Line 13: Line 13:
 
  '''galaxyNumber''' : Number (read-only)
 
  '''galaxyNumber''' : Number (read-only)
 
Returns the number of the galaxy the player is in.
 
Returns the number of the galaxy the player is in.
 +
 +
'''See also''': <code>[[Oolite JavaScript Reference: SystemInfo#galaxyID|galaxyID]]</code>
  
 
=== <code>global</code> ===
 
=== <code>global</code> ===
Line 20: Line 22:
 
=== <code>guiScreen</code> ===
 
=== <code>guiScreen</code> ===
 
  '''guiScreen''' : String (read-only)
 
  '''guiScreen''' : String (read-only)
Returns the screen the player is looking at. If in flight, this is <code>"GUI_SCREEN_MAIN"</code>. Currently, the other possible values are <code>"GUI_SCREEN_INTRO1"</code>, <code>"GUI_SCREEN_INTRO2"</code>, <code>"GUI_SCREEN_STATUS"</code>, <code>"GUI_SCREEN_MANIFEST"</code>, <code>"GUI_SCREEN_EQUIP_SHIP"</code>, <code>"GUI_SCREEN_SHIPYARD"</code>, <code>"GUI_SCREEN_LONG_RANGE_CHART"</code>, <code>"GUI_SCREEN_SHORT_RANGE_CHART"</code>, <code>"GUI_SCREEN_SYSTEM_DATA"</code>, <code>"GUI_SCREEN_MARKET"</code>, <code>"GUI_SCREEN_CONTRACTS"</code>, <code>"GUI_SCREEN_OPTIONS"</code>, <code>"GUI_SCREEN_GAMEOPTIONS"</code>, <code>"GUI_SCREEN_LOAD"</code>, <code>"GUI_SCREEN_SAVE"</code>, <code>"GUI_SCREEN_SAVE_OVERWRITE"</code>, <code>"GUI_SCREEN_STICKMAPPER"</code>, <code>"GUI_SCREEN_MISSION"</code> and <code>"GUI_SCREEN_REPORT"</code>. This list may change in future.
+
Returns the screen the player is looking at. If in flight, this is <code>"GUI_SCREEN_MAIN"</code>. In 1.76, the other possible values are <code>"GUI_SCREEN_INTRO1"</code>, <code>"GUI_SCREEN_INTRO2"</code>, <code>"GUI_SCREEN_STATUS"</code>(F5), <code>"GUI_SCREEN_MANIFEST"</code>(F5F5), <code>"GUI_SCREEN_EQUIP_SHIP"</code>(F3), <code>"GUI_SCREEN_SHIPYARD"</code>(F3F3), <code>"GUI_SCREEN_LONG_RANGE_CHART"</code>(F6F6), <code>"GUI_SCREEN_SHORT_RANGE_CHART"</code>(F6), <code>"GUI_SCREEN_SYSTEM_DATA"</code>(F7), <code>"GUI_SCREEN_MARKET"</code>(F8), <code>"GUI_SCREEN_CONTRACTS"</code>, <code>"GUI_SCREEN_OPTIONS"</code>, <code>"GUI_SCREEN_GAMEOPTIONS"</code>, <code>"GUI_SCREEN_LOAD"</code>, <code>"GUI_SCREEN_SAVE"</code>, <code>"GUI_SCREEN_SAVE_OVERWRITE"</code>, <code>"GUI_SCREEN_STICKMAPPER"</code>, <code>"GUI_SCREEN_MISSION"</code> and <code>"GUI_SCREEN_REPORT"</code>.  
 +
 
 +
In 1.77, <code>"GUI_SCREEN_INTERFACES"</code>(F4) is added, and <code>"GUI_SCREEN_CONTRACTS"</code> is removed.
  
 +
In 1.81, <code>"GUI_SCREEN_MARKETINFO"</code>(F8F8) is added.
  
 
=== <code>manifest</code> ===
 
=== <code>manifest</code> ===
Line 38: Line 43:
 
  missionVariables.exampleVar = 42;
 
  missionVariables.exampleVar = 42;
 
  let x = missionVariables.exampleVar; // x is now the number 42
 
  let x = missionVariables.exampleVar; // x is now the number 42
 +
Do not use <code>false</code> in missionVariables! It will return <code>true</code> because it will be parsed as a string. Use 0 or 1 to store boolean values.
  
Mission variables can also be used in legacy scripts and in [[Misc_plists|descriptions.plist]] string expansions, by prefixing the name with “mission_”. Example:
+
You can store arrays using [http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON JSON] stringify and parse methods. For example:
 +
this.$MyArray = [];
 +
 +
this.startUp = function() {
 +
        var s = missionVariables.$MyArray;
 +
        if( s && s.length > 0 ) this.$MyArray = JSON.parse(s);
 +
}
 +
 +
this.playerWillSaveGame = function(message) {
 +
        missionVariables.$MyArray = JSON.stringify(this.$MyArray);
 +
}
 +
Mission variables can also be used in legacy scripts and in [[descriptions.plist]] string expansions, by prefixing the name with <code>"mission_"</code>. Example:
 
  expandDescription("My variable is [mission_exampleVar].")
 
  expandDescription("My variable is [mission_exampleVar].")
 
 
Setting and retrieving mission variables has a significant overhead'''*'''. If a function needs to use a mission variable value several times, it is strongly recommended that it be copied into a local variable and, if necessary, stored back once. Example:
 
Setting and retrieving mission variables has a significant overhead'''*'''. If a function needs to use a mission variable value several times, it is strongly recommended that it be copied into a local variable and, if necessary, stored back once. Example:
 
  let x = missionVariables.exampleVar;
 
  let x = missionVariables.exampleVar;
Line 47: Line 63:
 
  else  x = processBigValue(x);
 
  else  x = processBigValue(x);
 
  missionVariables.exampleVar = x;
 
  missionVariables.exampleVar = x;
 
 
Mission variable names may not begin with an underscore (“_”). Unassigned mission variables are always <code>null</code>.
 
Mission variable names may not begin with an underscore (“_”). Unassigned mission variables are always <code>null</code>.
  
'''*''' On a computer where the loop "<code>for ( var i= 0 ; i < 1000 ; i++){}</code>" takes just 0.62 msec, will the same loop with missionVarriables <code>for (missionVariables.i= 0 ; missionVariables.i < 1000 ; missionVariables.i++){}</code> consumes a full 38 msec. That is 60 times longer.
+
'''*''' On a computer where the loop <code>for (var i = 0; i < 1000; i++) {}</code> takes just 0.62 msec, the same loop with missionVarriables <code>for (missionVariables.i = 0; missionVariables.i < 1000; missionVariables.i++) {}</code> consumes a full 38 msec. That is 60 times longer.
  
 
=== <code>oolite</code> ===
 
=== <code>oolite</code> ===
Line 67: Line 82:
 
  '''timeAccelerationFactor''' : Number (read/write)
 
  '''timeAccelerationFactor''' : Number (read/write)
 
Also known as TAF. Will change the ratio between game real time and actual real time (default is 1). The accepted range is between 0.0625 (1/16) and 16. Attempting to set numbers outside this range will reset the TAF to 1. (In end-user stable builds, this will be a read-only property with the value 1.)
 
Also known as TAF. Will change the ratio between game real time and actual real time (default is 1). The accepted range is between 0.0625 (1/16) and 16. Attempting to set numbers outside this range will reset the TAF to 1. (In end-user stable builds, this will be a read-only property with the value 1.)
 +
 +
=== <code>worldScriptNames</code> ===
 +
'''worldScriptNames''' : Array of strings (read-only)
 +
A list of the names of world script objects, the keys of <code>[[#worldScripts|worldScripts]]</code>.
  
 
=== <code>worldScripts</code> ===
 
=== <code>worldScripts</code> ===
 
  '''worldScripts''' : Object (read-only)
 
  '''worldScripts''' : Object (read-only)
A list of world script objects.
+
All loaded world script objects. The keys are the <code>name</code> properties of the scripts.
  
 
'''Example:'''
 
'''Example:'''
Line 78: Line 97:
 
=== <code>addFrameCallback</code> ===
 
=== <code>addFrameCallback</code> ===
 
  function '''addFrameCallback'''(callback : Function) : ''TrackingID''
 
  function '''addFrameCallback'''(callback : Function) : ''TrackingID''
Registers a ''frame callback'' which will be invoked every frame, after entity updates but before rendering. This can be used to implement animations. The return value is a ''tracking ID'' which may be passed to <code>[[#removeFrameCallback|removeFrameCallback()]]</code>; the type and meaning of the tracking ID is unspecified and may change at any time. Frame callbacks are automatically removed when the game resets (for instance, when the player dies), but not at any other time.
+
Registers a ''frame callback'' which will be invoked every frame, after entity updates but before rendering. This can be used to implement animations, to apply gradual changes in ship state, to build large data structures without risking reaching processing time limits by trying to do it all at once, or to watch variables which need a same-frame response to changes. The return value is a ''tracking ID'' which may be passed to <code>[[#removeFrameCallback|removeFrameCallback()]]</code>; the type and meaning of the tracking ID is unspecified and may change at any time. Frame callbacks are automatically removed when the game resets (for instance, when the player dies), but not at any other time.
  
 
The callback is passed one parameter, <code>delta</code>, which is the time since the last frame (in [[Time_scales in Oolite|game clock time]]). Frame callbacks fire even when the game is paused, in which case <code>delta</code> is 0.
 
The callback is passed one parameter, <code>delta</code>, which is the time since the last frame (in [[Time_scales in Oolite|game clock time]]). Frame callbacks fire even when the game is paused, in which case <code>delta</code> is 0.
Line 84: Line 103:
 
'''Example:'''
 
'''Example:'''
 
  var sum = 0;
 
  var sum = 0;
  this.fcb = addFrameCallback(function (delta)
+
  this.$fcb = addFrameCallback(function (delta)
 
  {
 
  {
 
     sum += delta;
 
     sum += delta;
 
     log("Time elapsed: " + sum + " (delta: " + delta + ")");
 
     log("Time elapsed: " + sum + " (delta: " + delta + ")");
  }
+
  });
 +
 
 +
'''See also:''' <code>[[#removeFrameCallback|removeFrameCallback()]]</code>, <code>[[#isValidFrameCallback|isValidFrameCallback()]]</code>, and for repeated events with a longer repeat interval, use [[Oolite_JavaScript_Reference:_Timer|Timers]] instead.
 +
 
 +
See [https://bb.oolite.space/viewtopic.php?f=4&t=8941 RFC: frame callbacks] (2011)
 +
 
 +
=== <code>clearExtraGuiScreenKeys</code> ===
 +
{{oolite-method-added|1.91}}
 +
function '''clearExtraGuiScreenKeys'''(guiScreen: string, key : string)
 +
Clears additional keys that have been defined for use on a particular gui screen with [[#setExtraGuiScreenKeys|setExtraGuiScreenKeys()]].
 +
 
 +
<code>guiScreen</code> is the gui screen that will have it's additional keys cleared.  Valid possibilities are:  GUI_SCREEN_OPTIONS, GUI_SCREEN_EQUIP_SHIP, GUI_SCREEN_SHIPYARD, GUI_SCREEN_INTERFACES, GUI_SCREEN_STATUS, GUI_SCREEN_MANIFEST, GUI_SCREEN_SHORT_RANGE_CHART, GUI_SCREEN_LONG_RANGE_CHART, GUI_SCREEN_SYSTEM_DATA, GUI_SCREEN_MARKET and GUI_SCREEN_MARKETINFO.<br>
 +
<code>key</code> is the key used to register the keys originally, usually <code>"this.name"</code>
 +
 
 +
'''Example'''
 +
clearExtraGuiScreenKeys("GUI_SCREEN_MANIFEST", this.name);
  
'''See also:''' <code>[[#removeFrameCallback|removeFrameCallback()]]</code>, <code>[[#isValidFrameCallback|isValidFrameCallback()]]</code>
+
'''See also:''' <code>[[#setExtraGuiScreenKeys|setExtraGuiScreenKeys()]]</code>
  
 
=== <code>displayNameForCommodity</code>  ===
 
=== <code>displayNameForCommodity</code>  ===
  function '''displayNameForCommodity'''(commodityName : String)  
+
  function '''displayNameForCommodity'''(commodityName : String) : String
Returns the display name corresponding to the specified commodity. Useful in conjunction with localisation OXPs, or expansions that rename commodities depending on which station / system the player is at.
+
Returns the display name corresponding to the specified commodity. Useful in conjunction with language-localisation OXPs, or expansions that rename commodities depending on which station / system the player is at.
 +
 
 +
'''Note''' See discussion at https://bb.oolite.space/viewtopic.php?f=3&t=12242 (2012)
  
 
=== <code>expandDescription</code>  ===
 
=== <code>expandDescription</code>  ===
 
  function '''expandDescription'''(description : String [, locals : Object (Dictionary)]) : String
 
  function '''expandDescription'''(description : String [, locals : Object (Dictionary)]) : String
Expands a string, substituting special tokens and any key inside square brackets with the substitution rules for [[Methods#Communications|Communications]].
+
Expands a string, substituting special tokens and any key inside square brackets with the substitution rules for [[Missiontext.plist#Special_Expansions|string expansions]].
 
When local key/value pairs are provided, they take precedence over any other values.
 
When local key/value pairs are provided, they take precedence over any other values.
 +
 +
In Oolite 1.79 or later, this method uses a higher quality random number generator which does not have noticeable correlation problems when used for recursive expansion.
  
 
'''Example:'''
 
'''Example:'''
  expandDescription("My ball is [my_color].", { my_color: "red" });  
+
  expandDescription("My ball is [my_color].", { my_color: "red" });
  
 
=== <code>expandMissionText</code>  ===
 
=== <code>expandMissionText</code>  ===
 
  function '''expandMissionText'''(textKey: String [, locals : Object (Dictionary)]) : String
 
  function '''expandMissionText'''(textKey: String [, locals : Object (Dictionary)]) : String
Load a string specified by <code>textKey</code> from [[missiontext.plist]], then perform <code>[[#expandDescription|expandDescription()]]</code>-type substitutions on it, and also replace \n” with line breaks. The <code>local</code> parameter works as with <code>[[#expandDescription|expandDescription()]]</code>.
+
Load a string specified by <code>textKey</code> from [[missiontext.plist]], then perform <code>[[#expandDescription|expandDescription()]]</code>type substitutions on it, and also replace <code>"\n"</code> with line breaks. The <code>local</code> parameter works as with <code>[[#expandDescription|expandDescription()]]</code>.
 +
 
 +
In Oolite 1.79 or later, this method uses a higher quality random number generator which does not have noticeable correlation problems when used for recursive expansion.
  
 
'''Example:'''
 
'''Example:'''
Line 113: Line 153:
 
=== <code>formatCredits</code>  ===
 
=== <code>formatCredits</code>  ===
 
  function '''formatCredits'''(value : number, [includeDeciCredits : boolean, [includeCurrencySymbol : boolean]]) : String
 
  function '''formatCredits'''(value : number, [includeDeciCredits : boolean, [includeCurrencySymbol : boolean]]) : String
Converts the <code>number</code> parameter to a string formatted in a currency friendly manner. If <code>includeDeciCredits</code> is <code>true</code> the string will be formated to 1 decimal place. If <code>includeCurrencySymbol</code> is <code>true</code> the string is terminated with the symbol.
+
Converts the <code>value</code> parameter to a string formatted in a currency friendly manner. If <code>includeDeciCredits</code> is <code>true</code> the string will be formatted to 1 decimal place. If <code>includeCurrencySymbol</code> is <code>true</code> an appropriate currency symbol following any localisation rules is included. The default currency symbol is a terminal ₢.
  
 
=== <code>formatInteger</code>  ===
 
=== <code>formatInteger</code>  ===
 
  function '''formatInteger'''(value : number) : String
 
  function '''formatInteger'''(value : number) : String
Converts the <code>number</code> parameter to a string formatted as an Integer.
+
Converts the <code>value</code> parameter to a string formatted as an integer following any localisation rules in place.
 +
 
 +
=== <code>getGuiColorSettingForKey</code> ===
 +
{{oolite-method-added|1.87}}
 +
function '''getGuiColorSettingForKey'''(keyname : string) : Array
 +
Returns the current color for a particular keyname (referenced in the [[gui-settings.plist]] file). Returns an array of RGBA values.
 +
 
 +
'''See also:''' <code>[[#setGuiColorSettingForKey|setGuiColorSettingForKey()]]</code>
 +
 
 +
=== <code>getScreenBackgroundForKey</code>  ===
 +
{{oolite-method-added|1.85}}
 +
function '''getScreenBackgroundForKey'''(keyname : string) : guiTextureSpecifier
 +
Returns the guiTextureSpecifier for a particular keyname (referenced in the screenbackgrounds.plist file).
 +
 
 +
''guiTextureSpecifier'' can be either a string or an object with the required key <code>name</code> and optional keys <code>width</code> and <code>height</code>. If neither width nor height is specified, the dimensions of the image are used. If only one is specified, the other is calculated such that the image is not distorted. The scale unit is 1/480 of the height of the window; in other words, the window is always considered 480 units high, and the width depends on the aspect ratio of the window.
 +
 
 +
'''Example:'''
 +
getScreenBackgroundForKey("long_range_chart_mission");
 +
 
 +
'''See also:''' <code>[[#setScreenBackgroundForKey|setScreenBackgroundForKey()]]</code>
  
 
=== <code>isValidFrameCallback</code> ===
 
=== <code>isValidFrameCallback</code> ===
Line 127: Line 186:
 
=== <code>log</code>  ===
 
=== <code>log</code>  ===
 
  function '''log'''([messageClass : String ,] message : String)
 
  function '''log'''([messageClass : String ,] message : String)
Writes a message to Oolite's log. The optional messageClass can be used to specify which type of message is written to the log.<br>
+
Writes a message to Oolite's log. The optional messageClass parameter can be used to specify which type of message is written to the log. The default messageClass is <code>script.debug.message</code>. When set to <code>true</code>, the messages will be written to the log file. The classes to be logged are set in the file <code>[[logcontrol.plist]]</code>. messageClasses not listed in <code>logcontrol.plist</code> are always logged.
The default messageClass is <code>script.debug.message</code>. When set to true, the messages will be written to the logfile. The classes to be logged are set in the file <code>logcontrol.plist</code>. messageClasses not listed in <code>logcontrol.plist</code> are always logged.
 
  
 
'''Example:'''
 
'''Example:'''
 
  log("myOXP.init","MyOXP initialised and ready!");
 
  log("myOXP.init","MyOXP initialised and ready!");
  
You can temporary enable/disable logging above message by typing in the console:
+
You can temporarily enable/disable logging the above message by typing in the console:
 
  console.setDisplayMessagesInClass("myOXP.init", true/false)
 
  console.setDisplayMessagesInClass("myOXP.init", true/false)
 +
 +
===<code>pauseGame</code>===
 +
function '''pauseGame'''() : Boolean
 +
Pauses the game.  It does not work on screens that cannot be paused by keyboard: mission screens, long range chart, arrival report, save menu. In those cases, the method returns <code>false</code>. Otherwise, it pauses the game and returns <code>true</code>.
 +
 +
This was added in v1.87 (the exact version is unconfirmed)
 +
 +
'''See also:''' [https://bb.oolite.space/viewtopic.php?f=6&t=18900 Scriptable pause?]
  
 
=== <code>randomInhabitantsDescription</code>  ===
 
=== <code>randomInhabitantsDescription</code>  ===
  function '''randomInhabitantsDescription'''([plural : boolean, default true])
+
  function '''randomInhabitantsDescription'''([plural : boolean, default true]) : String
Returns a random sentient species name, like “Large Red Fat Insects” or “Human Colonials”, following the same pattern (and probability distribution) as for planet inhabitants.
+
Returns a random sentient species name, like <code>"Large Red Fat Insects"</code> or <code>"Human Colonials"</code>, following the same pattern (and probability distribution) as for planet inhabitants.
  
 
'''Example:'''
 
'''Example:'''
  player.consoleMessage("You'll meet a " + randomInhabitantsDescription(false) +
+
  player.consoleMessage("You'll meet a " + randomInhabitantsDescription(false) + ". She'll be with a group of " + randomInhabitantsDescription() + ".");
                      ". She'll be with a group of " + randomInhabitantsDescription(true) +".");
 
  
 
=== <code>randomName</code>  ===
 
=== <code>randomName</code>  ===
  function '''randomName'''()
+
  function '''randomName'''() : String
 
Returns a random capitalised word, suitable for use as name, or indeed surname.
 
Returns a random capitalised word, suitable for use as name, or indeed surname.
  
 
'''Example:'''
 
'''Example:'''
  player.consoleMessage(randomName() + " " + randomName() +" rules this system with an iron fist.");
+
  player.consoleMessage(randomName() + " " + randomName() + " rules this system with an iron fist.");
  
 
=== <code>removeFrameCallback</code> ===
 
=== <code>removeFrameCallback</code> ===
Line 157: Line 222:
 
'''See also:''' <code>[[#addFrameCallback|addFrameCallback()]]</code>, <code>[[#isValidFrameCallback|isValidFrameCallback()]]</code>
 
'''See also:''' <code>[[#addFrameCallback|addFrameCallback()]]</code>, <code>[[#isValidFrameCallback|isValidFrameCallback()]]</code>
  
=== <code>setScreenBackground</code> ===
+
=== <code>setExtraGuiScreenKeys</code> ===
 +
{{oolite-method-added|1.91}}
 +
function '''setExtraGuiScreenKeys'''(key : string, options : dictionary)
 +
Allows additional keys to be defined for use on a particular gui screen.
 +
 
 +
<code>"key"</code> is a unique identifier, usually set as the script name.<br>
 +
<code>"options"</code> is a dictionary with the following properties:
 +
* <code>guiScreen</code> (string): the gui screen to which the extra keys will be attached. Valid possibilities are:  GUI_SCREEN_OPTIONS, GUI_SCREEN_EQUIP_SHIP, GUI_SCREEN_SHIPYARD, GUI_SCREEN_INTERFACES, GUI_SCREEN_STATUS, GUI_SCREEN_MANIFEST, GUI_SCREEN_SHORT_RANGE_CHART, GUI_SCREEN_LONG_RANGE_CHART, GUI_SCREEN_SYSTEM_DATA, GUI_SCREEN_MARKET and GUI_SCREEN_MARKETINFO
 +
* <code>registerKeys</code> (dictionary): the key definitions to be registered. For example: <code>options["registerKeys"]["myKey"] = [{key:"h",mod1:true}];</code> would register the Ctrl+h key, linking it to "myKey" as an ID.
 +
* <code>callback</code> (function): the function to call when the use presses one of the registered keys. The ID defined in the registerKeys properties will be passed to the function as a parameter.
 +
 
 +
'''Example'''
 +
setExtraGuiScreenKeys(this.name,
 +
  {
 +
    guiScreen:"GUI_SCREEN_MANIFEST",
 +
    registerKeys:{"key1":[{key:"g",mod1:true}],
 +
    callback:this.$myGuiScreenCallback.bind(this)
 +
  }
 +
);
 +
 
 +
This code registers the Ctrl+g keypress on the F5F5 Manifest screen. The function callback, <code>$myGuiScreenCallback</code> will be passed "key1" as a property when the Ctrl+g is pressed on that screen.
 +
 
 +
'''See also:''' <code>[[#clearExtraGuiScreenKeys|clearExtraGuiScreenKeys()]]</code>
 +
 
 +
=== <code>setGuiColorSettingForKey</code> ===
 +
{{oolite-method-added|1.87}}
 +
function '''setGuiColorSettingorKey'''(keyname : string , [[Materials_in_Oolite#Colour_specifiers|Colour specifier]] : string)
 +
Override the color setting for a particular keyname (referenced in the [[gui-settings.plist]] file) with the specified color.  This override is only for the current play-session and does not get written to [[gui-settings.plist]].
 +
 
 +
'''Example:'''
 +
setGuiColorSettingForKey("screen_title_color", "whiteColor");
 +
 
 +
'''See also:''' <code>[[#getGuiColorSettingForKey|getGuiColorSettingForKey()]]</code>
 +
 
 +
=== <code>setScreenBackground</code> ===
 
  function '''setScreenBackground'''(image : ''guiTextureSpecifier'')  
 
  function '''setScreenBackground'''(image : ''guiTextureSpecifier'')  
 
Temporary override that sets the background of the current gui screen to the specified image. Override is lost after the player switches screens.
 
Temporary override that sets the background of the current gui screen to the specified image. Override is lost after the player switches screens.
Line 164: Line 263:
  
 
'''Example:'''
 
'''Example:'''
  setScreenBackground({ name: "oolite-nova-system.png", height: 512 });
+
  setScreenBackground({ name: "oolite-nova-system.png", height: 480 });
 +
 
 +
'''See also:''' <code>[[#setScreenOverlay]]</code> & [[Screenbackgrounds.plist]]
 +
 
 +
=== <code>setScreenBackgroundForKey</code>  ===
 +
{{oolite-method-added|1.85}}
 +
function '''setScreenBackgroundForKey'''(keyname : string, image : ''guiTextureSpecifier'')
 +
Override the background for a particular keyname (referenced in the screenbackgrounds.plist file) with the specified image. Override is only for the current play-session only and does not get written out to screenbackgrounds.plist.
 +
 
 +
''guiTextureSpecifier'' can be either a string or an object with the required key <code>name</code> and optional keys <code>width</code> and <code>height</code>. If neither width nor height is specified, the dimensions of the image are used. If only one is specified, the other is calculated such that the image is not distorted. The scale unit is 1/480 of the height of the window; in other words, the window is always considered 480 units high, and the width depends on the aspect ratio of the window.
 +
 
 +
'''Example:'''
 +
setScreenBackgroundForKey("long_range_chart_mission", { name: "my_mission_background.png", height: 480 });
 +
 
 +
'''See also:''' <code>[[#getScreenBackgroundForKey|getScreenBackgroundForKey()]]</code>
  
 
=== <code>setScreenOverlay</code>  ===
 
=== <code>setScreenOverlay</code>  ===
Line 174: Line 287:
 
'''Example:'''
 
'''Example:'''
 
  setScreenOverlay('trumblebox.png');
 
  setScreenOverlay('trumblebox.png');
 +
 +
'''See also:''' [[Screenbackgrounds.plist]]
  
 
=== <code>takeSnapShot</code>  ===
 
=== <code>takeSnapShot</code>  ===
  function '''takeSnapShot'''([filename : String]) : Bool
+
  function '''takeSnapShot'''([filename : String]) : Boolean
Saves a snapshot of the current screen to your hard disk. A filename is optional. When a name is used, only alphanumeric values and "-" and "_" are allowed for the filename. The appropriate extension for the used operating system (like .png) is added by Oolite and should not be part of the filename.<br>
+
Saves a snapshot of the current screen to your hard disk. A filename is optional. When a name is used, only alphanumeric values and <code>"-"</code> and <code>"_"</code> are allowed for the filename. The appropriate extension for the used operating system (like .png) is added by Oolite and should not be part of the filename.<br>
When a filename already exists, it is not overwritten but the string "-xxx" is added, starting with "-001".<br>
+
When a filename already exists, it is not overwritten but the string <code>"-xxx"</code> is added, starting with <code>"-001"</code>.<br>
 
<code>takeSnapShot()</code> will not be available in the stable release version of Oolite, but will be available in a special OXP developer release.
 
<code>takeSnapShot()</code> will not be available in the stable release version of Oolite, but will be available in a special OXP developer release.
  
Line 185: Line 300:
  
 
[[Category:Oolite JavaScript Reference]]
 
[[Category:Oolite JavaScript Reference]]
 +
 +
== Reserved Words ==
 +
 +
=== <code>Quaternion</code> ===
 +
 +
[[Oolite_JavaScript_Reference:_Quaternion]]
 +
 +
=== <code>Vector3D</code> ===
 +
 +
[[Oolite_JavaScript_Reference:_Vector3D]]

Latest revision as of 09:47, 1 July 2024

Global variables and functions are visible to all scripts. They are also properties of global, which is itself a global variable and hence a property of itself.

Properties

clock

clock : Clock (read-only)

This property allows an OXP to access the game clock's properties and methods.

defaultFont

defaultFont : Object (read-only)

An object with a single method, measureString(string), which returns the width of the specified string, as it would be shown on the screen, in ems. One em is the intrinsic unit size of a font; for example, if a font is rendered at 12 points, 1 em = 12 pt. The mission screen text area is 32 em wide.

galaxyNumber

galaxyNumber : Number (read-only)

Returns the number of the galaxy the player is in.

See also: galaxyID

global

global : Global (read-only)

All global variables and functions are actually properties of the global object. The global object is a property of itself, and this is it.

guiScreen

guiScreen : String (read-only)

Returns the screen the player is looking at. If in flight, this is "GUI_SCREEN_MAIN". In 1.76, the other possible values are "GUI_SCREEN_INTRO1", "GUI_SCREEN_INTRO2", "GUI_SCREEN_STATUS"(F5), "GUI_SCREEN_MANIFEST"(F5F5), "GUI_SCREEN_EQUIP_SHIP"(F3), "GUI_SCREEN_SHIPYARD"(F3F3), "GUI_SCREEN_LONG_RANGE_CHART"(F6F6), "GUI_SCREEN_SHORT_RANGE_CHART"(F6), "GUI_SCREEN_SYSTEM_DATA"(F7), "GUI_SCREEN_MARKET"(F8), "GUI_SCREEN_CONTRACTS", "GUI_SCREEN_OPTIONS", "GUI_SCREEN_GAMEOPTIONS", "GUI_SCREEN_LOAD", "GUI_SCREEN_SAVE", "GUI_SCREEN_SAVE_OVERWRITE", "GUI_SCREEN_STICKMAPPER", "GUI_SCREEN_MISSION" and "GUI_SCREEN_REPORT".

In 1.77, "GUI_SCREEN_INTERFACES"(F4) is added, and "GUI_SCREEN_CONTRACTS" is removed.

In 1.81, "GUI_SCREEN_MARKETINFO"(F8F8) is added.

manifest

manifest : Manifest (read-only)

An alias to player.ship.manifest.

mission

mission : Mission (read-only)

See Oolite JavaScript Reference: Mission.

missionVariables

missionVariables : Object (read-only)

The missionVariables object stores values that are stored in saved games. This is the main way for scripts to store information permanently.

Whenever a value is assigned to a property of missionVariables, it is converted to a string object and tracked with the player. When the value is read, it will be converted to a number if possible, otherwise returned as a string. Example:

missionVariables.exampleVar = 42;
let x = missionVariables.exampleVar; // x is now the number 42

Do not use false in missionVariables! It will return true because it will be parsed as a string. Use 0 or 1 to store boolean values.

You can store arrays using JSON stringify and parse methods. For example:

this.$MyArray = [];

this.startUp = function() {
       var s = missionVariables.$MyArray;
       if( s && s.length > 0 ) this.$MyArray = JSON.parse(s);
}

this.playerWillSaveGame = function(message) {
       missionVariables.$MyArray = JSON.stringify(this.$MyArray);
}

Mission variables can also be used in legacy scripts and in descriptions.plist string expansions, by prefixing the name with "mission_". Example:

expandDescription("My variable is [mission_exampleVar].")

Setting and retrieving mission variables has a significant overhead*. If a function needs to use a mission variable value several times, it is strongly recommended that it be copied into a local variable and, if necessary, stored back once. Example:

let x = missionVariables.exampleVar;
if (x < 3)  x = processSmallValue(x);
else  x = processBigValue(x);
missionVariables.exampleVar = x;

Mission variable names may not begin with an underscore (“_”). Unassigned mission variables are always null.

* On a computer where the loop for (var i = 0; i < 1000; i++) {} takes just 0.62 msec, the same loop with missionVarriables for (missionVariables.i = 0; missionVariables.i < 1000; missionVariables.i++) {} consumes a full 38 msec. That is 60 times longer.

oolite

oolite : Oolite (read-only)

An object describing properties of the Oolite application; see Oolite JavaScript Reference: Oolite.

player

player : Player (read-only)

This property allows an OXP to access the player object's properties and methods.

system

system : System (read-only)

This property allows an OXP to access the current system's properties and methods.

timeAccelerationFactor

timeAccelerationFactor : Number (read/write)

Also known as TAF. Will change the ratio between game real time and actual real time (default is 1). The accepted range is between 0.0625 (1/16) and 16. Attempting to set numbers outside this range will reset the TAF to 1. (In end-user stable builds, this will be a read-only property with the value 1.)

worldScriptNames

worldScriptNames : Array of strings (read-only)

A list of the names of world script objects, the keys of worldScripts.

worldScripts

worldScripts : Object (read-only)

All loaded world script objects. The keys are the name properties of the scripts.

Example:

log(worldScripts["oolite-nova"].version);

Methods

addFrameCallback

function addFrameCallback(callback : Function) : TrackingID

Registers a frame callback which will be invoked every frame, after entity updates but before rendering. This can be used to implement animations, to apply gradual changes in ship state, to build large data structures without risking reaching processing time limits by trying to do it all at once, or to watch variables which need a same-frame response to changes. The return value is a tracking ID which may be passed to removeFrameCallback(); the type and meaning of the tracking ID is unspecified and may change at any time. Frame callbacks are automatically removed when the game resets (for instance, when the player dies), but not at any other time.

The callback is passed one parameter, delta, which is the time since the last frame (in game clock time). Frame callbacks fire even when the game is paused, in which case delta is 0.

Example:

var sum = 0;
this.$fcb = addFrameCallback(function (delta)
{
    sum += delta;
    log("Time elapsed: " + sum + " (delta: " + delta + ")");
});

See also: removeFrameCallback(), isValidFrameCallback(), and for repeated events with a longer repeat interval, use Timers instead.

See RFC: frame callbacks (2011)

clearExtraGuiScreenKeys

This method was added in Oolite test release 1.91.

function clearExtraGuiScreenKeys(guiScreen: string, key : string)

Clears additional keys that have been defined for use on a particular gui screen with setExtraGuiScreenKeys().

guiScreen is the gui screen that will have it's additional keys cleared. Valid possibilities are: GUI_SCREEN_OPTIONS, GUI_SCREEN_EQUIP_SHIP, GUI_SCREEN_SHIPYARD, GUI_SCREEN_INTERFACES, GUI_SCREEN_STATUS, GUI_SCREEN_MANIFEST, GUI_SCREEN_SHORT_RANGE_CHART, GUI_SCREEN_LONG_RANGE_CHART, GUI_SCREEN_SYSTEM_DATA, GUI_SCREEN_MARKET and GUI_SCREEN_MARKETINFO.
key is the key used to register the keys originally, usually "this.name"

Example

clearExtraGuiScreenKeys("GUI_SCREEN_MANIFEST", this.name);

See also: setExtraGuiScreenKeys()

displayNameForCommodity

function displayNameForCommodity(commodityName : String) : String

Returns the display name corresponding to the specified commodity. Useful in conjunction with language-localisation OXPs, or expansions that rename commodities depending on which station / system the player is at.

Note See discussion at https://bb.oolite.space/viewtopic.php?f=3&t=12242 (2012)

expandDescription

function expandDescription(description : String [, locals : Object (Dictionary)]) : String

Expands a string, substituting special tokens and any key inside square brackets with the substitution rules for string expansions. When local key/value pairs are provided, they take precedence over any other values.

In Oolite 1.79 or later, this method uses a higher quality random number generator which does not have noticeable correlation problems when used for recursive expansion.

Example:

expandDescription("My ball is [my_color].", { my_color: "red" });

expandMissionText

function expandMissionText(textKey: String [, locals : Object (Dictionary)]) : String

Load a string specified by textKey from missiontext.plist, then perform expandDescription()type substitutions on it, and also replace "\n" with line breaks. The local parameter works as with expandDescription().

In Oolite 1.79 or later, this method uses a higher quality random number generator which does not have noticeable correlation problems when used for recursive expansion.

Example:

expandMissionText("oolite_trumble_title");

formatCredits

function formatCredits(value : number, [includeDeciCredits : boolean, [includeCurrencySymbol : boolean]]) : String

Converts the value parameter to a string formatted in a currency friendly manner. If includeDeciCredits is true the string will be formatted to 1 decimal place. If includeCurrencySymbol is true an appropriate currency symbol following any localisation rules is included. The default currency symbol is a terminal ₢.

formatInteger

function formatInteger(value : number) : String

Converts the value parameter to a string formatted as an integer following any localisation rules in place.

getGuiColorSettingForKey

This method was added in Oolite test release 1.87.

function getGuiColorSettingForKey(keyname : string) : Array

Returns the current color for a particular keyname (referenced in the gui-settings.plist file). Returns an array of RGBA values.

See also: setGuiColorSettingForKey()

getScreenBackgroundForKey

This method was added in Oolite test release 1.85.

function getScreenBackgroundForKey(keyname : string) : guiTextureSpecifier

Returns the guiTextureSpecifier for a particular keyname (referenced in the screenbackgrounds.plist file).

guiTextureSpecifier can be either a string or an object with the required key name and optional keys width and height. If neither width nor height is specified, the dimensions of the image are used. If only one is specified, the other is calculated such that the image is not distorted. The scale unit is 1/480 of the height of the window; in other words, the window is always considered 480 units high, and the width depends on the aspect ratio of the window.

Example:

getScreenBackgroundForKey("long_range_chart_mission");

See also: setScreenBackgroundForKey()

isValidFrameCallback

function isValidFrameCallback(trackingID: TrackingID) : Boolean

Returns true if trackingID identifies a frame callback which has been registered with addFrameCallback() and not yet removed. (There should be no need to use this except for debugging and testing.)

See also: addFrameCallback(), removeFrameCallback()

log

function log([messageClass : String ,] message : String)

Writes a message to Oolite's log. The optional messageClass parameter can be used to specify which type of message is written to the log. The default messageClass is script.debug.message. When set to true, the messages will be written to the log file. The classes to be logged are set in the file logcontrol.plist. messageClasses not listed in logcontrol.plist are always logged.

Example:

log("myOXP.init","MyOXP initialised and ready!");

You can temporarily enable/disable logging the above message by typing in the console:

console.setDisplayMessagesInClass("myOXP.init", true/false)

pauseGame

function pauseGame() : Boolean

Pauses the game. It does not work on screens that cannot be paused by keyboard: mission screens, long range chart, arrival report, save menu. In those cases, the method returns false. Otherwise, it pauses the game and returns true.

This was added in v1.87 (the exact version is unconfirmed)

See also: Scriptable pause?

randomInhabitantsDescription

function randomInhabitantsDescription([plural : boolean, default true]) : String

Returns a random sentient species name, like "Large Red Fat Insects" or "Human Colonials", following the same pattern (and probability distribution) as for planet inhabitants.

Example:

player.consoleMessage("You'll meet a " + randomInhabitantsDescription(false) + ". She'll be with a group of " + randomInhabitantsDescription() + ".");

randomName

function randomName() : String

Returns a random capitalised word, suitable for use as name, or indeed surname.

Example:

player.consoleMessage(randomName() + " " + randomName() + " rules this system with an iron fist.");

removeFrameCallback

function removeFrameCallback(trackingID : TrackingID)

Removes a frame callback previously registered with addFrameCallback().

See also: addFrameCallback(), isValidFrameCallback()

setExtraGuiScreenKeys

This method was added in Oolite test release 1.91.

function setExtraGuiScreenKeys(key : string, options : dictionary)

Allows additional keys to be defined for use on a particular gui screen.

"key" is a unique identifier, usually set as the script name.
"options" is a dictionary with the following properties:

  • guiScreen (string): the gui screen to which the extra keys will be attached. Valid possibilities are: GUI_SCREEN_OPTIONS, GUI_SCREEN_EQUIP_SHIP, GUI_SCREEN_SHIPYARD, GUI_SCREEN_INTERFACES, GUI_SCREEN_STATUS, GUI_SCREEN_MANIFEST, GUI_SCREEN_SHORT_RANGE_CHART, GUI_SCREEN_LONG_RANGE_CHART, GUI_SCREEN_SYSTEM_DATA, GUI_SCREEN_MARKET and GUI_SCREEN_MARKETINFO
  • registerKeys (dictionary): the key definitions to be registered. For example: options["registerKeys"]["myKey"] = [{key:"h",mod1:true}]; would register the Ctrl+h key, linking it to "myKey" as an ID.
  • callback (function): the function to call when the use presses one of the registered keys. The ID defined in the registerKeys properties will be passed to the function as a parameter.

Example

setExtraGuiScreenKeys(this.name,
  {
    guiScreen:"GUI_SCREEN_MANIFEST",
    registerKeys:{"key1":[{key:"g",mod1:true}],
    callback:this.$myGuiScreenCallback.bind(this)
  }
);

This code registers the Ctrl+g keypress on the F5F5 Manifest screen. The function callback, $myGuiScreenCallback will be passed "key1" as a property when the Ctrl+g is pressed on that screen.

See also: clearExtraGuiScreenKeys()

setGuiColorSettingForKey

This method was added in Oolite test release 1.87.

function setGuiColorSettingorKey(keyname : string , Colour specifier : string) 

Override the color setting for a particular keyname (referenced in the gui-settings.plist file) with the specified color. This override is only for the current play-session and does not get written to gui-settings.plist.

Example:

setGuiColorSettingForKey("screen_title_color", "whiteColor");

See also: getGuiColorSettingForKey()

setScreenBackground

function setScreenBackground(image : guiTextureSpecifier) 

Temporary override that sets the background of the current gui screen to the specified image. Override is lost after the player switches screens.

guiTextureSpecifier can be either a string or an object with the required key name and optional keys width and height. If neither width nor height is specified, the dimensions of the image are used. If only one is specified, the other is calculated such that the image is not distorted. The scale unit is 1/480 of the height of the window; in other words, the window is always considered 480 units high, and the width depends on the aspect ratio of the window.

Example:

setScreenBackground({ name: "oolite-nova-system.png", height: 480 });

See also: #setScreenOverlay & Screenbackgrounds.plist

setScreenBackgroundForKey

This method was added in Oolite test release 1.85.

function setScreenBackgroundForKey(keyname : string, image : guiTextureSpecifier) 

Override the background for a particular keyname (referenced in the screenbackgrounds.plist file) with the specified image. Override is only for the current play-session only and does not get written out to screenbackgrounds.plist.

guiTextureSpecifier can be either a string or an object with the required key name and optional keys width and height. If neither width nor height is specified, the dimensions of the image are used. If only one is specified, the other is calculated such that the image is not distorted. The scale unit is 1/480 of the height of the window; in other words, the window is always considered 480 units high, and the width depends on the aspect ratio of the window.

Example:

setScreenBackgroundForKey("long_range_chart_mission", { name: "my_mission_background.png", height: 480 });

See also: getScreenBackgroundForKey()

setScreenOverlay

function setScreenOverlay(image : guiTextureSpecifier) 

Temporary override that sets the overlay of the current gui screen to the specified image. Override is lost after the player switches screens.

See setScreenBackground() for a discussion of guiTextureSpecifier.

Example:

setScreenOverlay('trumblebox.png');

See also: Screenbackgrounds.plist

takeSnapShot

function takeSnapShot([filename : String]) : Boolean

Saves a snapshot of the current screen to your hard disk. A filename is optional. When a name is used, only alphanumeric values and "-" and "_" are allowed for the filename. The appropriate extension for the used operating system (like .png) is added by Oolite and should not be part of the filename.
When a filename already exists, it is not overwritten but the string "-xxx" is added, starting with "-001".
takeSnapShot() will not be available in the stable release version of Oolite, but will be available in a special OXP developer release.

Example:

takeSnapShot('mission_target_1');

Reserved Words

Quaternion

Oolite_JavaScript_Reference:_Quaternion

Vector3D

Oolite_JavaScript_Reference:_Vector3D