Search in sources :

Example 21 with RootModel

use of artisynth.core.workspace.RootModel in project artisynth_core by artisynth.

the class Main method setSelectionMode.

/**
 * Set the current selection mode. Also set the display of the selection
 * buttons.
 *
 * @param selectionMode selection mode
 */
public void setSelectionMode(SelectionMode selectionMode) {
    if (mySelectionMode != selectionMode) {
        // point will be added to whichever rigid body is clicked on
        if (selectionMode == SelectionMode.AddComponent) {
            myViewerManager.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
        // myViewerManager.setSelectionEnabled(false);
        } else if (selectionMode == SelectionMode.EllipticSelect) {
            myViewerManager.setCursor(null);
        } else {
            myViewerManager.setCursor(getDefaultCursor());
        // myREnderDriver.setSelectionEnabled(true);
        }
        if (selectionMode == SelectionMode.Pull) {
            // switching into a Pull selection ...
            myViewerManager.setSelectOnPress(true);
            myViewerManager.addMouseListener(myPullController);
            // myViewerManager.addRenderable (myPullController);
            mySelectionManager.clearSelections();
            mySelectionManager.addSelectionListener(myPullController);
            RootModel root = getRootModel();
            if (root != null) {
                myPullController.setRootModelDefaults(root);
                root.addController(myPullController, findMechSystem(root));
            }
        } else if (mySelectionMode == SelectionMode.Pull) {
            // switching out of a Pull selection ...
            myViewerManager.setSelectOnPress(false);
            RootModel root = getRootModel();
            if (root != null) {
                root.removeController(myPullController);
            }
            mySelectionManager.removeSelectionListener(myPullController);
            // myViewerManager.removeRenderable (myPullController);
            myViewerManager.removeMouseListener(myPullController);
        }
        if (selectionMode == SelectionMode.EllipticSelect) {
            myViewerManager.setEllipticSelection(true);
        } else {
            myViewerManager.setEllipticSelection(false);
        }
        mySelectionMode = selectionMode;
        if (myMenuBarHandler.modeSelectionToolbar != null) {
            SelectionToolbar toolbar = (SelectionToolbar) myMenuBarHandler.modeSelectionToolbar;
            toolbar.setSelectionButtons();
        }
        if (myWorkspace != null) {
            rerender();
        }
        setDragger();
    }
}
Also used : RootModel(artisynth.core.workspace.RootModel)

Example 22 with RootModel

use of artisynth.core.workspace.RootModel in project artisynth_core by artisynth.

the class Main method doLoadModel.

private boolean doLoadModel(String className, String modelName, String[] modelArgs) {
    // the Jython console.
    if (myViewer != null && !SwingUtilities.isEventDispatchThread()) {
        LoadModelRunner runner = new LoadModelRunner(className, modelName, modelArgs);
        if (!runInSwing(runner)) {
            return false;
        } else {
            return runner.getStatus();
        }
    }
    Class<?> demoClass = null;
    RootModel newRoot = null;
    try {
        demoClass = Class.forName(className);
    } catch (ClassNotFoundException e) {
        myErrMsg = "class " + className + " not found";
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        if (className == null) {
            myErrMsg = " model " + modelName + " cannot be initialized";
        } else {
            myErrMsg = " class " + className + " cannot be initialized";
        }
        e.printStackTrace();
        return false;
    }
    // to remove dots since they aren't allowed in names
    if (className.equals(modelName)) {
        modelName = demoClass.getSimpleName();
    } else if (modelName.contains(".")) {
        String[] splitNames = modelName.split("\\.");
        // get last item
        modelName = splitNames[splitNames.length - 1];
    }
    clearRootModel();
    // objects like an HUD while a new model is loading
    if (myViewerManager != null) {
        myViewerManager.clearRenderables();
        // refresh the rendering lists
        myViewerManager.render();
    }
    // getWorkspace().getWayPoints().clear();
    // set to a large number for testing memory leaks
    int numLoads = 1;
    for (int i = 0; i < numLoads; i++) {
        newRoot = createRootModel(demoClass, modelName, modelArgs);
        if (newRoot == null) {
            // load empty model since some state info from existing model
            // has been cleared, causing it to crash
            doLoadModel("artisynth.core.workspace.RootModel", "EmptyModel", modelArgs);
            if (myViewerManager != null) {
                myViewerManager.render();
            }
            return false;
        }
        setRootModel(newRoot, modelName, modelArgs);
        if (numLoads > 1) {
            System.out.println("load instance " + i);
        }
    }
    if (myFrame != null) {
        // Sanchez, July 11, 2013
        // force repaint again, updating viewer bounds to reflect
        // new renderables
        // set external render lists
        myViewerManager.render();
        // when a model is loaded reset the viewer so no view is selected
        // setViewerMode (null);
        // remove the selected item in the selectComponentPanel otherwise the
        // text for that selected component remains when a new model is loaded
        myFrame.getSelectCompPanelHandler().clear();
        myFrame.getSelectCompPanelHandler().setComponentFilter(null);
        myFrame.setBaseTitle("ArtiSynth " + modelName);
    }
    return true;
}
Also used : RootModel(artisynth.core.workspace.RootModel) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) InternalErrorException(maspack.util.InternalErrorException) WayPoint(artisynth.core.probes.WayPoint)

