package Savage.Tools.Explosions;

import org.web3d.x3d.jsail.Core.*;
import org.web3d.x3d.jsail.EnvironmentalEffects.*;
import org.web3d.x3d.jsail.fields.*;
import org.web3d.x3d.jsail.Grouping.*;
import org.web3d.x3d.jsail.Interpolation.*;
import org.web3d.x3d.jsail.Navigation.*;
import org.web3d.x3d.jsail.Networking.*;
import org.web3d.x3d.jsail.Scripting.*;
import org.web3d.x3d.jsail.Shape.*;
import org.web3d.x3d.jsail.Text.*;
import org.web3d.x3d.jsail.Time.*;

// Javadoc metadata annotations follow, see below for X3DJSAIL Java source code.
/**
 * <p> A simple exploding structure, experimenting with the "Hello World" of explosions - click on the silver chimney to trigger the explosion. </p>
 <p> Related links: Catalog page <a href="../../../../Tools/Explosions/MultipleTimerExplodingBuildingPrototypeIndex.html" target="_blank">MultipleTimerExplodingBuildingPrototype</a>,  source <a href="../../../../Tools/Explosions/MultipleTimerExplodingBuildingPrototype.java">MultipleTimerExplodingBuildingPrototype.java</a>, <a href="https://www.web3d.org/x3d/content/examples/X3dResources.html" target="_blank">X3D Resources</a>, <a href="https://www.web3d.org/x3d/content/examples/X3dSceneAuthoringHints.html" target="_blank">X3D Scene Authoring Hints</a>, and <a href="https://www.web3d.org/x3d/content/X3dTooltips.html" target="_blank">X3D Tooltips</a>. </p>
	<table style="color:black; border:0px solid; border-spacing:10px 0px;">
        <caption>Scene Meta Information</caption>
		<tr style="background-color:silver; border-color:silver;">
			<td style="text-align:center; padding:10px 0px;"><i>meta tags</i></td>
			<td style="text-align:left;   padding:10px 0px;">&nbsp; Document Metadata </td>
		</tr>

		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> title </i> </td>
			<td> <a href="../../../../Tools/Explosions/MultipleTimerExplodingBuildingPrototype.x3d">MultipleTimerExplodingBuildingPrototype.x3d</a> </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> description </i> </td>
			<td> A simple exploding structure, experimenting with the "Hello World" of explosions - click on the silver chimney to trigger the explosion. </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> creator </i> </td>
			<td> Don Brutzman </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> created </i> </td>
			<td> 1 January 2001 </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> modified </i> </td>
			<td> 28 November 2019 </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> Image </i> </td>
			<td> <a href="../../../../Tools/Explosions/MultipleTimerExplodingBuildingExampleIntermediateAnimation.png">MultipleTimerExplodingBuildingExampleIntermediateAnimation.png</a> </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> MovingImage </i> </td>
			<td> <a href="../../../../Tools/Explosions/MultipleTimerExplodingBuildingVideo.mov">MultipleTimerExplodingBuildingVideo.mov</a> </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> reference </i> </td>
			<td> Exploding building schematic layout diagram: </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> reference </i> </td>
			<td> <a href="../../../../Tools/Explosions/ExplodingBuildingLayout.pdf">ExplodingBuildingLayout.pdf</a> </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> reference </i> </td>
			<td> ExplodingBuildingLargeExample.wrl </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> reference </i> </td>
			<td> Rotation calculations performed using the Dizzy utility from Vapour Technologies by James Smith. </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> reference </i> </td>
			<td> <a href="http://www.vapourtech.com" target="_blank">http://www.vapourtech.com</a> </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> reference </i> </td>
			<td> DIS-Java-VRML Working Group </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> reference </i> </td>
			<td> <a href="https://www.web3d.org/WorkingGroups/vrtp/dis-java-vrml" target="_blank">https://www.web3d.org/WorkingGroups/vrtp/dis-java-vrml</a> </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> identifier </i> </td>
			<td> <a href="https://www.web3d.org/x3d/content/examples/Savage/Tools/Explosions/MultipleTimerExplodingBuildingPrototype.x3d" target="_blank">https://www.web3d.org/x3d/content/examples/Savage/Tools/Explosions/MultipleTimerExplodingBuildingPrototype.x3d</a> </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> generator </i> </td>
			<td> X3D-Edit 3.2, <a href="https://www.web3d.org/x3d/tools/X3D-Edit" target="_blank">https://www.web3d.org/x3d/tools/X3D-Edit</a> </td>
		</tr>
		<tr>
			<td style="text-align:right; vertical-align: text-top;"> <i> license </i> </td>
			<td> <a href="../../../../Tools/Explosions/../../license.html">../../license.html</a> </td>
		</tr>
		<tr style="background-color:silver; border-color:silver;">
			<td style="text-align:center;" colspan="2">  &nbsp; </td>
		</tr>
	</table>

	<p>
		This program uses the
		<a href="https://www.web3d.org/specifications/java/X3DJSAIL.html" target="_blank">X3D Java Scene Access Interface Library (X3DJSAIL)</a>.
		It has been produced using the 
		<a href="https://www.web3d.org/x3d/stylesheets/X3dToJava.xslt" target="_blank">X3dToJava.xslt</a>
		stylesheet
	       (<a href="https://sourceforge.net/p/x3d/code/HEAD/tree/www.web3d.org/x3d/stylesheets/X3dToJava.xslt" target="_blank">version control</a>)
                which is used to create Java source code from an original <code>.x3d</code> model.
	</p>

	* @author Don Brutzman
 */

