Mod Tool: Difference between revisions

From OniGalore
Jump to navigation Jump to search
mNo edit summary
m (better lede)
 
(100 intermediate revisions by 3 users not shown)
Line 1: Line 1:
==General information==
Autodesk's Mod Tool used to be the main choice for modders when working on level and character models (at least in Windows, since it's Windows-only). It was a free and accessible program, but has long since been discontinued. Nowadays, modders are encouraged to use [[Blender]] instead.
Various modders of the community use [http://usa.autodesk.com/adsk/servlet/pc/item?siteID=123112&id=13571257 "Autodesk Softimage Mod Tool"]. Usually we just call it "Mod Tool" or "XSI" (old name of the program).
{| class="wikitable" style="float:right;"
 
|width="200px"|
Beside the free version, there's also the retail and student version "Autodesk Softimage [year]"
;sub pages
: Those versions are also available as 64-bit versions.
: [[Mod_Tool/Scripting]]
: If you are a student you can get Autodesk Software for free if your school is a partner of Autodesk.
: [[Mod_Tool/Rigging]]
:: In that case you can register with your email address given by your school.
: [[Mod_Tool/OniTools_addon]]
 
: [[Mod_Tool/Oni_level_rebuilder]]
But in the very most cases "Mod Tool" isn't really in disadvantage towards the retail version when it comes to modding Oni.
|}
==Installation==
Full name: "Autodesk Softimage Mod Tool". Usually we just call it "Mod Tool" or "XSI", the old name of the program.


There's also the possibility to get files that extent Mod Tool's range of functions.
'''Download'''
: Those are scripts (.vbs, .js), toolbars (.xsitb) and addons (.xsiaddon).
* '''Get it from [https://www.moddb.com/downloads/autodesk-softimage-mod-tool-75 Mod DB].'''
: They can be create on one's own and also shared with other users.
* It's no longer possible to download Softimage from Autodesk because the [https://www.autodesk.com/products/softimage/overview software was discontinued] by Autodesk in favor of their major software packages Maya and 3ds Max.


'''Newer Windows installations usually require .NET 2.0 to be installed before the XSI installer can fully run.'''
: Downloading and installing .Net 2.0 manually from the internet might not work.
: '''Therefore use the Windows search and look for "features".''' (Enable/disable Windows features.)
: From the Windows feature page install '''".NET framework 3.5 (includes .NET 2.0 and 3.0)"'''.


'''Wanted knowledge:'''
There are various ways to extend Mod Tool's range of functions: scripts (.vbs, .js), toolbars (.xsitb) and addons (.xsiaddon). They can be created on one's own and also shared with other users.
* How to setup particle in Mod Tool? We still need an Oni particle editor!
* How to rig models and then extract the animation data?


 
===Extensions===
==Extensions==
'''links'''
'''links'''
* [http://www.si-community.com/community/viewtopic.php?f=35&t=796 "Roadkill" UV Tool]
* [https://www.si-community.com/community/viewtopic.php?f=35&t=796 "Roadkill" UV Tool]
* [http://www.xsidatabase.com/content/drag_and_drop_obj_files_jscript drag and drop support for OBJ files]  
* [http://web.archive.org/web/20121001104022/http://www.xsidatabase.com:80/content/drag_and_drop_obj_files_jscript drag and drop support for OBJ files]  
* [http://www.si-community.com/community/viewtopic.php?f=35&t=797 OBJ exporter]
* [https://www.si-community.com/community/viewtopic.php?f=35&t=797 OBJ exporter]
* [http://mods.oni2.net/node/210 OBJ + OFGA exporter] for Oni
* [http://mods.oni2.net/node/210 OBJ + OFGA exporter] for Oni
** might need the regular OBJ exporter to be installed first
** might need the regular OBJ exporter to be installed first
* [http://mods.oni2.net/node/210 adjusting existing fw throws] [http://www.youtube.com/watch?v=Zcbv7y5HvRI (instructions)]
* [http://mods.oni2.net/node/210 adjusting existing fw throws] [https://www.youtube.com/watch?v=vDTPYfvMf4M (instructions)]
* ''put more links here''




Line 54: Line 56:




'''[http://softimage.wiki.softimage.com/sdkdocs/cus_addons_WalkthroughBuildinganAddon.htm building add-ons]'''
'''building add-ons (<nowiki>http://softimage.wiki.softimage.com/sdkdocs/cus_addons_WalkthroughBuildinganAddon.htm</nowiki>, dead link)'''
* Building an add-on file needs more effort than the other 'extensions' but for the end user it's best because it can hold all other files: toolbars, plugins (scripts), etc.
* Building an add-on file needs more effort than the other 'extensions' but for the end user it's best because it can hold all other files: toolbars, plugins (scripts), etc.
** The user can install a newer version of the addon by repeating the installation with the new file: it's unnecessary to remove the old version.
** The user can install a newer version of the addon by repeating the installation with the new file: it's unnecessary to remove the old version.
Line 146: Line 148:
  end if
  end if
  end function
  end function


==Selected wisdom==
==Selected wisdom==
We've also a [http://oni.bungie.org/community/forum/viewtopic.php?id=1229 tutorial thread on OCF.]
We've also a [http://oni.bungie.org/forum/viewtopic.php?id=1229 tutorial thread on OCF.]


Hotkey list can be found [http://www.keyxl.com/aaacbe0/415/SoftImage-XSI-keyboard-shortcuts.htm here].
Hotkey list can be found [http://www.keyxl.com/aaacbe0/415/SoftImage-XSI-keyboard-shortcuts.htm here].
Line 245: Line 246:


===Material and texture===
===Material and texture===
[[Image:apply_new_main_texture_in_Mod_Tool.png|thumb|200px|right|how to apply a new main texture]]
[[Image:apply_new_polygon_cluster_texture_in_Mod_Tool.png|thumb|200px|right|how to apply a new polygon cluster texture]]
* objects use the scene material by default, objects need their own material if they should have individual textures
* objects use the scene material by default, objects need their own material if they should have individual textures
* selecting a material and surface: Model > Material > Phong (simply close the windows that pops up)
* selecting a material and surface: Model > Material > Phong (simply close the windows that pops up)
Line 254: Line 257:
** choose "diffuse" as illumination mode (for instance "ambient" won't work - the texture would be visible in Mod Tool but Onisplit can't use it)
** choose "diffuse" as illumination mode (for instance "ambient" won't work - the texture would be visible in Mod Tool but Onisplit can't use it)
* now "Image" can be double-clicked (the Texture Editor will pop up), in the section "Image" click on "New" to choose an image
* now "Image" can be double-clicked (the Texture Editor will pop up), in the section "Image" click on "New" to choose an image
* to change textures '''don't drag and drop textures directly one meshes''', this creates textures layers which are ignored by OniSplit




Line 276: Line 280:
* freeze object to ''bake'' projections (green lines in the 3D view will disappear)
* freeze object to ''bake'' projections (green lines in the 3D view will disappear)
* getting a picture of the UV: apply first a black texture then enter the Texture Editor [Alt] + [7], Edit > Stamp UV Mesh [Shift] + [S], save the texture
* getting a picture of the UV: apply first a black texture then enter the Texture Editor [Alt] + [7], Edit > Stamp UV Mesh [Shift] + [S], save the texture
Things to test:
* https://vimeo.com/67783125
===Rendering===
Rendering doesn't work well on my PCs.--[[User:Paradox-01|paradox-01]] ([[User talk:Paradox-01|talk]]) 01:09, 9 March 2016 (CET)
Especially PNG, it works one time. But as soon as I import another dae the next render will fail.
So, for creating a object library we might use blender. Nice thing is, it can also render in the background when called from CMD. This means you could keep working in XSI and render images in blender at the same time.
example of a batch file:
cd C:\Program Files\Blender Foundation\Blender
blender -b --python C:\Users\Paradox-01\Desktop\blender-out\pythonScript.py
example of a render script:
import bpy
# delete blender default cube object
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_by_type(type='MESH')
bpy.ops.object.delete(use_global=False)
# load new object
bpy.ops.wm.collada_import(filepath = "C:/Oni/r.dae")
# render settings
bpy.data.scenes['Scene'].render.resolution_x = 900
bpy.data.scenes['Scene'].render.resolution_y = 900
# default resolution percentage seems to be 50
bpy.data.scenes['Scene'].render.resolution_percentage = 100
bpy.data.scenes['Scene'].render.use_antialiasing = True
# 5 | 8 | 11 | 16
bpy.data.scenes['Scene'].render.antialiasing_samples = "8"
#TGA IRIS JPEG MOVIE IRIZ RAWTGA
#AVIRAW AVIJPEG PNG BMP FRAMESERVER
#no gif ? could be created by more code, maybe merging single frames of jpgs
bpy.data.scenes['Scene'].render.image_settings.file_format = 'JPEG'
bpy.data.scenes['Scene'].render.image_settings.quality = 100
# file suffix is overwritten by file_formate
#bpy.data.scenes['Scene'].render.filepath = 'C:/Oni/renders/test.jpg'
bpy.data.scenes['Scene'].render.filepath = 'C:/Oni/renders/test'
# start render
bpy.ops.render.render( write_still=True )




===Animating===
===Animating===
[[Image:Scale_animations_in_Mod_Tool_Animation_Editor_DopeSheet.png|thumb|200px|right|an animation that got scaled down from 116 to 58 frames]]
* preparing ModTool to save animations Oni can use: File > Preferences... > Preferences > Tools > Output Format
* preparing ModTool to save animations Oni can use: File > Preferences... > Preferences > Tools > Output Format
** Frame Step: 1
** Frame Step: 1
** Frame Format: Custom framerate
** Frame Format: Custom framerate
** Frame Rate: 60
** '''Frame Rate: 60'''
* for real-time playback click on "Playback" option button and then "Real-Time Playback"
* opening the Animation Editor : [0]
* opening the Animation Editor : [0]
* opening the DopeSheet: from any other Animation Editor, Editor > DopeSheet
* opening the DopeSheet: from any other Animation Editor, Editor > DopeSheet
* making an animation shorter or longer: in DopeSheet click Region button (arrow with rectangle), click and hold to select keyframes, at selection edge a) [shift] plus left-click and move mouse or b) middle-click and move mouse
* '''making an animation shorter or longer:''' in DopeSheet click Region button (arrow with rectangle), click and hold to select keyframes, at selection edge a) [shift] plus left-click and move mouse or b) middle-click and move mouse
 


====Issues when saving and sharing animation files (*.dae, *.exp)====
That what you currently see in Mod Tool and that what you get when saving data can be different.


===Scripting===
1) *.dae files might save data differently than expected.
* open the Script Editor: [Alt] + [4]
 
* run the current code in the Script Editor window: [F5]
''Rotation flips'' might appear.
* clear the log: Edit > Clear History Log
* Actions from button embedded code will be logged.
* Actions from code files that are linked in a button won't be logged. (This results in a performance boost.)
* Logged stuff will be rewritten if you change the script language. (File > Preferences...)
* You can also change the language by right-click the white script box and click on "Set to JScript" or "Set to VBScript".
* Python can be added as script language if you install it on your PC.
* Right-clicking the white script box gives you also access to a few code piece, e.g. "Syntax Help" > "If..Else" or "Catch Error".
* Mark code you want to disable ("Comment Out") or enable ("Comment Remove").
* You can save your code to a file via "File" > "Save As..." or "Save Selection"


2) *.exp and *.dae save data differently.


'''Links'''
*.exp files store the frames as they are.
* [http://softimage.wiki.softimage.com/index.php?title=Scripting_Tips_and_Tricks_%28XSISDK%29 xsi wiki page about scripting]
* '''[http://softimage.wiki.softimage.com/sdkdocs/scriptsdb/scriptsdb/scrdb_vbscript.htm many vbscript examples]'''
* [http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/filesfolders/files/ objFSO/objWSHShell: Scripts to manage Files] (replace "Wscript.Echo" with "logmessage")
* [http://activexperts.com/activmonitor/windowsmanagement/adminscripts/other/textfiles/ objFSO/objWSHShell: Scripts to manage Text Files]
* [http://www.kxcad.net/Softimage_XSI/Softimage_XSI_Documentation/script_basics_IncludingExternalScripts.htm using external scripts]
* [http://download.autodesk.com/global/docs/softimage2013/en_us/sdkguide/index.html?url=si_om/XSIUIToolkit.html,topicNumber=si_om_XSIUIToolkit_html progress bar and open file dialog<!-- (hm, InitialDirectory code for quick save idea ?)-->]
<!--* [http://download.autodesk.com/global/docs/softimage2013/en_us/sdkguide/index.html?url=files/cus_ppg_FileBrowserWidget.htm,topicNumber=d30e11980,hash=WS34BA39B437A993419C80CAB58E3BEFA1-0059 text box]-->


*.dae file store their actions (rotations/translation/...) in seconds and eventually depend on what framerate a Modder uses.


'''Notes about polygon extraction'''
* a grid of 9 polygons (ID 0 to 8)
* you extract the middle polygon (ID 4)
* grid's polygon of ID 8 will change to ID 4
* if you now extract 5th, the 7th gets the ID
* now the ID order is: 0, 1, 2, 3, 6, 5, 4
* this means that an automatic extraction of several polygons requires two changes in the code
* 1) the ID array of selected polygons must be sorted
* 2) the extraction must start with the last ID to avoid ID shift during the process (see code pieces)


'''Following scenario: a modder wants to share an animation as *.exp and another modder wants to use that animation.'''


'''Some basics of VBScript'''
Modder A uses 30 fps in his settings and exports an *.exp that is 58 frame long.
* In VBS you declare variables only as a variant e.g. "dim PolygonCount". Mod Tool decides what type it becomes when it uses the variable the first time.
* You can put "option explicit" at the start of your script. Then you will be forced to declare all variables with "dim". That looks quite unnecessary but help to find mistakes for example if you mistyped a variable somewhere in a long script.


* The commands are not case-sensitive, e.g. you can write "LogMessage" or "logmessage".
Modder B uses 60 fps in his setting and imports the *.exp, to his surprise the animation is 116 frames long. What now?
* Vbs functions can be found [http://www.w3schools.com/vbscript/vbscript_ref_functions.asp HERE.]


' while it is possible to use + in strings,
If Modder B saves the *.exp under a new name would not help, the frames will be still the same.
' you should actually use & only for strings
 
' and + only for numbers
Instead Modder B could scale the animation. The way to do so is described in the [[#Animating|Animating]] section, "making an animation shorter or longer".
 
logmessage "How about ... " + "a riddle?"
Modder B scales the animation and saves it as dae.
logmessage "Where can you find following phrase in Oni? " & "The day is mine !!"
 
logmessage "Did you know that Bungie likes to hide sevens? The digits of the year 2032 add up to " & cstr(2 + 0 + 3 + 2) & "."
Now he wants to see if it worked. He opens a new scene [Strg]+[N] and loads the dae.
' INFO : How about ... a riddle?
' INFO : Where can you find following phrase in Oni? The day is mine !!
' INFO : Did you know that Bungie likes to hide sevens? The digits of the year 2032 add up to 7.




'''More tips'''
'''Summary of issue-holding aspects'''


* You can replace each "logmessage" with a variable. In that case don't forget the = sign.
* '''Frames Per Second (FPS)'''
* Selection(0) means that from all selected objects the first one is taken.
When you share *.dae files with other Modders be sure that the output formate is 60 fps. Different framerates among modders can cause confusion.
* Use a loop to get all objects.


for each n in selection
Dae file store their actions (rotation/translation/...) in seconds.
logmessage n
next


* In order to shorten the code you might want to set script objects.
An example:
: The command to create a standard cube is ''CreatePrim "Cube", "MeshSurface"''
 
: If you use '''''set name = ''''' the cube or other object will be available under that ''name''.
  <float_array count="10" id="pelvis_rotation_x_ANGLE-anim-input-array">
: Then you can use any valid method or property with that ''name''.
    0.000000 0.166833 0.333667 0.500500 0.600600 0.934267 1.267933 1.601600 1.768433 1.935267
: Example:
  </float_array>
 
  set c = CreatePrim ("Cube", "MeshSurface")
action at [s] * framerate [f/s] = frame [f]
 
logmessage selection(0).name
In this example the last rotation occurs at 1.935267s.
logmessage selection(0).length.value
 
  logmessage c.name
: Modder A uses 30 fps, his last frame is 58.
logmessage c.length.value
: Modder B uses 60 fps, his last frame is 116.
 
' INFO : cube
 
' INFO : 8
* '''Euler rotations'''
' INFO : cube
' INFO : 8


you will get [[wikipedia:Bézier_curve|BEZIER]] (cubic) interpolation instead of LINEAR if you use
: "Convert Quarternion Rotation to Euler"
: "Spline Interpolation" in the animation (fcurve) editor


'''Some ModTool commands in vbs language that might be interesting for Oni related stuff'''
Those smooth the rotations.


{| class="wikitable" width="100%"
[...]
| width=50% valign=top | LogMessage <nowiki>[string | var | object]</nowiki>
 
| A command to log information. It requires a string or a variable. Example:
 
: LogMessage "The object's name is: " & selection(0).Name
* '''Quaternion rotations'''
|-
 
| logmessage selection.count
Don't use this.
| Logs the number of selected objects.
 
|-
[...]
| logmessage selection(0).Name
 
| Logs the object name.
 
|-
* '''Make Rotation Keys Continuous'''
| logmessage selection(0).Material.Name
 
| Logs the material name.
[...]
|-
 
|valign=top| logmessage selection(0).Material.CurrentImageClip.source.filename.value
 
| Logs absolute path of the texture. Output example:
====Animation mixer====
: ''C:\Users\RRM\Desktop\TV_tex.png''
This could help with creating cutscenes and complex animations (e.g. run cycles for FILM files).
|-
 
|valign=top| logmessage selection(0).Material.CurrentImageClip.source.Parameters("XRes").Value<br>logmessage selection(0).Material.CurrentImageClip.source.Parameters("YRes").Value
Open the animation mixer with [Alt]+[0].
| Logs the horizontal (X) and vertical (Y) pixel length of the texture. Output example:
 
: ''512''
Further information over [http://web.archive.org/web/20170103065301/http://softimage.wiki.softimage.com/xsidocs/nla_mixer.htm#Rdw10200 HERE.]
|-
 
| logmessage selection(0).sclx.value<br>logmessage selection(0).scly.value<br>logmessage selection(0).sclz.value
Here are a few videos:
|valign=top| Logs object's scaling (X, Y, Z).
* '''https://www.youtube.com/watch?v=-xC31Q7zpM0'''
|-
* https://www.youtube.com/watch?v=njLrAIpDOFU
| logmessage selection(0).rotx.value<br>logmessage selection(0).roty.value<br>logmessage selection(0).rotz.value
* https://www.youtube.com/watch?v=PRDZaEo5CGo
|valign=top| Logs object's rotation (X, Y, Z).
 
|-
 
| logmessage selection(0).posx.value<br>logmessage selection(0).posy.value<br>logmessage selection(0).posz.value
=====Sounds=====
|valign=top| Logs object's position (X, Y, Z).
Within the animation mixer also sounds can be added.
|-
 
|valign=top| logmessage selection(0).rotorder.value
Further information over [http://web.archive.org/web/20170102120711/http://softimage.wiki.softimage.com/xsidocs/audio_LoadingAudioFilesintheAnimationMixer.htm#Rdy36984 HERE.]
| Logs object's rotation order. Oni characters have ZYX as rotation order.
 
:0 = XYZ
This could be used to synchronize sounds effect with physical actions in the scene.
:1 = XZY
 
:2 = YXZ
 
:3 = YZX
===Scripting===
:4 = ZXY
* open the Script Editor: [Alt] + [4]
:5 = ZYX
* run the current code in the Script Editor window: [F5]
|-
* clear the log: Edit > Clear History Log
|valign=top| SelectObj <nowiki>[string | var]</nowiki>
* Actions from button embedded code will be logged.
| select one or more objects. Comma serves as separator. Example:
* Actions from code files that are linked in a button won't be logged. (This results in a performance boost.)
: SelectObj "grid,grid1"
* Logged stuff will be rewritten if you change the script language. (File > Preferences...)  
|-
* You can also change the language by right-click the white script box and click on "Set to JScript" or "Set to VBScript".
|valign=top| ToggleSelection <nowiki>[string | var]</nowiki>
* Python can be added as script language if you install it on your PC.
| Adds one or more objects from current selection. If the objects are already selected then they become subtracted from the selection. Example:
* Right-clicking the white script box gives you also access to a few code piece, e.g. "Syntax Help" > "If..Else" or "Catch Error".
: ToggleSelection "grid2,grid3"
* Mark code you want to disable ("Comment Out") or enable ("Comment Remove").
|-
* You can save your code to a file via "File" > "Save As..." or "Save Selection"
|valign=top| [http://download.autodesk.com/global/docs/softimage2013/en_us/sdkguide/index.html?url=si_cmds/SelectAllUsingFilter.html,topicNumber=si_cmds_SelectAllUsingFilter_html SelectAllUsingFilter] <nowiki>[SelFilter], [CheckComponentVisibility], [AffectSelectionList], [CheckObjectSelectability]</nowiki>
 
|Selects everything that matches the filter and other options. Example:
 
: SelectAllUsingFilter "object", siCheckComponentVisibility
'''Links'''
:: selects all roots, lights, cameras, and geometry (meshes)
* [http://web.archive.org/web/20160803061035/http://softimage.wiki.softimage.com/index.php?title=Scripting_Tips_and_Tricks_%28XSISDK%29 xsi wiki page about scripting]
: SelectAllUsingFilter "geometry", siCheckComponentVisibility
* '''[http://web.archive.org/web/20170616035120/http://softimage.wiki.softimage.com/sdkdocs/scriptsdb/scriptsdb/scrdb_vbscript.htm many vbscript examples]'''
:: selects all geometry (meshes)
* '''[https://ss64.com/vb/ vbs commands]'''
|-
* [https://web.archive.org/web/20070510173452/https://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/filesfolders/files/ objFSO/objWSHShell: Scripts to manage Files] (replace "Wscript.Echo" with "logmessage")
| DeselectAll
* [https://web.archive.org/web/20150504221146/http://activexperts.com/activmonitor/windowsmanagement/adminscripts/other/textfiles/ objFSO/objWSHShell: Scripts to manage Text Files]
| deselects everything
* [http://web.archive.org/web/20080905102848/http://www.kxcad.net/softimage_xsi/Softimage_XSI_Documentation/script_basics_IncludingExternalScripts.htm using external scripts]
|-
* [https://download.autodesk.com/global/docs/softimage2013/en_us/sdkguide/index.html?url=si_om/XSIUIToolkit.html,topicNumber=si_om_XSIUIToolkit_html progress bar and open file dialog<!-- (hm, InitialDirectory code for quick save idea ?)-->]
|valign=top| DeleteObj <nowiki>[string | var]</nowiki>
<!--* [http://download.autodesk.com/global/docs/softimage2013/en_us/sdkguide/index.html?url=files/cus_ppg_FileBrowserWidget.htm,topicNumber=d30e11980,hash=WS34BA39B437A993419C80CAB58E3BEFA1-0059 text box]-->
| Deletes one or more objects. Comma used as separator. Example:
 
: DeleteObj "grid"
 
: DeleteObj "grid,grid1"
'''Notes about polygon extraction'''
|-
* a grid of 9 polygons (ID 0 to 8)
| FreezeObj
* you extract the middle polygon (ID 4)
| Makes all changes final. But saving those changes is still necessary. (Click on key symbol so it gets red.)
* grid's polygon of ID 8 will change to ID 4
|-
* if you now extract 5th, the 7th gets the ID
| [http://download.autodesk.com/global/docs/softimage2013/en_us/sdkguide/index.html?url=si_cmds/Translate.html,topicNumber=si_cmds_Translate_html Translate] <nowiki>[InputObjs], [X], [Y], [Z], [Delta], [RefMode], [Center], [AxesFilter], [Snap], [SnapReference], [SnapFilter], [SplitLocalComponents], [PropTagOnly], [Pivot], [PivotX], [PivotY], [PivotZ], [ConstructionMode], [SlideComponents]</nowiki>
* now the ID order is: 0, 1, 2, 3, 6, 5, 4
| see link
* this means that an automatic extraction of several polygons requires two changes in the code
|-
* 1) the ID array of selected polygons must be sorted
| [http://download.autodesk.com/global/docs/softimage2013/en_us/sdkguide/index.html?url=si_cmds/Rotate.html,topicNumber=si_cmds_Rotate_html Rotate] <nowiki>[InputObjs], [X], [Y], [Z], [Delta], [RefMode], [Center], [AxesFilter], [Reference], [SplitLocalComponents], [PropTagOnly], [Pivot], [PivotX], [PivotY], [PivotZ], [ConstructionMode], [SlideComponents]</nowiki>
* 2) the extraction must start with the last ID to avoid ID shift during the process (see code pieces)
| see link
 
|}
 
'''Some basics of VBScript'''
* In VBS you declare variables only as a variant e.g. "dim PolygonCount". Mod Tool decides what type it becomes when it uses the variable the first time.
* You can put "option explicit" at the start of your script. Then you will be forced to declare all variables with "dim". That looks quite unnecessary but help to find mistakes for example if you mistyped a variable somewhere in a long script.


* The commands are not case-sensitive, e.g. you can write "LogMessage" or "logmessage".
* Vbs functions can be found [https://web.archive.org/web/20150707131602/https://www.w3schools.com/vbscript/vbscript_ref_functions.asp HERE.]


====Code pieces (VB Script)====
' while it is possible to use + in strings,
Remember that you can use the search function of your web browser.
' you should actually use & only for strings
' and + only for numbers
logmessage "How about ... " + "a riddle?"
logmessage "Where can you find following phrase in Oni? " & "The day is mine !!"
logmessage "Did you know that Bungie likes to hide sevens? The digits of the year 2032 add up to " & cstr(2 + 0 + 3 + 2) & "."
' INFO : How about ... a riddle?
' INFO : Where can you find following phrase in Oni? The day is mine !!
' INFO : Did you know that Bungie likes to hide sevens? The digits of the year 2032 add up to 7.


If you see absolute paths adapt them so that the code works on your system too.


{| class="wikitable" width="100%"
'''More tips'''
|width=33%| [1] creating and extending an array
 
|width=33%| [2] check selection mode
* You can replace each "logmessage" with a variable. In that case don't forget the = sign.
| [3] getting the IDs of selected polygons plus sorting them
* Selection(0) means that from all selected objects the first one is taken.
|-
* Use a loop to get all objects.
| [4] converting euler rotations (in degrees) to quaternions
 
| [5] converting quaternions to euler rotations (in degrees)
for each n in selection
| [6] get and set values of the playcontrol (timeline)
logmessage n
|-
next
| [7] get keyframes
 
| [8] message box
* In order to shorten the code you might want to set script objects.
| [9] input box
: The command to create a standard cube is ''CreatePrim "Cube", "MeshSurface"''
|-
: If you use '''''set name = ''''' the cube or other object will be available under that ''name''.
| [10] getting the desktop path
: Then you can use any valid method or property with that ''name''.
| [11] selecting a folder
: Example:
| [12] selecting a file of a specific type
|-
| [13] reading out environment variables
| [14] check if file exist
| [15] check if folder exist + create folder
|-
| [16] write xml file
| [17] create txt file + write lines
| [18] read txt file
|-
| [19] check onisplit version
| [20] call CMD, e.g. to use onisplit
| [21] building forms in ModTool
|-
| [22] UserDataBlob
| [23] getting the position of points (with selection mode point)
| [24] getting the position of points (with selection mode object)
|-
| [25] getting and setting the position of points (without selection)
| [26] getting the rotation and position of selected objects
| [27] getting the rotation and position of not selected objects
|-
| [28] decrypting merged integer flags
| [29] disabling PPG popups
| [30] disabling logmessages
|-
| [31] getting bounding box values
| [32] open an explorer window
| [33] working with hierarchies
|-
| [34] drag and drop (DnD) support for specific oni files
| [35] dae export
| [36] fbx export
|-
| [37] import an image clip only once
|
|
|}
 
 
' '''[1] creating and extending an array'''
   
   
set c = CreatePrim ("Cube", "MeshSurface")
   
   
  ' creating an array
  logmessage selection(0).name
' () sets the number of array items
  logmessage selection(0).length.value
  redim nums (3)
  logmessage c.name
  for i = 0 to 3
  logmessage c.length.value
nums(i) = (i)
  next
   
   
  logmessage "output all items"
  ' INFO : cube
  for each n in nums
  ' INFO : 8
logmessage n
' INFO : cube
  next
  ' INFO : 8
logmessage "first array item holds: " & lbound(nums)
 
logmessage "last array item holds: " & ubound(nums)
 
logmessage "-------------------------------------"
'''Some ModTool commands in vbs language that might be interesting for Oni related stuff'''
 
{| class="wikitable" width="100%"
' extending an array
| width=50% valign=top | LogMessage <nowiki>[string | var | object]</nowiki>
' use "preserve" to keep the old content
| A command to log information. It requires a string or a variable. Example:
' find next higher value
: LogMessage "The object's name is: " & selection(0).Name
plus_one = ubound(nums) + 1
|-
redim preserve nums (plus_one)
| logmessage selection.count
nums(plus_one) = 4
| Logs the number of selected objects.
|-
for each n in nums
| logmessage selection(0).Name
logmessage n
| Logs the object name.
next
|-
logmessage "first array item holds: " & lbound(nums)
| logmessage selection(0).Materials(0).Name
logmessage "last array item holds: " & ubound(nums)
| Logs the material name.
|-
| logmessage selection(0).Materials(0).Library.name
' INFO : output all items
| Logs the material library name.
' INFO : 0
|-
' INFO : 1
| logmessage selection(0).Materials(0).shaders(0).name
' INFO : 2
| Logs the material shader (e.g. phong).
' INFO : 3
|-
' INFO : first array item holds: 0
|valign=top| logmessage selection(0).Materials(0).CurrentImageClip.source.filename.value
' INFO : last array item holds: 3
| Logs absolute path of the texture. Output example:
' INFO : -------------------------------------
: ''C:\Users\RRM\Desktop\TV_tex.png''
' INFO : 0
|-
' INFO : 1
|valign=top| logmessage selection(0).Materials(0).CurrentImageClip.source.Parameters("XRes").Value<br>logmessage selection(0).Material.CurrentImageClip.source.Parameters("YRes").Value
' INFO : 2
| Logs the horizontal (X) and vertical (Y) pixel length of the texture. Output example:
' INFO : 3
: ''512''
' INFO : 4
|-
' INFO : first array item holds: 0
| logmessage selection(0).sclx.value<br>logmessage selection(0).scly.value<br>logmessage selection(0).sclz.value
' INFO : last array item holds: 4
|valign=top| Logs object's scaling (X, Y, Z).
 
|-
 
| logmessage selection(0).rotx.value<br>logmessage selection(0).roty.value<br>logmessage selection(0).rotz.value
' '''[2] check selection mode '''
|valign=top| Logs object's rotation (X, Y, Z).
|-
checkfilter
| logmessage selection(0).posx.value<br>logmessage selection(0).posy.value<br>logmessage selection(0).posz.value
'use sub to make use of the exit command
|valign=top| Logs object's position (X, Y, Z).
|-
sub checkfilter
|valign=top| logmessage selection(0).rotorder.value
Select Case Selection.Filter.Name
| Logs object's rotation order. Oni characters have ZYX as rotation order.
'caution: case-sensitive
:0 = XYZ
:1 = XZY
Case "object"
:2 = YXZ
logmessage "object mode"
:3 = YZX
Case "Edge"
:4 = ZXY
logmessage "edge mode"
:5 = ZYX
Case "Vertex"
|-
logmessage "point mode"
|valign=top| SelectObj <nowiki>[string | var]</nowiki>
Case "Polygon"
| select one or more objects. Comma serves as separator. Example:
logmessage "polygon mode"
: SelectObj "grid,grid1"
Case Else
|-
logmessage "unknown mode"
|valign=top| ToggleSelection <nowiki>[string | var]</nowiki>
exit sub
| Adds one or more objects from current selection. If the objects are already selected then they become subtracted from the selection. Example:
End Select
: ToggleSelection "grid2,grid3"
end sub
|-
|valign=top| [https://download.autodesk.com/global/docs/softimage2013/en_us/sdkguide/index.html?url=si_cmds/SelectAllUsingFilter.html,topicNumber=si_cmds_SelectAllUsingFilter_html SelectAllUsingFilter] <nowiki>[SelFilter], [CheckComponentVisibility], [AffectSelectionList], [CheckObjectSelectability]</nowiki>
|Selects everything that matches the filter and other options. Example:
: SelectAllUsingFilter "object", siCheckComponentVisibility
:: selects all roots, lights, cameras, and geometry (meshes)
: SelectAllUsingFilter "geometry", siCheckComponentVisibility
:: selects all geometry (meshes)
|-
| DeselectAll
| deselects everything
|-
|valign=top| DeleteObj <nowiki>[string | var]</nowiki>
| Deletes one or more objects. Comma used as separator. Example:
: DeleteObj "grid"
: DeleteObj "grid,grid1"
|-
| FreezeObj
| Makes all changes final. But saving those changes is still necessary. (Click on key symbol so it gets red.)
|-
| [https://download.autodesk.com/global/docs/softimage2013/en_us/sdkguide/index.html?url=si_cmds/Translate.html,topicNumber=si_cmds_Translate_html Translate] <nowiki>[InputObjs], [X], [Y], [Z], [Delta], [RefMode], [Center], [AxesFilter], [Snap], [SnapReference], [SnapFilter], [SplitLocalComponents], [PropTagOnly], [Pivot], [PivotX], [PivotY], [PivotZ], [ConstructionMode], [SlideComponents]</nowiki>
| see link
|-
| [https://download.autodesk.com/global/docs/softimage2013/en_us/sdkguide/index.html?url=si_cmds/Rotate.html,topicNumber=si_cmds_Rotate_html Rotate] <nowiki>[InputObjs], [X], [Y], [Z], [Delta], [RefMode], [Center], [AxesFilter], [Reference], [SplitLocalComponents], [PropTagOnly], [Pivot], [PivotX], [PivotY], [PivotZ], [ConstructionMode], [SlideComponents]</nowiki>
| see link
|}
 
 
====Code pieces (VB Script)====
Remember that you can use the search function of your web browser.
 
If you see absolute paths adapt them so that the code works on your system too.


([[Mod_Tool/Scripting|Here]]'s another page for math related code pieces.)


' '''[3] getting the IDs of selected polygons plus sorting them'''
{| class="wikitable" width="100%"
|width=33%| [1] creating and extending an array
poly_count = Selection(0).SubComponent.ComponentCollection.count
|width=33%| [2] check selection mode
logmessage "poly_count: " & poly_count
| [3] getting the IDs of selected polygons plus sorting them
redim selected (poly_count)
|-
logmessage "Show ID as it is."
| [4] converting euler rotations (in degrees) to quaternions
for i=0 to poly_count - 1
| [5] converting quaternions to euler rotations (in degrees)
' build ID array
| [6] get and set values of the playcontrol (timeline)
selected(i) = Selection(0).SubComponent.ComponentCollection(i).index
|-
logmessage selected(i)
| [7] get keyframes
next
| [8] message box
| [9] input box
' change sort order by replacing ">" with "<"
|-
For i = 0 To poly_count - 1
| [10] getting the desktop path
For j = 0 To poly_count - 1
| [11] selecting a folder
If selected(i) > selected(j) Then
| [12] selecting a file of a specific type
tmp = selected(i)
|-
selected(i) = selected(j)
| [13] reading out environment variables
selected(j) = tmp
| [14] check if file exist
End If
| [15] check if folder exist + create folder
Next
|-
Next
| [16] write xml file
logmessage "Show sorted ID."
| [17] read xml file
| [18] read xml file (attribute/content-based)
for i=0 to poly_count - 1
|-
logmessage selected(i)
| [19] create txt file + write lines
next
| [20] read txt file
 
| [21] check onisplit version
 
|-
' '''[4] converting euler rotations (in degrees) to quaternions'''
| [22] call CMD, e.g. to use onisplit
| [23] building forms in ModTool
dim x, y, z, dRotation, qRotation
| [24] UserDataBlob
x = 90
|-
y = 0
| [25] getting the position of points (with selection mode point)
z = 0
| [26] getting the position of points (with selection mode object)
| [27] getting and setting the position of points (without selection)
set dRotation = XSIMath.CreateRotation(XSIMath.DegreesToRadians(x), XSIMath.DegreesToRadians(y), XSIMath.DegreesToRadians(z))  
|-
set qRotation = XSIMath.CreateQuaternion()
| [28] getting the rotation and position of selected objects
| [29] getting the rotation and position of not selected objects
dRotation.GetQuaternion (qRotation)
| [30] decrypting merged integer flags
LogMessage qRotation.W
|-
LogMessage qRotation.X
| [31] disabling PPG popups
LogMessage qRotation.Y
| [32] disabling logmessages
LogMessage qRotation.Z
| [33] getting bounding box values
' INFO : 0,707106781186548
|-
' INFO : 0,707106781186547
| [34] open an explorer window
' INFO : 0
| [35] working with hierarchies
' INFO : 0
| [36] drag and drop (DnD) support for specific oni files
|-
| [37] dae export
| [38] fbx export
| [39] import an image clip only once
|-
| [40] layers
| [41] onisplit update
| [42] get vertex color
|-
| [43] get all used textures
| [44] get global point position
|
|}




  ' '''[5] converting quaternions to euler rotations (in degrees)'''
  ' '''[1] creating and extending an array'''
   
   
dim qW, qX, qY, qZ, qRotation, x, y, z
   
   
qW = 0.707106781186548
' creating an array
  qX = 0.707106781186547
' () sets the number of array items
  qY = 0
redim nums (3)
qZ = 0
for i = 0 to 3
  nums(i) = (i)
next
logmessage "output all items"
for each n in nums
  logmessage n
next
logmessage "first array item holds: " & lbound(nums)
logmessage "last array item holds: " & ubound(nums)
logmessage "-------------------------------------"
   
   
set qRotation = XSIMath.CreateQuaternion (qW, qX , qY, qZ)
   
   
qRotation.GetXYZAngleValues x, y, z
' extending an array
logmessage XSIMath.RadiansToDegrees(x)
' use "preserve" to keep the old content
logmessage XSIMath.RadiansToDegrees(y)
' find next higher value
logmessage XSIMath.RadiansToDegrees(z)
plus_one = ubound(nums) + 1
' INFO : 89,9999999999999
redim preserve nums (plus_one)
' INFO : 0
  nums(plus_one) = 4
' INFO : 0
 
 
  ' '''[6] get and set values of the playcontrol (timeline)'''
   
   
  ' timeline variables (tl)
  for each n in nums
  dim tlStart, tlEnd, tlCurrent
logmessage n
next
logmessage "first array item holds: " & lbound(nums)
  logmessage "last array item holds: " & ubound(nums)
   
   
' get values
tlStart = GetValue ("PlayControl.In")
tlEnd = GetValue ("PlayControl.Out")
tlCurrent = GetValue ("PlayControl.Current")
   
   
  ' set values
  ' INFO : output all items
  SetValue ("PlayControl.In"), 7
  ' INFO : 0
  SetValue ("PlayControl.Out"), 70
  ' INFO : 1
  SetValue ("PlayControl.Current"), 14
  ' INFO : 2
' INFO : 3
' INFO : first array item holds: 0
' INFO : last array item holds: 3
' INFO : -------------------------------------
' INFO : 0
' INFO : 1
' INFO : 2
' INFO : 3
' INFO : 4
' INFO : first array item holds: 0
' INFO : last array item holds: 4




  ' '''[7] get keyframes'''
  ' '''[2] check selection mode '''
   
   
  ' keyframe counting code like "selection(0).rotx.Source.Keys.count" will produce an error if no keys exist
  checkfilter
  ' that's why we need to catch possible errors for each counting
  'use sub to make use of the exit command
   
   
  on error resume next
  sub checkfilter
  logmessage "--------------------------------------------------"
  Select Case Selection.Filter.Name
logmessage "X rotation keys: " & selection(0).rotx.Source.Keys.count
  'caution: case-sensitive
  for each k in selection(0).rotx.Source.Keys
logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
next
if err <> 0 then
logmessage "no X rotation keys"
end if
on error goto 0
   
   
on error resume next
Case "object"
logmessage "--------------------------------------------------"
logmessage "object mode"
  logmessage "Y rotation keys: " & selection(0).roty.Source.Keys.count
  Case "Edge"
  for each k in selection(0).roty.Source.Keys
logmessage "edge mode"
  logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
  Case "Vertex"
  next
  logmessage "point mode"
if err <> 0 then
Case "Polygon"
logmessage "no Y rotation keys"
logmessage "polygon mode"
  end if
  Case Else
  on error goto 0
logmessage "unknown mode"
exit sub
End Select
  end sub
 
 
  ' '''[3] getting the IDs of selected polygons plus sorting them'''
   
   
  on error resume next
  poly_count = Selection(0).SubComponent.ComponentCollection.count
logmessage "--------------------------------------------------"
logmessage "poly_count: " & poly_count
logmessage "Z rotation keys: " & selection(0).rotz.Source.Keys.count
redim selected (poly_count)
for each k in selection(0).rotz.Source.Keys
logmessage "Show ID as it is."
logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
for i=0 to poly_count - 1
  next
  ' build ID array
if err <> 0 then
selected(i) = Selection(0).SubComponent.ComponentCollection(i).index
  logmessage "no Z rotation keys"
  logmessage selected(i)
  end if
  next
on error goto 0
   
   
  on error resume next
  ' change sort order by replacing ">" with "<"
  logmessage "--------------------------------------------------"
For i = 0 To poly_count - 1
logmessage "X position keys: " & selection(0).posx.Source.Keys.count
  For j = 0 To poly_count - 1
for each k in selection(0).posx.Source.Keys
If selected(i) > selected(j) Then
  logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
tmp = selected(i)
  next
selected(i) = selected(j)
  if err <> 0 then
selected(j) = tmp
logmessage "no X position keys"
  End If
end if
  Next
on error goto 0
  Next
logmessage "Show sorted ID."
   
   
  on error resume next
  for i=0 to poly_count - 1
logmessage "--------------------------------------------------"
  logmessage selected(i)
  logmessage "Y position keys: " & selection(0).posy.Source.Keys.count
next
for each k in selection(0).posy.Source.Keys
 
logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
 
next
  ' '''[4] converting euler rotations (in degrees) to quaternions'''
if err <> 0 then
logmessage "no Y position keys"
  end if
on error goto 0
   
   
  on error resume next
  dim x, y, z, dRotation, qRotation
logmessage "--------------------------------------------------"
x = 90
logmessage "Z position keys: " & selection(0).posz.Source.Keys.count
  y = 0
for each k in selection(0).posz.Source.Keys
  z = 0
logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
next
  if err <> 0 then
logmessage "no Z position keys"
end if
  on error goto 0
   
   
set dRotation = XSIMath.CreateRotation(XSIMath.DegreesToRadians(x), XSIMath.DegreesToRadians(y), XSIMath.DegreesToRadians(z))
set qRotation = XSIMath.CreateQuaternion()
dRotation.GetQuaternion (qRotation)
LogMessage qRotation.W
LogMessage qRotation.X
LogMessage qRotation.Y
LogMessage qRotation.Z
' INFO : 0,707106781186548
' INFO : 0,707106781186547
' INFO : 0
' INFO : 0
' '''[5] converting quaternions to euler rotations (in degrees)'''
   
   
  ' output example (0 rot keys, 2 pos keys):
  dim qW, qX, qY, qZ, qRotation, x, y, z
   
   
' INFO : --------------------------------------------------
qW = 0.707106781186548
' INFO : no X rotation keys
qX = 0.707106781186547
' INFO : --------------------------------------------------
qY = 0
' INFO : no Y rotation keys
qZ = 0
' INFO : --------------------------------------------------
   
' INFO : no Z rotation keys
  set qRotation = XSIMath.CreateQuaternion (qW, qX , qY, qZ)
' INFO : --------------------------------------------------
' INFO : X position keys: 2
' INFO : index: 0 // time: 2 // value: 5,14534318031942
  ' INFO : index: 1 // time: 6 // value: 8,2411504340802
  ' INFO : --------------------------------------------------
' INFO : Y position keys: 2
' INFO : index: 0 // time: 2 // value: 0,365325291829147
' INFO : index: 1 // time: 6 // value: 1,11923927115289
' INFO : --------------------------------------------------
' INFO : Z position keys: 2
' INFO : index: 0 // time: 2 // value: 1,96103417177471
' INFO : index: 1 // time: 6 // value: 1,88564277384233
 
 
' '''[8] message box'''
   
   
[http://download.autodesk.com/global/docs/softimage2013/en_us/sdkguide/index.html?url=si_om/XSIUIToolkit.MsgBox.html,topicNumber=si_om_XSIUIToolkit_MsgBox_html msgbox] "message", , "title"
qRotation.GetXYZAngleValues x, y, z
logmessage XSIMath.RadiansToDegrees(x)
logmessage XSIMath.RadiansToDegrees(y)
logmessage XSIMath.RadiansToDegrees(z)
' INFO : 89,9999999999999
' INFO : 0
' INFO : 0




  ' '''[9] input box'''
  ' '''[6] get and set values of the playcontrol (timeline)'''
   
   
  logmessage inputbox ("message", "title" , "pre-entered content")
  ' timeline variables (tl)
 
  dim tlStart, tlEnd, tlCurrent
 
  ' '''[10] getting the desktop path'''
   
   
  ' this can be useful for ''default locations'' like when selecting a folder
  ' get values
  DesktopPath = CreateObject("WScript.Shell").SpecialFolders("Desktop")
  tlStart = GetValue ("PlayControl.In")
  logmessage DesktopPath
tlEnd = GetValue ("PlayControl.Out")
 
  tlCurrent = GetValue ("PlayControl.Current")
 
' '''[11] selecting a folder'''
   
   
  ' the default path is in this case my desktop
  ' set values
  ' to make it work on other systems, you would need the code of "getting the desktop path" section and replace my path with the ''DesktopPath''
  SetValue ("PlayControl.In"), 7
  logmessage XSIUIToolkit.PickFolder("C:\Users\RMM\Desktop\", "title" )
  SetValue ("PlayControl.Out"), 70
SetValue ("PlayControl.Current"), 14




  ' '''[12] selecting a file of a specific type'''
  ' '''[7] get keyframes'''
   
   
set oFileBrowser = XSIUIToolkit.FileBrowser
  ' keyframe counting code like "selection(0).rotx.Source.Keys.count" will produce an error if no keys exist
oFileBrowser.DialogTitle = "Select an image file (png/tga/jpg)"
  ' that's why we need to catch possible errors for each counting
  ' (default folder)
oFileBrowser.InitialDirectory = "c:\"
oFileBrowser.Filter = "JPEG (*.jpg)|*.jpg|PNG (*.png)|*.png| Targa (*.tga)|*.tga||"
oFileBrowser.ShowOpen
If oFileBrowser.FilePathName <> "" Then
logmessage "User selected " & oFileBrowser.FilePathName
Else
logmessage "User pressed cancel"
  End If
 
 
' '''[13] reading out environment variables'''
   
   
  ' some infos about env vars: [http://softimage.wiki.softimage.com/xsidocs/config_envirovars.htm (1)], [http://softimage.wiki.softimage.com/xsidocs/EnvVars_SettingandUsingEnvironmentVariables.htm (2)], [http://softimage.wiki.softimage.com/xsidocs/EnvVars_EnvironmentVariableReference.htm (3)]
  on error resume next
' those variables are stored inside the setenv.bat, two disadvantages:
logmessage "--------------------------------------------------"
' adding or editing those vars appears to not work in vbs or I just did it wrong
logmessage "X rotation keys: " & selection(0).rotx.Source.Keys.count
' anyway, new vars can only be read out after app restart
for each k in selection(0).rotx.Source.Keys
' therefore let's concentrate on reading out existing ones and then how to create our own via txt files (example: [https://dl.dropbox.com/u/139715/OniGalore/ModToolScript/Oni_env_vars.txt Oni_env_vars.txt])
logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
  ' code for reading out:
next
logmessage XSIUtils.ResolvePath("$SI_HOME/")
  if err <> 0 then
 
logmessage "no X rotation keys"
 
end if
  ' '''[14] check if file exist'''
  on error goto 0
   
   
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  on error resume next
If objFSO.FileExists ("C:\folder\file.txt") then
logmessage "--------------------------------------------------"
  logmessage "File exists."
logmessage "Y rotation keys: " & selection(0).roty.Source.Keys.count
  else
  for each k in selection(0).roty.Source.Keys
  logmessage "File doesn't exist."
logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
next
  if err <> 0 then
  logmessage "no Y rotation keys"
  end if
  end if
 
  on error goto 0
 
  ' '''[15] check if folder exist + create folder'''
   
   
  dim strDirectory
  on error resume next
  strDirectory = "C:\test"
logmessage "--------------------------------------------------"
logmessage "Z rotation keys: " & selection(0).rotz.Source.Keys.count
for each k in selection(0).rotz.Source.Keys
logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
next
  if err <> 0 then
logmessage "no Z rotation keys"
end if
on error goto 0
   
   
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  on error resume next
If objFSO.FolderExists(strDirectory) Then
logmessage "--------------------------------------------------"
    Set objFolder = objFSO.GetFolder(strDirectory)
logmessage "X position keys: " & selection(0).posx.Source.Keys.count
    logmessage strDirectory & " already exists"
for each k in selection(0).posx.Source.Keys
  Else
logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
    Set objFolder = objFSO.CreateFolder(strDirectory)
next
    logmessage "created folder " & strDirectory
  if err <> 0 then
  End If
logmessage "no X position keys"
 
  end if
 
  on error goto 0
  ' '''[16] write xml file'''
   
   
  FolderName = CreateObject("WScript.Shell").SpecialFolders("Desktop")
  on error resume next
FileName = "test"
logmessage "--------------------------------------------------"
FilePath = FolderName & "\OBAN" & FileName & ".xml"
logmessage "Y position keys: " & selection(0).posy.Source.Keys.count
for each k in selection(0).posy.Source.Keys
logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
next
if err <> 0 then
logmessage "no Y position keys"
end if
on error goto 0
   
   
  Set oFS = CreateObject("Scripting.FileSystemObject")
  on error resume next
Set objXMLFile = oFS.OpenTextFile(FilePath, 2, True, 0)
logmessage "--------------------------------------------------"
logmessage "Z position keys: " & selection(0).posz.Source.Keys.count
' quote sign in a string needs two quote signs
for each k in selection(0).posz.Source.Keys
objXMLFile.WriteLine "<?xml version=""1.0"" encoding=""utf-8""?>"
logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
  objXMLFile.WriteLine "<Oni>"
next
objXMLFile.WriteLine "..."
  if err <> 0 then
  objXMLFile.Close
logmessage "no Z position keys"
 
  end if
 
  on error goto 0
  ' '''[17] create txt file + write lines'''
   
   
txt_location = "C:\Softimage\Softimage_Mod_Tool_7.5\test.txt"
Set fso = CreateObject ("Scripting.FileSystemObject")
Set wText = fso.CreateTextFile (txt_location, 1)
wText.WriteLine "I'm a test file."
wText.WriteLine "Yo!"
wText.Close
' '''[18] read txt file'''
   
   
  Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Softimage\Softimage_Mod_Tool_7.5\test.txt", 1)
  ' output example (0 rot keys, 2 pos keys):
   
   
  do while not objFileToRead.AtEndOfStream
  ' INFO : --------------------------------------------------
    strLine = objFileToRead.ReadLine()
' INFO : no X rotation keys
    logmessage strLine
' INFO : --------------------------------------------------
  loop
  ' INFO : no Y rotation keys
  ' INFO : I'm a test file.
  ' INFO : --------------------------------------------------
  ' INFO : Yo!
' INFO : no Z rotation keys
  ' INFO : --------------------------------------------------
' INFO : X position keys: 2
' INFO : index: 0 // time: 2 // value: 5,14534318031942
' INFO : index: 1 // time: 6 // value: 8,2411504340802
' INFO : --------------------------------------------------
' INFO : Y position keys: 2
' INFO : index: 0 // time: 2 // value: 0,365325291829147
' INFO : index: 1 // time: 6 // value: 1,11923927115289
' INFO : --------------------------------------------------
' INFO : Z position keys: 2
' INFO : index: 0 // time: 2 // value: 1,96103417177471
' INFO : index: 1 // time: 6 // value: 1,88564277384233
 
 
' '''[8] message box'''
   
   
  objFileToRead.Close
  [https://download.autodesk.com/global/docs/softimage2013/en_us/sdkguide/index.html?url=si_om/XSIUIToolkit.MsgBox.html,topicNumber=si_om_XSIUIToolkit_MsgBox_html msgbox] "message", , "title"
Set objFileToRead = Nothing




  ' '''[19] check onisplit version'''
  ' '''[9] input box'''
   
   
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  logmessage inputbox ("message", "title" , "pre-entered content")
  logmessage objFSO.GetFileVersion("F:\Program Files (x86)\Oni\Edition\install\onisplit.exe")
 
 
  ' '''[10] getting the desktop path'''
   
   
  ' result looks like this:
  ' this can be useful for ''default locations'' like when selecting a folder
  ' INFO : 0.9.59.0
  DesktopPath = CreateObject("WScript.Shell").SpecialFolders("Desktop")
logmessage DesktopPath




  ' '''[20] call CMD, e.g. to lunch onisplit or the game'''
  ' '''[11] selecting a folder'''
   
   
  ' relative path
  ' the default path is in this case my desktop
' to make it work on other systems, you would need the code of "getting the desktop path" section and replace my path with the ''DesktopPath''
logmessage XSIUIToolkit.PickFolder("C:\Users\RMM\Desktop\", "title" )
 
 
' '''[12] selecting a file of a specific type'''
   
   
  ' the "GameDataFolder" isn't inside the "install" folder
set oFileBrowser = XSIUIToolkit.FileBrowser
  ' so we will use ..\ to go one folder backwards
oFileBrowser.DialogTitle = "Select an image file (png/tga/jpg)"
   
  ' (default folder)
  ' additional quote signs tells the program where the
oFileBrowser.InitialDirectory = "c:\"
  ' paths strings start and end in case the path contains spaces
oFileBrowser.Filter = "JPEG (*.jpg)|*.jpg|PNG (*.png)|*.png| Targa (*.tga)|*.tga||"
  oFileBrowser.ShowOpen
If oFileBrowser.FilePathName <> "" Then
logmessage "User selected " & oFileBrowser.FilePathName
  Else
logmessage "User pressed cancel"
  End If
 
 
  ' '''[13] reading out environment variables'''
   
   
  ' if you are going to use the xml file right after its extraction (which is likely)
  ' some infos about env vars: [http://web.archive.org/web/20170309190841/http://softimage.wiki.softimage.com/xsidocs/config_envirovars.htm (1)], [http://web.archive.org/web/20180416194626/http://softimage.wiki.softimage.com/xsidocs/EnvVars_SettingandUsingEnvironmentVariables.htm (2)], [http://web.archive.org/web/20170617095054/http://softimage.wiki.softimage.com/xsidocs/EnvVars_EnvironmentVariableReference.htm (3)]
  ' then the "/wait" argument inside the onisplit_action string is important
' those variables are stored inside the setenv.bat, two disadvantages:
  ' without it the code would continue and might try to read the not existing xml file and produce an error
' adding or editing those vars appears to not work in vbs or I just did it wrong
' anyway, new vars can only be read out after app restart
' therefore let's concentrate on reading out existing ones and then how to create our own via txt files (example: <nowiki>https://dl.dropbox.com/u/139715/OniGalore/ModToolScript/Oni_env_vars.txt Oni_env_vars.txt</nowiki> (dead link))
  ' code for reading out:
logmessage XSIUtils.ResolvePath("$SI_HOME/")
 
 
  ' '''[14] check if file exist'''
   
   
  onisplit_location = "F:\Program Files (x86)\Oni\Edition\install"
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  input_folder = """..\GameDataFolder\level19_Final\ONLVcompound.oni"""
  If objFSO.FileExists ("C:\folder\file.txt") then
output_folder = """..\GameDataFolder"""
logmessage "File exists."
  onisplit_action = "cmd /C start /wait OniSplit.exe -extract:xml " & output_folder & " " & input_folder
  else
  logmessage "relative path: " & onisplit_action
logmessage "File doesn't exist."
  ' expected logmessage:
  end if
' INFO : relative path: cmd /C start OniSplit.exe -extract:xml "..\GameDataFolder" "..\GameDataFolder\level19_Final\ONLVcompound.oni"
 
XSIUtils.LaunchProcess onisplit_action, 1, onisplit_location
 
  ' '''[15] check if folder exist + create folder'''
   
   
dim strDirectory
strDirectory = "C:\test"
   
   
  ' absolute path
  Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strDirectory) Then
    Set objFolder = objFSO.GetFolder(strDirectory)
    logmessage strDirectory & " already exists"
Else
    Set objFolder = objFSO.CreateFolder(strDirectory)
    logmessage "created folder " & strDirectory
End If
   
   
  'adapt paths so it works on your computer
  ' ### or simply:
  onisplit_location = "F:\Program Files (x86)\Oni\Edition\install"
  dir = "C:\test"
  input_folder = """F:\Program Files (x86)\Oni\Edition\GameDataFolder\level19_Final\ONLVcompound.oni"""
  XSIUtils.EnsureFolderExists (dir)
output_folder = """F:\Program Files (x86)\Oni\Edition\GameDataFolder"""
 
onisplit_action = "cmd /C start /wait OniSplit.exe -extract:xml " & output_folder & " " & input_folder
 
logmessage "absolute path: " & onisplit_action
  ' '''[16] write xml file'''
  ' expected logmessage:
' <small>INFO : absolute path: cmd /C start OniSplit.exe -extract:xml "F:\Program Files (x86)\Oni\Edition\GameDataFolder" "F:\Program Files (x86)\Oni\Edition\GameDataFolder\level19_Final\ONLVcompound.oni"</small>
XSIUtils.LaunchProcess onisplit_action, 1, onisplit_location
   
   
FolderName = CreateObject("WScript.Shell").SpecialFolders("Desktop")
FileName = "test"
FilePath = FolderName & "\OBAN" & FileName & ".xml"
   
   
  ' you can also lunch bat files
  Set oFS = CreateObject("Scripting.FileSystemObject")
Set objXMLFile = oFS.OpenTextFile(FilePath, 2, True, 0)
   
   
  onibat = "cmd /C start run_wind.bat"
  ' quote sign in a string needs two quote signs
  onilocation = "F:\Program Files (x86)\Oni\Edition"
objXMLFile.WriteLine "<?xml version=""1.0"" encoding=""utf-8""?>"
  XSIUtils.LaunchProcess onibat, 0, onilocation
  objXMLFile.WriteLine "<Oni>"
objXMLFile.WriteLine "..."
  objXMLFile.Close
 


  ' alternative to cmd: call onisplit via winmgmts
  ' '''[17] read xml file'''
Set xmlDoc = CreateObject( "Microsoft.XMLDOM" )
xmlDoc.Async = "False"
path = "C:\Users\RRM\Oni\AE\AEInstaller\vanilla\level19_Final\BINACJBOWeapon.xml"
xmlDoc.Load( path )
Set colPosition = xmlDoc.selectNodes( "Oni/Objects/WEAP/Header/Position" )
Set colRotation = xmlDoc.selectNodes( "Oni/Objects/WEAP/Header/Rotation" )
Set colClass =    xmlDoc.selectNodes( "Oni/Objects/WEAP/OSD/Class" )
   
   
  ' slightly modified code from [http://blogs.technet.com/b/heyscriptingguy/archive/2006/12/08/how-can-i-start-a-process-and-then-wait-for-the-process-to-end-before-terminating-the-script.aspx that site]
  loop_count = xmlDoc.selectNodes( "Oni/Objects/WEAP").length
' ''logmessage "onisplit finished."'' will be executed after the conversion finished, there should be also an delay of 3 seconds to support very slow computers
' if you are going to use this method consider to extent the code to check if input file and output directory exist
osp_loca = "C:\OniAE\Edition\install\OniSplit.exe"
osp_action = "-extract:xml"
osp_output = """C:\OniAE\Edition\GameDataFolder"""
osp_input = """C:\OniAE\Edition\GameDataFolder\level1_Final\AKEVEnvWarehouse.oni"""
osp_total = osp_loca & " " & osp_action & " " & osp_output & " " & osp_input
logmessage osp_total
   
   
  strComputer = "."
  logmessage "found " & loop_count & " weapons:"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
  logmessage "================"
  objWMIService.Create osp_total, null, null, intProcessID
  for i=0 to loop_count - 1
  Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
   
   
' wait 3 second to find event - should be enough time for single actions on a slow computer
'split string into pices as array, space is used as seperator by default
Set colMonitoredProcesses = objWMIService.ExecNotificationQuery _
'element 0 = X; element 1 = Y; element 2 = Z
    ("Select * From __InstanceDeletionEvent Within 3 Where TargetInstance ISA 'Win32_Process'")
pos = split(colPosition.item(i).text)
rot = split(colRotation.item(i).text)
' Mod Tool wants comma instead of point for decimal seperator
pos(0) = replace (pos(0), ".", ",")
pos(1) = replace (pos(1), ".", ",")
pos(2) = replace (pos(2), ".", ",")
rot(0) = replace (rot(0), ".", ",")
rot(1) = replace (rot(1), ".", ",")
rot(2) = replace (rot(2), ".", ",")
   
   
Do Until i = 1
logmessage colClass.item(i).text
    Set objLatestProcess = colMonitoredProcesses.NextEvent
logmessage pos(0) & " " & pos(1) & " " & pos(2)
    If objLatestProcess.TargetInstance.ProcessID = intProcessID Then
logmessage rot(0) & " " & rot(1) & " " & rot(2)
        i = 1
logmessage "----------------"
    End If
next
  Loop
  logmessage "onisplit finished."
  ' now you can work with the extracted xml file
' INFO : found 2 weapons:
' INFO : ================
' INFO : w5_sbg
' INFO : 23,16747 84,8193359 757,1958
' INFO : 0 0 0
' INFO : ----------------
' INFO : w4_psm
  ' INFO : 18,1105652 84,8193359 749,121
  ' INFO : 0 0 0
  ' INFO : ----------------




{| border=0 cellpadding=0 style="float:right"
| [http://i305.photobucket.com/albums/nn207/unknownfuture/Oni_Galore_Images/XSI_modding/PPG_zpsda38090b.png http://i305.photobucket.com/albums/nn207/unknownfuture/Oni_Galore_Images/XSI_modding/PPG_tn_zps84e07fe6.png]
|}


  ' '''[21] building a form (PPG)'''
  ' '''[18] read xml file (attribute/content-based)'''
   
   
  dim oPSet, oPPGLayout, oItem, PPG_exist
  Set xmlDoc = CreateObject( "Microsoft.XMLDOM" )
' tells the program to wait until the file was loaded conpletely
xmlDoc.Async = "False"
xmlDoc.Load( "C:\Users\RRM\Oni\AE\AEInstaller\vanilla\level0_Final\BINAEINOimpact_effects.xml" )
' example 1 ('''we use this one''')
' nodes only with a certain attribute and conent will be collected
' content-based search: node [child_node = 'content']
' attribute-based search: node [@attribute_name = 'attribute_value']
' if things get too long an underscore _ can be used to make a linebreak
'''set w1_tap = xmlDoc.selectNodes _'''
'''( "Oni/ImpactEffects/Impact[@Name = 'w1_tap']/Material[@Name = 'Unbreak_Glass']/ImpactEffect [Component = 'Damage']" )'''
   
   
' set check value to 0
PPG_exist = 0
   
   
  ' check if PPG exists
  ' example 2
  for each prop in ActiveProject.ActiveScene.Root.Properties
  ' use "or" for a search of various material
logmessage prop.name
'set w1_tap = xmlDoc.selectNodes _
if instr(1, prop.name, "my_new_PPG") > 0 then
' ( "Oni/ImpactEffects/Impact/Material[@Name = 'Default' or @Name = 'Character']/ImpactEffect" )
PPG_exist = 1
logmessage "found " & """" & prop.name & """"
end if
next
   
   
  ' create PPG if it doesn't exist
   
  if PPG_exist = 0 then
' example 3
set oPSet = ActiveSceneRoot.AddProperty("CustomProperty", false, "my_new_PPG")
' use (|) for a search of various content, e.g. ''<ImpactEffect><Modifier>Light'' plus ''<ImpactEffect><Modifier>Medium''
  set oPPGLayout = oPSet.PPGLayout
  'set w1_tap = xmlDoc.selectNodes _
' ( "Oni/ImpactEffects/Impact/Material/(ImpactEffect [Modifier = 'Light'] | ImpactEffect [Modifier = 'Medium'])" )
for each element in w1_tap
logmessage "Impact: " & element.parentNode.parentNode.getAttribute("Name")
  logmessage "Material: " & element.parentNode.getAttribute("Name")
 
 
  ' setup PPG parameters
  ' outputs "tag name: tag content"
' ###################################################################################
  logmessage element.childNodes(0).nodename & ": " & element.childNodes(0).text
' create checkbox and remove key symboles by setting parameter "Animatable" to false
  logmessage element.childNodes(1).nodename & ": " & element.childNodes(1).text
  oPSet.AddParameter3 "Check1", siBool, 0, , , false
  logmessage "-----------------------------------"
oPSet.AddParameter3 "Check2", siBool, 0, , , false
oPSet.AddParameter3 "Check3", siBool, 1, , , false
  oPSet.AddParameter3 "Check4", siBool, 1, , , false
oPSet.AddParameter3 "text1", siString
' last parameter of "int1" is set to ReadOnly
oPSet.AddParameter3 "int1", siInt2, , , , false, 1  
  oPSet.AddParameter3 "int2", siInt2, , , , false, 0
 
 
  ' add PPG items
  'check for sounds
  ' ###################################################################################
  if element.childNodes(2).childNodes.length = 0 then
oPPGLayout.AddItem "text1", "Hi there!"
logmessage "sound not present"
  oPPGLayout.AddItem "int1", "number 1"
  else
oPPGLayout.AddItem "int2", "number 2"
logmessage "sound is present"
oPPGLayout.AddGroup "4 checkboxes", true
logmessage "-----------------------------------"
oPPGLayout.AddRow
logmessage element.childNodes(2).childNodes(0).nodename & ": " & element.childNodes(2).childNodes(0).text
  oPPGLayout.AddItem "Check1", "C1"
  logmessage element.childNodes(2).childNodes(1).nodename & ": " & element.childNodes(2).childNodes(1).text
  oPPGLayout.AddItem "Check3", "C3"
  logmessage element.childNodes(2).childNodes(2).nodename & ": " & element.childNodes(2).childNodes(2).text
oPPGLayout.EndRow
  logmessage element.childNodes(2).childNodes(3).nodename & ": " & element.childNodes(2).childNodes(3).text
oPPGLayout.AddRow
  end if
  oPPGLayout.AddItem "Check2", "C2"
  logmessage "-----------------------------------"
oPPGLayout.AddItem "Check4", "C4"
  oPPGLayout.EndRow
  ' check for particle
  oPPGLayout.EndGroup
  if element.childNodes(3).childNodes.length = 0 then
 
  logmessage "no particle present"
  oPPGLayout.AddButton("log_values", "log PPG values").setAttribute siUICX, 120
  else
logmessage "number of particle: " & element.childNodes(3).childNodes.length
oPPGLayout.Logic = "sub log_values_OnClicked" & vbCrlf & _
for each particle_section in element.childNodes(3).childNodes
  " logmessage ""text 1 = "" & getvalue(""my_new_PPG.text1"")" & vbCrlf & _
logmessage "-----------------------------------"
" logmessage ""number 1 = "" & getvalue(""my_new_PPG.int1"")" & vbCrlf & _
for each particle_tag in particle_section.childnodes
" logmessage ""C1 = "" & getvalue(""my_new_PPG.Check1"")" & vbCrlf & _
logmessage particle_tag.nodename & ": " & particle_tag.text
  " end sub"
next
 
next
oPPGLayout.Language = "VBScript" 'Optional because this is the default
  end if
  logmessage "==================================="
next
   
   
' open PPG
' INFO : Impact: w1_tap
InspectObj oPSet
' INFO : Material: Unbreak_Glass
  else
' INFO : Component: Damage
' open that PPG if it already exist
' INFO : Modifier: Any
InspectObj "my_new_PPG"
' INFO : -----------------------------------
  end if
  ' INFO : sound not present
' INFO : -----------------------------------
' INFO : number of particle: 2
  ' INFO : -----------------------------------
' INFO : Name: d__GLASSCRACK
' INFO : Orientation: 0
' INFO : Location: 4
' INFO : Decal1: false
' INFO : Decal2: true
' INFO : -----------------------------------
' INFO : Name: w1_tap_x03
' INFO : Orientation: 0
' INFO : Location: 1
' INFO : Offset: -1
' INFO : ===================================
 
 
' '''[] remove xml nodes'''


  ' set values from outside the PPG
  Set objXMLDoc = CreateObject("Microsoft.XMLDOM")
  setvalue "my_new_PPG.text1", "any text could stand here"
objXMLDoc.async = False
  setvalue "my_new_PPG.int1", "42"
  setvalue "my_new_PPG.check1", true
Dim XMLFile
  XMLFile = "C:\Softimage\Softimage_Mod_Tool_7.5\OniLevels\ONLV\test\ONLVAirport.xml"
  objXMLDoc.load(XMLFile)
Set nodes = objXMLDoc.selectNodes("Oni/CRSA/*")
  For Each node In nodes
    node.parentNode.removeChild(node)
Next
   
   
  ' get values from outside the PPG
  objXMLDoc.Save(XMLFile)
logmessage getvalue("my_new_PPG.text1")
 
logmessage getvalue("my_new_PPG.int1")
logmessage getvalue("my_new_PPG.check1")


' '''[19] create txt file + write lines'''
txt_location = "C:\Softimage\Softimage_Mod_Tool_7.5\test.txt"
Set fso = CreateObject ("Scripting.FileSystemObject")
Set wText = fso.CreateTextFile (txt_location, 1)
wText.WriteLine "I'm a test file."
wText.WriteLine "Yo!"
wText.Close


{| border=0 cellpadding=0 style="float:right"
| [http://i305.photobucket.com/albums/nn207/unknownfuture/Oni_Galore_Images/3D_modding/UserDataBlob.png http://i305.photobucket.com/albums/nn207/unknownfuture/Oni_Galore_Images/3D_modding/UserDataBlob_tn.png]
|}


  ' '''[22] UserDataBlob'''
  ' '''[20] read txt file'''
   
   
  ' you can attach data to objects, e.g. new properties for the scene root or Oni Trigger Volumes
  Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Softimage\Softimage_Mod_Tool_7.5\test.txt", 1)
' the so-called "UserDataBlob" can't be saved in *.dae, so save the whole scene to keep your progress
   
   
  ' check if my property exist
  do while not objFileToRead.AtEndOfStream
found_my_prop = 0
    strLine = objFileToRead.ReadLine()
set oProps = ActiveProject.ActiveScene.Root
    logmessage strLine
logmessage "root name: " & ActiveProject.ActiveScene.Root
  loop
  for each prop in oProps.Properties
' INFO : I'm a test file.
' remove apostroph in line beneath to log all root properties
  ' INFO : Yo!
  'LogMessage prop.Name
if instr(1, prop.Name, "my_prop") = 1 then
found_my_prop = 1
end if
  next
   
   
  ' prop doesn't exist, create it
  objFileToRead.Close
  if found_my_prop = 0 then
  Set objFileToRead = Nothing
' create property (must also have content, in this case "yes")
 
oProps.AddProperty( "UserDataBlob", , "my_prop" ).value = "yes"
 
logmessage "created my new prop"
  ' '''[21] check onisplit version'''
  end if
   
   
  ' prop exists, change/read its value
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  if found_my_prop = 1 then
  logmessage objFSO.GetFileVersion("F:\Program Files (x86)\Oni\Edition\install\onisplit.exe")
' change property
oProps.Properties( "my_prop" ).value = "no"
   
   
' read property
' result looks like this:
logmessage oProps.Properties( "my_prop" ).value
' INFO : 0.9.59.0
' if you want to read a property from another script be sure that it was already created
' reuse code under "check if my property exist"
end if




  ' '''[23] getting the position of points (with selection mode point)'''
  ' '''[22] call CMD, e.g. to lunch onisplit or the game'''
' relative path
   
   
  ' a point must be selected
  ' the "GameDataFolder" isn't inside the "install" folder
' gets xyz position of first selected point of the first selected object
  ' so we will use ..\ to go one folder backwards
  logmessage Selection(0).SubComponent.ComponentCollection(0).position.x
logmessage Selection(0).SubComponent.ComponentCollection(0).position.y
logmessage Selection(0).SubComponent.ComponentCollection(0).position.z
 
 
' '''[24] getting the position of points (with selection mode object)'''
   
   
  ' an object must be selected
  ' additional quote signs tells the program where the  
' gets xyz position of point 0 of the first selected object
  ' paths strings start and end in case the path contains spaces
logmessage selection(0).activeprimitive.geometry.Points(0).Position.x
logmessage selection(0).activeprimitive.geometry.Points(0).Position.y
logmessage selection(0).activeprimitive.geometry.Points(0).Position.z
 
 
  ' '''[25] getting and setting the position of points (without selection) right after object creation'''
   
   
  ' point positions are relative to the object's center
  ' if you are going to use the xml file right after its extraction (which is likely)
  ' to get the absolute point positions add center to point
  ' then the "/wait" argument inside the onisplit_action string is important
  ' to set the absolute point positions subtract center from point
  ' without it the code would continue and might try to read the not existing xml file and produce an error
   
   
  set oRoot = application.activeproject.activescene.root
  onisplit_location = "F:\Program Files (x86)\Oni\Edition\install"
  set oObj = oRoot.addgeometry( "Cube", "MeshSurface", "test" )
input_folder = """..\GameDataFolder\level19_Final\ONLVcompound.oni"""
  output_folder = """..\GameDataFolder"""
onisplit_action = "cmd /C start /wait OniSplit.exe -extract:xml " & output_folder & " " & input_folder
logmessage "relative path: " & onisplit_action
' expected logmessage:
' INFO : relative path: cmd /C start OniSplit.exe -extract:xml "..\GameDataFolder" "..\GameDataFolder\level19_Final\ONLVcompound.oni"
XSIUtils.LaunchProcess onisplit_action, 1, onisplit_location
   
   
' to test our code move center to somewhere else
Translate oObj, 9, 11, 13, siRelative, siGlobal, siCtr, siXYZ, , , , , , , , , , 0
SaveKey oObj & ".kine.local.posx," & oObj & ".kine.local.posy," & oObj & ".kine.local.posz", 1, , , , True
   
   
  FreezeObj oObj
  ' absolute path
  set oGeometry = oObj.activeprimitive.geometry
   
  aPositions = oGeometry.Points.PositionArray
  'adapt paths so it works on your computer
  ' get old position
  onisplit_location = "F:\Program Files (x86)\Oni\Edition\install"
  '                                        (xyz, point)
  input_folder = """F:\Program Files (x86)\Oni\Edition\GameDataFolder\level19_Final\ONLVcompound.oni"""
  logmessage "old point 0 posx: " & aPositions(0, 0) + GetValue(oObj & ".kine.global.posx")
  output_folder = """F:\Program Files (x86)\Oni\Edition\GameDataFolder"""
  logmessage "old point 0 posy: " & aPositions(1, 0) + GetValue(oObj & ".kine.global.posy")
  onisplit_action = "cmd /C start /wait OniSplit.exe -extract:xml " & output_folder & " " & input_folder
  logmessage "old point 0 posz: " & aPositions(2, 0) + GetValue(oObj & ".kine.global.posz")
  logmessage "absolute path: " & onisplit_action
' expected logmessage:
' <small>INFO : absolute path: cmd /C start OniSplit.exe -extract:xml "F:\Program Files (x86)\Oni\Edition\GameDataFolder" "F:\Program Files (x86)\Oni\Edition\GameDataFolder\level19_Final\ONLVcompound.oni"</small>
XSIUtils.LaunchProcess onisplit_action, 1, onisplit_location
   
   
' set new position
aPositions(0, 0) = -7 - GetValue(oObj & ".kine.global.posx")
aPositions(1, 0) = -7 - GetValue(oObj & ".kine.global.posy")
aPositions(2, 0) = -7 - GetValue(oObj & ".kine.global.posz")
   
   
  ' update the array
  ' you can also lunch bat files
oGeometry.Points.PositionArray = aPositions
' get new position
logmessage "new point 0 posx: " & aPositions(0, 0) + GetValue(oObj & ".kine.global.posx")
logmessage "new point 0 posy: " & aPositions(1, 0) + GetValue(oObj & ".kine.global.posy")
logmessage "new point 0 posz: " & aPositions(2, 0) + GetValue(oObj & ".kine.global.posz")
   
   
  ' INFO : old point 0 posx: -4
  onibat = "cmd /C start run_wind.bat"
' INFO : old point 0 posy: -4
  onilocation = "F:\Program Files (x86)\Oni\Edition"
' INFO : old point 0 posz: -4
  XSIUtils.LaunchProcess onibat, 0, onilocation
' INFO : new point 0 posx: -7
  ' INFO : new point 0 posy: -7
  ' INFO : new point 0 posz: -7


 
  ' alternative to cmd: call onisplit via winmgmts
  ' '''[26] getting the scaling, rotation and position of selected objects'''
   
   
  logmessage "mesh name: " & selection(0)
  ' slightly modified code from [https://devblogs.microsoft.com/scripting/how-can-i-start-a-process-and-then-wait-for-the-process-to-end-before-terminating-the-script/ that site]
  logmessage selection(0).sclx.value
' ''logmessage "onisplit finished."'' will be executed after the conversion finished, there should be also an delay of 3 seconds to support very slow computers
  logmessage selection(0).scly.value
' if you are going to use this method consider to extent the code to check if input file and output directory exist
  logmessage selection(0).sclz.value
osp_loca = "C:\OniAE\Edition\install\OniSplit.exe"
logmessage selection(0).rotx.value
osp_action = "-extract:xml"
  logmessage selection(0).roty.value
osp_output = """C:\OniAE\Edition\GameDataFolder"""
logmessage selection(0).rotz.value
osp_input = """C:\OniAE\Edition\GameDataFolder\level1_Final\AKEVEnvWarehouse.oni"""
  logmessage selection(0).posx.value
osp_total = osp_loca & " " & osp_action & " " & osp_output & " " & osp_input
  logmessage selection(0).posy.value
  logmessage osp_total
  logmessage selection(0).posz.value
strComputer = "."
  Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
objWMIService.Create osp_total, null, null, intProcessID
  Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
' wait 3 second to find event - should be enough time for single actions on a slow computer
Set colMonitoredProcesses = objWMIService.ExecNotificationQuery _
    ("Select * From __InstanceDeletionEvent Within 3 Where TargetInstance ISA 'Win32_Process'")
   
Do Until i = 1
    Set objLatestProcess = colMonitoredProcesses.NextEvent
    If objLatestProcess.TargetInstance.ProcessID = intProcessID Then
        i = 1
    End If
  Loop
  logmessage "onisplit finished."
  ' now you can work with the extracted xml file




' '''[27] getting the scaling, rotation, and position of not selected objects'''
[[Image:XSI_Mod_Tool_PPG.png|thumb]]
' GetValue("NAME.kine.global.rotx")
' NAME must be the exact mesh name
' let's say you want the data of one character's pelvis
logmessage GetValue("pelvis.kine.global.sclx")
logmessage GetValue("pelvis.kine.global.scly")
logmessage GetValue("pelvis.kine.global.sclz")
logmessage GetValue("pelvis.kine.global.rotx")
logmessage GetValue("pelvis.kine.global.roty")
logmessage GetValue("pelvis.kine.global.rotz")
logmessage GetValue("pelvis.kine.global.posx")
logmessage GetValue("pelvis.kine.global.posy")
logmessage GetValue("pelvis.kine.global.posz")
 


  ' '''[28] decrypting merged integer flags'''
  ' '''[23] building a form (PPG)'''
   
   
  ' for example the [[XML:BINA/OBJC/TRGV|BINACJBOTrigger Volume.xml]] file has flags as strings for the <Flags> tag
  dim oPSet, oPPGLayout, oItem, PPG_exist
' and integer values for the <Teams> tag whereby the values are merged to one value
' so if <Teams> tag holds "101" we have to think what flags it holds, the flags can be broken down with following code
   
   
  ' x: hypothetical value of <Teams>
  ' set check value to 0
  x=101
  PPG_exist = 0
' 101 = 64 + 32 + 4 + 1
   
   
  x_255
  ' check if PPG exists
  sub x_255
  for each prop in ActiveProject.ActiveScene.Root.Properties
  if x > 255 then
logmessage prop.name
  msgbox "Flags bigger than 255 are not allowed.", ,"error"
  if instr(1, prop.name, "my_new_PPG") > 0 then
exit sub
  PPG_exist = 1
logmessage "found " & """" & prop.name & """"
  end if
  end if
if x >= 128 and x <= 255 then
next
logmessage "128"
x = x - 128
' create PPG if it doesn't exist
  end if
if PPG_exist = 0 then
  if x >= 64 and x < 128 then
set oPSet = ActiveSceneRoot.AddProperty("CustomProperty", false, "my_new_PPG")
logmessage "64"
set oPPGLayout = oPSet.PPGLayout
x = x - 64
  end if
' setup PPG parameters
  if x >= 32 and x < 64 then
  ' ###################################################################################
logmessage "32"
  ' create checkbox and remove key symboles by setting parameter "Animatable" to false
x = x - 32
oPSet.AddParameter3 "Check1", siBool, 0, , , false
  end if
oPSet.AddParameter3 "Check2", siBool, 0, , , false
  if x >= 16 and x < 32 then
  oPSet.AddParameter3 "Check3", siBool, 1, , , false
logmessage "16"
  oPSet.AddParameter3 "Check4", siBool, 1, , , false
x = x - 16
oPSet.AddParameter3 "text1", siString
  end if
' last parameter of "int1" is set to ReadOnly
  if x >= 8 and x < 16 then
  oPSet.AddParameter3 "int1", siInt2, , , , false, 1
logmessage "8"
  oPSet.AddParameter3 "int2", siInt2, , , , false, 0
x = x - 8
  end if
  ' add PPG items
  if x >= 4 and x < 8 then
  ' ###################################################################################
  logmessage "4"
oPPGLayout.AddItem "text1", "Hi there!"
  x = x - 4
oPPGLayout.AddItem "int1", "number 1"
  end if
  oPPGLayout.AddItem "int2", "number 2"
  if x >= 2 and x < 4 then
  oPPGLayout.AddGroup "4 checkboxes", true
  logmessage "2"
oPPGLayout.AddRow
  x = x - 2
  oPPGLayout.AddItem "Check1", "C1"
  end if
  oPPGLayout.AddItem "Check3", "C3"
  if x = 2 then
  oPPGLayout.EndRow
logmessage "2"
  oPPGLayout.AddRow
x = x - 2
  oPPGLayout.AddItem "Check2", "C2"
  end if
  oPPGLayout.AddItem "Check4", "C4"
  if x = 1 then
oPPGLayout.EndRow
logmessage "1"
  oPPGLayout.EndGroup
x = x - 1
 
  end if
oPPGLayout.AddButton("log_values", "log PPG values").setAttribute siUICX, 120
  if x = 0 then
logmessage "finished check"
  oPPGLayout.Logic = "sub log_values_OnClicked" & vbCrlf & _
end if
  " logmessage ""text 1 = "" & getvalue(""my_new_PPG.text1"")" & vbCrlf & _
end sub
" logmessage ""number 1 = "" & getvalue(""my_new_PPG.int1"")" & vbCrlf & _
" logmessage ""C1 = "" & getvalue(""my_new_PPG.Check1"")" & vbCrlf & _
  " end sub"
  oPPGLayout.Language = "VBScript" 'Optional because this is the default
   
   
' INFO : 64
' open PPG
  ' INFO : 32
InspectObj oPSet
' INFO : 4
  else
' INFO : 1
' open that PPG if it already exist
  ' INFO : finished check
InspectObj "my_new_PPG"
  end if


 
  ' set values from outside the PPG
  ' '''[29] disabling PPG popups'''
setvalue "my_new_PPG.text1", "any text could stand here"
setvalue "my_new_PPG.int1", "42"
setvalue "my_new_PPG.check1", true
   
   
  ' for example if code of a script button creates numerous objects in one go, the same number of property pages (PPG) can appear
  ' get values from outside the PPG
  ' for user convenience those PPG popups can be disabled
  logmessage getvalue("my_new_PPG.text1")
  logmessage getvalue("my_new_PPG.int1")
' disable PPG popup
  logmessage getvalue("my_new_PPG.check1")
Preferences.SetPreferenceValue "Interaction.autoinspect", false
   
' creates the cube mesh but no PPG will show up
CreatePrim "Cube", "MeshSurface"
   
' enable PPG popup again
Preferences.SetPreferenceValue "Interaction.autoinspect", true




' '''[30] disabling logmessages'''
[[Image:XSI_Mod_Tool_UserDataBlob.png|thumb]]
' msglogverbos is probably already set to false by default
' could be set at the start of a final script to increase performance
setvalue "preferences.scripting.msglogverbose", false
setvalue "preferences.scripting.msglog", false


 
  ' '''[24] UserDataBlob'''
  ' '''[31] getting bounding box values'''
   
   
  ' this could be useful to create a bounding box for [[OBD_talk:OFGA#XML|OFGA files]]
  ' you can attach data to objects, e.g. new properties for the scene root or Oni Trigger Volumes
' the so-called "UserDataBlob" can't be saved in *.dae, so save the whole scene to keep your progress
   
   
  ' let's get the bounding box of a simple cylinder
  ' check if my property exist
  ' the output values will be absolute positions
found_my_prop = 0
  CreatePrim "Cylinder", "MeshSurface"
  set oProps = ActiveProject.ActiveScene.Root
  logmessage "root name: " & ActiveProject.ActiveScene.Root
for each prop in oProps.Properties
' remove apostroph in line beneath to log all root properties
  'LogMessage prop.Name
if instr(1, prop.Name, "my_prop") = 1 then
found_my_prop = 1
end if
next
   
   
  dim xmin, ymin, zmin, xmax, ymax, zmax
  ' prop doesn't exist, create it
  dim list
  if found_my_prop = 0 then
'if you use SelectionList the objects will be treated as one single object
' create property (must also have content, in this case "yes")
'set list = GetValue( "SelectionList" )
oProps.AddProperty( "UserDataBlob", , "my_prop" ).value = "yes"
set list = GetValue( selection(0) )
logmessage "created my new prop"
GetBBox list, TRUE, xmin, ymin, zmin, xmax, ymax, zmax
  end if
LogMessage "Lower Bound: " & xmin & " / " & ymin & " / " & zmin
  LogMessage "Upper Bound: " & xmax & " / " & ymax & " / " & zmax
   
   
  ' expected output:
  ' prop exists, change/read its value
  ' INFO : Lower Bound: -1 / -2 / -1
  if found_my_prop = 1 then
' INFO : Upper Bound: 1 / 2 / 1
' change property
 
oProps.Properties( "my_prop" ).value = "no"
 
' '''[32] open an explorer window'''
   
   
' this could be used open an output folder ...
' read property
strPath = "[http://support.microsoft.com/kb/152457 explorer.exe /e]," & XSIUtils.ResolvePath("$SI_HOME/")
logmessage oProps.Properties( "my_prop" ).value
Set objShell = CreateObject("Wscript.Shell")
' if you want to read a property from another script be sure that it was already created
objShell.Run strPath
' reuse code under "check if my property exist"
end if
' to select a generated file inside the folder:
strPath = "explorer.exe /select," & "C:\folder\test.txt"




{| border=0 cellpadding=0 style="float: right; padding-top: 10px"
  ' '''[25] getting the position of points (with selection mode point)'''
| SelectNeighborObj obj 5<br>[http://i305.photobucket.com/albums/nn207/unknownfuture/Oni_Galore_Images/XSI_modding/SelectNeighborObj_obj_5.png http://i305.photobucket.com/albums/nn207/unknownfuture/Oni_Galore_Images/XSI_modding/SelectNeighborObj_obj_5_tn.png]
|}
  ' '''[33] working with hierarchies'''  
   
   
  ' let's be sure we have an object selected
  ' a point must be selected
  if selection.count > 0 and typename(selection(0)) = "X3DObject" then
  ' gets xyz position of first selected point of the first selected object
 
logmessage Selection(0).SubComponent.ComponentCollection(0).position.x
' the object itself
logmessage Selection(0).SubComponent.ComponentCollection(0).position.y
logmessage selection(0)
logmessage Selection(0).SubComponent.ComponentCollection(0).position.z
 
 
' the parent object
' '''[26] getting the position of points (with selection mode object)'''
logmessage selection(0).parent
' the children
for each n in selection(0).FindChildren( , , , 0 )
logmessage n
next
' the 4the parameter of FindChildren can be set to 0 or 1
' with 0 you get all direct children
' with 1 you get everything located under that object no matter how deep the level
   
   
' an object must be selected
' gets xyz position of point 0 of the first selected object
logmessage selection(0).activeprimitive.geometry.Points(0).Position.x
logmessage selection(0).activeprimitive.geometry.Points(0).Position.y
logmessage selection(0).activeprimitive.geometry.Points(0).Position.z
' '''[27] getting and setting the position of points (without selection) right after object creation'''
' point positions are relative to the object's center
' to get the absolute point positions add center to point
' to set the absolute point positions subtract center from point
   
   
' count all objects
set oRoot = application.activeproject.activescene.root
logmessage "children: " & selection(0).FindChildren( , , , 1).count
set oObj = oRoot.addgeometry( "Cube", "MeshSurface", "test" )
' caution: if the 3rd parameter is set to siMeshFamily
' then the selected object will be also counted
' find the root object of the hierarchy, any object could be selected
SelectNeighborObj selection(0), 4
   
   
' to test our code move center to somewhere else
Translate oObj, 9, 11, 13, siRelative, siGlobal, siCtr, siXYZ, , , , , , , , , , 0
SaveKey oObj & ".kine.local.posx," & oObj & ".kine.local.posy," & oObj & ".kine.local.posz", 1, , , , True
   
   
' go through the hierarchy in different directions
FreezeObj oObj
' SelectNeighborObj [parameter1], [parameter2], [parameter3], [parameter4]
set oGeometry = oObj.activeprimitive.geometry
' options of the second parameters
aPositions = oGeometry.Points.PositionArray
' 0 go one level up
' get old position
' 1 go one level down
'                                         (xyz, point)
' 2 go to next silbing
logmessage "old point 0 posx: " & aPositions(0, 0) + GetValue(oObj & ".kine.global.posx")
' 3 go to previous silbing
logmessage "old point 0 posy: " & aPositions(1, 0) + GetValue(oObj & ".kine.global.posy")
' 4 go to highest level
logmessage "old point 0 posz: " & aPositions(2, 0) + GetValue(oObj & ".kine.global.posz")
' 5 go to deepest level of current selected obj
' 5: if there are more than one children, the path goes always for the first (left) child (see image)
   
   
' set new position
aPositions(0, 0) = -7 - GetValue(oObj & ".kine.global.posx")
aPositions(1, 0) = -7 - GetValue(oObj & ".kine.global.posy")
aPositions(2, 0) = -7 - GetValue(oObj & ".kine.global.posz")
   
   
' select the hierarchy as a whole
' update the array
SelectObj "left_thigh", "TREE", true
oGeometry.Points.PositionArray = aPositions
' first parameter could be any object of the hierarchy
' get new position
' after using this the selection of an Oni character will be "B:pelvis"
logmessage "new point 0 posx: " & aPositions(0, 0) + GetValue(oObj & ".kine.global.posx")
  else
logmessage "new point 0 posy: " & aPositions(1, 0) + GetValue(oObj & ".kine.global.posy")
msgbox "no object was selected"
logmessage "new point 0 posz: " & aPositions(2, 0) + GetValue(oObj & ".kine.global.posz")
  end if
' INFO : old point 0 posx: -4
' INFO : old point 0 posy: -4
' INFO : old point 0 posz: -4
  ' INFO : new point 0 posx: -7
' INFO : new point 0 posy: -7
  ' INFO : new point 0 posz: -7




'''[34] drag and drop support for specific oni files'''
' '''[28] getting the scaling, rotation and position of selected objects'''
 
function XSILoadPlugin( in_reg )
in_reg.Author = ""
in_reg.Name = "Oni_drag_and_drop"
in_reg.Email = ""
in_reg.URL = ""
in_reg.Major = 1
in_reg.Minor = 0
   
   
in_reg.RegisterEvent "support_oni_DnD",siOnDragAndDrop
logmessage "mesh name: " & selection(0)
'RegistrationInsertionPoint - do not remove this line
logmessage selection(0).sclx.value
logmessage selection(0).scly.value
logmessage selection(0).sclz.value
logmessage selection(0).rotx.value
logmessage selection(0).roty.value
logmessage selection(0).rotz.value
logmessage selection(0).posx.value
logmessage selection(0).posy.value
logmessage selection(0).posz.value
 
 
' '''[29] getting the scaling, rotation, and position of not selected objects'''
   
   
XSILoadPlugin = true
' GetValue("NAME.kine.global.rotx")
  end function
' NAME must be the exact mesh name
' let's say you want the data of one character's pelvis
logmessage GetValue("pelvis.kine.global.sclx")
logmessage GetValue("pelvis.kine.global.scly")
logmessage GetValue("pelvis.kine.global.sclz")
logmessage GetValue("pelvis.kine.global.rotx")
logmessage GetValue("pelvis.kine.global.roty")
logmessage GetValue("pelvis.kine.global.rotz")
logmessage GetValue("pelvis.kine.global.posx")
logmessage GetValue("pelvis.kine.global.posy")
logmessage GetValue("pelvis.kine.global.posz")
 
 
  ' '''[30] decrypting merged integer flags'''
   
   
  function XSIUnloadPlugin( in_reg )
  ' for example the [[XML:BINA/OBJC/TRGV|BINACJBOTrigger Volume.xml]] file has flags as strings for the <Flags> tag
dim strPluginName
' and integer values for the <Teams> tag whereby the values are merged to one value
strPluginName = in_reg.Name
' so if <Teams> tag holds "101" we have to think what flags it holds, the flags can be broken down with following code
Application.LogMessage strPluginName & " has been unloaded.",siVerbose
XSIUnloadPlugin = true
end function
   
   
  function support_oni_DnD_Init( in_ctxt )
  ' x: hypothetical value of <Teams>
dim action
x=101
set action = in_ctxt.GetAttribute( "DragAndDropAction" )
  ' 101 = 64 + 32 + 4 + 1
  end function
   
   
  ' Callback for the support_oni_DnD event.
  x_255
  function support_oni_DnD_OnEvent( in_ctxt )
  sub x_255
  filename = in_ctxt.GetAttribute("DragSource")
  if x > 255 then
' isolate file extension from full name
msgbox "Flags bigger than 255 are not allowed.", ,"error"
FileExt = right(filename, len(filename) - instrrev(filename, "."))
  exit sub
' use LCase to recognize extension that might be in upper case, e.g. rewrites "ONI" to "oni"
if len(FileExt) = 3 and instr(LCase(FileExt), "oni") = 1 then
  'enable drop if file extension is "oni"
in_ctxt.SetAttribute "DragSourceSupported", true
  end if
  end if
  if x >= 128 and x <= 255 then
' catch file drop event
  logmessage "128"
  if in_ctxt.GetAttribute("DragAndDropAction") = 1 then
  x = x - 128
  ' code that handels the imported file
  ' there could be a subtype recognition e.g. to let onisplit convert AKEV to dae files
' [...]
  end if
  end if
if x >= 64 and x < 128 then
' Return value is ignored as this event can not be aborted.
logmessage "64"
support_oni_DnD_OnEvent = true
x = x - 64
end function
end if
 
if x >= 32 and x < 64 then
 
logmessage "32"
'''[35] dae export'''
x = x - 32
 
  end if
set oProps = ActiveProject.ActiveScene.Root.Properties
if x >= 16 and x < 32 then
if typename (oProps.find("ExportCrosswalkOptions")) = "Nothing" then
logmessage "16"
logmessage "Export settings not set"
x = x - 16
CreateExportCrosswalkOptions , "ExportCrosswalkOptions"
end if
else
if x >= 8 and x < 16 then
  logmessage "Export settings present"
logmessage "8"
end if
x = x - 8
end if
' sets the extension to dae
if x >= 4 and x < 8 then
SetValue "ExportCrosswalkOptions.Format", 1
logmessage "4"
' set export path and file name
x = x - 4
SetValue "ExportCrosswalkOptions.Filename", CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\export_test.dae"
  end if
' selection only
  if x >= 2 and x < 4 then
SetValue "ExportCrosswalkOptions.ExportSelectionOnly", True
  logmessage "2"
' export
  x = x - 2
ExportCrosswalk "ExportCrosswalkOptions"
 
 
'''[36] fbx export'''
 
FBXExportLights (false)
FBXExportSelection (true)
' mark FBXExport and hit F1 to get more options
FBXExport (CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\export_test.fbx" )
 
 
'''[37] import an image clip only once'''
 
found_img = 0
set clips = ActiveProject.ActiveScene.ImageClips
for each clip in clips
  logmessage clip.name
  if clip.name = "white_512_512_tga" then
  logmessage "found img"
  found_img = 1
  end if
  end if
next
if x = 2 then
if found_placeholder_img = 0 then
logmessage "2"
  ' import a new texture
x = x - 2
  ' just so:
end if
SICreateImageClip "C:\Users\RRM\Desktop\white_512_512.tga"
if x = 1 then
  ' or as script object:
logmessage "1"
'set oImage = AddImageSource ("C:\Users\RRM\Desktop\white_512_512.tga")
x = x - 1
'set oImageClip = AddImageClip (oImage)
  end if
  end if
  if x = 0 then
logmessage "finished check"
  end if
end sub
' INFO : 64
' INFO : 32
' INFO : 4
' INFO : 1
  ' INFO : finished check




====Script ideas====
' '''[31] disabling PPG popups'''
* addon to make easily use of onisplit within Mod Tool [done]
** supports drag and drop of onisplit
' for example if code of a script button creates numerous objects in one go, the same number of property pages (PPG) can appear
** onisplit's location will be saved and resaved in a txt
' for user convenience those PPG popups can be disabled
** updates scene property after txt changes
** loads txt on app start as scene property
' disable PPG popup
** use backup onisplit from addon if user is to lazy for DnD
Preferences.SetPreferenceValue "Interaction.autoinspect", false
* import/export of flag collection
* import/export of patrol path collection
' creates the cube mesh but no PPG will show up
* import/export of weapons collection
CreatePrim "Cube", "MeshSurface"
* import/export of powerup collection
* [...]
' enable PPG popup again
* autoheal discontinuities (blue lines) of overlaying edges (for repairing google sketchup objects that weren't yet textured)
Preferences.SetPreferenceValue "Interaction.autoinspect", true
* making loops from parts of animations
* copying animation data from one character to another
 
The following sections are about ideas that are checked right now for their possibility of realization or already in the making.
 
 
=====Oni tools addon=====
{| border=0 cellpadding=0 style="float: right;"
| exported warehouse TVs<br>[http://i305.photobucket.com/albums/nn207/unknownfuture/Oni_Galore_Images/3D_modding/TRGV_Oni_to_ModTool.png http://i305.photobucket.com/albums/nn207/unknownfuture/Oni_Galore_Images/3D_modding/TRGV_Oni_to_ModTool_tn.png]
|}


* current content
** Trigger volumes: import / add / export
** camera OBAN: import ([[wikipedia:Drag_and_drop|DnD]]) / export


Code needs improvement to ease integration of other file types and other code pieces.
' '''[32] disabling logmessages'''
' msglogverbos is probably already set to false by default
' could be set at the start of a final script to increase performance
setvalue "preferences.scripting.msglogverbose", false
setvalue "preferences.scripting.msglog", false




=====Selection tracking camera=====
' '''[33] getting bounding box values'''
* https://dl.dropbox.com/u/139715/auto_selection_tracking.txt
 
' this could be useful to create a bounding box for [[XML:OFGA|OFGA files]]
  ' enable automatic tracking
  set_auto_tracking ("yes")
  ' let's get the bounding box of a simple cylinder
  ' disable automatic tracking
' the output values will be absolute positions
  set_auto_tracking ("no")
  CreatePrim "Cylinder", "MeshSurface"
 
There could be other buttons to jump to previous/next object grouped under their parent.
dim xmin, ymin, zmin, xmax, ymax, zmax
  SelectNeighborObj , 2
dim list
  SelectNeighborObj , 3
  'if you use SelectionList the objects will be treated as one single object
 
  'set list = GetValue( "SelectionList" )
 
set list = GetValue( selection(0) )
=====New camera animations=====
  GetBBox list, TRUE, xmin, ymin, zmin, xmax, ymax, zmax
{| border=0 cellpadding=0 style="float: right;"
  LogMessage "Lower Bound: " & xmin & " / " & ymin & " / " & zmin
| last frame of OBANOutroCam02<br>[http://i305.photobucket.com/albums/nn207/unknownfuture/Oni_Galore_Images/Mod_Tool/camera_OBAN_examination_zpsaf16d39e.png http://i305.photobucket.com/albums/nn207/unknownfuture/Oni_Galore_Images/Mod_Tool/camera_OBAN_examination_tn_zpsc8295474.png]
LogMessage "Upper Bound: " & xmax & " / " & ymax & " / " & zmax
|}
 
' expected output:
There's already an excel macro available but now I want to build cam anims without excel.
' INFO : Lower Bound: -1 / -2 / -1
' INFO : Upper Bound: 1 / 2 / 1


The last frame's rotation of level1_Final file OBANOutroCam02 is: -0.0158410165 0.854542 0.0261086561 -0.518483639.


Those quaternions are sorted in X Y Z -W order, so we've to watch out a bit when setting the input for converting them to euler rotations in degrees.
' '''[34] open an explorer window'''
' this could be used open an output folder ...
strPath = "[http://web.archive.org/web/20150212074443/http://support.microsoft.com/kb/152457 explorer.exe /e]," & XSIUtils.ResolvePath("$SI_HOME/")
Set objShell = CreateObject("Wscript.Shell")
objShell.Run strPath
' to select a generated file inside the folder:
strPath = "explorer.exe /select," & "C:\folder\test.txt"


If a newly created object (in this case a cube) shall serve as camera placeholder then the X output has to be multiplied by -1 and the Y output has to be reduced by -180. Those changes must repeated again when exporting the object's rotation to xml.


'''Update: Sept. 29, 2012'''
[[Image:XSI_Mod_Tool_SelectNeighborObj_obj_5.png|thumb|SelectNeighborObj obj 5]]
 
' '''[35] working with hierarchies'''  
If camera is a real one then the additional X and Y changes aren't necessary. (Primitive > Camera > ''any should do'')
 
Positions and rotations keyframes can be applied to the camera root object.
 
 
=====Adding multiple textures to level geometry=====
Material and textures are normally stored right under the object. But AKEV geometry can have more than one texture. Here comes polygon clusters in to play.
 
An example:
 
set oCube = Application.ActiveProject.ActiveScene.Root.AddGeometry("Cube","MeshSurface")
SelectObj "cube", , True
SelectGeometryComponents "cube.poly[LAST]"
CreateCluster
   
   
  AddToCluster "cube.polymsh.cls.Polygon, cube.poly[2-4]"
  ' let's be sure we have an object selected
RemoveFromCluster "cube.polymsh.cls.Polygon, cube.poly[3]"
  if selection.count > 0 and typename(selection(0)) = "X3DObject" then
 
 
The cube has now a polygon cluster. More can be added. Each cluster must get its own material before a texture can be applied to the desired polygons.
  ' the object itself
 
  logmessage selection(0)
[...]
 
 
  ' the parent object
=====TRBS-fitting TRMA creation=====
  logmessage selection(0).parent
{| width="100%"
|valign="top"|
With the following code ...
' the children
* the objects get listed one after another (TRMA-ready)
  for each n in selection(0).FindChildren( , , , 0 )
* the textures get listed for TRMA and TXMP creation
  logmessage n
* the texture sizes get checked to see if "-large" argument is necessary
 
One more idea is to add support for reflective textures.
 
 
Current status:
* http://youtu.be/RqSsXTzHTA8
* drag and drop [http://mods.oni2.net/system/files/Oni_Character_Helper_with_onisplit_dnd_updater_wip.zip add-on file] into Mod Tool to install it
* no LOD, no envmap support
 
|style="float:right"|
hexhound hierarchy
 
[http://i305.photobucket.com/albums/nn207/unknownfuture/Oni_Galore_Images/3D_modding/hexhound_hierarchy_zpsf32e971c.png http://i305.photobucket.com/albums/nn207/unknownfuture/Oni_Galore_Images/3D_modding/hexhound_hierarchy_tn_zpsd82230ce.png]
|}
 
  if selection.count > 0 then
  ' any part could be selected, let's find the root body part
  SelectNeighborObj selection(0), 4
  ' get all members including the pelvis
  set bodyparts = '''selection(0).FindChildren( , , siMeshFamily)'''
  for each member in bodyparts
logmessage "object name: " & member.name
if not typename(member.Material.CurrentImageClip) = "Nothing" then
logmessage "texture: " & member.Material.CurrentImageClip.source.filename.value
'logmessage "material: " & member.Material.name
'logmessage "shader: " & member.Material.shaders(0).name
logmessage "X: " & member.Material.CurrentImageClip.source.Parameters("XRes").Value
logmessage "Y: " & member.Material.CurrentImageClip.source.Parameters("YRes").Value
end if
  logmessage "----------------------------------------------------------"
  next
  next
  logmessage "counted body parts: " & bodyparts.count
' the 4the parameter of FindChildren can be set to 0 or 1
  else
' with 0 you get all direct children
  logmessage "no object was selected"
' with 1 you get everything located under that object no matter how deep the level
  end if
 
{{divhide|logmessage examples}}
' count all objects
  logmessage "children: " & selection(0).FindChildren( , , , 1).count
' caution: if the 3rd parameter is set to siMeshFamily
' then the selected object will be also counted
   
  ' find the root object of the hierarchy, any object could be selected
SelectNeighborObj selection(0), 4
   
   
   
' INFO  : object name: A
' go through the hierarchy in different directions
' INFO  : texture: C:\Users\RRM\Desktop\A.tga
' SelectNeighborObj [parameter1], [parameter2], [parameter3], [parameter4]
' INFO  : X: 512
' options of the second parameters
' INFO  : Y: 512
' 0 go one level up
' INFO  : ----------------------------------------------------------
' 1 go one level down
' INFO  : object name: R
' 2 go to next silbing
' INFO  : texture: C:\Users\RRM\Desktop\R.tga
' 3 go to previous silbing
' INFO  : X: 512
' 4 go to highest level
' INFO  : Y: 512
' 5 go to deepest level of current selected obj
' INFO  : ----------------------------------------------------------
' 5: if there are more than one children, the path goes always for the first (left) child (see image)
  ' INFO  : object name: S
   
  ' INFO  : texture: C:\Users\RRM\Desktop\S.tga
   
' INFO  : X: 512
' select the hierarchy as a whole
' INFO  : Y: 512
SelectObj "left_thigh", "TREE", true
' INFO  : ----------------------------------------------------------
' first parameter could be any object of the hierarchy
' INFO  : object name: P
' after using this the selection of an Oni character will be "B:pelvis"
' INFO  : texture: C:\Users\RRM\Desktop\P.tga
  else
' INFO  : X: 512
msgbox "no object was selected"
' INFO  : Y: 512
  end if
' INFO  : ----------------------------------------------------------
' INFO  : object name: Q
' INFO  : texture: C:\Users\RRM\Desktop\Q.tga
' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : object name: N
' INFO  : texture: C:\Users\RRM\Desktop\N.tga
' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : object name: O
' INFO  : texture: C:\Users\RRM\Desktop\O.tga
' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : object name: L
' INFO  : texture: C:\Users\RRM\Desktop\L.tga
' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : object name: M
' INFO  : texture: C:\Users\RRM\Desktop\M.tga
' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : object name: B
' INFO  : texture: C:\Users\RRM\Desktop\B.tga
  ' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : object name: C
' INFO  : texture: C:\Users\RRM\Desktop\C.tga
' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : object name: D
' INFO  : texture: C:\Users\RRM\Desktop\D.tga
' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : object name: E
' INFO  : texture: C:\Users\RRM\Desktop\E.tga
' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : object name: F
' INFO  : texture: C:\Users\RRM\Desktop\F.tga
' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : object name: G
' INFO  : texture: C:\Users\RRM\Desktop\G.tga
' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : object name: H
' INFO  : texture: C:\Users\RRM\Desktop\H.tga
' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : object name: I
' INFO  : texture: C:\Users\RRM\Desktop\I.tga
' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : object name: J
' INFO  : texture: C:\Users\RRM\Desktop\J.tga
' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : object name: K
' INFO  : texture: C:\Users\RRM\Desktop\K.tga
  ' INFO  : X: 512
' INFO  : Y: 512
' INFO  : ----------------------------------------------------------
' INFO  : counted body parts: 19
{{divhide|end}}
 
 
=====New door animations=====
Final door animation depends on:
* BINACJBODOOR position and rotation
* OBAN positions and rotations
* ZAxisUp (Does this flag do something else?)
 
 
'''Theory of the (Oni to ModTool) import from scratch:'''
 
* import BINACJBODOOR
* get door classes
* extract M3GM from DOOR, etc.
 
* import M3GM
* move center to lower bounding box Z
* move object to Z = 0
* import OBAN
* apply rotations and positions to object
 
* create null object
* make null a parent of door object
* rotate null in X = -90 (to make Z axis pointing up)
* add BINACJBODOOR rotation and position to null object
 
The current version of onisplit (v0.9.68.0) imports the doors from AKEV without animations.
 
Those door have there centers at the lower bounding box Z, got corrected from their ZAxisUp, and have (BINACJBODOOR) rotation and position.


Writing an own combined import would not only take more time, also it wouldn't be so fast and efficient. So, I will go with the existing import but then do some changes on the doors (appling null object, custom properties, etc.)


The door objects can be identified by their naming. Each name contains the BINACJBODOOR ID, e.g. <DOOR Id="7294">.
'''[36] drag and drop support for specific oni files'''
 
There could be a loop scanning all objects for those numbers.
 
 
=====Hierarchy builder for characters=====
Based on old knowledge. See [[Mod_Tool#exchange_of_meshes_in_hierarchies|HERE]] for an easy manual way to change the meshes in hierarchies.


function XSILoadPlugin( in_reg )
in_reg.Author = ""
in_reg.Name = "Oni drag and drop support"
in_reg.Email = ""
in_reg.URL = ""
in_reg.Major = 1
in_reg.Minor = 0
in_reg.RegisterEvent "support_oni_DnD",siOnDragAndDrop
  'RegistrationInsertionPoint - do not remove this line
XSILoadPlugin = true
end function
function XSIUnloadPlugin( in_reg )
dim strPluginName
strPluginName = in_reg.Name
Application.LogMessage strPluginName & " has been unloaded.",siVerbose
XSIUnloadPlugin = true
end function
function support_oni_DnD_OnEvent( in_ctxt )
Set objFSO = CreateObject("Scripting.FileSystemObject")
FullFilePath = in_ctxt.GetAttribute("DragSource")
  FileExt = objFSO.GetExtensionName(FullFilePath)
FileName = objFSO.GetBaseName(FullFilePath)
  if instr(LCase(FileExt), "oni") = 1 then
  in_ctxt.SetAttribute "DragSourceSupported", true
 
  ' next line prevents the code from being repeated
if in_ctxt.GetAttribute("DragAndDropAction") = 1 then
logmessage "What I'm supposed to do with that oni?"
' do more stuff here
' ..................
' e.g. telling onisplit to extract the oni
end if
end if
support_oni_DnD_OnEvent = true
end function


'''Important:'''


'''(old notes in the following)'''
Mod Tool has its own drag and drop event handler for dae and xml file.


{| border=0 cellpadding=0 style="float: right;"
If we succeed in modifying and shipping that new file, we could finally trigger scripts with those files and process them.
| hierarchy breaker beta<br>[http://i305.photobucket.com/albums/nn207/unknownfuture/Oni_Galore_Images/3D_modding/hierarchy_breaker_beta.png http://i305.photobucket.com/albums/nn207/unknownfuture/Oni_Galore_Images/3D_modding/hierarchy_breaker_beta_tn.png]
|}


(Automatic rigging.) Maybe null objects could stand for the centers of body parts. Then one click and the real centers gets positioned. The [[User:Paradox-01/for_WIP_pages#Mod_Tool:_putting_a_character_together_while_preserving_body_part_positions|rotations are known]] and the names would lead to the correct hierarchy.
The original file can be found at:
logmessage XSIUtils.ResolvePath("$XSI_HOME/") & "Application\DSScripts\Model.vbs"
' C:\Softimage\Softimage_Mod_Tool_7.5\Application\DSScripts\'''Model.vbs'''
A backup of the original file can be found here: '''<nowiki>https://dl.dropboxusercontent.com/u/139715/OniGalore/ModToolScript/Model.vbs</nowiki> (dead link)'''


In order to make edits there is also a need of destroying the hierarchy again while preserving the rotation and position of the meshes.
There are two issues that can be fixed by modifying this file.
* import of xml files created by onisplit
* import of dae and xml files with relative path from a html page


Relative file pathes will be transformed to absolute pathes whereby an unwanted "file:///" is added.


code pieces
A solution to is to transform the path again.


if instr(in_Filename,"file:///") = 1 then
in_Filename = replace(in_Filename, "file:///", "")
end if


hierarchy breaker
Following function is always triggered, so we will modify it.
* [https://dl.dropbox.com/u/139715/OniGalore/ModToolScript/hierarchy_breaker_beta.txt hierarchy_breaker_beta.txt] (works only with strict correct names)
sub ImportDotXSIProc( in_Filename, in_Parent )
<font style="color:#DD0000">if instr(in_Filename,"file:///") = 1 then
in_Filename = replace(in_Filename, "file:///", "")
end if
Set objFSO = CreateObject("Scripting.FileSystem<Object")
FileExt = objFSO.GetExtensionName(in_Filename)</font>
if application.license = "Avid 3D" then
SIImportDotXSIFile in_Filename, in_Parent
else
Set oFS = CreateObject("Scripting.FileSystemObject")
<font style="color:#DD0000">if oFS.FileExists(in_Filename) = True then
if FileExt = "xml" then
' is this an Oni xml file ?
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = "False"
xmlDoc.Load(in_Filename)
if xmlDoc.selectNodes("Oni").length > 0 then
logmessage "Oni xml file detected"
read_xml "OFGA", in_Filename
end if
exit sub
end if</font>


The lines in red has been added.


hierarchy builder
* [https://dl.dropbox.com/u/139715/OniGalore/ModToolScript/delete_keyframes.txt delete_keyframes.txt] (deletes keys, saves and reloads character)
* [...]




'''Keyframe affects hierarchy building'''
'''[37] dae export'''


situation: "cube" and "cube1" were created
set oProps = ActiveProject.ActiveScene.Root.Properties
if typename (oProps.find("ExportCrosswalkOptions")) = "Nothing" then
logmessage "Export settings not set"
CreateExportCrosswalkOptions , "ExportCrosswalkOptions"
else
logmessage "Export settings present"
end if
' sets the extension to dae
SetValue "ExportCrosswalkOptions.Format", 1
' set export path and file name
SetValue "ExportCrosswalkOptions.Filename", CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\export_test.dae"
' selection only
SetValue "ExportCrosswalkOptions.ExportSelectionOnly", True
' export
ExportCrosswalk "ExportCrosswalkOptions"


* case 1:
** apply 45° y rotation to cube
** make cube1 a child of cube
** cube1 will not inherit the 45°


* case 2:
'''[38] fbx export'''
** apply 45° y rotation to cube
** make rotation keyframe for cube1
** make cube1 a child of cube
** cube1 inherit the 45°


* case 3:
FBXExportLights (false)
** apply 45° y rotation to cube
FBXExportSelection (true)
** make rotation keyframe for cube1
' mark FBXExport and hit F1 to get more options
** remove that keyframe again
FBXExport (CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\export_test.fbx" )
** make cube1 a child of cube
** cube1 inherit the 45°


* case 4:
** apply 45° y rotation to cube
** make rotation keyframe for cube1
** remove that keyframe again
** save both cube to a dae file
** make new scene and load dae
** make cube1 a child of cube
** cube1 will not inherit the 45°


Case 1 might be a bug (case 4 is a variant of it) but it simplify the hierarchy creation.
'''[39] import an image clip only once'''
 
image_path =  "C:\Users\RRM\Desktop\white_512_512.tga"
Set FSO = CreateObject("Scripting.FileSystemObject")
image_clip = FSO.GetBaseName(image_path) & "_" & FSO.GetExtensionName(image_path)
logmessage image_clip
if not typename(ActiveProject.ActiveScene.ImageClips(image_clip)) = "Nothing" then
logmessage "found image clip"
else
logmessage "image clip not yet present, going to import ..."
SICreateImageClip image_path
  ' or as script object:
'set oImage = AddImageSource (image_path)
'set oImageClip = AddImageClip (oImage)
end if
 
 
'''[40] layers'''
 
[[Image:ModTool_layers.png|thumb|200px|right|how to access scene layers]]
 
To access scene layers switch from Main Control Panel (MCP) to Keying Panel/Layers (KP/L) and then click "Scene".
 
After the user became used to layers, they can help to organize work in a scene. This is especially interesting for some scripting tasks like getting TRGV/FURN data for xml files.
 
' get current layer
GetCurrentLayer CurrentLayer
logmessage CurrentLayer
 
 
' create a new layer named "FurnLayer" if it doesn't already exist
' make new layer the current layer
if typename(ActiveProject.ActiveScene.Layers("FurnLayer")) = "Nothing" then
SICreateLayer , "FurnLayer", FurnLayer
SetCurrentLayer FurnLayer
else
SetCurrentLayer "Layers.FurnLayer"
end if




While doing those test you can observe red letters next to the meshes in the Schematic window.
' get objects in FurnLayer and count objects
: A means the presence of keyframes. Removing the keyframe doesn't remove the A. Object must be saved and reloaded.
' exit sub if there are no objects
: D means that mesh center was changed by rotation or translation (center mode) or by clicking Transform > Freeze(...). D can be removed by clicking the normal Freeze button. Yea, whatever...
SelectMembers "Layers.FurnLayer"
: C can be seen next to camera objects, present when Camera_Interest is horizontal attached to it.
if selection.count = 0 then
MsgBox "No OFGA data found to export.", , "Export canceled"
exit sub
end if
 
' if there are Furn objects
for each obj in selection
' do something e.g. create xml
next
 
 
' '''[41] onisplit update'''
' this downloads and unzips the last attachment from the [http://mods.oni2.net/node/38 onisplit page]
output_dir = "F:\test\"
' get onisplit link ################################################
set xmlhttp = createobject ("msxml2.xmlhttp.3.0")
xmlhttp.open "get", "http://mods.oni2.net/node/38/index.html", false
xmlhttp.send
<nowiki>webtext = xmlhttp.responseText
webtext = replace(replace(webtext, vbcr,""),vblf,"")
webtext = split(webtext, "<table class=""sticky-enabled""> <thead><tr><th>Attachment</th>" )(1)
webtext = split(webtext, "</td> </tr></tbody></table>") (0)</nowiki>
link_start = instrrev(webtext, "http")
link_end = instrrev(webtext, ".zip"" type") + 4 ' + zip
' mid (text, begin, length)
link = mid(webtext, link_start, link_end - link_start)
logmessage "last link in attachment: " & link
dim xHttp: Set xHttp = createobject("Microsoft.XMLHTTP")
dim bStrm: Set bStrm = createobject("Adodb.Stream")
xHttp.Open "GET", link, False
xHttp.Send
' get file name ###################################################
hdr = xHttp.getResponseHeader("Content-Disposition")
hdr = replace (hdr, "attachment; filename=""", "")
hdr = replace (hdr, """", "")
logmessage hdr
' save file #######################################################
filename = output_dir & hdr
with bStrm
.type = 1 '//binary
.open
.write xHttp.responseBody
.savetofile filename, 2 '//overwrite
end with
' extract file ####################################################
UnzipFile filename, output_dir
Function UnzipFile(ZipFile, ExtractTo)
Set fso = CreateObject("Scripting.FileSystemObject")
If NOT fso.FolderExists(ExtractTo) Then
fso.CreateFolder(ExtractTo)
End If
set objShell = CreateObject("Shell.Application")
set FilesInZip=objShell.NameSpace(ZipFile).items
objShell.NameSpace(ExtractTo).CopyHere(FilesInZip)
Set fso = Nothing
Set objShell = Nothing
End Function
 
 
' '''[42] get vertex color'''
set oGeometry = selection(0).activeprimitive.geometry
set oTriangles = oGeometry.Triangles
for each oTriangle in oTriangles
    logmessage oTriangle.Name
    for each oVertex in oTriangle.Points
        set oColor = oVertex.Color
        logmessage vbTab & "RGBA(" & _
          oColor.red & "," & _
          oColor.green & "," & _
          oColor.blue & "," & _
          oColor.alpha & ")"
    next
next
 
 
' '''[43] get all used textures'''
DeleteAllUnusedMaterials
DeleteUnusedImageClips
'DeleteUnusedImageSources
for each i in Application.ActiveProject.ActiveScene.ExternalFiles
if i.filetype = "Pictures" then
logmessage i
end if
next
 
 
' ''' [44] get global point position'''
set oObj = selection(0)
set oTrans = oObj.Kinematics.Local.Transform  
set oPoint0 = oObj.ActivePrimitive.Geometry.Points(0)
set oPoint7 = oObj.ActivePrimitive.Geometry.Points(7)
set oPos0 = oPoint0.Position
set oPos7 = oPoint7.Position
' scaling must be frozen to 1 before we can calculate the size from local values
ResetTransform selection(0), siCtr, siScl, siXYZ
logmessage "local p0: "& oPos0.X & " " & oPos0.Y & " " & oPos0.Z
set oGlobalPos0 = XSIMath.MapObjectPositionToWorldSpace( oTrans, oPos0)
logmessage "global p0: "& oGlobalPos0.X & " " & oGlobalPos0.Y & " " & oGlobalPos0.Z
logmessage "local p7: "& oPos7.X & " " & oPos7.Y & " " & oPos7.Z
set oGlobalPos7 = XSIMath.MapObjectPositionToWorldSpace( oTrans, oPos7)
logmessage "global p7: "& oGlobalPos7.X & " " & oGlobalPos7.Y & " " & oGlobalPos7.Z
 
logmessage "size: " & oPos7.X - oPos0.X & " " & _
oPos7.Y - oPos0.Y & " " & _
oPos7.Z - oPos0.Z
' with a rotation of: -3,8792 16,4039 -13,5017
' INFO : local p0: -4 -4 -4
' INFO : local p7: 4 4 4
' INFO : global p0: -5,74764582364017 -3,00250371537919 -2,43916767056426 ' TRGV start point
' INFO : global p7: 5,74764582364017 3,00250371537919 2,43916767056426
' INFO : size: 8 8 8
 
 
===Interactive Creative Environment (ICE)===
* [[wikipedia:Autodesk_Softimage#ICE_Interactive_Creative_Environment|ICE]]
 
'''tutorials:'''
* https://www.youtube.com/watch?v=ioMQ2rBVO4g
* http://dot3d.blogspot.com/2009/10/softimage-ice-tree-building-step-by.html
* [https://www.si-community.com/community/viewtopic.php?f=41&t=1707 an ICE tutorial thread]
* [https://download.autodesk.com/global/docs/softimage2013/en_us/userguide/index.html?url=files/ICE_trees_DebuggingICETrees.htm,topicNumber=d30e269791 ICE trees Debugging]
* <nowiki>https://support.solidangle.com/display/SItoAUG/ICE</nowiki> (dead link)
 
==Wanted knowledge==
* How to set up particles in Mod Tool? We still need an Oni particle editor!
* How to rig models and then extract the animation data?
* How to make complex new UV maps?


[[Category:Windows-only modding tools]]
[[Category:Modding tutorials]][[Category:Outdated modding tools]][[Category:Windows-only modding tools]]

Latest revision as of 16:20, 28 September 2023

Autodesk's Mod Tool used to be the main choice for modders when working on level and character models (at least in Windows, since it's Windows-only). It was a free and accessible program, but has long since been discontinued. Nowadays, modders are encouraged to use Blender instead.

sub pages
Mod_Tool/Scripting
Mod_Tool/Rigging
Mod_Tool/OniTools_addon
Mod_Tool/Oni_level_rebuilder

Installation

Full name: "Autodesk Softimage Mod Tool". Usually we just call it "Mod Tool" or "XSI", the old name of the program.

Download

  • Get it from Mod DB.
  • It's no longer possible to download Softimage from Autodesk because the software was discontinued by Autodesk in favor of their major software packages Maya and 3ds Max.

Newer Windows installations usually require .NET 2.0 to be installed before the XSI installer can fully run.

Downloading and installing .Net 2.0 manually from the internet might not work.
Therefore use the Windows search and look for "features". (Enable/disable Windows features.)
From the Windows feature page install ".NET framework 3.5 (includes .NET 2.0 and 3.0)".

There are various ways to extend Mod Tool's range of functions: scripts (.vbs, .js), toolbars (.xsitb) and addons (.xsiaddon). They can be created on one's own and also shared with other users.

Extensions

links


how to bind scripts to buttons (embedded code or .vbs / .js)

  • You can enable/disable the Main Shelf over "View" > "Optional Panels" > "Main Shelf". Then click the "Custom" tab.
  • A) Right-click the free gray space, click on "Customize Toolbar...". Select "Toolbar Widgets" > "Script Button".
  • Enter your code and make sure you selected the correct Scripting Language. Click okay when you are done.
  • B) You can also drag'n'drop your script file directly onto the free gray space.
  • A new window pops up, check the settings and click okay when done.
  • Right-click the Main Shelf and use the "Save" option. ("Save As" let you save the Main Shelf as toolbar file.)


how to install toolbars (.xsitb)

  • creation: goto "View" > "New custom toolbar"
  • Now you can add buttons like in Main Shelf. Remember to save your changes. (Right-click, "Save As".)
  • installation: Drag'n'drop the xsitb file onto the viewport (it's simply the window where you can see 3D objects).
  • access: goto "View" > "Toolbars"
  • deletion: goto "View" > "Manage..." Check a toolbar and click Delete button.
  • The file will remain with a new file suffix ".bak" You can restore this backup if you remove the ".bak" from the name.


how to install add-ons (.xsiaddon)

  • A) drag'n'drop the file into the so-called viewport (it's simply the window where you can see 3D objects), then restart Mod Tool
  • B) if drag and drop doesn't work, goto "File" > "Add-On" > "Install"
  • Then click on the "..." button to search for the file. When you found it, click the "Install" button.


building add-ons (http://softimage.wiki.softimage.com/sdkdocs/cus_addons_WalkthroughBuildinganAddon.htm, dead link)

  • Building an add-on file needs more effort than the other 'extensions' but for the end user it's best because it can hold all other files: toolbars, plugins (scripts), etc.
    • The user can install a newer version of the addon by repeating the installation with the new file: it's unnecessary to remove the old version.
  • File > Add-On > Package... doesn't work with ModTool "Add-Ons cannot be created with Softimage Demo Version."
  • Images and any other files can be put into any folder of the add-on.
    • Let's say you have an addon called "my_stuff", a subfolder "images" and an image called "test.png". The image can be accessed via:
XSIUtils.ResolvePath("$XSI_USERHOME/") & "Addons\my_stuff\images\test.png"
  • The problem with embedded code: commands like CreatePrim can call an property page (PPG).
    • Those popups can be disabled. Search for "disabling PPG popups" on this page.
  • Putting scripts simply into folders doesn't work, they must be "plugins", the file extension can be the same e.g. "vbs".
    • A script function can run on another computer if it is found as command, and plugin register new commands.
    • E.g. you can use those commands in your toolbar's script buttons.
  • Example of turning a function into a command:


function with arguments as it is

' this function can only be used inside the script where it was defined

function simple_math (a, b, operator)
	if operator = "+" then
 		simple_math = a + b
	elseif operator = "-" then
		simple_math = a - b
	elseif operator = "/" then
		simple_math = a / b
	elseif operator = "x" then
		simple_math = a * b
	else
		logmessage "The used operator is not allowed. Choose one of the following:" & vbCrlf & "+ - / x"
	end if
end function

' example of usage
result = simple_math(5, 3, "+")
logmessage result


the same function as command

' the command simple_math can now be used in any script

function XSILoadPlugin( in_reg )
	in_reg.Author = "your_name"
	in_reg.Name = "simple_mathPlugin"
	in_reg.Email = ""
	in_reg.URL = ""
	in_reg.Major = 1
	in_reg.Minor = 0

	in_reg.RegisterCommand "simple_math","simple_math"
	'RegistrationInsertionPoint - do not remove this line

	XSILoadPlugin = true
end function

function XSIUnloadPlugin( in_reg )
	dim strPluginName
	strPluginName = in_reg.Name
	Application.LogMessage strPluginName & " has been unloaded.",siVerbose
	XSIUnloadPlugin = true
end function

function simple_math_Init( in_ctxt )
	dim oCmd
	set oCmd = in_ctxt.Source
	oCmd.Description = ""
	oCmd.ReturnValue = true

	dim oArgs
	set oArgs = oCmd.Arguments
	oArgs.Add "a",siArgumentInput,"0"
	oArgs.Add "b",siArgumentInput,"0"
	oArgs.Add "operator",siArgumentInput,"0"
	simple_math_Init = true
end function

function simple_math_Execute( a, b, operator )
	' convert to double
	a = cdbl(a)
	b = cdbl(b)
	
	if operator = "+" then
		simple_math_Execute = a + b
	elseif operator = "-" then
		simple_math_Execute = a - b
	elseif operator = "/" then
		simple_math_Execute = a / b
	elseif operator = "x" then
		simple_math_Execute = a * b
	else
		logmessage "The used operator is not allowed. Choose one of the following:" & vbCrlf & "+ - / x"
	end if
end function

Selected wisdom

We've also a tutorial thread on OCF.

Hotkey list can be found here.


Visibility

  • show/hide grid: [G]
  • display polygon normals: click the eye symbol, select "Polygon Normals" (now you know the polygons up and down)
  • display triangle count: click the eye symbole, select "Selection Info"


Camera navigation

  • reset view: [R]
  • zoom camera: [Scrolling]
  • move camera: [S] + [LClick] + [MoveMouse]
  • rotate camera: [S] + [RClick] + [MoveMouse]
  • pan camera: [S] + [MClick] + [MoveMouse]
  • move camera mode: [Z]
  • rotate camera mode: [O]
  • pan camera mode: [P]
  • use camera mode move/rotate/pan with: [LClick] + [MoveMouse]


Mesh

  • scale mode: [X]
  • rotate mode: [C]
  • translate mode [V]
  • manipulate tool: [B] (a gray box appears with gray balls at the corners)
    • drag inside the object to move it
    • drag an edge to rotate it
    • drag a ball to scale it
  • object selection mode: [Space]
  • extracting a polygon from an object: select polygon, right-click, "Extract Polygons (Delete)"
  • copying an polygon from an object: select polygon, right-click, "Extract Polygons (Keep)"
  • merging two objects: select object A, then goto Model > Modify > Poly. Mesh > Boolean > Union, select object B
(this makes a copy of object B and attaches it to A, the merged objects (A) must be freezed before the original object B can be removed)
  • filling a hole: select all edges surrounding the hole and choose one of the following methods
    • A) goto Model > Modify > Poly. Mesh > Weld Boundary Points/Edges
    • B) goto Model > Modify > Poly. Mesh > Bridge Boundary Points/Edges (if blue lines appear try to disable the checkbox "Angle > 90")
  • merging two objects at blue lines: merge the objects at first, then proceed with the point above "filling a hole"
  • merging two objects with UVs: Create > Poly. Mesh > Merge
    • extracted Oni characters have their materials and hence textures directly grouped under the mesh (see Explorer)
    • when adding (merging) a new part to the existing mesh, the materials/textures will be grouped under (Explorer again) mesh > Polygon Mesh > Clusters > ...
    • Samer reported that saving the file via fbx solves a problem when trying to convert TRBS
    • one would need to move the content by hand in the explorer to bypass the fbx
  • hiding some objects/polygons: select object/polygon and hit [H], use [Control] + [H] to unhide all
  • mirroring an object: select object, Modify > Poly. Mesh > Symmetrize Polygons
  • working with symmetry mode (look below at "Low poly modeling" section for other possibilities with symmetry)
    • select object, Property > Symmetry Map (YZ/XZ/XY) (press [W] to preview symmetry plane)
    • click on Sym buttom (in Transform area) to enable/disable symmetry mode
    • changing the Symmetry plane: Explorer [8] > unfold object > Polygon Mesh > Cluster > delete SymmetryMapCls; then add a new symmetry plane


Low poly modeling

  • select edge loop: while being in selection mode Edge, press [Alt] + [MClick]
  • modify point/edge/polygon: [M]
    • press left mouse button and hold it, move mouse to translate point/edge/polygon freely
if axes symbol is active you can left-click a component and the translate axes pop up
if magnet symbol is active the translation will be limited by the surrounded components
if point symbol is active then only points can be selected, moving one point onto another will weld them
  • By the way, combining edge loop with component selection [M] and active magnet gives an interesting effect: a line of edges will mimic the shape of their neighbor edges as closer the selected edges comes to the neighbors.
  • getting images into Mod Tool that serve as modeling reference:
    • click where you can set the view mode (e.g. to "Wireframe"), select "Rotoscope"
    • in the appearing window at "Image Placement" choose "Fixed" so that the image will be zoomed when you zoom on the object
    • choose an image by clicking the button "New"


symmetry in modeling:

You could make A) only one half of an object or B) selected polygons and then mirror and merge the parts.

  • A) select object, [Alt] + [RClick] object, Symmetrize Polygons
  • B) select polygons, [RClick] one of them, Symmetrize Polygons


Or you start with a half object and create a mirrored clone. You can then work on the original mesh. (In Schematics the cloned mesh will have a red "Cl" and a trapezoid shape as symbol.)

  • select object then goto Edit > Duplicate/Instantiate > Clone Single
  • scale X or one of the other axes to -1
  • make any modification on the original mesh, the clone will adept them
  • eventually merge cloned and original mesh, freeze them to make changes final


Exchange meshes in hierarchies

Let's say you loaded an Oni character with his 19 body parts into the scene, something is wrong and you want to fix it.

To destroy the hierarchy you must be sure the model is not animated. If there are keyframes the model will be one big mess after breaking the hierarchical links.

So, save the model with the settings "Selection Only [X]" and "Animation [ ]". Then reload the model.

Next, disable the red "Auto" button under "Animation" (if enabled). Keyframes affects also the creation of hierarchies, that's why we don't want new keyframes.

Now you can safely exchange, move and rotate meshes and their centers, and eventually rebuild the hierarchy.


Material and texture

how to apply a new main texture
how to apply a new polygon cluster texture
  • objects use the scene material by default, objects need their own material if they should have individual textures
  • selecting a material and surface: Model > Material > Phong (simply close the windows that pops up)
  • connecting the texture with the material:
    • [7] to open Render Tree
    • in first column: "Texture"
    • in second column: drag'n'drop "Image" into the free space
    • click and hold the red point of "Image", then move it to "Phong" and release the mouse click
    • choose "diffuse" as illumination mode (for instance "ambient" won't work - the texture would be visible in Mod Tool but Onisplit can't use it)
  • now "Image" can be double-clicked (the Texture Editor will pop up), in the section "Image" click on "New" to choose an image
  • to change textures don't drag and drop textures directly one meshes, this creates textures layers which are ignored by OniSplit


Projection and UV

getting started

  • in section "Texture Projection" click on "New", choose a projection similar to the mesh shape (planar / cylindrical / cubic / spherical)
  • select the object
  • Texture editor: [Alt]+[7] (open it while being in selection mode "Object" or "Polygon", otherwise the UVs aren't shown)

modify single/all UVs

  • rotate 90°: [R]
  • rotate: [C]
  • scale: [X]
  • scale height only: [X], then [Shift] + [MClick] + [MoveMouse]
  • scale length only: [X], then [Shift] + [RClick] + [MoveMouse]
  • move: [V]
  • tearing single UV parts: [Control] + [T], then move [V]
  • heal (re-connect) selected UV parts: click on the plus symbol (the parts should be very near to each other, best if the points are on same spot)
  • snap function for move tool: Snap > Enable Snapping; check "Points" (if not already active)
  • relax (smooth warped UVs): [Control] + [R] (usually pressing several times that combination)
  • a new projection can also be applied to currently selected UV parts
  • freeze object to bake projections (green lines in the 3D view will disappear)
  • getting a picture of the UV: apply first a black texture then enter the Texture Editor [Alt] + [7], Edit > Stamp UV Mesh [Shift] + [S], save the texture

Things to test:


Rendering

Rendering doesn't work well on my PCs.--paradox-01 (talk) 01:09, 9 March 2016 (CET)

Especially PNG, it works one time. But as soon as I import another dae the next render will fail.


So, for creating a object library we might use blender. Nice thing is, it can also render in the background when called from CMD. This means you could keep working in XSI and render images in blender at the same time.


example of a batch file:

cd C:\Program Files\Blender Foundation\Blender
blender -b --python C:\Users\Paradox-01\Desktop\blender-out\pythonScript.py


example of a render script:

import bpy

# delete blender default cube object
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_by_type(type='MESH')
bpy.ops.object.delete(use_global=False)

# load new object
bpy.ops.wm.collada_import(filepath = "C:/Oni/r.dae")

# render settings
bpy.data.scenes['Scene'].render.resolution_x = 900
bpy.data.scenes['Scene'].render.resolution_y = 900
# default resolution percentage seems to be 50 
bpy.data.scenes['Scene'].render.resolution_percentage = 100
bpy.data.scenes['Scene'].render.use_antialiasing = True
# 5 | 8 | 11 | 16
bpy.data.scenes['Scene'].render.antialiasing_samples = "8"

#TGA IRIS JPEG MOVIE IRIZ RAWTGA
#AVIRAW AVIJPEG PNG BMP FRAMESERVER
#no gif ? could be created by more code, maybe merging single frames of jpgs
bpy.data.scenes['Scene'].render.image_settings.file_format = 'JPEG'
bpy.data.scenes['Scene'].render.image_settings.quality = 100

# file suffix is overwritten by file_formate
#bpy.data.scenes['Scene'].render.filepath = 'C:/Oni/renders/test.jpg'
bpy.data.scenes['Scene'].render.filepath = 'C:/Oni/renders/test'

# start render
bpy.ops.render.render( write_still=True )


Animating

an animation that got scaled down from 116 to 58 frames
  • preparing ModTool to save animations Oni can use: File > Preferences... > Preferences > Tools > Output Format
    • Frame Step: 1
    • Frame Format: Custom framerate
    • Frame Rate: 60
  • for real-time playback click on "Playback" option button and then "Real-Time Playback"
  • opening the Animation Editor : [0]
  • opening the DopeSheet: from any other Animation Editor, Editor > DopeSheet
  • making an animation shorter or longer: in DopeSheet click Region button (arrow with rectangle), click and hold to select keyframes, at selection edge a) [shift] plus left-click and move mouse or b) middle-click and move mouse


Issues when saving and sharing animation files (*.dae, *.exp)

That what you currently see in Mod Tool and that what you get when saving data can be different.

1) *.dae files might save data differently than expected.

Rotation flips might appear.

2) *.exp and *.dae save data differently.

  • .exp files store the frames as they are.
  • .dae file store their actions (rotations/translation/...) in seconds and eventually depend on what framerate a Modder uses.


Following scenario: a modder wants to share an animation as *.exp and another modder wants to use that animation.

Modder A uses 30 fps in his settings and exports an *.exp that is 58 frame long.

Modder B uses 60 fps in his setting and imports the *.exp, to his surprise the animation is 116 frames long. What now?

If Modder B saves the *.exp under a new name would not help, the frames will be still the same.

Instead Modder B could scale the animation. The way to do so is described in the Animating section, "making an animation shorter or longer".

Modder B scales the animation and saves it as dae.

Now he wants to see if it worked. He opens a new scene [Strg]+[N] and loads the dae.


Summary of issue-holding aspects

  • Frames Per Second (FPS)

When you share *.dae files with other Modders be sure that the output formate is 60 fps. Different framerates among modders can cause confusion.

Dae file store their actions (rotation/translation/...) in seconds.

An example:

<float_array count="10" id="pelvis_rotation_x_ANGLE-anim-input-array">
    0.000000 0.166833 0.333667 0.500500 0.600600 0.934267 1.267933 1.601600 1.768433 1.935267
</float_array>

action at [s] * framerate [f/s] = frame [f]

In this example the last rotation occurs at 1.935267s.

Modder A uses 30 fps, his last frame is 58.
Modder B uses 60 fps, his last frame is 116.


  • Euler rotations

you will get BEZIER (cubic) interpolation instead of LINEAR if you use

"Convert Quarternion Rotation to Euler"
"Spline Interpolation" in the animation (fcurve) editor

Those smooth the rotations.

[...]


  • Quaternion rotations

Don't use this.

[...]


  • Make Rotation Keys Continuous

[...]


Animation mixer

This could help with creating cutscenes and complex animations (e.g. run cycles for FILM files).

Open the animation mixer with [Alt]+[0].

Further information over HERE.

Here are a few videos:


Sounds

Within the animation mixer also sounds can be added.

Further information over HERE.

This could be used to synchronize sounds effect with physical actions in the scene.


Scripting

  • open the Script Editor: [Alt] + [4]
  • run the current code in the Script Editor window: [F5]
  • clear the log: Edit > Clear History Log
  • Actions from button embedded code will be logged.
  • Actions from code files that are linked in a button won't be logged. (This results in a performance boost.)
  • Logged stuff will be rewritten if you change the script language. (File > Preferences...)
  • You can also change the language by right-click the white script box and click on "Set to JScript" or "Set to VBScript".
  • Python can be added as script language if you install it on your PC.
  • Right-clicking the white script box gives you also access to a few code piece, e.g. "Syntax Help" > "If..Else" or "Catch Error".
  • Mark code you want to disable ("Comment Out") or enable ("Comment Remove").
  • You can save your code to a file via "File" > "Save As..." or "Save Selection"


Links


Notes about polygon extraction

  • a grid of 9 polygons (ID 0 to 8)
  • you extract the middle polygon (ID 4)
  • grid's polygon of ID 8 will change to ID 4
  • if you now extract 5th, the 7th gets the ID
  • now the ID order is: 0, 1, 2, 3, 6, 5, 4
  • this means that an automatic extraction of several polygons requires two changes in the code
  • 1) the ID array of selected polygons must be sorted
  • 2) the extraction must start with the last ID to avoid ID shift during the process (see code pieces)


Some basics of VBScript

  • In VBS you declare variables only as a variant e.g. "dim PolygonCount". Mod Tool decides what type it becomes when it uses the variable the first time.
  • You can put "option explicit" at the start of your script. Then you will be forced to declare all variables with "dim". That looks quite unnecessary but help to find mistakes for example if you mistyped a variable somewhere in a long script.
  • The commands are not case-sensitive, e.g. you can write "LogMessage" or "logmessage".
  • Vbs functions can be found HERE.
' while it is possible to use + in strings,
' you should actually use & only for strings
' and + only for numbers

logmessage "How about ... " + "a riddle?"
logmessage "Where can you find following phrase in Oni? " & "The day is mine !!"
logmessage "Did you know that Bungie likes to hide sevens? The digits of the year 2032 add up to " & cstr(2 + 0 + 3 + 2) & "."

' INFO : How about ... a riddle?
' INFO : Where can you find following phrase in Oni? The day is mine !!
' INFO : Did you know that Bungie likes to hide sevens? The digits of the year 2032 add up to 7.


More tips

  • You can replace each "logmessage" with a variable. In that case don't forget the = sign.
  • Selection(0) means that from all selected objects the first one is taken.
  • Use a loop to get all objects.
for each n in selection
	logmessage n
next
  • In order to shorten the code you might want to set script objects.
The command to create a standard cube is CreatePrim "Cube", "MeshSurface"
If you use set name = the cube or other object will be available under that name.
Then you can use any valid method or property with that name.
Example:
set c = CreatePrim ("Cube", "MeshSurface")

logmessage selection(0).name
logmessage selection(0).length.value
logmessage c.name
logmessage c.length.value

' INFO : cube
' INFO : 8
' INFO : cube
' INFO : 8


Some ModTool commands in vbs language that might be interesting for Oni related stuff

LogMessage [string | var | object] A command to log information. It requires a string or a variable. Example:
LogMessage "The object's name is: " & selection(0).Name
logmessage selection.count Logs the number of selected objects.
logmessage selection(0).Name Logs the object name.
logmessage selection(0).Materials(0).Name Logs the material name.
logmessage selection(0).Materials(0).Library.name Logs the material library name.
logmessage selection(0).Materials(0).shaders(0).name Logs the material shader (e.g. phong).
logmessage selection(0).Materials(0).CurrentImageClip.source.filename.value Logs absolute path of the texture. Output example:
C:\Users\RRM\Desktop\TV_tex.png
logmessage selection(0).Materials(0).CurrentImageClip.source.Parameters("XRes").Value
logmessage selection(0).Material.CurrentImageClip.source.Parameters("YRes").Value
Logs the horizontal (X) and vertical (Y) pixel length of the texture. Output example:
512
logmessage selection(0).sclx.value
logmessage selection(0).scly.value
logmessage selection(0).sclz.value
Logs object's scaling (X, Y, Z).
logmessage selection(0).rotx.value
logmessage selection(0).roty.value
logmessage selection(0).rotz.value
Logs object's rotation (X, Y, Z).
logmessage selection(0).posx.value
logmessage selection(0).posy.value
logmessage selection(0).posz.value
Logs object's position (X, Y, Z).
logmessage selection(0).rotorder.value Logs object's rotation order. Oni characters have ZYX as rotation order.
0 = XYZ
1 = XZY
2 = YXZ
3 = YZX
4 = ZXY
5 = ZYX
SelectObj [string | var] select one or more objects. Comma serves as separator. Example:
SelectObj "grid,grid1"
ToggleSelection [string | var] Adds one or more objects from current selection. If the objects are already selected then they become subtracted from the selection. Example:
ToggleSelection "grid2,grid3"
SelectAllUsingFilter [SelFilter], [CheckComponentVisibility], [AffectSelectionList], [CheckObjectSelectability] Selects everything that matches the filter and other options. Example:
SelectAllUsingFilter "object", siCheckComponentVisibility
selects all roots, lights, cameras, and geometry (meshes)
SelectAllUsingFilter "geometry", siCheckComponentVisibility
selects all geometry (meshes)
DeselectAll deselects everything
DeleteObj [string | var] Deletes one or more objects. Comma used as separator. Example:
DeleteObj "grid"
DeleteObj "grid,grid1"
FreezeObj Makes all changes final. But saving those changes is still necessary. (Click on key symbol so it gets red.)
Translate [InputObjs], [X], [Y], [Z], [Delta], [RefMode], [Center], [AxesFilter], [Snap], [SnapReference], [SnapFilter], [SplitLocalComponents], [PropTagOnly], [Pivot], [PivotX], [PivotY], [PivotZ], [ConstructionMode], [SlideComponents] see link
Rotate [InputObjs], [X], [Y], [Z], [Delta], [RefMode], [Center], [AxesFilter], [Reference], [SplitLocalComponents], [PropTagOnly], [Pivot], [PivotX], [PivotY], [PivotZ], [ConstructionMode], [SlideComponents] see link


Code pieces (VB Script)

Remember that you can use the search function of your web browser.

If you see absolute paths adapt them so that the code works on your system too.

(Here's another page for math related code pieces.)

[1] creating and extending an array [2] check selection mode [3] getting the IDs of selected polygons plus sorting them
[4] converting euler rotations (in degrees) to quaternions [5] converting quaternions to euler rotations (in degrees) [6] get and set values of the playcontrol (timeline)
[7] get keyframes [8] message box [9] input box
[10] getting the desktop path [11] selecting a folder [12] selecting a file of a specific type
[13] reading out environment variables [14] check if file exist [15] check if folder exist + create folder
[16] write xml file [17] read xml file [18] read xml file (attribute/content-based)
[19] create txt file + write lines [20] read txt file [21] check onisplit version
[22] call CMD, e.g. to use onisplit [23] building forms in ModTool [24] UserDataBlob
[25] getting the position of points (with selection mode point) [26] getting the position of points (with selection mode object) [27] getting and setting the position of points (without selection)
[28] getting the rotation and position of selected objects [29] getting the rotation and position of not selected objects [30] decrypting merged integer flags
[31] disabling PPG popups [32] disabling logmessages [33] getting bounding box values
[34] open an explorer window [35] working with hierarchies [36] drag and drop (DnD) support for specific oni files
[37] dae export [38] fbx export [39] import an image clip only once
[40] layers [41] onisplit update [42] get vertex color
[43] get all used textures [44] get global point position


' [1] creating and extending an array


' creating an array
' () sets the number of array items
redim nums (3)
for i = 0 to 3
	nums(i) = (i)
next

logmessage "output all items"
for each n in nums
	logmessage n
next
logmessage "first array item holds: " & lbound(nums)
logmessage "last array item holds: " & ubound(nums)
logmessage "-------------------------------------"


' extending an array
' use "preserve" to keep the old content
' find next higher value
plus_one = ubound(nums) + 1
redim preserve nums (plus_one)
nums(plus_one) = 4

for each n in nums
	logmessage n
next
logmessage "first array item holds: " & lbound(nums)
logmessage "last array item holds: " & ubound(nums)


' INFO : output all items
' INFO : 0
' INFO : 1
' INFO : 2
' INFO : 3
' INFO : first array item holds: 0
' INFO : last array item holds: 3
' INFO : -------------------------------------
' INFO : 0
' INFO : 1
' INFO : 2
' INFO : 3
' INFO : 4
' INFO : first array item holds: 0
' INFO : last array item holds: 4


' [2] check selection mode 

checkfilter
'use sub to make use of the exit command

sub checkfilter
	Select Case Selection.Filter.Name
	'caution: case-sensitive

	Case "object"
		logmessage "object mode"
	Case "Edge"
		logmessage "edge mode"
	Case "Vertex"
		logmessage "point mode"
	Case "Polygon"
		logmessage "polygon mode"
	Case Else
		logmessage "unknown mode"
		exit sub
	End Select
end sub


' [3] getting the IDs of selected polygons plus sorting them

poly_count = Selection(0).SubComponent.ComponentCollection.count
logmessage "poly_count: " & poly_count
redim selected (poly_count)
logmessage "Show ID as it is."
for i=0 to poly_count - 1
	' build ID array
	selected(i) = Selection(0).SubComponent.ComponentCollection(i).index
	logmessage selected(i)
next

' change sort order by replacing ">" with "<"
For i = 0 To poly_count - 1
	For j = 0 To poly_count - 1
		If selected(i) > selected(j) Then
			tmp = selected(i)
			selected(i) = selected(j)
			selected(j) = tmp
		End If
	Next
Next
logmessage "Show sorted ID."

for i=0 to poly_count - 1
	logmessage selected(i)
next


' [4] converting euler rotations (in degrees) to quaternions

dim x, y, z, dRotation, qRotation
x = 90
y = 0
z = 0

set dRotation = XSIMath.CreateRotation(XSIMath.DegreesToRadians(x), XSIMath.DegreesToRadians(y), XSIMath.DegreesToRadians(z)) 
set qRotation = XSIMath.CreateQuaternion() 

	dRotation.GetQuaternion (qRotation) 
	LogMessage qRotation.W
	LogMessage qRotation.X
	LogMessage qRotation.Y
	LogMessage qRotation.Z
	' INFO : 0,707106781186548
	' INFO : 0,707106781186547
	' INFO : 0
	' INFO : 0


' [5] converting quaternions to euler rotations (in degrees)

dim qW, qX, qY, qZ, qRotation, x, y, z

	qW = 0.707106781186548
	qX = 0.707106781186547
	qY = 0
	qZ = 0

set qRotation = XSIMath.CreateQuaternion (qW, qX , qY, qZ)

	qRotation.GetXYZAngleValues x, y, z
	logmessage XSIMath.RadiansToDegrees(x)
	logmessage XSIMath.RadiansToDegrees(y)
	logmessage XSIMath.RadiansToDegrees(z)
	' INFO : 89,9999999999999
	' INFO : 0
	' INFO : 0


' [6] get and set values of the playcontrol (timeline)

' timeline variables (tl)
dim tlStart, tlEnd, tlCurrent

' get values
tlStart = GetValue ("PlayControl.In")
tlEnd = GetValue ("PlayControl.Out")
tlCurrent = GetValue ("PlayControl.Current")

' set values
SetValue ("PlayControl.In"), 7
SetValue ("PlayControl.Out"), 70
SetValue ("PlayControl.Current"), 14


' [7] get keyframes

' keyframe counting code like "selection(0).rotx.Source.Keys.count" will produce an error if no keys exist
' that's why we need to catch possible errors for each counting

on error resume next
	logmessage "--------------------------------------------------"
	logmessage "X rotation keys: " & selection(0).rotx.Source.Keys.count
	for each k in selection(0).rotx.Source.Keys
		logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
	next
if err <> 0 then
	logmessage "no X rotation keys"
end if
on error goto 0

on error resume next
	logmessage "--------------------------------------------------"
	logmessage "Y rotation keys: " & selection(0).roty.Source.Keys.count
	for each k in selection(0).roty.Source.Keys
		logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
	next
if err <> 0 then
	logmessage "no Y rotation keys"
end if
on error goto 0

on error resume next
	logmessage "--------------------------------------------------"
	logmessage "Z rotation keys: " & selection(0).rotz.Source.Keys.count
	for each k in selection(0).rotz.Source.Keys
		logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
	next
if err <> 0 then
	logmessage "no Z rotation keys"
end if
on error goto 0

on error resume next
	logmessage "--------------------------------------------------"
	logmessage "X position keys: " & selection(0).posx.Source.Keys.count
	for each k in selection(0).posx.Source.Keys
		logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
	next
if err <> 0 then
	logmessage "no X position keys"
end if
on error goto 0

on error resume next
	logmessage "--------------------------------------------------"
	logmessage "Y position keys: " & selection(0).posy.Source.Keys.count
	for each k in selection(0).posy.Source.Keys
		logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
	next
if err <> 0 then
	logmessage "no Y position keys"
end if
on error goto 0

on error resume next
	logmessage "--------------------------------------------------"
	logmessage "Z position keys: " & selection(0).posz.Source.Keys.count
	for each k in selection(0).posz.Source.Keys
		logmessage "index: " & k.index & " // time: " & k.time & " // value: " & k.value
	next
if err <> 0 then
	logmessage "no Z position keys"
end if
on error goto 0


' output example (0 rot keys, 2 pos keys):

' INFO : --------------------------------------------------
' INFO : no X rotation keys
' INFO : --------------------------------------------------
' INFO : no Y rotation keys
' INFO : --------------------------------------------------
' INFO : no Z rotation keys
' INFO : --------------------------------------------------
' INFO : X position keys: 2
' INFO : index: 0 // time: 2 // value: 5,14534318031942
' INFO : index: 1 // time: 6 // value: 8,2411504340802
' INFO : --------------------------------------------------
' INFO : Y position keys: 2
' INFO : index: 0 // time: 2 // value: 0,365325291829147
' INFO : index: 1 // time: 6 // value: 1,11923927115289
' INFO : --------------------------------------------------
' INFO : Z position keys: 2
' INFO : index: 0 // time: 2 // value: 1,96103417177471
' INFO : index: 1 // time: 6 // value: 1,88564277384233


' [8] message box

msgbox "message", , "title"


' [9] input box

logmessage inputbox ("message", "title" , "pre-entered content")


' [10] getting the desktop path

' this can be useful for default locations like when selecting a folder
DesktopPath = CreateObject("WScript.Shell").SpecialFolders("Desktop")
logmessage DesktopPath


' [11] selecting a folder

' the default path is in this case my desktop
' to make it work on other systems, you would need the code of "getting the desktop path" section and replace my path with the DesktopPath
logmessage XSIUIToolkit.PickFolder("C:\Users\RMM\Desktop\", "title" )


' [12] selecting a file of a specific type

set oFileBrowser = XSIUIToolkit.FileBrowser
oFileBrowser.DialogTitle = "Select an image file (png/tga/jpg)" 
' (default folder)
oFileBrowser.InitialDirectory = "c:\"
oFileBrowser.Filter = "JPEG (*.jpg)|*.jpg|PNG (*.png)|*.png| Targa (*.tga)|*.tga||"
oFileBrowser.ShowOpen
If oFileBrowser.FilePathName <> "" Then
	logmessage "User selected " & oFileBrowser.FilePathName
Else
	logmessage "User pressed cancel"
End If


' [13] reading out environment variables

' some infos about env vars: (1), (2), (3)
' those variables are stored inside the setenv.bat, two disadvantages:
' adding or editing those vars appears to not work in vbs or I just did it wrong
' anyway, new vars can only be read out after app restart
' therefore let's concentrate on reading out existing ones and then how to create our own via txt files (example: https://dl.dropbox.com/u/139715/OniGalore/ModToolScript/Oni_env_vars.txt Oni_env_vars.txt (dead link))
' code for reading out:
logmessage XSIUtils.ResolvePath("$SI_HOME/")


' [14] check if file exist

Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists ("C:\folder\file.txt") then
	logmessage "File exists."
else
	logmessage "File doesn't exist."
end if


' [15] check if folder exist + create folder

dim strDirectory
strDirectory = "C:\test"

Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strDirectory) Then
   Set objFolder = objFSO.GetFolder(strDirectory)
   logmessage strDirectory & " already exists"
Else
   Set objFolder = objFSO.CreateFolder(strDirectory)
   logmessage "created folder " & strDirectory
End If

' ### or simply:
dir = "C:\test"
XSIUtils.EnsureFolderExists (dir)


' [16] write xml file

FolderName = CreateObject("WScript.Shell").SpecialFolders("Desktop")
FileName = "test"
FilePath = FolderName & "\OBAN" & FileName & ".xml"

Set oFS = CreateObject("Scripting.FileSystemObject")
Set objXMLFile = oFS.OpenTextFile(FilePath, 2, True, 0)

' quote sign in a string needs two quote signs
objXMLFile.WriteLine "<?xml version=""1.0"" encoding=""utf-8""?>"
objXMLFile.WriteLine "<Oni>"
objXMLFile.WriteLine "..."
objXMLFile.Close


' [17] read xml file

Set xmlDoc = CreateObject( "Microsoft.XMLDOM" )
xmlDoc.Async = "False"
path = "C:\Users\RRM\Oni\AE\AEInstaller\vanilla\level19_Final\BINACJBOWeapon.xml"
xmlDoc.Load( path )

Set colPosition = xmlDoc.selectNodes( "Oni/Objects/WEAP/Header/Position" )
Set colRotation = xmlDoc.selectNodes( "Oni/Objects/WEAP/Header/Rotation" )
Set colClass =    xmlDoc.selectNodes( "Oni/Objects/WEAP/OSD/Class" )

loop_count = xmlDoc.selectNodes( "Oni/Objects/WEAP").length

logmessage "found " & loop_count & " weapons:"
logmessage "================"
for i=0 to loop_count - 1

	'split string into pices as array, space is used as seperator by default
	'element 0 = X; element 1 = Y; element 2 = Z
	pos = split(colPosition.item(i).text)
	rot = split(colRotation.item(i).text)
	
	' Mod Tool wants comma instead of point for decimal seperator
	pos(0) = replace (pos(0), ".", ",")
	pos(1) = replace (pos(1), ".", ",")
	pos(2) = replace (pos(2), ".", ",")
	
	rot(0) = replace (rot(0), ".", ",")
	rot(1) = replace (rot(1), ".", ",")
	rot(2) = replace (rot(2), ".", ",")

	logmessage colClass.item(i).text
	logmessage pos(0) & " " & pos(1) & " " & pos(2)
	logmessage rot(0) & " " & rot(1) & " " & rot(2)
	logmessage "----------------"
next


' INFO : found 2 weapons:
' INFO : ================
' INFO : w5_sbg
' INFO : 23,16747 84,8193359 757,1958
' INFO : 0 0 0
' INFO : ----------------
' INFO : w4_psm
' INFO : 18,1105652 84,8193359 749,121
' INFO : 0 0 0
' INFO : ----------------


' [18] read xml file (attribute/content-based)

Set xmlDoc = CreateObject( "Microsoft.XMLDOM" )

' tells the program to wait until the file was loaded conpletely
xmlDoc.Async = "False"
xmlDoc.Load( "C:\Users\RRM\Oni\AE\AEInstaller\vanilla\level0_Final\BINAEINOimpact_effects.xml" )


' example 1 (we use this one)
' nodes only with a certain attribute and conent will be collected

' content-based search: node [child_node = 'content']
' attribute-based search: node [@attribute_name = 'attribute_value']

' if things get too long an underscore _ can be used to make a linebreak
set w1_tap = xmlDoc.selectNodes _
	( "Oni/ImpactEffects/Impact[@Name = 'w1_tap']/Material[@Name = 'Unbreak_Glass']/ImpactEffect [Component = 'Damage']" )


' example 2
' use "or" for a search of various material
'set w1_tap = xmlDoc.selectNodes _
'	( "Oni/ImpactEffects/Impact/Material[@Name = 'Default' or @Name = 'Character']/ImpactEffect" )


' example 3
' use (|) for a search of various content, e.g. <ImpactEffect><Modifier>Light plus <ImpactEffect><Modifier>Medium
'set w1_tap = xmlDoc.selectNodes _
'	( "Oni/ImpactEffects/Impact/Material/(ImpactEffect [Modifier = 'Light'] | ImpactEffect [Modifier = 'Medium'])" )



for each element in w1_tap
	logmessage "Impact: " & element.parentNode.parentNode.getAttribute("Name")
	logmessage "Material: " & element.parentNode.getAttribute("Name")
	
	' outputs "tag name: tag content"
	logmessage element.childNodes(0).nodename & ": " & element.childNodes(0).text
	logmessage element.childNodes(1).nodename & ": " & element.childNodes(1).text
	logmessage "-----------------------------------"
	
	'check for sounds
	if element.childNodes(2).childNodes.length = 0 then
		logmessage "sound not present"
	else
		logmessage "sound is present"
		logmessage "-----------------------------------"
		logmessage element.childNodes(2).childNodes(0).nodename & ": " & element.childNodes(2).childNodes(0).text
		logmessage element.childNodes(2).childNodes(1).nodename & ": " & element.childNodes(2).childNodes(1).text
		logmessage element.childNodes(2).childNodes(2).nodename & ": " & element.childNodes(2).childNodes(2).text
		logmessage element.childNodes(2).childNodes(3).nodename & ": " & element.childNodes(2).childNodes(3).text
	end if
	logmessage "-----------------------------------"

	' check for particle
	if element.childNodes(3).childNodes.length = 0 then
 		logmessage "no particle present"
	else
		logmessage "number of particle: " & element.childNodes(3).childNodes.length
		for each particle_section in element.childNodes(3).childNodes
			logmessage "-----------------------------------"
			for each particle_tag in particle_section.childnodes
				logmessage particle_tag.nodename & ": " & particle_tag.text
			next		
		next	
	end if
	logmessage "==================================="
next


' INFO : Impact: w1_tap
' INFO : Material: Unbreak_Glass
' INFO : Component: Damage
' INFO : Modifier: Any
' INFO : -----------------------------------
' INFO : sound not present
' INFO : -----------------------------------
' INFO : number of particle: 2
' INFO : -----------------------------------
' INFO : Name: d__GLASSCRACK
' INFO : Orientation: 0
' INFO : Location: 4
' INFO : Decal1: false
' INFO : Decal2: true
' INFO : -----------------------------------
' INFO : Name: w1_tap_x03
' INFO : Orientation: 0
' INFO : Location: 1
' INFO : Offset: -1
' INFO : ===================================


' [] remove xml nodes
Set objXMLDoc = CreateObject("Microsoft.XMLDOM") 
objXMLDoc.async = False 

Dim XMLFile
XMLFile = "C:\Softimage\Softimage_Mod_Tool_7.5\OniLevels\ONLV\test\ONLVAirport.xml"
objXMLDoc.load(XMLFile) 
Set nodes = objXMLDoc.selectNodes("Oni/CRSA/*")
For Each node In nodes
    node.parentNode.removeChild(node)
Next

objXMLDoc.Save(XMLFile)


' [19] create txt file + write lines

txt_location = "C:\Softimage\Softimage_Mod_Tool_7.5\test.txt"
Set fso = CreateObject ("Scripting.FileSystemObject")
Set wText = fso.CreateTextFile (txt_location, 1)
wText.WriteLine "I'm a test file."
wText.WriteLine "Yo!"
wText.Close


' [20] read txt file

Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Softimage\Softimage_Mod_Tool_7.5\test.txt", 1)

do while not objFileToRead.AtEndOfStream
    strLine = objFileToRead.ReadLine()
    logmessage strLine
loop
' INFO : I'm a test file.
' INFO : Yo!

objFileToRead.Close
Set objFileToRead = Nothing


' [21] check onisplit version

Set objFSO = CreateObject("Scripting.FileSystemObject")
logmessage objFSO.GetFileVersion("F:\Program Files (x86)\Oni\Edition\install\onisplit.exe")

' result looks like this:
' INFO : 0.9.59.0


' [22] call CMD, e.g. to lunch onisplit or the game

' relative path

' the "GameDataFolder" isn't inside the "install" folder
' so we will use ..\ to go one folder backwards

' additional quote signs tells the program where the 
' paths strings start and end in case the path contains spaces

' if you are going to use the xml file right after its extraction (which is likely)
' then the "/wait" argument inside the onisplit_action string is important
' without it the code would continue and might try to read the not existing xml file and produce an error

onisplit_location = "F:\Program Files (x86)\Oni\Edition\install"
input_folder = """..\GameDataFolder\level19_Final\ONLVcompound.oni"""
output_folder = """..\GameDataFolder"""
onisplit_action = "cmd /C start /wait OniSplit.exe -extract:xml " & output_folder & " " & input_folder
logmessage "relative path: " & onisplit_action
' expected logmessage:
' INFO : relative path: cmd /C start OniSplit.exe -extract:xml "..\GameDataFolder" "..\GameDataFolder\level19_Final\ONLVcompound.oni"
XSIUtils.LaunchProcess onisplit_action, 1, onisplit_location


' absolute path

'adapt paths so it works on your computer
onisplit_location = "F:\Program Files (x86)\Oni\Edition\install"
input_folder = """F:\Program Files (x86)\Oni\Edition\GameDataFolder\level19_Final\ONLVcompound.oni"""
output_folder = """F:\Program Files (x86)\Oni\Edition\GameDataFolder"""
onisplit_action = "cmd /C start /wait OniSplit.exe -extract:xml " & output_folder & " " & input_folder
logmessage "absolute path: " & onisplit_action
' expected logmessage:
' INFO : absolute path: cmd /C start OniSplit.exe -extract:xml "F:\Program Files (x86)\Oni\Edition\GameDataFolder" "F:\Program Files (x86)\Oni\Edition\GameDataFolder\level19_Final\ONLVcompound.oni"
XSIUtils.LaunchProcess onisplit_action, 1, onisplit_location


' you can also lunch bat files

onibat = "cmd /C start run_wind.bat"
onilocation = "F:\Program Files (x86)\Oni\Edition"
XSIUtils.LaunchProcess onibat, 0, onilocation
' alternative to cmd: call onisplit via winmgmts

' slightly modified code from that site
' logmessage "onisplit finished." will be executed after the conversion finished, there should be also an delay of 3 seconds to support very slow computers 
' if you are going to use this method consider to extent the code to check if input file and output directory exist
osp_loca = "C:\OniAE\Edition\install\OniSplit.exe"
osp_action = "-extract:xml"
osp_output = """C:\OniAE\Edition\GameDataFolder"""
osp_input = """C:\OniAE\Edition\GameDataFolder\level1_Final\AKEVEnvWarehouse.oni"""
osp_total = osp_loca & " " & osp_action & " " & osp_output & " " & osp_input
logmessage osp_total

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
objWMIService.Create osp_total, null, null, intProcessID
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

' wait 3 second to find event - should be enough time for single actions on a slow computer
Set colMonitoredProcesses = objWMIService.ExecNotificationQuery _
    ("Select * From __InstanceDeletionEvent Within 3 Where TargetInstance ISA 'Win32_Process'")

Do Until i = 1
    Set objLatestProcess = colMonitoredProcesses.NextEvent
    If objLatestProcess.TargetInstance.ProcessID = intProcessID Then
        i = 1
    End If
Loop
logmessage "onisplit finished."
' now you can work with the extracted xml file


XSI Mod Tool PPG.png
' [23] building a form (PPG)

dim oPSet, oPPGLayout, oItem, PPG_exist

' set check value to 0
PPG_exist = 0

' check if PPG exists
for each prop in ActiveProject.ActiveScene.Root.Properties
	logmessage prop.name
	if instr(1, prop.name, "my_new_PPG") > 0 then
		PPG_exist = 1
		logmessage "found " & """" & prop.name & """"
	end if
next

' create PPG if it doesn't exist
if PPG_exist = 0 then
	set oPSet = ActiveSceneRoot.AddProperty("CustomProperty", false, "my_new_PPG")
	set oPPGLayout = oPSet.PPGLayout
	
	' setup PPG parameters
	' ###################################################################################
	' create checkbox and remove key symboles by setting parameter "Animatable" to false
	oPSet.AddParameter3 "Check1", siBool, 0, , , false
	oPSet.AddParameter3 "Check2", siBool, 0, , , false
	oPSet.AddParameter3 "Check3", siBool, 1, , , false
	oPSet.AddParameter3 "Check4", siBool, 1, , , false
	oPSet.AddParameter3 "text1", siString
	' last parameter of "int1" is set to ReadOnly
	oPSet.AddParameter3 "int1", siInt2, , , , false, 1 
	oPSet.AddParameter3 "int2", siInt2, , , , false, 0
	
	' add PPG items
	' ###################################################################################
	oPPGLayout.AddItem "text1", "Hi there!"
	oPPGLayout.AddItem "int1", "number 1"
	oPPGLayout.AddItem "int2", "number 2"
	oPPGLayout.AddGroup "4 checkboxes", true
	oPPGLayout.AddRow
		oPPGLayout.AddItem "Check1", "C1"
		oPPGLayout.AddItem "Check3", "C3"
	oPPGLayout.EndRow
	oPPGLayout.AddRow
		oPPGLayout.AddItem "Check2", "C2"
		oPPGLayout.AddItem "Check4", "C4"
	oPPGLayout.EndRow
	oPPGLayout.EndGroup
	
	oPPGLayout.AddButton("log_values", "log PPG values").setAttribute siUICX, 120
	
	oPPGLayout.Logic = "sub log_values_OnClicked" & vbCrlf & _
	"		logmessage ""text 1 = "" & getvalue(""my_new_PPG.text1"")" & vbCrlf & _
	"		logmessage ""number 1 = "" & getvalue(""my_new_PPG.int1"")" & vbCrlf & _
	"		logmessage ""C1 = "" & getvalue(""my_new_PPG.Check1"")" & vbCrlf & _
	"	end sub"
	
	oPPGLayout.Language = "VBScript" 'Optional because this is the default

	' open PPG
	InspectObj oPSet		
else
	' open that PPG if it already exist
	InspectObj "my_new_PPG"
end if 
' set values from outside the PPG
setvalue "my_new_PPG.text1", "any text could stand here"
setvalue "my_new_PPG.int1", "42"
setvalue "my_new_PPG.check1", true

' get values from outside the PPG
logmessage getvalue("my_new_PPG.text1")
logmessage getvalue("my_new_PPG.int1")
logmessage getvalue("my_new_PPG.check1")


XSI Mod Tool UserDataBlob.png
' [24] UserDataBlob

' you can attach data to objects, e.g. new properties for the scene root or Oni Trigger Volumes
' the so-called "UserDataBlob" can't be saved in *.dae, so save the whole scene to keep your progress

' check if my property exist
found_my_prop = 0
set oProps = ActiveProject.ActiveScene.Root
logmessage "root name: " & ActiveProject.ActiveScene.Root
for each prop in oProps.Properties
	' remove apostroph in line beneath to log all root properties
 	'LogMessage prop.Name
	if instr(1, prop.Name, "my_prop") = 1 then
		found_my_prop = 1
	end if
next

' prop doesn't exist, create it
if found_my_prop = 0 then
	' create property (must also have content, in this case "yes")
	oProps.AddProperty( "UserDataBlob", , "my_prop" ).value = "yes"
	logmessage "created my new prop"
end if

' prop exists, change/read its value
if found_my_prop = 1 then
	' change property
	oProps.Properties( "my_prop" ).value = "no"

	' read property
	logmessage oProps.Properties( "my_prop" ).value
	' if you want to read a property from another script be sure that it was already created
	' reuse code under "check if my property exist"
end if


' [25] getting the position of points (with selection mode point)

' a point must be selected
' gets xyz position of first selected point of the first selected object
logmessage Selection(0).SubComponent.ComponentCollection(0).position.x
logmessage Selection(0).SubComponent.ComponentCollection(0).position.y
logmessage Selection(0).SubComponent.ComponentCollection(0).position.z


' [26] getting the position of points (with selection mode object)

' an object must be selected
' gets xyz position of point 0 of the first selected object
logmessage selection(0).activeprimitive.geometry.Points(0).Position.x
logmessage selection(0).activeprimitive.geometry.Points(0).Position.y
logmessage selection(0).activeprimitive.geometry.Points(0).Position.z


' [27] getting and setting the position of points (without selection) right after object creation

' point positions are relative to the object's center
' to get the absolute point positions add center to point
' to set the absolute point positions subtract center from point

set oRoot = application.activeproject.activescene.root
set oObj = oRoot.addgeometry( "Cube", "MeshSurface", "test" )

' to test our code move center to somewhere else
Translate oObj, 9, 11, 13, siRelative, siGlobal, siCtr, siXYZ, , , , , , , , , , 0
SaveKey oObj & ".kine.local.posx," & oObj & ".kine.local.posy," & oObj & ".kine.local.posz", 1, , , , True

FreezeObj oObj
set oGeometry = oObj.activeprimitive.geometry
aPositions = oGeometry.Points.PositionArray
' get old position
'                                         (xyz, point)
logmessage "old point 0 posx: " & aPositions(0, 0) + GetValue(oObj & ".kine.global.posx")
logmessage "old point 0 posy: " & aPositions(1, 0) + GetValue(oObj & ".kine.global.posy")
logmessage "old point 0 posz: " & aPositions(2, 0) + GetValue(oObj & ".kine.global.posz")

' set new position
aPositions(0, 0) = -7 - GetValue(oObj & ".kine.global.posx")
aPositions(1, 0) = -7 - GetValue(oObj & ".kine.global.posy")
aPositions(2, 0) = -7 - GetValue(oObj & ".kine.global.posz")

' update the array
oGeometry.Points.PositionArray = aPositions
' get new position
logmessage "new point 0 posx: " & aPositions(0, 0) + GetValue(oObj & ".kine.global.posx")
logmessage "new point 0 posy: " & aPositions(1, 0) + GetValue(oObj & ".kine.global.posy")
logmessage "new point 0 posz: " & aPositions(2, 0) + GetValue(oObj & ".kine.global.posz")

' INFO : old point 0 posx: -4
' INFO : old point 0 posy: -4
' INFO : old point 0 posz: -4

' INFO : new point 0 posx: -7
' INFO : new point 0 posy: -7
' INFO : new point 0 posz: -7


' [28] getting the scaling, rotation and position of selected objects

logmessage "mesh name: " & selection(0)
logmessage selection(0).sclx.value
logmessage selection(0).scly.value
logmessage selection(0).sclz.value
logmessage selection(0).rotx.value
logmessage selection(0).roty.value
logmessage selection(0).rotz.value
logmessage selection(0).posx.value
logmessage selection(0).posy.value
logmessage selection(0).posz.value


' [29] getting the scaling, rotation, and position of not selected objects

' GetValue("NAME.kine.global.rotx")
' NAME must be the exact mesh name
' let's say you want the data of one character's pelvis
logmessage GetValue("pelvis.kine.global.sclx")
logmessage GetValue("pelvis.kine.global.scly")
logmessage GetValue("pelvis.kine.global.sclz")
logmessage GetValue("pelvis.kine.global.rotx")
logmessage GetValue("pelvis.kine.global.roty")
logmessage GetValue("pelvis.kine.global.rotz")
logmessage GetValue("pelvis.kine.global.posx")
logmessage GetValue("pelvis.kine.global.posy")
logmessage GetValue("pelvis.kine.global.posz")


' [30] decrypting merged integer flags

' for example the BINACJBOTrigger Volume.xml file has flags as strings for the <Flags> tag
' and integer values for the <Teams> tag whereby the values are merged to one value
' so if <Teams> tag holds "101" we have to think what flags it holds, the flags can be broken down with following code

' x: hypothetical value of <Teams>
x=101
' 101 = 64 + 32 + 4 + 1

x_255
sub x_255
	if x > 255 then
		msgbox "Flags bigger than 255 are not allowed.", ,"error"
		exit sub
	end if
	if x >= 128 and x <= 255 then
		logmessage "128"
		x = x - 128
	end if
	if x >= 64 and x < 128 then
		logmessage "64"
		x = x - 64
	end if
	if x >= 32 and x < 64 then
		logmessage "32"
		x = x - 32
	end if
	if x >= 16 and x < 32 then
		logmessage "16"
		x = x - 16
	end if
	if x >= 8 and x < 16 then
		logmessage "8"
		x = x - 8
	end if
	if x >= 4 and x < 8 then
		logmessage "4"
		x = x - 4
	end if
	if x >= 2 and x < 4 then
		logmessage "2"
		x = x - 2
	end if
	if x = 2 then
		logmessage "2"
		x = x - 2
	end if
	if x = 1 then
		logmessage "1"
		x = x - 1
	end if
	if x = 0 then
		logmessage "finished check"
	end if
end sub

' INFO : 64
' INFO : 32
' INFO : 4
' INFO : 1
' INFO : finished check


' [31] disabling PPG popups

' for example if code of a script button creates numerous objects in one go, the same number of property pages (PPG) can appear
' for user convenience those PPG popups can be disabled

' disable PPG popup
Preferences.SetPreferenceValue "Interaction.autoinspect", false

' creates the cube mesh but no PPG will show up
CreatePrim "Cube", "MeshSurface"

' enable PPG popup again
Preferences.SetPreferenceValue "Interaction.autoinspect", true


' [32] disabling logmessages

' msglogverbos is probably already set to false by default
' could be set at the start of a final script to increase performance
setvalue "preferences.scripting.msglogverbose", false
setvalue "preferences.scripting.msglog", false


' [33] getting bounding box values

' this could be useful to create a bounding box for OFGA files

' let's get the bounding box of a simple cylinder
' the output values will be absolute positions
CreatePrim "Cylinder", "MeshSurface"

dim xmin, ymin, zmin, xmax, ymax, zmax
dim list
'if you use SelectionList the objects will be treated as one single object
'set list = GetValue( "SelectionList" )
set list = GetValue( selection(0) )
GetBBox list, TRUE, xmin, ymin, zmin, xmax, ymax, zmax
LogMessage "Lower Bound: " & xmin & " / " & ymin & " / " & zmin
LogMessage "Upper Bound: " & xmax & " / " & ymax & " / " & zmax

' expected output:
' INFO : Lower Bound: -1 / -2 / -1
' INFO : Upper Bound: 1 / 2 / 1


' [34] open an explorer window

' this could be used open an output folder ...
strPath = "explorer.exe /e," & XSIUtils.ResolvePath("$SI_HOME/")
Set objShell = CreateObject("Wscript.Shell")
objShell.Run strPath

' to select a generated file inside the folder:
strPath = "explorer.exe /select," & "C:\folder\test.txt"


SelectNeighborObj obj 5
' [35] working with hierarchies 

' let's be sure we have an object selected
if selection.count > 0 and typename(selection(0)) = "X3DObject" then
 
	' the object itself
	logmessage selection(0)
	
	
	' the parent object
	logmessage selection(0).parent
	
	
	' the children
	for each n in selection(0).FindChildren( , , , 0 )
		logmessage n
	next
	' the 4the parameter of FindChildren can be set to 0 or 1
	' with 0 you get all direct children
	' with 1 you get everything located under that object no matter how deep the level


	' count all objects
	logmessage "children: " & selection(0).FindChildren( , , , 1).count
	' caution: if the 3rd parameter is set to siMeshFamily
	' then the selected object will be also counted

	' find the root object of the hierarchy, any object could be selected
	SelectNeighborObj selection(0), 4


	' go through the hierarchy in different directions
	' SelectNeighborObj [parameter1], [parameter2], [parameter3], [parameter4]
	' options of the second parameters
	' 0 go one level up
	' 1 go one level down
	' 2 go to next silbing
	' 3 go to previous silbing
	' 4 go to highest level
	' 5 go to deepest level of current selected obj
	' 5: if there are more than one children, the path goes always for the first (left) child (see image)


	' select the hierarchy as a whole 
	SelectObj "left_thigh", "TREE", true
	' first parameter could be any object of the hierarchy
	' after using this the selection of an Oni character will be "B:pelvis"
else
	msgbox "no object was selected"	
end if


[36] drag and drop support for specific oni files

function XSILoadPlugin( in_reg )
	in_reg.Author = ""
	in_reg.Name = "Oni drag and drop support"
	in_reg.Email = ""
	in_reg.URL = ""
	in_reg.Major = 1
	in_reg.Minor = 0

	in_reg.RegisterEvent "support_oni_DnD",siOnDragAndDrop
 	'RegistrationInsertionPoint - do not remove this line

	XSILoadPlugin = true
end function

function XSIUnloadPlugin( in_reg )
	dim strPluginName
	strPluginName = in_reg.Name
	Application.LogMessage strPluginName & " has been unloaded.",siVerbose
	XSIUnloadPlugin = true
end function

function support_oni_DnD_OnEvent( in_ctxt )
	Set objFSO = CreateObject("Scripting.FileSystemObject")

	FullFilePath = in_ctxt.GetAttribute("DragSource")
 	FileExt = objFSO.GetExtensionName(FullFilePath)
	FileName = objFSO.GetBaseName(FullFilePath)

 	if instr(LCase(FileExt), "oni") = 1 then
 		in_ctxt.SetAttribute "DragSourceSupported", true
 
 		' next line prevents the code from being repeated
	 	if in_ctxt.GetAttribute("DragAndDropAction") = 1 then

			logmessage "What I'm supposed to do with that oni?"
			' do more stuff here
			' ..................
			' e.g. telling onisplit to extract the oni

		end if
	end if

	support_oni_DnD_OnEvent = true
end function

Important:

Mod Tool has its own drag and drop event handler for dae and xml file.

If we succeed in modifying and shipping that new file, we could finally trigger scripts with those files and process them.

The original file can be found at:

logmessage XSIUtils.ResolvePath("$XSI_HOME/") & "Application\DSScripts\Model.vbs"
' C:\Softimage\Softimage_Mod_Tool_7.5\Application\DSScripts\Model.vbs

A backup of the original file can be found here: https://dl.dropboxusercontent.com/u/139715/OniGalore/ModToolScript/Model.vbs (dead link)

There are two issues that can be fixed by modifying this file.

  • import of xml files created by onisplit
  • import of dae and xml files with relative path from a html page

Relative file pathes will be transformed to absolute pathes whereby an unwanted "file:///" is added.

A solution to is to transform the path again.

if instr(in_Filename,"file:///") = 1 then
	in_Filename = replace(in_Filename, "file:///", "")
end if

Following function is always triggered, so we will modify it.

sub ImportDotXSIProc( in_Filename, in_Parent )
	if instr(in_Filename,"file:///") = 1 then
		in_Filename = replace(in_Filename, "file:///", "")
	end if
	Set objFSO = CreateObject("Scripting.FileSystem<Object")
	FileExt = objFSO.GetExtensionName(in_Filename)

	if application.license = "Avid 3D" then
		SIImportDotXSIFile in_Filename, in_Parent
	else
		Set oFS = CreateObject("Scripting.FileSystemObject") 
		if oFS.FileExists(in_Filename) = True then
			if FileExt = "xml" then
				' is this an Oni xml file ?
		 		Set xmlDoc = CreateObject("Microsoft.XMLDOM")
				xmlDoc.Async = "False"
				xmlDoc.Load(in_Filename)
				if xmlDoc.selectNodes("Oni").length > 0 then
					logmessage "Oni xml file detected"
					read_xml "OFGA", in_Filename
				end if
				exit sub
			end if

The lines in red has been added.


[37] dae export

set oProps = ActiveProject.ActiveScene.Root.Properties
if typename (oProps.find("ExportCrosswalkOptions")) = "Nothing" then
	logmessage "Export settings not set"
	CreateExportCrosswalkOptions , "ExportCrosswalkOptions"
else
	logmessage "Export settings present"
end if

' sets the extension to dae
SetValue "ExportCrosswalkOptions.Format", 1
' set export path and file name
SetValue "ExportCrosswalkOptions.Filename", CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\export_test.dae"
' selection only
SetValue "ExportCrosswalkOptions.ExportSelectionOnly", True
' export
ExportCrosswalk "ExportCrosswalkOptions"


[38] fbx export

FBXExportLights (false)
FBXExportSelection (true)
' mark FBXExport and hit F1 to get more options
FBXExport (CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\export_test.fbx" )


[39] import an image clip only once

image_path =  "C:\Users\RRM\Desktop\white_512_512.tga"

Set FSO = CreateObject("Scripting.FileSystemObject")
image_clip = FSO.GetBaseName(image_path) & "_" & FSO.GetExtensionName(image_path)
logmessage image_clip

if not typename(ActiveProject.ActiveScene.ImageClips(image_clip)) = "Nothing" then
	logmessage "found image clip"
else
	logmessage "image clip not yet present, going to import ..."
	
	SICreateImageClip image_path
 	' or as script object:
	'set oImage = AddImageSource (image_path)
	'set oImageClip = AddImageClip (oImage)
end if


[40] layers

how to access scene layers

To access scene layers switch from Main Control Panel (MCP) to Keying Panel/Layers (KP/L) and then click "Scene".

After the user became used to layers, they can help to organize work in a scene. This is especially interesting for some scripting tasks like getting TRGV/FURN data for xml files.

' get current layer
GetCurrentLayer CurrentLayer
logmessage CurrentLayer


' create a new layer named "FurnLayer" if it doesn't already exist
' make new layer the current layer
if typename(ActiveProject.ActiveScene.Layers("FurnLayer")) = "Nothing" then
	SICreateLayer , "FurnLayer", FurnLayer
	SetCurrentLayer FurnLayer
else
	SetCurrentLayer "Layers.FurnLayer"
end if


' get objects in FurnLayer and count objects
' exit sub if there are no objects
SelectMembers "Layers.FurnLayer"
if selection.count = 0 then
	MsgBox "No OFGA data found to export.", , "Export canceled"
	exit sub
end if


' if there are Furn objects
for each obj in selection
	' do something e.g. create xml
next


' [41] onisplit update

' this downloads and unzips the last attachment from the onisplit page
output_dir = "F:\test\"

' get onisplit link ################################################
set xmlhttp = createobject ("msxml2.xmlhttp.3.0")
xmlhttp.open "get", "http://mods.oni2.net/node/38/index.html", false
xmlhttp.send

webtext = xmlhttp.responseText
 webtext = replace(replace(webtext, vbcr,""),vblf,"")
 webtext = split(webtext, "<table class=""sticky-enabled""> <thead><tr><th>Attachment</th>" )(1)
 webtext = split(webtext, "</td> </tr></tbody></table>") (0)

link_start = instrrev(webtext, "http")
link_end = instrrev(webtext, ".zip"" type") + 4 ' + zip
' mid (text, begin, length)
link = mid(webtext, link_start, link_end - link_start)
logmessage "last link in attachment: " & link

dim xHttp: Set xHttp = createobject("Microsoft.XMLHTTP")
dim bStrm: Set bStrm = createobject("Adodb.Stream")
xHttp.Open "GET", link, False
xHttp.Send

' get file name ###################################################
hdr = xHttp.getResponseHeader("Content-Disposition")
hdr = replace (hdr, "attachment; filename=""", "")
hdr = replace (hdr, """", "")
logmessage hdr

' save file #######################################################
filename = output_dir & hdr
with bStrm
	.type = 1 '//binary
	.open
	.write xHttp.responseBody
	.savetofile filename, 2 '//overwrite
end with

' extract file ####################################################

UnzipFile filename, output_dir

Function UnzipFile(ZipFile, ExtractTo)
	Set fso = CreateObject("Scripting.FileSystemObject")
	If NOT fso.FolderExists(ExtractTo) Then
		fso.CreateFolder(ExtractTo)
	End If
	set objShell = CreateObject("Shell.Application")
	set FilesInZip=objShell.NameSpace(ZipFile).items
	objShell.NameSpace(ExtractTo).CopyHere(FilesInZip)
	Set fso = Nothing
	Set objShell = Nothing
End Function


' [42] get vertex color

set oGeometry = selection(0).activeprimitive.geometry
set oTriangles = oGeometry.Triangles

for each oTriangle in oTriangles
   logmessage oTriangle.Name 

   for each oVertex in oTriangle.Points
       set oColor = oVertex.Color
       logmessage vbTab & "RGBA(" & _
          oColor.red & "," & _
          oColor.green & "," & _
          oColor.blue & "," & _
          oColor.alpha & ")"
   next
next


' [43] get all used textures

DeleteAllUnusedMaterials
DeleteUnusedImageClips
'DeleteUnusedImageSources
for each i in Application.ActiveProject.ActiveScene.ExternalFiles
	if i.filetype = "Pictures" then
		logmessage i
	end if
next


'  [44] get global point position

set oObj = selection(0)
set oTrans = oObj.Kinematics.Local.Transform 
set oPoint0 = oObj.ActivePrimitive.Geometry.Points(0)
set oPoint7 = oObj.ActivePrimitive.Geometry.Points(7)
set oPos0 = oPoint0.Position
set oPos7 = oPoint7.Position

' scaling must be frozen to 1 before we can calculate the size from local values
ResetTransform selection(0), siCtr, siScl, siXYZ

logmessage "local p0: "& oPos0.X & " " & oPos0.Y & " " & oPos0.Z
set oGlobalPos0 = XSIMath.MapObjectPositionToWorldSpace( oTrans, oPos0)
logmessage "global p0: "& oGlobalPos0.X & " " & oGlobalPos0.Y & " " & oGlobalPos0.Z

logmessage "local p7: "& oPos7.X & " " & oPos7.Y & " " & oPos7.Z
set oGlobalPos7 = XSIMath.MapObjectPositionToWorldSpace( oTrans, oPos7)
logmessage "global p7: "& oGlobalPos7.X & " " & oGlobalPos7.Y & " " & oGlobalPos7.Z
 
logmessage "size: " &		oPos7.X - oPos0.X & " " & _
							oPos7.Y - oPos0.Y & " " & _
							oPos7.Z - oPos0.Z
' with a rotation of: -3,8792 16,4039 -13,5017
' INFO : local p0: -4 -4 -4
' INFO : local p7: 4 4 4
' INFO : global p0: -5,74764582364017 -3,00250371537919 -2,43916767056426 ' TRGV start point
' INFO : global p7: 5,74764582364017 3,00250371537919 2,43916767056426
' INFO : size: 8 8 8


Interactive Creative Environment (ICE)

tutorials:

Wanted knowledge

  • How to set up particles in Mod Tool? We still need an Oni particle editor!
  • How to rig models and then extract the animation data?
  • How to make complex new UV maps?