####################################################################################################
#
# Invoking X3D model self-test:
#
#   $ python DEF_USE_AnimationExample.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.3',
  head=head(
    children=[
    meta(content='DEF_USE_AnimationExample.x3d',name='title'),
    meta(content='Illustrate how USE nodes implement copy by reference, resulting in immediate changes when original DEF node is modified. A single MasterMaterial node is animated, and changes in the parent MasterAppearance are reflected throughout the scene graph.',name='description'),
    meta(content='Don Brutzman',name='creator'),
    meta(content='1 September 2024',name='modified'),
    meta(content='DEF_USE_AnimationExampleScreenshot.png',name='Image'),
    meta(content='X3D Specification Mantis Issue https://www.web3d.org/member-only/mantis/view.php?id=690',name='TODO'),
    meta(content='Wikipedia: Evaluation strategy, pass by sharing https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing',name='reference'),
    meta(content='X3D 4.0 Architecture, ISO/IEC 19775-1:2023, clause 4 Concepts, 4.4.3 DEF/USE semantics',name='specificationSection'),
    meta(content='https://www.web3d.org/specifications/X3Dv4Draft/ISO-IEC19775-1v4-IS.proof/Part01/concepts.html#DEF_USE_Semantics',name='specificationUrl'),
    meta(content='https://www.web3d.org/x3d/content/examples/X3dForWebAuthors/Chapter02GeometryPrimitives/GeometryPrimitiveNodes.x3d',name='reference'),
    meta(content='https://www.web3d.org/x3d/content/examples/X3dForAdvancedModeling/Animation/DEF_USE_AnimationExample.x3d',name='identifier'),
    meta(content='Altova XMLSpy https://www.altova.com/xmlspy-xml-editor',name='generator'),
    meta(content='XMLSpyPrettyPrintSpacingTextViewSettings.png',name='reference'),
    meta(content='X3D-Edit 4.0 https://www.web3d.org/x3d/tools/X3D-Edit',name='generator'),
    meta(content='../license.html',name='license')]),
  Scene=Scene(
    children=[
    WorldInfo(title='DEF_USE_AnimationExample.x3d'),
    Background(skyColor=[(0.6,0.8,0.8)]),
    Viewpoint(DEF='EntryView',description='DEF - USE Animation Example',position=(0,0,13)),
    Comment('Selectable Text design pattern has transparent Box and TouchSensor description as a tooltip'),
    TouchSensor(DEF='TopLevelTouchSensor',description='select and hold to run animation'),
    Group(
      children=[
      Shape(DEF='TransparentSelectableBox',
        geometry=Box(size=(16,8,.001)),
        appearance=Appearance(
          material=Material(transparency=1))),
      Transform(DEF='HighererRowTransform',translation=(0,1.5,0),
        children=[
        Transform(translation=(-5,0,0),
          children=[
          Shape(
            geometry=Box(DEF='DefaultBox'),
            appearance=Appearance(DEF='MasterAppearance',
              material=Material(DEF='MasterMaterial',diffuseColor=(0.4,0.4,0.4)))),
          Transform(translation=(0,1.6,0),
            children=[
            Shape(DEF='SmallDEFText',
              geometry=Text(string=["DEF"],
                fontStyle=FontStyle(DEF='SmallFontStyle',justify=["MIDDLE","MIDDLE"],size=0.5)),
              appearance=Appearance(DEF='TextAppearance',
                material=Material(diffuseColor=(1,1,1))))])]),
        Transform(translation=(-2.5,0,0),
          children=[
          Shape(
            geometry=Cone(DEF='DefaultCone'),
            appearance=Appearance(USE='MasterAppearance')),
          Transform(translation=(0,1.6,0),
            children=[
            Shape(DEF='SmallUSEText',
              geometry=Text(string=["USE"],
                fontStyle=FontStyle(USE='SmallFontStyle')),
              appearance=Appearance(USE='TextAppearance'))])]),
        Transform(
          children=[
          Shape(
            geometry=Cylinder(DEF='DefaultCylinder'),
            appearance=Appearance(USE='MasterAppearance')),
          Transform(translation=(0,1.6,0),
            children=[
            Shape(USE='SmallUSEText')])]),
        Transform(translation=(2.5,0,0),
          children=[
          Shape(
            geometry=Sphere(DEF='DefaultSphere'),
            appearance=Appearance(USE='MasterAppearance')),
          Transform(translation=(0,1.6,0),
            children=[
            Shape(USE='SmallUSEText')])]),
        Transform(translation=(4,0,0),
          children=[
          Shape(
            geometry=Text(DEF='DefaultText',string=["hello","X3D!"],
              fontStyle=FontStyle(DEF='DefaultFontStyle')),
            appearance=Appearance(USE='MasterAppearance')),
          Transform(translation=(1.2,1.6,0),
            children=[
            Shape(USE='SmallUSEText')])])]),
      TimeSensor(DEF='Clock',cycleInterval=8,enabled=False,loop=True),
      ColorInterpolator(DEF='ColorChanger',key=[0,0.5,0.5,0.75,1.0],keyValue=[(1,1,1),(1,0,0),(0,1,0),(0,0,1),(1,1,1)]),
      ROUTE(fromField='isActive',fromNode='TopLevelTouchSensor',toField='enabled',toNode='Clock'),
      ROUTE(fromField='fraction_changed',fromNode='Clock',toField='set_fraction',toNode='ColorChanger'),
      ROUTE(fromField='value_changed',fromNode='ColorChanger',toField='diffuseColor',toNode='MasterMaterial'),
      Transform(DEF='LowerRowTransform',translation=(0,-2,0),
        children=[
        Shape(
          geometry=Text(DEF='UserMessage',string=["ColorInterpolator modifies one Material","in a single DEF=MasterAppearance node,","other USE nodes apply those values.","","To animate, select and hold","using your pointing device."],
            fontStyle=FontStyle(DEF='MessageFontStyle',justify=["MIDDLE","MIDDLE"],size=0.6,style_='BOLD')),
          appearance=Appearance(
            material=Material(diffuseColor=(1,1,1))))])])])
)

### X3D model conversion complete ###

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

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