public class MultipleTimerExplodingBuildingPrototype
{
	/** Default constructor to create this object. */
	public MultipleTimerExplodingBuildingPrototype ()
	{
	  initialize();
	}

	/** Create and initialize the X3D model for this object. */
	public final void initialize()
	{
            try { // catch-all
  x3dModel = new X3D().setProfile(X3D.PROFILE_IMMERSIVE).setVersion(X3D.VERSION_3_0)
  .setHead(new head()
    .addMeta(new meta().setName(meta.NAME_TITLE      ).setContent("MultipleTimerExplodingBuildingPrototype.x3d"))
    .addMeta(new meta().setName(meta.NAME_DESCRIPTION).setContent("A simple exploding structure, experimenting with the \"Hello World\" of explosions - click on the silver chimney to trigger the explosion."))
    .addMeta(new meta().setName(meta.NAME_CREATOR    ).setContent("Don Brutzman"))
    .addMeta(new meta().setName(meta.NAME_CREATED    ).setContent("1 January 2001"))
    .addMeta(new meta().setName(meta.NAME_MODIFIED   ).setContent("28 November 2019"))
    .addMeta(new meta().setName(meta.NAME_IMAGE      ).setContent("MultipleTimerExplodingBuildingExampleIntermediateAnimation.png"))
    .addMeta(new meta().setName(meta.NAME_MOVINGIMAGE).setContent("MultipleTimerExplodingBuildingVideo.mov"))
    .addMeta(new meta().setName(meta.NAME_REFERENCE  ).setContent("Exploding building schematic layout diagram:"))
    .addMeta(new meta().setName(meta.NAME_REFERENCE  ).setContent("ExplodingBuildingLayout.pdf"))
    .addMeta(new meta().setName(meta.NAME_REFERENCE  ).setContent("ExplodingBuildingLargeExample.wrl"))
    .addMeta(new meta().setName(meta.NAME_REFERENCE  ).setContent("Rotation calculations performed using the Dizzy utility from Vapour Technologies by James Smith."))
    .addMeta(new meta().setName(meta.NAME_REFERENCE  ).setContent("http://www.vapourtech.com"))
    .addMeta(new meta().setName(meta.NAME_REFERENCE  ).setContent("DIS-Java-VRML Working Group"))
    .addMeta(new meta().setName(meta.NAME_REFERENCE  ).setContent("https://www.web3d.org/WorkingGroups/vrtp/dis-java-vrml"))
    .addMeta(new meta().setName(meta.NAME_IDENTIFIER ).setContent("https://www.web3d.org/x3d/content/examples/Savage/Tools/Explosions/MultipleTimerExplodingBuildingPrototype.x3d"))
    .addMeta(new meta().setName(meta.NAME_GENERATOR  ).setContent("X3D-Edit 3.2, https://www.web3d.org/x3d/tools/X3D-Edit"))
    .addMeta(new meta().setName(meta.NAME_LICENSE    ).setContent("../../license.html")))
  .setScene(new Scene()
    .addChild(new WorldInfo().setTitle("MultipleTimerExplodingBuildingPrototype.x3d"))
    .addChild(new ProtoDeclare("Exploder").setName("Exploder").setAppinfo("Prototype to explode different pieces and parts in different ways.")
      .setProtoInterface(new ProtoInterface()
        .addField(new field().setName("geometry").setType(field.TYPE_SFNODE).setAccessType(field.ACCESSTYPE_INITIALIZEONLY).setAppinfo("geometry node, to be used inside a Shape")
          .addComments(" initialization node (if any) goes here "))
        .addField(new field().setName("material").setType(field.TYPE_SFNODE).setAccessType(field.ACCESSTYPE_INITIALIZEONLY).setAppinfo("Material node for this geometry, to be used inside a Shape")
          .addComments(" initialization node (if any) goes here "))
        .addField(new field().setName("initialPosition").setType(field.TYPE_SFVEC3F).setAccessType(field.ACCESSTYPE_INITIALIZEONLY).setValue(new SFVec3f(0.0,0.0,0.0)).setAppinfo("starting point"))
        .addField(new field().setName("finalPosition").setType(field.TYPE_SFVEC3F).setAccessType(field.ACCESSTYPE_INITIALIZEONLY).setValue(new SFVec3f(0.0,0.0,0.0)).setAppinfo("finish point"))
        .addField(new field().setName("initialOrientation").setType(field.TYPE_SFROTATION).setAccessType(field.ACCESSTYPE_INITIALIZEONLY).setValue(new SFRotation(0.0,1.0,0.0,0.0)).setAppinfo("starting point orientation"))
        .addField(new field().setName("finalOrientation").setType(field.TYPE_SFROTATION).setAccessType(field.ACCESSTYPE_INITIALIZEONLY).setValue(new SFRotation(0.0,1.0,0.0,0.0)).setAppinfo("finish point orientation"))
        .addField(new field().setName("set_fraction").setType(field.TYPE_SFFLOAT).setAccessType(field.ACCESSTYPE_INPUTONLY).setAppinfo("animation input"))
        .addField(new field().setName("startTime").setType(field.TYPE_SFTIME).setAccessType(field.ACCESSTYPE_INPUTOUTPUT).setValue(0).setAppinfo("animation trigger")))
      .setProtoBody(new ProtoBody()
        .addChild(new Transform("LocationTransform")
          .setIS(new IS()
            .addConnect(new connect().setNodeField("translation").setProtoField("initialPosition")))
          .addChild(new Transform("RotationTransform")
            .setIS(new IS()
              .addConnect(new connect().setNodeField("rotation").setProtoField("initialOrientation")))
            .addChild(new Shape("AnimatedShape")
              .setIS(new IS()
                .addConnect(new connect().setNodeField("geometry").setProtoField("geometry")))
              .setAppearance(new Appearance("AnimatedShapeAppearance")
                .setIS(new IS()
                  .addConnect(new connect().setNodeField("material").setProtoField("material")))))))
        .addChild(new Script("ProtoAnimationScript").setSourceCode("""
ecmascript:

function initialize ()
{
	dx = finalPosition.x - initialPosition.x;
	dy = finalPosition.y - initialPosition.y;
	dz = finalPosition.z - initialPosition.z;
//	Browser.println ('dx=' + dx + ', dy=' + dy + ', dz=' + dz);
	distance = Math.sqrt (dx*dx + dy*dy + dz*dz);
	runTime = distance/20;
//	Browser.println ('runTime = ' + runTime);
//	Browser.println ('distance          =' + distance);
	quarterPoint   = initialPosition.add (new SFVec3f (  dx/4,   dy/4 + 0.707*distance,     dz/4));
	halfwaypoint   = initialPosition.add (new SFVec3f (  dx/2,   dy/2 +       distance,     dz/2));
	three4thsPoint = initialPosition.add (new SFVec3f (3*dx/4, 3*dy/4 + 0.707*distance/2, 3*dz/4));
	position_changeds = new MFVec3f (initialPosition, initialPosition, quarterPoint, halfwaypoint, three4thsPoint, finalPosition);
//	Browser.println ('position_changeds    =' + position_changeds);
	rotationValues = new MFRotation (initialOrientation, finalOrientation);
//	Browser.println ('initialPosition   =' + initialPosition);
//	Browser.println ('finalPosition     =' + finalPosition);
//	Browser.println ('position_changeds    =' + position_changeds);
//	Browser.println ('initialOrientation=' + initialOrientation);
//	Browser.println ('finalOrientation  =' + finalOrientation);
//	Browser.println ('rotationValues=' + rotationValues);
}
""")
          .addField(new field().setName("initialPosition").setType(field.TYPE_SFVEC3F).setAccessType(field.ACCESSTYPE_INITIALIZEONLY))
          .addField(new field().setName("finalPosition").setType(field.TYPE_SFVEC3F).setAccessType(field.ACCESSTYPE_INITIALIZEONLY))
          .addField(new field().setName("initialOrientation").setType(field.TYPE_SFROTATION).setAccessType(field.ACCESSTYPE_INITIALIZEONLY))
          .addField(new field().setName("finalOrientation").setType(field.TYPE_SFROTATION).setAccessType(field.ACCESSTYPE_INITIALIZEONLY))
          .addField(new field().setName("runTime").setType(field.TYPE_SFTIME).setAccessType(field.ACCESSTYPE_OUTPUTONLY))
          .addField(new field().setName("position_changeds").setType(field.TYPE_MFVEC3F).setAccessType(field.ACCESSTYPE_OUTPUTONLY))
          .addField(new field().setName("rotationValues").setType(field.TYPE_MFROTATION).setAccessType(field.ACCESSTYPE_OUTPUTONLY))
          .addComments(" <field accessType='outputOnly' name='fraction_changed' type='SFFloat'/> ")
          .setIS(new IS()
            .addConnect(new connect().setNodeField("initialPosition").setProtoField("initialPosition"))
            .addConnect(new connect().setNodeField("finalPosition").setProtoField("finalPosition"))
            .addConnect(new connect().setNodeField("initialOrientation").setProtoField("initialOrientation"))
            .addConnect(new connect().setNodeField("finalOrientation").setProtoField("finalOrientation"))))
        .addChild(new TimeSensor("ProtoTimeSensor")
          .setIS(new IS()
            .addConnect(new connect().setNodeField("startTime").setProtoField("startTime"))))
        .addChild(new PositionInterpolator("ProtoPositionInterpolatorCalculated").setKey(new double[] {0.0,0.2,0.4,0.6,0.8,1.0}).setKeyValue(new MFVec3f(new double[] {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}))
          .setIS(new IS()
            .addConnect(new connect().setNodeField("set_fraction").setProtoField("set_fraction"))))
        .addChild(new OrientationInterpolator("ProtoOrientationInterpolatorCalculated").setKey(new double[] {0.0,1.0}).setKeyValue(new MFRotation(new double[] {0.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0}))
          .setIS(new IS()
            .addConnect(new connect().setNodeField("set_fraction").setProtoField("set_fraction"))))
        .addChild(new ROUTE().setFromNode("ProtoPositionInterpolatorCalculated").setFromField("value_changed").setToNode("LocationTransform").setToField("translation"))
        .addChild(new ROUTE().setFromNode("ProtoOrientationInterpolatorCalculated").setFromField("value_changed").setToNode("RotationTransform").setToField("rotation"))
        .addChild(new ROUTE().setFromNode("ProtoAnimationScript").setFromField("position_changeds").setToNode("ProtoPositionInterpolatorCalculated").setToField("keyValue"))
        .addChild(new ROUTE().setFromNode("ProtoAnimationScript").setFromField("rotationValues").setToNode("ProtoOrientationInterpolatorCalculated").setToField("keyValue"))
        .addChild(new ROUTE().setFromNode("ProtoAnimationScript").setFromField("runTime").setToNode("ProtoTimeSensor").setToField("cycleInterval"))
        .addChild(new ROUTE().setFromNode("ProtoTimeSensor").setFromField("fraction_changed").setToNode("ProtoPositionInterpolatorCalculated").setToField("set_fraction"))
        .addChild(new ROUTE().setFromNode("ProtoTimeSensor").setFromField("fraction_changed").setToNode("ProtoOrientationInterpolatorCalculated").setToField("set_fraction"))))
    .addComments(" ==================== ")
    .addChild(new Viewpoint().setDescription("Multiple Timer Exploding Building").setPosition(0.0,0.0,12.0))
    .addChild(new Background().setGroundAngle(new double[] {1.57}).setGroundColor(new MFColor(new double[] {0.6,0.9,0.6,0.6,0.9,0.6})).setSkyColor(new MFColor(new double[] {0.6,0.6,0.9})))
    .addChild(new Anchor().setDescription("MultipleTimerExplodingBuildingExample").setParameter(new String[] {"target=_blank"}).setUrl(new String[] {"MultipleTimerExplodingBuildingExample.x3d","https://www.web3d.org/x3d/content/examples/Savage/Tools/Explosions/MultipleTimerExplodingBuildingExample.x3d","MultipleTimerExplodingBuildingExample.wrl","https://www.web3d.org/x3d/content/examples/Savage/Tools/Explosions/MultipleTimerExplodingBuildingExample.wrl"})
      .addChild(new Shape()
        .setGeometry(new Text().setString(new String[] {"MultipleTimerExplodingBuildingPrototype","is a prototype definition file","","Click this text to see","MultipleTimerExplodingBuildingExample"})
          .setFontStyle(new FontStyle().setJustify(FontStyle.JUSTIFY_MIDDLE_MIDDLE)))
        .setAppearance(new Appearance()
          .setMaterial(new Material().setDiffuseColor(0.2,0.2,0.8))))));
            }
            catch (Exception ex)
            {       
                System.err.println ("*** Further hints on X3DJSAIL errors and exceptions at");
                System.err.println ("*** https://www.web3d.org/specifications/java/X3DJSAIL.html");
                throw (ex);
            }
	}
	// end of initialize() method

