LouiZeForum

3D vrml
 
HomeHome  FAQFAQ  SearchSearch  RegisterRegister  MemberlistMemberlist  UsergroupsUsergroups  Log in  3Dchats / forums3Dchats / forums  

Share | 
 

 blaxxun Contact 3D 5.0- Scripting

View previous topic View next topic Go down 
AuthorMessage
mark
+200
+200


Number of posts : 451
Registration date : 2012-06-01

PostSubject: blaxxun Contact 3D 5.0- Scripting   Wed 23 Apr - 14:56

blaxxun Contact 3D 5.0- Scripting




Introduction

This document provides information about implementation notes for the Script node.


Script Node

The Script Node implements VrmlScript and a JavaScript subset as defined in Annex C of the VRML97 specification and in Proposal for a VRML Script Node Authorin by Chris Marrin, Jim Kent (Originally from Cosmo site).

Supported Script node URL strings are strings that begin with the VrmlScript identifier tag "vrmlscript:" or strings that begin with the JavaScript identifier tag "javascript:". The later is treated internally as "vrmlscript:". Also script can reside in files with the extension .vs or .js.

The "object:" tag allows to embed native COM object, implementing the blaxxun VRML Script COM Interface. An Examples is a availabe in the blaxxun Client SDK.

Java in the Script node is currently not supported.

Contact vrmlscript limitations compared to ECMA Script (ECMA)
Vrmlscript statements need to be properly terminated with a semicolon ; like in C or Java.
the following statements are not valid and result in error messages:
a=1 b=2 if (a) { b=c } return 5
These statements are fine:
a=1; b=2; if (a){ b=c; } return 5;

Vrmlmatrix is treated as single-level array with 16 elements.

The Date and Array objects are partly supported.
The with, switch statement and other expression like eval are not supported
adding new properties to field objects like sfcolor.someNewProperty = x is not supported.
All undeclared variables are local to a function like in C or Java ; global variables are only those declared in the script interface as field, exposedField or eventOut.
The != == operators are not properly supported for objects

Scripts inside PROTOs need to set the directOuput TRUE flag, if nodes are modified via direct access, or browser calls like addRoute, deleteRoute, createVrmlFromUrl. All nodes of the PROTO definition that the script is going to modify need to be listed directly (i.e. not as children of a Group node) in some SFNode / MFNode field of the script. Otherwise the node may be shared between different instances of the PROTO, resulting in unexpected behavior.




vrmlscript Browser object extensions

additional member functions

float getCurrentTime() - gets the computer's current system time
float getTime() - gets the browser's current simulation time
float getWorldStartTime() - gets the time the world was loaded


void print(string); - print the string to the console. A typical use would be to debug scripts. Too many prints can slow down the performance due to the VRML Console update.

function x(value) { Browser.print(' value is '+value); }

In order to print timeStamps more easily, the following code fragment could be used:
Browser.print('Time = '+ (timeStamp - Browser.getWorldStartTime()));

For compatibility with other VRML browsers, the built-in functions print(string); and trace(string); are supported.

createVrmlFromString - knows about PROTO definitions in the top-level VRML file. (non-standard !)

void setMyAvatar(node) - sets the avatar for third-person mode display

bool showMyAvatar(flag) - toggles third-person mode on/off

bool getThirdPersonView() -query if 3rd persion view mode is active



void setRenderMode(string) - changes rendering mode; supported values are Flat, Gouraud, Wireframe, Vertices. In addition, the OpenGL version supports Solid NonLighted BoundingBoxes.

void setNavigationMode(string) - changes navigation mode
string getNavigationMode() - gets the navigation mode (4.0)

void setCollisionDetection(flag) - changes collision detection mode
bool getCollisionDetection()
void setGravity(flag) - changes gravity, terrain following mode
bool getGravity()
void setHeadlight(flag) - changes headlight mode
bool getHeadLight() - returns current state of headlight
void setViewpointAnimation(flag) - If TRUE, viewpoint changes are animated; if FALSE, viewpoint changes are immediate.
bool getViewpointAnimation() - returns current state of viewpoint animation
void setAvatarHeight(float value) - sets the avatar height, used for computing distance of viewpoint to ground
void setCollisionDistance(float value) - changes the collision distance
float getCollisionDistance()
void setVisibilityLimit(float value) - changes visibility limit
float getVisibilityLimit()
void setWalkSpeed(float value) - changes walk speed

