####################################################################################################
#
# Invoking X3D model self-test:
#
#   $ python OahuCollisionSite.py
#
# Python package x3d.py package is available on PyPI for import.
#   This approach simplifies Python X3D deployment and use.
#   https://pypi.org/project/x3d
#
# Installation:
#       pip install x3d
# or
#       python -m pip install x3d
#
# Developer options for loading x3d package in other Python programs:
#
#    from x3d import *  # preferred approach, terser source that avoids x3d.* class prefixes
#
# or
#    import x3d         # traditional way to subclass x3d package, all classes require x3d.* prefix,
#                       # but python source is very verbose, for example x3d.Material x3d.Shape etc.
#                       # X3dToPython.xslt stylesheet insertPackagePrefix=true supports this option.
#
# Project home page:    # X3D Python Scene Access Interface Library (X3DPSAIL)
#                       # https://www.web3d.org/x3d/stylesheets/python/python.html
# Conversion generator: # https://www.web3d.org/x3d/stylesheets/X3dToPython.xslt
#
####################################################################################################

from x3d import *

newModel=X3D(profile='Immersive',version='3.0',
  head=head(
    children=[
    meta(content='OahuCollisionSite.x3d',name='title'),
    meta(content='This program reenacts the collision of the USS Greenville and the Ehime Maru. A previously written, stand-alone reenactment of the collision has been inlined. The islands of Oahu and Molaki (partial) have been inlined as the background.',name='description'),
    meta(content='Capt Mark Lennerton USMC',name='creator'),
    meta(content='Capt Mark Lennerton USMC',name='translator'),
    meta(content='terrain is misaligned 90 degrees with respect to North',name='warning'),
    meta(content='20 October 2019',name='modified'),
    meta(content='20 October 2019',name='modified'),
    meta(content='MakingOahuAreaModelInVRMLX3D.ppt',name='reference'),
    meta(content='Oahu Hawaii collision Greenville Ehime Maru submarine',name='subject'),
    meta(content='https://www.web3d.org/x3d/content/examples/Savage/Locations/Hawaii/OahuCollisionSite.x3d',name='identifier'),
    meta(content='X3D-Edit 3.2, https://www.web3d.org/x3d/tools/X3D-Edit',name='generator'),
    meta(content='../../license.html',name='license')]),
  Scene=Scene(
    children=[
    WorldInfo(title='OahuCollisionSite.x3d'),
    ExternProtoDeclare(name='CameraCompass36',url=["../../../Savage/Tools/HeadsUpDisplays/CameraCompassPrototypes.wrl#CameraCompass36","https://www.web3d.org/x3d/content/examples/Savage/Tools/HeadsUpDisplays/CameraCompassPrototypes.wrl#CameraCompass36","../../../Savage/Tools/HeadsUpDisplays/CameraCompassPrototypes.x3d#CameraCompass36","https://www.web3d.org/x3d/content/examples/Savage/Tools/HeadsUpDisplays/CameraCompassPrototypes.x3d#CameraCompass36"],
      field=[
      field(accessType='inputOutput',name='enabled',type='SFBool'),
      field(accessType='inputOutput',name='positionOffsetFromCamera',type='SFVec3f'),
      field(accessType='inputOutput',name='markerColor',type='SFColor'),
      field(accessType='inputOutput',name='labelColor',type='SFColor')]),
    NavigationInfo(avatarSize=[10,1.6,1],speed=1000,visibilityLimit=1000000),
    Viewpoint(description='Collision_Point_Boresighted',orientation=(1,-1,0,-.401),position=(65000,3000,-8250)),
    Transform(
      children=[
      Viewpoint(description='Turn_to_Mag_North')]),
    Background(DEF='BackgroundCyan-ish',groundAngle=[1.309,1.570796],groundColor=[(0.15,0.15,0.7),(0.2,0.2,0.65),(0.6,0.6,0.6)],skyAngle=[1.309,1.571],skyColor=[(0,0.2,0.7),(0.0,0.5,1),(1,1,1)]),
    Background(DEF='BackgroundReddish',groundAngle=[1.309,1.570796],groundColor=[(0.15,0.15,0.7),(0.2,0.2,0.65),(0.6,0.6,0.2)],skyAngle=[1.309,1.571],skyColor=[(1,0,0),(1,0.4,0),(1,1,0)]),
    Transform(rotation=(0,1,0,1.57),translation=(62000,0,-18250),
      children=[
      Inline(url=["CollisionCourses.x3d","https://www.web3d.org/x3d/content/examples/Savage/Locations/Hawaii/CollisionCourses.x3d","CollisionCourses.wrl","https://www.web3d.org/x3d/content/examples/Savage/Locations/Hawaii/CollisionCourses.wrl"])]),
    Inline(url=["OahuAndSouthernBathymetry.x3d","https://www.web3d.org/x3d/content/examples/Savage/Locations/Hawaii/OahuAndSouthernBathymetry.x3d","OahuAndSouthernBathymetry.wrl","https://www.web3d.org/x3d/content/examples/Savage/Locations/Hawaii/OahuAndSouthernBathymetry.wrl"]),
    ProtoInstance(name='CameraCompass36',
      fieldValue=[
      fieldValue(name='enabled',value=True),
      fieldValue(name='positionOffsetFromCamera',value=(0,5,0)),
      fieldValue(name='markerColor',value=(0.9,0.9,0.9)),
      fieldValue(name='labelColor',value=(0.9,0.9,0.9))]),
    Group(DEF='BackgroundControls',
      children=[
      Transform(DEF='LatLongOn',scale=(2000,2000,2000),translation=(-10000,5000,-120000),
        children=[
        Shape(
          geometry=Sphere(),
          appearance=Appearance(
            material=Material(diffuseColor=(0,0.5,0.8)))),
        TouchSensor(DEF='SensorButton1')]),
      Transform(scale=(2000,2000,2000),translation=(-5000,5000,-120000),
        children=[
        Shape(
          geometry=Sphere(),
          appearance=Appearance(
            material=Material(diffuseColor=(1,0.4,0)))),
        TouchSensor(DEF='SensorButton2')]),
      Script(DEF='Filter1',
        field=[
        field(accessType='inputOnly',name='set_boolean',type='SFBool'),
        Comment('activated: provides a persistent binding value, otherwise isActive events will toggle Background binding on/off.'),
        field(accessType='outputOnly',name='activated',type='SFBool'),
        Comment('count: only used locally, so it is declared for persistence'),
        field(accessType='initializeOnly',name='count',type='SFInt32',value=1)],

      sourceCode="""
ecmascript:

function initialize () {
  Browser.println (' '); // skip line
  Browser.println ('Click shapes to select a background...');
  Browser.println (' '); // skip line
}

// setting the value of an eventOut variable also sends it as an event

function set_boolean ( value, eventTime ) {
  if ( value == true ) {
	activated = value;
	Browser.println ('Display blue clear sky' + count);
  }
  else count++;  // received isActive value = false
}
"""),
      Script(DEF='Filter2',
        field=[
        field(accessType='inputOnly',name='set_boolean',type='SFBool'),
        field(accessType='outputOnly',name='activated',type='SFBool'),
        field(accessType='initializeOnly',name='count',type='SFInt32',value=1)],

      sourceCode="""
ecmascript:

// setting the value of an eventOut variable also sends it as an event

function set_boolean ( value, eventTime ) {
  if ( value == true ) {
	activated = value;
	Browser.println ('Display red sunset sky' + count);
  }
  else count++;  // received isActive value = false
}
""")]),
    ROUTE(fromField='isActive',fromNode='SensorButton1',toField='set_boolean',toNode='Filter1'),
    ROUTE(fromField='activated',fromNode='Filter1',toField='set_bind',toNode='BackgroundCyan-ish'),
    ROUTE(fromField='isActive',fromNode='SensorButton2',toField='set_boolean',toNode='Filter2'),
    ROUTE(fromField='activated',fromNode='Filter2',toField='set_bind',toNode='BackgroundReddish')])
)