	/** The initialized model object, created within initialize() method. */
	private X3D x3dModel;

	/** 
	 * Provide a 
	 * <a href="https://dzone.com/articles/java-copy-shallow-vs-deep-in-which-you-will-swim" target="_blank">shallow copy</a>
	 * of the X3D model.
	 * @see <a href="https://www.web3d.org/specifications/java/javadoc/org/web3d/x3d/jsail/Core/X3D.html">X3D</a>
	 * @return MultipleTimerExplodingBuildingPrototype model
	 */
	public X3D getX3dModel()
	{	  
		return x3dModel;
	}
	   
    /** 
     * Default main() method provided for test purposes, uses CommandLine to set global ConfigurationProperties for this object.
     * @param args array of input parameters, provided as arguments
     * @see <a href="https://www.web3d.org/specifications/java/javadoc/org/web3d/x3d/jsail/Core/X3D.html#handleArguments-java.lang.String:A-">X3D.handleArguments(args)</a>
     * @see <a href="https://www.web3d.org/specifications/java/javadoc/org/web3d/x3d/jsail/Core/X3D.html#validationReport--">X3D.validationReport()</a>
     * @see <a href="https://www.web3d.org/specifications/java/javadoc/org/web3d/x3d/jsail/CommandLine.html">CommandLine</a>
     * @see <a href="https://www.web3d.org/specifications/java/javadoc/org/web3d/x3d/jsail/CommandLine.html#USAGE">CommandLine.USAGE</a>
     * @see <a href="https://www.web3d.org/specifications/java/javadoc/org/web3d/x3d/jsail/ConfigurationProperties.html">ConfigurationProperties</a>
     */
    public static void main(String args[])
    {
        System.out.println("Build this X3D model, showing validation diagnostics...");
        X3D thisExampleX3dModel = new MultipleTimerExplodingBuildingPrototype().getX3dModel();
//      System.out.println("X3D model construction complete.");
	
        // next handle command line arguments
        boolean hasArguments = (args != null) && (args.length > 0);
        boolean validate = true; // default
        boolean argumentsLoadNewModel = false;
        String  fileName = new String();

        if (args != null)
        {
                for (String arg : args)
                {
                        if (arg.toLowerCase().startsWith("-v") || arg.toLowerCase().contains("validate"))
                        {
                                validate = true; // making sure
                        }
                        if (arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_X3D) ||
                                arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_CLASSICVRML) ||
                                arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_X3DB) ||
                                arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_VRML97) ||
                                arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_EXI) ||
                                arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_GZIP) ||
                                arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_ZIP) ||
                                arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_HTML) ||
                                arg.toLowerCase().endsWith(X3D.FILE_EXTENSION_XHTML))
                        {
                                argumentsLoadNewModel = true;
                                fileName = arg;
                        }
                }
        }
        if      (argumentsLoadNewModel)
                System.out.println("WARNING: \"Savage.Tools.Explosions.MultipleTimerExplodingBuildingPrototype\" model invocation is attempting to load file \"" + fileName + "\" instead of simply validating itself... file loading ignored.");
        else if (hasArguments) // if no arguments provided, this method produces usage warning
                thisExampleX3dModel.handleArguments(args);
	
        if (validate)
        {
            //  System.out.println("--- TODO fix duplicated outputs ---"); // omit when duplicated outputs problem is solved/refactored
		String validationResults = thisExampleX3dModel.validationReport();
            //  System.out.println("-----------------------------------"); // omit when duplicated outputs problem is solved/refactored
                System.out.print("Savage.Tools.Explosions.MultipleTimerExplodingBuildingPrototype self-validation test confirmation: ");
                if (!validationResults.equals("success"))
                    System.out.println();
                System.out.println(validationResults.trim());

                // experimental: test X3DJSAIL output files
                // Tools/Explosions/MultipleTimerExplodingBuildingPrototype_JavaExport.* file validation is checked when building X3D Example Archives
                String filenameX3D  = "Tools/Explosions/MultipleTimerExplodingBuildingPrototype_JavaExport.x3d"; 
                String filenameX3DV = "Tools/Explosions/MultipleTimerExplodingBuildingPrototype_JavaExport.x3dv"; 
                String filenameJSON = "Tools/Explosions/MultipleTimerExplodingBuildingPrototype_JavaExport.json";
                thisExampleX3dModel.toFileX3D        (filenameX3D);
                thisExampleX3dModel.toFileClassicVRML(filenameX3DV);
// TODO         thisExampleX3dModel.toFileJSON       (filenameJSON);
        }
    }
}