int getWindowSizeX() - returns the horizontal size in pixels of the rendering window
int getWindowSizeY() - returns the vertical size in pixels of the rendering window
float getWindowAspect() - get the aspect ratio (width/height) of the rendering window, useful to adjust HUD display

float getAvatarHeight()
float getStepOverSize()
float getZNear() - return current actual znear clipping value
float getZFar() - return current actual zfar clipping value

Node computeRayHit (SFVec3f startPoint,SFVec3f endPoint, startingNode optional)

Computes an intersection of a ray with the scene graph. Result is null if no intersection found or a PseudoNode RayHitInfo with the following information stored:



PROTO RayHitInfo [

eventOut MFNode hitPath // the chain of grouping nodes, to the geometry node intersected
eventOut SFVec3f hitNormal // normal at point of intersection
eventOut SFVec3f hitPoint // point of intersection in global, world coordinates
eventOut SFVec2f hitTexCoord // texture coordinate at point of intersection (without any texture matrix applied)
eventOut SFMatrix hitMatrix // matrix transforming shape local coordinates to world coordinates

eventOut SFVec3f hitNormalLocal
eventOut SFVec3f hitPointLocal // intersection point in the shape's local coordinate system
eventOut MFInt32 hitInfo // vertex index information
]

Example: rayhittest.wrl Navigate so that an object is in the center of the view and click the cylinder, information on hit will be displayed in the console.

Node mouseSelect (SFVec2f startPoint)

Computes an intersection of a ray throught the given 2D mouse position with the scene graph. Result is null if no intersection found or a PseudoNode RayHitInfo.

Node computeCollision (SFNode sourceNode,VrmlMatrix sourceMatrix, SFNode targetScenegraph, VrmlMatrix targetMatrix)

Computes collission between a geometry node the scene graph routed by target. Result is null if no intersection found or a PseudoNode CollisionInfo with the following information stored:



PROTO CollisionInfo [





eventOut
MFNode hitPath // the chain of grouping nodes, to the geometry node

source collided with
eventOut SFMatrix hitMatrix // matrix transforming shape local coordinates to world coordinates
eventOut MFInt32 hitInfo // vertex index information
]

Example: rayhittest.wrlClick the cylinder, information on collision will be displayed in the console.

setUnloadMode(int minNotActiveInlines, float percentage factor to purge)

set strategy for purging inlines from memory:
if the number of inlines currently not rendered is greater minActiveInlines,
purge up to (number * percentage ) inlines from memory
if percentage < 0 its an absolute number of inlines to purge

Example:
setUnloadMode(100,0.05)
if (more than 100 inlines are currently not rendered)
delete 5 % of the inlines not used for the longest time


setBspMode(order) - set bsp Traversal order
setBspLoadingMode( order) - set bsp inline Traversal order

TRAVERSE_NORMAL 0
TRAVERSE_BACK_TO_FRONT 1
TRAVERSE_FRONT_TO_BACK 2

int getCap(int what) - return browser capability information.

Example usage: adapt content to client platform, check if a certain feature like alpha blending is present.

Example: captest.wrl All available browser information is displayed in the console.

boolean isKeyPressed(int keyCode) - determines if the virtual key determined by keyCode is down

string getWorldBaseURL() - returns the base URL of the toplevel world

string getBaseURL() - get the base URL for the script node

Url's inside EXTERNPROTO instanced VRML Nodes are relative to including VRML world. getBaseURL would return the baseUrl of the VRML file containing the Script node. So this call could be resolve for common authoring problems, if URL references in the PROTO should be relative to the implementing PROTO.

loadURLrel(MFString url,MFString parameters) - same as loadURL - but URL is relative to getBaseURL()

setViewpointByValue(SFVec3f position,SFRotation orientation, int mode) - set current viewpoint position to position / orientation

Mode can be set to the following :

bit 0 1: animated transistion 0 : not animated
bit 1 1: set absolute viewpoint (unbind any bound viewpoint)
bit 2 1: values are a relative move distance (left/right, up/down, > in/out, look left/right, look up/down, roll,)
bit 3 1: check for collision, 0 not
bit 4 1: check for ground, 0 not