### X3D model conversion complete ###

####################################################################################################
# Self-test diagnostics
####################################################################################################

print('Self-test diagnostics for OahuCollisionSite.py:')
if        metaDiagnostics(newModel): # built-in utility method in X3D class
    print(metaDiagnostics(newModel)) # display meta info, hint, warning, error, TODO values in this model
# print('check newModel.XML() serialization...')
newModelXML= newModel.XML() # test export method XML() for exceptions during export
newModel.XMLvalidate()
# print(newModelXML) # diagnostic

try:
#   print('check newModel.VRML() serialization...')
    newModelVRML=newModel.VRML() # test export method VRML() for exceptions during export
    # print(prependLineNumbers(newModelVRML)) # debug
    print("Python-to-VRML export of VRML output successful", flush=True)
except Exception as err: # usually BaseException
    # https://stackoverflow.com/questions/18176602/how-to-get-the-name-of-an-exception-that-was-caught-in-python
    print("*** Python-to-VRML export of VRML output failed:", type(err).__name__, err)
    if newModelVRML: # may have failed to generate
        print(prependLineNumbers(newModelVRML, err.lineno))

try:
#   print('check newModel.JSON() serialization...')
    newModelJSON=newModel.JSON() # test export method JSON() for exceptions during export
#   print(prependLineNumbers(newModelJSON)) # debug
    print("Python-to-JSON export of JSON output successful (under development)")
except Exception as err: # usually SyntaxError
    print("*** Python-to-JSON export of JSON output failed:", type(err).__name__, err)
    if newModelJSON: # may have failed to generate
        print(prependLineNumbers(newModelJSON,err.lineno))

print("python OahuCollisionSite.py load and self-test diagnostics complete.")