Example 23 with RootModel

use of artisynth.core.workspace.RootModel in project artisynth_core by artisynth.

the class Main method main.

/**
 * the main entry point
 *
 * @param args command line arguments
 */
public static void main(String[] args) {
    // some interfaces (like Matlab) may pass args in as null
    if (args == null) {
        args = new String[0];
    }
    ArgParser parser = new ArgParser("java artisynth.core.driver.Main", false);
    parser.addOption("-help %v #prints help message", printHelp);
    parser.addOption("-width %d #width (pixels)", viewerWidth);
    parser.addOption("-height %d #height (pixels)", viewerHeight);
    parser.addOption("-bgColor %fX3 #background color (3 rgb values, 0 to 1)", bgColor);
    parser.addOption("-maxStep %f #maximum time for a single step (sec)", maxStep);
    parser.addOption("-drawAxes %v #draw coordinate axes", drawAxes);
    parser.addOption("-drawGrid %v #draw grid", drawGrid);
    parser.addOption("-axisLength %f #coordinate axis length", axisLength);
    parser.addOption("-play %v #play model immediately", play);
    parser.addOption("-playFor %f #play model immediately for x seconds", playFor);
    parser.addOption("-exitOnBreak %v #exit artisynth when playing stops", exitOnBreak);
    parser.addOption("-demosFile %s #demo file (e.g. .demoModels)", demosFilename);
    parser.addOption("-demosMenu %s #demo menu file (e.g. .demoMenu.xml)", demosMenuFilename);
    parser.addOption("-historyFile %s #model history file (e.g. .history)", historyFilename);
    parser.addOption("-scriptsFile %s #script file (e.g. .artisynthModels)", scriptsFilename);
    parser.addOption("-mousePrefs %s #kees for pure mouse controls", mousePrefs);
    parser.addOption("-ortho %v #use orthographic viewing", orthographic);
    parser.addOption("-axialView %s{xy,xz} #initial view of x-y or x-z axes", axialView);
    parser.addOption("-noTimeline %v{false} #do not start with a timeline", startWithTimeline);
    parser.addOption("-showJythonConsole %v{true} #create jython console on startup", startWithJython);
    parser.addOption("-largeTimeline %v{true} #start with vertically expanded timeline", largeTimeline);
    parser.addOption("-timelineRight %v{true} #start with a timeline alligned to the right", timelineRight);
    parser.addOption("-fps %f#frames per second", framesPerSecond);
    parser.addOption("-fullscreen %v #full screen renderer", fullScreen);
    // parser.addOption("-yup %v #initialize viewer with Y-axis up", yup);
    parser.addOption("-timelineZoom %d #zoom level for timeline", zoom);
    parser.addOption("-options %v #print options only", printOptions);
    parser.addOption("-abortOnInvertedElems %v #abort on nonlinear element inversion", abortOnInvertedElems);
    parser.addOption("-disableHybridSolves %v #disable hybrid linear solves", disableHybridSolves);
    parser.addOption("-numSolverThreads %d #number of threads to use for linear solver", numSolverThreads);
    parser.addOption("-posCorrection %s{Default,GlobalMass,GlobalStiffness} " + "#position correction mode", posCorrection);
    parser.addOption("-noIncompressDamping %v #ignore incompress stiffness for damping", noIncompressDamping);
    // parser.addOption ("-useOldTimeline %v #use old timeline", useOldTimeline);
    parser.addOption("-useSignedDistanceCollider %v " + "#use SignedDistanceCollider where possible", useSignedDistanceCollider);
    parser.addOption("-useAjlCollision" + "%v #use AJL collision detection", useAjlCollision);
    parser.addOption("-useBodyVelsInSolve" + "%v #use body velocities for dynamic solves", useBodyVelsInSolve);
    parser.addOption("-useArticulatedTransforms %v #enforce articulation " + "constraints with transformers", useArticulatedTransforms);
    parser.addOption("-updateLibs %v #update libraries from ArtiSynth server", updateLibs);
    parser.addOption("-flags %x #flag bits passed to the application", flags);
    parser.addOption("-noGui %v #run ArtiSynth without the GUI", noGui);
    parser.addOption("-openMatlabConnection %v " + "#open a MATLAB connection if possible", openMatlab);
    parser.addOption("-GLVersion %d{2,3} " + "#version of openGL for graphics", glVersion);
    parser.addOption("-useGLJPanel %v " + "#use GLJPanel for creating the openGL viewer", useGLJPanel);
    parser.addOption("-useGLCanvas %v{false} " + "#use GLJCanvas for creating the openGL viewer", useGLJPanel);
    parser.addOption("-logLevel %s", logLevel);
    parser.addOption("-testSaveRestoreState %v #test save/restore state when running models", testSaveRestoreState);
    parser.addOption("-movieFrameRate %f #frame rate to use when making movies", movieFrameRate);
    parser.addOption("-movieMethod %s #method to use when making movies", movieMethod);
    Locale.setDefault(Locale.CANADA);
    URL initUrl = ArtisynthPath.findResource(".artisynthInit");
    if (initUrl == null) {
    // Removed warning message for now
    // System.out.println (".artisynthInit not found");
    } else {
        InputStream is = null;
        try {
            is = initUrl.openStream();
        } catch (Exception e) {
            // do nothing if we can't open
            System.out.println(".artisynthInit not found");
        }
        if (is != null) {
            try {
                args = ArgParser.prependArgs(new InputStreamReader(is), args);
            } catch (Exception e) {
                System.err.println("Error reading init file " + initUrl);
                System.err.println(e.getMessage());
            }
        }
    }
    if (System.getProperty("file.separator").equals("\\")) {
        // then we are running windows, so set noerasebackground to
        // try and remove flicker bug
        System.setProperty("sun.awt.noerasebackground", "true");
    } else {
        System.setProperty("awt.useSystemAAFontSettings", "on");
    }
    // Separate program arguments from model arguments introduced by -M
    ArrayList<String> progArgs = new ArrayList<String>();
    ArrayList<String> modelArgs = null;
    ArrayList<String> scriptArgs = null;
    ArrayList<String> taskManagerArgs = null;
    for (String arg : args) {
        if (modelArgs != null) {
            modelArgs.add(arg);
        } else {
            if (arg.equals("-M")) {
                modelArgs = new ArrayList<String>();
            } else {
                progArgs.add(arg);
            }
        }
    }
    // Match arguments one at a time so we can avoid exitOnError if we are
    // running inside matlab
    String[] pargs = progArgs.toArray(new String[0]);
    int lastSwitch = -1;
    int idx = 0;
    while (idx < pargs.length) {
        try {
            int pidx = idx;
            // check for list of arguments:
            if ("-model".equals(pargs[pidx])) {
                modelName.value = pargs[++idx];
                modelArgs = new ArrayList<String>();
                int nidx = maybeCollectArgs(pargs, ++idx, modelArgs);
                if (nidx == idx) {
                    modelArgs = null;
                }
                idx = nidx;
            } else if ("-script".equals(pargs[pidx])) {
                scriptFile.value = pargs[++idx];
                scriptArgs = new ArrayList<String>();
                int nidx = maybeCollectArgs(pargs, ++idx, scriptArgs);
                if (nidx == idx) {
                    scriptArgs = null;
                }
                idx = nidx;
            } else if ("-taskManager".equals(pargs[pidx])) {
                taskManagerClassName.value = pargs[++idx];
                taskManagerArgs = new ArrayList<String>();
                int nidx = maybeCollectArgs(pargs, ++idx, taskManagerArgs);
                if (nidx == idx) {
                    taskManagerArgs = null;
                }
                idx = nidx;
            } else {
                idx = parser.matchArg(pargs, idx);
            }
            String unmatched;
            if ((unmatched = parser.getUnmatchedArgument()) != null) {
                boolean valid = false;
                if (!valid) {
                    System.err.println("Unrecognized argument: " + unmatched + "\nUse -help for help information");
                    return;
                }
            } else {
                lastSwitch = pidx;
            }
        } catch (Exception e) {
            System.err.println("Error parsing options: " + e.getMessage());
            return;
        }
    }
    // parser.matchAllArgs (progArgs.toArray(new String[0]));
    if (printOptions.value || printHelp.value) {
        System.out.println(parser.getOptionsMessage(2));
        System.out.println("  -model <string> [ <string>... ]\n" + "                        name of model to start, with optional arguments\n" + "                        delimited by square brackets\n" + "  -script <string> [ <string>... ]\n" + "                        script to run immediately, with optional arguments\n" + "                        delimited by square brackets\n" + "  -taskManager <className> [ <string>... ]\n" + "                        name of task manager class to run immediately, with\n" + "                        optional arguments delimited by square brackets\n");
        return;
    }
    // Set system logger level
    Logger.getSystemLogger().setLogLevel(LogLevel.find(logLevel.value));
    MechSystemSolver.myDefaultHybridSolveP = !disableHybridSolves.value;
    if (numSolverThreads.value > 0) {
        PardisoSolver.setDefaultNumThreads(numSolverThreads.value);
    }
    FemModel3d.abortOnInvertedElems = abortOnInvertedElems.value;
    // }
    if (posCorrection.value.equals("GlobalMass")) {
        MechSystemBase.setDefaultStabilization(PosStabilization.GlobalMass);
    } else if (posCorrection.value.equals("GlobalStiffness")) {
        MechSystemBase.setDefaultStabilization(PosStabilization.GlobalStiffness);
    }
    FemModel3d.noIncompressStiffnessDamping = noIncompressDamping.value;
    if (useAjlCollision.value) {
        CollisionManager.setDefaultColliderType(ColliderType.AJL_CONTOUR);
    }
    if (testSaveRestoreState.value) {
        RootModel.testSaveAndRestoreState = true;
    }
    if (useGLJPanel.value == true) {
        maspack.render.GL.GLViewer.useGLJPanel = true;
    }
    if (noGui.value == true) {
        viewerWidth.value = -1;
    }
    GLVersion glv = (glVersion.value == 3 ? GLVersion.GL3 : GLVersion.GL2);
    Main m = new Main(PROJECT_NAME, viewerWidth.value, viewerHeight.value, glv);
    m.setArticulatedTransformsEnabled(useArticulatedTransforms.value);
    if (axialView.value.equals("xy")) {
        m.setDefaultViewOrientation(AxisAngle.IDENTITY);
    } else if (axialView.value.equals("xz")) {
        m.setDefaultViewOrientation(AxisAngle.ROT_X_90);
    } else {
        throw new InternalErrorException("Unknown axial view: " + axialView.value);
    }
    if (m.myFrame != null) {
        m.myViewer.setBackgroundColor(bgColor[0], bgColor[1], bgColor[2]);
        // XXX this should be done in the Main constructor, but needs
        // to be done here instead because of sizing effects
        m.myMenuBarHandler.initToolbar();
        if (movieMethod.value != null) {
            MovieMaker movieMaker = m.getMovieMaker();
            try {
                movieMaker.setMethod(movieMethod.value);
            } catch (Exception e) {
                System.out.println("Warning: unknown movie making method " + movieMethod.value);
            }
        }
        if (movieFrameRate.value != -1) {
            MovieMaker movieMaker = m.getMovieMaker();
            try {
                movieMaker.setFrameRate(movieFrameRate.value);
            } catch (Exception e) {
                System.out.println("Warning: illegal movie frame rate " + movieFrameRate.value);
            }
        }
    }
    if (mousePrefs.value != null && m.myViewer != null) {
        m.setMouseBindings(mousePrefs.value);
    }
    m.setFlags(flags.value);
    if (useBodyVelsInSolve.value) {
        Frame.dynamicVelInWorldCoords = false;
    }
    m.start(startWithTimeline.value, timelineRight.value, largeTimeline.value);
    // because setting it earlier can cause incorrect results
    if (m.myFrame != null) {
        m.setViewerSize(viewerWidth.value, viewerHeight.value);
    }
    if (System.getProperty("os.name").contains("Windows")) {
        // XXX see function docs
        fixPardisoThreadCountHack();
    }
    m.verifyNativeLibraries(updateLibs.value);
    // the whole frame to be visible
    if (m.myFrame != null && orthographic.value) {
        m.getViewer().setOrthographicView(true);
    }
    // XXX store model arguments for future use?
    if (modelArgs != null) {
        m.myModelArgs = modelArgs.toArray(new String[modelArgs.size()]);
    }
    if (modelName.value != null) {
        // load the specified model. See first if the name corresponds to a file
        File file = new File(modelName.value);
        if (file.exists() && file.canRead()) {
            try {
                m.loadModelFile(file);
            } catch (IOException e) {
                System.out.println("Error reading or loading model file " + modelName.value);
                e.printStackTrace();
                m.setRootModel(new RootModel(), null, null);
            }
        } else // otherwise, try to determine the model from the class name or alias
        {
            String className = m.getDemoClassName(modelName.value);
            if (className == null) {
                System.out.println("No class associated with model name " + modelName.value);
                m.setRootModel(new RootModel(), null, null);
            } else {
                String name = modelName.value;
                if (name.indexOf('.') != -1) {
                    name = name.substring(name.lastIndexOf('.') + 1);
                    if (name.length() == 0) {
                        name = "Unknown";
                    }
                }
                // load the model
                ModelInfo mi = new ModelInfo(className, name, createArgArray(modelArgs));
                m.loadModel(mi);
            }
        }
    } else {
        m.setRootModel(new RootModel(), null, null);
    }
    if (exitOnBreak.value) {
        m.myScheduler.addListener(new QuitOnBreakListener(m));
    }
    if (playFor.value > 0) {
        m.play(playFor.value);
    } else if (play.value) {
        m.play();
    }
    if (scriptFile.value != null && taskManagerClassName.value != null) {
        System.out.println("Cannot specify both a script (option '-script') and a task manager (option \n" + "'-taskManager' at the same time");
        System.exit(1);
    } else if (scriptFile.value != null) {
        m.runScriptFile(scriptFile.value, scriptArgs);
    } else if (taskManagerClassName.value != null) {
        m.runTaskManager(taskManagerClassName.value, taskManagerArgs);
    }
    if (m.myJythonConsole != null && m.myJythonFrame == null) {
        m.myJythonConsole.interact();
    }
    if (openMatlab.value) {
        m.openMatlabConnection();
    }
}
Also used : RootModel(artisynth.core.workspace.RootModel) InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) InternalErrorException(maspack.util.InternalErrorException) IOException(java.io.IOException) ArgParser(argparser.ArgParser) URL(java.net.URL) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) InternalErrorException(maspack.util.InternalErrorException) WayPoint(artisynth.core.probes.WayPoint) GLVersion(maspack.render.GL.GLViewer.GLVersion) MovieMaker(artisynth.core.moviemaker.MovieMaker) File(java.io.File)