This function can be used to program a custom navigation.
For navigation a new relative move distance can be computed from user input an passed to the Browser as Browser.setViewpointByValue(distance,rotation,(4+8+16) );

In relative move (bit 2, value = 4) the orientation axis is interpreted as 3 rotation angles about the relative x y z axes of the camera.

getViewpointByValue(SFVec3f position,SFRotation orientation, int mode) - get current viewpoint position

mode 0 : return data of local viewpoint
mode 1 : global viewpoint, value of local viewpoint transformed to global coordinates if bound viepoints is inside a Transform
mode 2 : third person mode viewpoint

void setSoundEnabled(flag) - if set to false lock the usage of the sound device for this scene

flag getSoundEnabled() - returns current state of sound enabled state

String getInstallDirectory() - returns the string of the directory blaxxun CC3D resides

int prefetch(mfNode argument, boolean loadInlnes=true, boolean loadTextures=true)

prefetch instructs the browser to load the Media resources listed in argument, parameter 1 and 2 are true by default. If argument directly references ImageTexture MovieTexture Inline Script or AudioClip nodes the return value is the number of those nodes loaded.

Node getScript() - returns an SFNode referering the Script node of the script. Often script authors need to have a "this" reference in a Script. The common Method using an extra SFNode field in the Script field list is also possible but could result in Memory Leaks in Contact.

bool setOption(string option, string optionValue)

string getOption(string option)

The following options string are supported :

ISSE- Setting & querying Pentium III ISSE support :

print('ISSE = '+Browser.getOption('ISSE'));
Browser.setOption('ISSE','TRUE');
http://Browser.setOption('ISSE','FALSE');

driver - returns the graphics card driver description

Overriding Nurbs Tessellation mode settings :

Browser.setOption('NurbsTesselationScale', '2.0');
Browser.setOption('NurbsTargetFps', '25');
Browser.setOption('NurbsTessellationMode', '0'); // 0 = static, 1=DYNAMIC, 2= Frame Rate, 2= DYNAMIC & FRAME RATE

List of setOption values

antiAliasing TRUE/FALSE
collisionDetection "
dithering " dithering on/off
exactCollision "
fullScreen "
set fullscreen mode (D3D version)
gravity " set terrain following on/off
ISSE " Katmai ISSE instructions on/off
mipmap " mip/map on/off
lodScale float global scale factor for visibilityLimit, LOD (same as performance visibiltz factor)
lightScale float global scale factor for light intensity
NurbsTesselationScale float NURBS Dialog settings
NurbsTargetFps float
NurbsTessellationMode int NURBS tesselation mode : 0 STATIC_TESSELATION, 1 DYNAMIC_TESSELATION, 2 FRAMERATE_TESSELATION 3 DYNAMIC_FRAMERATE_TESSELATION
smooth TRUE/FALSE Smooth texture filtering
soundQuality int SOUND quality settings (intial value)
texturing TRUE/FALSE Texturing enable / disable


Browsers object properties

The Browser object itself is a VRML node with certain events and fields. By adding ROUTEs from vrmlscript or eventOut Observers from the EAI, these events can be observed.

Access from vrmlscript: Browser.xxxx
Access from EAI: Browser.getEventIn(xxx) Browser.getEventOut(xxx)

eventIn MFNode set_myAvatarNodes - set my avatar nodes (for createVrmlFromURL callback)
eventIn SFString set_myAvatarURL - set my avatar URL
eventIn SFString set_myAvatarName - set my avatar nickname
eventIn SFBool set_showMyAvatar - toggle third-person mode
exposedField SFString myAvatarURL - current avatar URL
exposedField SFNode boundAvatar - the bound (displayed) avatar node (may contain wrapper around myAvatar)
exposedField SFNode myAvatar - node currently used as myAvatar node
exposedField SFString myAvatarName - current avatar nickname
exposedField SFVec3f followDolly - x,y,z relative translation distance for third-person viewing mode
exposedField SFVec3f followOrbit - x,y rotation value for third person viewing mode
exposedField SFVec3f followPan - x,y pan rotation value for third person viewing mode


// observable eventOuts
eventOut SFTime time_changed - the master clock

eventOut SFVec3f viewpointPosition - global viewer postion
eventOut SFRotation viewpointOrientation
eventOut SFVec2f windowSize - rendering window width height
eventOut SFFloat windowAspect - aspect ratio of rendering window

