####################################################################################################
#
# Invoking X3D model self-test:
#
#   $ python Type209PrevezeDieselSubmarineAnimated.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='Type209PrevezeDieselSubmarineAnimated.x3d',name='title'),
    meta(content='Alper SINAV',name='creator'),
    meta(content='1 August 2001',name='created'),
    meta(content='28 November 2019',name='modified'),
    meta(content='This is a Type 209 Preveze Class Submarine From Turkish Submarine Fleet. It consists of a cylindric pressure hull, hydroplanes, rudder, propeller and superstructure with tower.',name='description'),
    meta(content='Alper SINAV',name='creator'),
    meta(content='https://www.web3d.org/x3d/content/examples/Savage/Submarines/Various/Type209PrevezeDieselSubmarineAnimated.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='Type209PrevezeDieselSubmarineAnimated.x3d'),
    Background(groundAngle=[1.309,1.570796],groundColor=[(0,0.4,0.4),(0.25,0.6,0.6),(0.1,0.4,0.4)],skyAngle=[1.309,1.571],skyColor=[(0.1,0.1,0.6),(0.1,0.25,0.8),(0.6,0.6,0.9)]),
    Viewpoint(description='Look away'),
    Viewpoint(description='Listen Sonar',position=(0,0,3)),
    Comment(' Following is construction of submarine '),
    Transform(scale=(0.2,0.2,0.2),
      children=[
      Comment(' original rotation 0 0 1 -0.8 '),
      Transform(DEF='ROT',
        children=[
        Transform(DEF='SUBTRANS',
          children=[
          Transform(DEF='SUBROTATE',
            children=[
            Group(DEF='SUBMARINE',
              children=[
              Comment(' Main Pessure Hull and upper form super structure '),
              Transform(rotation=(-1,0,0,1.57),
                children=[
                Transform(DEF='Z90',rotation=(0,0,1,1.57),
                  children=[
                  Shape(
                    appearance=Appearance(DEF='SUBOUT',
                      material=Material(DEF='Total',diffuseColor=(0.0,0.0,0.1),emissiveColor=(0.1,0.1,0.1),specularColor=(0.6,0.5,0.5))),
                    geometry=Extrusion(ccw=False,creaseAngle=0.785,crossSection=[(0,2),(0.2,1.95),(0.4,1.92),(0.6,1.9),(0.8,1.8),(1,1.7),(1,2.19),(0.9,2.28),(0.8,2.37),(0.7,2.4),(-0.7,2.4),(-0.8,2.37),(-0.9,2.28),(-1,2.19),(-1,1.7),(-0.8,1.8),(-0.6,1.9),(-0.4,1.92),(-0.2,1.95),(0,2)],spine=[(0,-7,0),(0,7,0)])),
                  Shape(
                    appearance=Appearance(
                      material=Material(USE='Total')),
                    geometry=Cylinder(height=14,radius=2)),
                  Transform(scale=(2,2,2),
                    children=[
                    Shape(
                      appearance=Appearance(
                        material=Material(USE='Total')),
                      geometry=Extrusion(creaseAngle=0.785,crossSection=[(1.00,0.00),(0.92,-0.38),(0.71,-0.71),(0.38,-0.92),(0.00,-1.00),(-0.38,-0.92),(-0.71,-0.71),(-0.92,-0.38),(-1.00,-0.00),(-0.92,0.38),(-0.71,0.71),(-0.38,0.92),(0.00,1.00),(0.38,0.92),(0.71,0.71),(0.92,0.38),(1.00,0.00)],scale=[(0.3,0.3),(1,1)],spine=[(0,7,0),(0,3.5,0)]))]),
                  Shape(
                    appearance=Appearance(
                      material=Material(USE='Total')),
                    geometry=Extrusion(ccw=False,creaseAngle=0.785,crossSection=[(0,2),(0.2,1.95),(0.4,1.92),(0.6,1.9),(0.8,1.8),(1,1.7),(1,2.19),(0.9,2.28),(0.8,2.37),(0.7,2.4),(-0.7,2.4),(-0.8,2.37),(-0.9,2.28),(-1,2.19),(-1,1.7),(-0.8,1.8),(-0.6,1.9),(-0.4,1.92),(-0.2,1.95),(0,2)],scale=[(1,1),(0.1,0.1)],spine=[(0,-7,0),(0,-9,0)]))])]),
              Comment(' Head section of submarine MAIN BALAST TANKS '),
              Transform(center=(0,0,14),translation=(7,0,0),
                children=[
                Shape(
                  geometry=Sphere(radius=2),
                  appearance=Appearance(
                    material=Material(USE='Total')))]),
              Comment(' Propeller copyright LtJg Burcin KAYALI '),
              Transform(scale=(0.2,0.15,0.15),translation=(-14.2,0,0),
                children=[
                Inline(url=["Type209Propeller.wrl","https://www.web3d.org/x3d/content/examples/Savage/Submarines/Various/Type209Propeller.wrl"])]),
              Comment(' TOWER '),
              Transform(scale=(4,0.5,1),translation=(-2,3,0),
                children=[
                Shape(
                  appearance=Appearance(
                    material=Material(USE='Total')),
                  geometry=Cylinder(height=4,radius=0.6))]),
              Comment(' Retractable Mast Group '),
              Transform(DEF='PERISCOPETRANS',translation=(-2,3,0),
                children=[
                Shape(DEF='PERISCOPE',
                  appearance=Appearance(
                    material=Material(USE='Total')),
                  geometry=Cylinder(height=6,radius=0.1))]),
              Transform(DEF='UHFANTENNATRANS',translation=(-4,3,0),
                children=[
                Shape(USE='PERISCOPE')]),
              Comment(' Rudder and Hydro planes '),
              Group(DEF='RUDDER',
                children=[
                Transform(translation=(-13,1,0),
                  children=[
                  Transform(DEF='LowRudderRot',
                    children=[
                    Transform(scale=(1,1,0.2),
                      children=[
                      Shape(
                        geometry=Cylinder(DEF='BOWHYDPLANE',height=1,radius=0.5),
                        appearance=Appearance(
                          material=Material(USE='Total')))])])]),
                Transform(translation=(-13,-1,0),
                  children=[
                  Transform(DEF='UpRudderRot',
                    children=[
                    Transform(scale=(1,1,0.2),
                      children=[
                      Shape(
                        geometry=Cylinder(USE='BOWHYDPLANE'),
                        appearance=Appearance(
                          material=Material(USE='Total')))])])])]),
              Group(DEF='BOWPLANE',
                children=[
                Transform(translation=(-12.5,0,1),
                  children=[
                  Transform(rotation=(1,0,0,1.57),
                    children=[
                    Transform(DEF='RBowPlaneRot',
                      children=[
                      Transform(scale=(1,1,0.2),
                        children=[
                        Shape(
                          geometry=Cylinder(USE='BOWHYDPLANE'),
                          appearance=Appearance(
                            material=Material(USE='Total')))])])])]),
                Transform(translation=(-12.5,0,-1),
                  children=[
                  Transform(rotation=(1,0,0,1.57),
                    children=[
                    Transform(DEF='LBowPlaneRot',rotation=(0,1,0,0.8),
                      children=[
                      Transform(scale=(1,1,0.2),
                        children=[
                        Shape(
                          geometry=Cylinder(USE='BOWHYDPLANE'),
                          appearance=Appearance(
                            material=Material(USE='Total')))])])])])])])]),
          Sound(intensity=0.5,maxBack=70,maxFront=120,minBack=50,minFront=100,
            source=AudioClip(description='sonar ping',loop=True,url=["sonar.wav","https://www.web3d.org/x3d/content/examples/Savage/Submarines/Various/sonar.wav","https://www.web3d.org/x3d/content/examples/Vrml2Sourcebook/tone1.wav"]))])])]),
    TimeSensor(DEF='CLOCK',cycleInterval=40,loop=True),
    PositionInterpolator(DEF='PATH',key=[0,0.5,1],keyValue=[(2,0,0),(5,0,0),(6,0,0)]),
    OrientationInterpolator(DEF='RUDDERANGLE',key=[0,0.2,0.7],keyValue=[(0,1,0,0),(0,1,0,0.8),(0,1,0,1.1)]),
    ROUTE(fromField='fraction_changed',fromNode='CLOCK',toField='set_fraction',toNode='RUDDERANGLE'),
    ROUTE(fromField='value_changed',fromNode='RUDDERANGLE',toField='set_rotation',toNode='RBowPlaneRot'),
    ROUTE(fromField='value_changed',fromNode='RUDDERANGLE',toField='set_rotation',toNode='LBowPlaneRot'),
    
      field=[
DEF='MOVER',
      field=[
      field(accessType='inputOnly',name='set_fraction',type='SFFloat'),
      field(accessType='outputOnly',name='value_changed',type='SFVec3f'),
      field(accessType='initializeOnly',name='radius',type='SFFloat',value=10),
      field(accessType='initializeOnly',name='turns',type='SFFloat',value=1)],

    sourceCode="""
ecmascript:

function set_fraction ( fraction, eventTime ) {
	value_changed = new SFVec3f (radius * Math.sin( turns * fraction * 6.28 ), 0, radius * Math.cos( turns * fraction * 6.28 ));
}
"""),
    
      field=[
DEF='TURNER',
      field=[
      field(accessType='inputOnly',name='set_fraction',type='SFFloat'),
      field(accessType='outputOnly',name='value_changed',type='SFRotation'),
      # <field accessType="initializeOnly" name="radius" type="SFFloat" value="1"/> <field accessType="initializeOnly" name="turns" type="SFFloat" value="1"/>
,

    sourceCode="""
ecmascript:

function set_fraction ( fraction, eventTime ) {
	value_changed = new SFRotation (0, 1, 0, fraction*6.28);
}
"""),
    ROUTE(fromField='fraction_changed',fromNode='CLOCK',toField='set_fraction',toNode='TURNER'),
    ROUTE(fromField='value_changed',fromNode='TURNER',toField='set_rotation',toNode='SUBROTATE'),
    ROUTE(fromField='fraction_changed',fromNode='CLOCK',toField='set_fraction',toNode='MOVER'),
    ROUTE(fromField='value_changed',fromNode='MOVER',toField='set_translation',toNode='SUBTRANS')])
)

### X3D model conversion complete ###

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

print('Self-test diagnostics for Type209PrevezeDieselSubmarineAnimated.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 Type209PrevezeDieselSubmarineAnimated.py load and self-test diagnostics complete.")
