package org.opentrafficsim.draw.network; import java.rmi.RemoteException; import java.util.LinkedHashSet; import java.util.Set; import javax.naming.NamingException; import org.opentrafficsim.core.network.Network; import org.opentrafficsim.core.network.NetworkUtils; import nl.tudelft.simulation.dsol.animation.Locatable; import nl.tudelft.simulation.dsol.animation.D2.Renderable2DInterface; import nl.tudelft.simulation.dsol.simulators.AnimatorInterface; import nl.tudelft.simulation.dsol.simulators.SimulatorInterface; import nl.tudelft.simulation.naming.context.ContextInterface; import nl.tudelft.simulation.naming.context.util.ContextUtil; /** * NetworkAnimationUtils can make a deep clone of a network, including animation, and can destroy the animation. *

* Copyright (c) 2003-2021 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. * BSD-style license. See OpenTrafficSim License. *

* @author Alexander Verbraeck */ public final class NetworkAnimationUtils { /** */ private NetworkAnimationUtils() { // utility class } /** * Remove all objects and animation in the network. * @param network Network; the network to destroy * @param simulator SimulatorInterface.TimeDoubleUnit; the simulator of the old network */ public static void destroy(final Network network, final SimulatorInterface.TimeDoubleUnit simulator) { Set> animationObjects = new LinkedHashSet<>(); try { ContextInterface context = ContextUtil.lookupOrCreateSubContext(simulator.getReplication().getContext(), "animation/2D"); for (Object element : context.values()) { Renderable2DInterface animationObject = (Renderable2DInterface) element; animationObjects.add(animationObject); } for (Renderable2DInterface ao : animationObjects) { try { ao.destroy(simulator); } catch (Exception e) { // } } } catch (NamingException | RemoteException exception) { System.err.println("Error when destroying animation objects"); } // destroy the network, GTUs, Routes, etc. NetworkUtils.destroy(network); } /** * Remove all animation objects of the given class. * @param clazz Class<?>; the class to remove the animation objects for * @param oldSimulator SimulatorInterface.TimeDoubleUnit; the old simulator */ public static void removeAnimation(final Class clazz, final SimulatorInterface.TimeDoubleUnit oldSimulator) { if (!(oldSimulator instanceof AnimatorInterface)) { return; } try { ContextInterface context = ContextUtil.lookupOrCreateSubContext(oldSimulator.getReplication().getContext(), "animation/2D"); for (Object element : context.values()) { Renderable2DInterface animationObject = (Renderable2DInterface) element; Locatable locatable = animationObject.getSource(); if (clazz.isAssignableFrom(locatable.getClass())) { animationObject.destroy(oldSimulator); } } } catch (NamingException | RemoteException exception) { System.err.println("Error when destroying animation objects for class " + clazz.getSimpleName()); } } }