exposedField MFNode viewpoints

exposedField SFNode boundViewpoint - the current bound viewpoint (top of stack)
exposedField MFNode boundViewpointStack - the other stacked viewpoints (if any)
exposedField SFNode boundNavigationInfo - the currently bound navigation info
exposedField MFNode boundNavigationInfoStack
exposedField SFNode boundFog - the currently bound fog
exposedField MFNode boundFogStack
exposedField SFNode boundBackground - the currently bound background node
exposedField MFNode boundBackgroundStack


exposedField SFString name - Browser name
exposedField SFString version - Browser version
exposedField SFString worldUrl - URL of the currently loaded world (set observer to get a world changed notification)

exposedField MFNode overTouchSensors - list of TouchSensor's the mouse is over
exposedField MFNode activeVisibilitySensors - list of VisibilitySensors and Occlusion nodes currently assumed to be visible

exposedField MFNode protoScenes - list of scenes with prototypes (loaded via EXTERNPROTO URL ..)



Extensions to field objects object

Methods

string getType() - get the type of the field as VRML fieldType name

string toString() - convert the field to its VRML string representation.

Extensions to vrmlscript SFNode object

Methods

string getType() - get the type of the node as VRML nodeType or prototype name

string getName() - get the node's DEF name if available. The node name is not avaible if the node is part of a PROTO and the node in this instance was copied.

node copy() - creates a copy of the node (no deep copy on SFNode / MFNode fields)

fieldObject getEventIn(string eventInName) - get eventIn object of Node

boolean hasEventIn(string eventInName) - returns true if Node has an eventIn namved eventInName

fieldObject getEventOut(string eventOutName) - get eventOut object of Node

boolean hasEventOut(string eventOutName) - returns true if Node has an eventOut namved eventOutName

VrmlMatrix getMatrix() - get Matrix of Transform, MatrixTransform or last Matrix of HUD, Billboard or related VRML 1.0 nodes

boolean setMatrix(vrmlMatrix) - set Matrix of Transform MatrixTransform nodes, false if matrix can not be set.

MFVec3f getBBox() - return the bounding box of the node, return value [0] returns the min position, value[1] the max position. The function is optimized if called for a Geometry node.



MFTime object

supports same members and methods as MFFloat object, but values are stored in double precicision.

Extensions to vrmlscript MFVec3f object

Methods:


setByVertexTransform(MFVec3f srcPoints, MFInt32 srcIndex,MFVec3f translation,MFRotation rotation,MFVec3f scale, MFRotation scaleOrientation,MFVec3f center)

This assignment function performs a series of transformations to coordinates in srcPoints and assigns the result to the object. The operation is comparable to a nested Transform scene graph used to animated a hierarichal model like an Avatar.

Up to the last 5 parameters can be omitted, in order to speed up the operation. if there a n group of vertices to transform, length of srcIndex must be n*3 and the length of each transformation data arraymust be at least n or 0.

The operation expressed in pseudo code:

VrmlMatrix matrixStack[];
var index;

for(index=0; index var level=srcIndex[index*3]; // get the nesting level
var startIndex=srcIndex[index*3+1]; // start vertex index
var endIndex=srcIndex[index*3+2]; // end vertex index

// compute transformation, right most arguments could be omitted for speed
matrixStack[level]=m.setTransform(translation[index], rotation[index],
scaleFactor[index],scaleOrientation[index], center[index]) ;

if (level!=0) matrixStack[level].MultiplyRight( matrixStack[level-1]); // combine with parent
for(var i=startIndex;i this[i] = matrixStack[level] * srcPoints[i];
}

}

MFVec3f getBBox() - return the bounding box of the arrar of Vec3f, return value [0] returns the min position, value[1] the max position.

Extensions to vrmlscript Math object


double atan2(double dy, double dx) - arc tangent -PI .. PI
double cosh(double x)
double sinh(double x)
double tanh(double x)
double randomGaussian() - gaussian random number -1 ..1
double noise(double x) - evaluates solid noise function on x

SFString object extensions

int string.getCharCodeAt(index); returns the character code as integer at position i

string string.fromCharCode(int1, .... intn); constructs & returns a new string composed out the given sequence of character codes

SFImage extensions

SFImage new SFImage(int width,int height, int componenents, MFFloat pixels) - construct SFImage using a float array of length widht*height*components. This function can be used to avoid the time consuming pixel packing in vrmlscript for dynamically computed SFImage objects.