Example 24 with RootModel

use of artisynth.core.workspace.RootModel in project artisynth_core by artisynth.

the class MenuBarHandler method doClearModel.

private void doClearModel() {
    myMain.clearRootModel();
    myMain.setRootModel(new RootModel(), null, null);
}
Also used : RootModel(artisynth.core.workspace.RootModel)

Example 25 with RootModel

use of artisynth.core.workspace.RootModel in project artisynth_core by artisynth.

the class MenuBarHandler method createApplicationMenu.

private void createApplicationMenu(JMenu menu) {
    RootModel rootModel = myMain.getRootModel();
    ArrayList<Object> items = getApplicationMenuItems(rootModel);
    if (items != null) {
        for (int i = 0; i < items.size(); i++) {
            Object item = items.get(i);
            if (item instanceof JMenuItem) {
                menu.add((JMenuItem) item);
            } else if (item instanceof JSeparator && i == items.size() - 1) {
            // ignore
            } else if (item instanceof Component) {
                menu.add((Component) item);
            } else if (item instanceof String) {
                menu.add((String) item);
            } else {
            // ignore
            }
        }
    }
}
Also used : RootModel(artisynth.core.workspace.RootModel) JMenuItem(javax.swing.JMenuItem) Component(java.awt.Component) ModelComponent(artisynth.core.modelbase.ModelComponent) CompositeComponent(artisynth.core.modelbase.CompositeComponent) JSeparator(javax.swing.JSeparator)

Aggregations

RootModel (artisynth.core.workspace.RootModel)44 ModelComponent (artisynth.core.modelbase.ModelComponent)10 InternalErrorException (maspack.util.InternalErrorException)7 IOException (java.io.IOException)6 WayPoint (artisynth.core.probes.WayPoint)4 FileNotFoundException (java.io.FileNotFoundException)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 Probe (artisynth.core.probes.Probe)3 WayPointProbe (artisynth.core.probes.WayPointProbe)3 File (java.io.File)3 Property (maspack.properties.Property)3 ControlPanel (artisynth.core.gui.ControlPanel)2 CompositeComponent (artisynth.core.modelbase.CompositeComponent)2 TracingProbe (artisynth.core.probes.TracingProbe)2 Point (java.awt.Point)2 JFileChooser (javax.swing.JFileChooser)2 JMenuItem (javax.swing.JMenuItem)2 JSeparator (javax.swing.JSeparator)2 CompositeProperty (maspack.properties.CompositeProperty)2 ArgParser (argparser.ArgParser)1