####################################################################################################
#
# Invoking X3D model self-test:
#
#   $ python ParallelepipedPrototype.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='ParallelepipedPrototype.x3d',name='title'),
    meta(content='Reusable prototype for creating a Parallelepiped, which is a 3D figure formed by six parallelograms; also sometimes referred to as a rhomboid.',name='description'),
    meta(content='Don Brutzman',name='creator'),
    meta(content='25 November 2011',name='created'),
    meta(content='7 December 2024',name='modified'),
    meta(content='ParallelepipedExamples.x3d',name='reference'),
    meta(content='ParallelepipedVertexIndices.png',name='Image'),
    meta(content='GeometricShapes.vsdx',name='drawing'),
    meta(content='https://en.wikipedia.org/wiki/Parallelepiped',name='reference'),
    meta(content='http://upload.wikimedia.org/wikipedia/commons/f/f6/Parallelepiped.svg',name='reference'),
    meta(content='http://upload.wikimedia.org/wikipedia/commons/thumb/f/f6/Parallelepiped.svg/500px-Parallelepiped.svg.png',name='reference'),
    meta(content='parallelepiped rhomboid geometry polyhedron',name='subject'),
    meta(content='https://www.web3d.org/x3d/content/examples/X3dForAdvancedModeling/GeometricShapes/ParallelepipedPrototype.x3d',name='identifier'),
    meta(content='https://www.web3d.org/x3d/content/examples/X3dResources.html',name='reference'),
    meta(content='X3D-Edit 3.3, https://www.web3d.org/x3d/tools/X3D-Edit',name='generator'),
    meta(content='../license.html',name='license')]),
  Scene=Scene(
    children=[
    WorldInfo(title='ParallelepipedPrototype.x3d'),
    ProtoDeclare(appinfo='Parallelepiped is a 3D figure formed by six parallelograms; also sometimes referred to as a rhomboid',name='Parallelepiped',
      ProtoInterface=ProtoInterface(
        field=[
        field(accessType='inputOutput',name='point',type='MFVec3f',value=[(0,1,0),(1,1,0),(1,1,1),(0,1,1),(0,0,0),(1,0,0),(1,0,1),(0,0,1)]),
        field(accessType='initializeOnly',name='colorPerVertex',type='SFBool',value=True),
        field(accessType='initializeOnly',name='normalPerVertex',type='SFBool',value=True),
        field(accessType='initializeOnly',name='colorIndex',type='MFInt32'),
        field(accessType='initializeOnly',name='normalIndex',type='MFInt32'),
        field(accessType='initializeOnly',name='texCoordIndex',type='MFInt32'),
        field(accessType='inputOutput',name='colorNode',type='SFNode',
          children=[
          Color(DEF='DefaultColor')]),
        field(accessType='inputOutput',name='normalNode',type='SFNode',
          children=[
          Normal(DEF='DefaultNormal')]),
        field(accessType='inputOutput',name='texCoordNode',type='SFNode',
          children=[
          TextureCoordinate(DEF='DefaultTextureCoordinate')])]),
      ProtoBody=ProtoBody(
        children=[
        Comment('First node determines node type of this prototype'),
        IndexedFaceSet(DEF='IFS',convex=False,coordIndex=[0,3,2,1,-1,4,5,6,7,-1,0,1,5,4,-1,1,2,6,5,-1,2,3,7,6,-1,3,0,4,7,-1],solid=False,
          IS=IS(
            connect=[
            connect(nodeField='colorPerVertex',protoField='colorPerVertex'),
            connect(nodeField='normalPerVertex',protoField='normalPerVertex'),
            connect(nodeField='colorIndex',protoField='colorIndex'),
            connect(nodeField='normalIndex',protoField='normalIndex'),
            connect(nodeField='texCoordIndex',protoField='texCoordIndex'),
            connect(nodeField='colorNode',protoField='colorNode'),
            connect(nodeField='normalNode',protoField='normalNode'),
            connect(nodeField='texCoordNode',protoField='texCoordNode')]),
          coord=Coordinate(
            IS=IS(
              connect=[
              connect(nodeField='point',protoField='point')]))),
        Comment('This embedded Script provides the X3D author with additional visibility and control over prototype inputs and outputs'),
        Script(DEF='ParallelepipedScript',
          field=[
          field(accessType='inputOutput',name='point',type='MFVec3f')],
          IS=IS(
            connect=[
            connect(nodeField='point',protoField='point')]),

        sourceCode="""
ecmascript:
function initialize ()
{
    checkCoordinatePoints ();
}
function checkCoordinatePoints ()
{
    // A parallelepiped has three sets of four parallel edges; the edges within each set are of equal length.
    // Quality assurance: check that lengths of corresponding sides match.
    
    edge01 = length2(point[0], point[1]); // top
    edge12 = length2(point[1], point[2]);
    edge23 = length2(point[2], point[3]);
    edge30 = length2(point[3], point[0]);
    edge45 = length2(point[4], point[5]); // bottom
    edge56 = length2(point[5], point[6]);
    edge67 = length2(point[6], point[7]);
    edge74 = length2(point[7], point[4]);
    edge04 = length2(point[0], point[4]); // sides
    edge15 = length2(point[1], point[5]);
    edge26 = length2(point[2], point[6]);
    edge37 = length2(point[3], point[7]);
    
    epsilon = edge01 * 0.001;
    
    if      ((Math.abs(edge01 - edge23) > epsilon) ||
             (Math.abs(edge23 - edge67) > epsilon) ||
             (Math.abs(edge67 - edge45) > epsilon) ||
             (Math.abs(edge45 - edge01) > epsilon))
         Browser.println ('Warning, mismatched parallelepiped sides 02/33/45/67');
    else if ((Math.abs(edge30 - edge12) > epsilon) ||
             (Math.abs(edge12 - edge56) > epsilon) ||
             (Math.abs(edge56 - edge74) > epsilon) ||
             (Math.abs(edge74 - edge30) > epsilon))
         Browser.println ('Warning, mismatched parallelepiped sides 30/12/56/74');
    else if ((Math.abs(edge04 - edge15) > epsilon) ||
             (Math.abs(edge15 - edge26) > epsilon) ||
             (Math.abs(edge26 - edge37) > epsilon) ||
             (Math.abs(edge37 - edge04) > epsilon))
         Browser.println ('Warning, mismatched parallelepiped sides 04/15/26/37');
}
function length2 (pointA, pointB)
{    
    return Math.sqrt((pointA.x - pointB.x)*(pointA.x - pointB.x) +
                     (pointA.y - pointB.y)*(pointA.y - pointB.y) +
                     (pointA.z - pointB.z)*(pointA.z - pointB.z));
}
function set_point (eventValue)
{
   // input eventValue received for inputOutput field
    point = eventValue;
    checkCoordinatePoints ();
}
""")])),
    Comment('================================================================================'),
    Background(skyColor=[(0.905882,1,0.858824)]),
    Anchor(description='Open ParallelepipedExamples scene',url=["ParallelepipedExamples.x3d","https://www.web3d.org/x3d/content/examples/X3dForAdvancedModeling/GeometricShapes/ParallelepipedExamples.x3d","ParallelepipedExamples.wrl","https://www.web3d.org/x3d/content/examples/X3dForAdvancedModeling/GeometricShapes/ParallelepipedExamples.wrl"],
      children=[
      Shape(
        geometry=Text(string=["This scene defines a","Parallelepiped prototype","","Select this text to open","ParallelepipedExamples scene"],
          fontStyle=FontStyle(justify=["MIDDLE","MIDDLE"])),
        appearance=Appearance(DEF='BlueAppearance',
          material=Material(diffuseColor=(0,0.698039,1)))),
      Shape(DEF='TransparentBox',
        geometry=Box(size=(11,5,0.1)),
        appearance=Appearance(
          material=Material(transparency=1)))])])
)

### X3D model conversion complete ###

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

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