Extensions to vrmlscript MFNode object

Methods:


boolean add(SFNode node) adds a single SFNode to the field.

boolean remove(SFNode node) removes a single SFNode to the field.

int find(SFNode node) returns the index of a node in field, -1 if not found.

Node findByName(String name) returns a the first node with a matching name, void if not found.




Controlling download
Contact 3D fetches URL objects and EXTERNPROTO's in the order encountered during scene graph traversal, in the order top to bottom of file, depth first. Currently not needed objects, because not "visible" due to a Switch, LOD or BspTree node are only retreived if they become part of the visible scene graph.

Loading of Textures in the appearance node of a shape max be delayed until the shape's geometry becomes visible.

In order to preload currently unneeded objects, ImageTexture / MovieTexture / AudioClip nodes can be directly specified as children of Groups. The ordering of the nodes with url controls the download sequencing of the assets. The Appearance / Sound node references the asset by USE.

The BspTree or BspGroup node traverses child nodes nearer to the viewer first. This would mean Inline parts nearer to the viewer are earlier loaded then further away parts. Bsp - tree Parts outside the visibilityLimit (the viewing pyramid) are not fetched. The drawback is that once a new section of the world becomes visible there is some halting due to the decoding of image texture from harddisk to video memory.

The LOD node display lower levels if the requested level is an Inline node, currently not loaded.

A common request from content developers is to have more control over Resource loading notification and unloading capabilities.

The inline nodes behaves as a group-node, the children field is exposed to access the nodes of the inline. By observing children_changed a notification is sent, once an Inline node is loaded and processed.
The additional eventOut SFBool isLoaded indicates loading success, TRUE is sent if the inline node is loaded and children are loaded, FALSE is sent if the inline node's url couldn't be retreived or there was some other problem with the data. In addition set_unload can be used to unload an Node from memory, however the application should normally use this if its shure that the node is currentlly not part of the visible node subsets (i.e. out of viewfrustrum, not in traversed scene graph etc.)

This extened Inline version is described by the following prototype :

Inline {
field SFVec3f bboxSize -1 -1 -1
field SFVec3f bboxCenter 0 0 0
exposedField MFString url []
exposedField MFNode children []
eventIn MFNode addChildren
eventIn MFNode removeChildren
eventOut SFBool isLoaded # TRUE if loaded & parsed sucessfully

eventIn SFBool set_unload # new in 4.1, send TRUE to unload Inline from memory
}

ImageTexture {

... standard fields

eventOut SFBool isLoaded # new in 4.1
eventIn SFBool set_unload # new in 4.1, send TRUE to unload from memory
}

This node extension is not VRML97 compatbile, so it should be used with care.
It is possible to add an proper Externproto definition or using script code checking the browser version :

EXTERNPROTO Inline2[
field SFVec3f bboxSize -1 -1 -1
field SFVec3f bboxCenter 0 0 0
exposedField MFString url []
exposedField MFNode children []
eventIn MFNode addChildren
eventIn MFNode removeChildren
eventOut SFBool isLoaded
eventIn SFBool set_unload

] ["urn:inet:blaxxun.com:node:Inline","nodes.wrl#Inline2"]



For textures one method is to use a MovieTexture and observe the duration_changed eventOut. Oberving the "last" asset, in file order can give a hint of a world completely loaded event. A new method in Version 4.1 is the additional eventOut SFBool isLoaded forImageTexture.
Back to top Go down
View user profile
mark
+200
+200


Number of posts : 451
Registration date : 2012-06-01

PostSubject: Re: blaxxun Contact 3D 5.0- Scripting   Wed 23 Apr - 14:56

Back to top Go down
View user profile
 
blaxxun Contact 3D 5.0- Scripting
View previous topic View next topic Back to top 
Page 1 of 1
 Similar topics
-
» Contact retrosignalisation
» 1er contact : Bonjour!
» Mauvais contact entre câble allume-cigares et berceau 765T
» [Résolu] Perdu liste contact Windows Live Mail (carnet d'adresse)
» Verres de contact d'essai gratuits

Permissions in this forum:You cannot reply to topics in this forum
LouiZeForum :: ARTS :: 3D art :: 3D FAQ and News-
Jump to: