예제 #1
0
def load(simulationWindow, jsonStream):
    """Loads the simulation from jsonStream and returns it.

    The logic of loading is the following:

    1. We create the graph of objects from ``json.load()``. When initialized,
       each object stores its JSON data.
    2. When all the objects are created, we call the
       :meth:`~ts2.simulation.Simulation.initialize` method of the
       :class:`~ts2.simulation.Simulation` which calls in turn the
       ``initialize()`` method of each object.

    This method will create all the missing links between the object and the
    simulation (and other objects).

    :param simulationWindow:
    :param jsonStream:
    """
    simulation = json.load(jsonStream, object_hook=json_hook, encoding='utf-8')
    if not isinstance(simulation, Simulation):
        raise utils.FormatException(
            translate("simulation.load",
                      "Loaded file is not a TS2 simulation"))
    simulation.initialize(simulationWindow)
    return simulation
예제 #2
0
    def checkTrackItemsLinks(self):
        """
        :return: Checks that all :class:`~ts2.scenery.abstract.TrackItem`'s are
        linked together
        :raises FormatException if items are not linked.

        """
        for ti in self._trackItems.values():
            if not isinstance(ti, placeitem.Place) \
                    and not isinstance(ti, platformitem.PlatformItem) \
                    and not isinstance(ti, textitem.TextItem):
                if ti.nextItem is None and not isinstance(ti, enditem.EndItem):
                    raise utils.FormatException(
                        "Item %s not linked to a next item" % ti.tiId)
                if ti.previousItem is None:
                    raise utils.FormatException(
                        "Item %s not linked to a previous item" % ti.tiId)
예제 #3
0
파일: simulation.py 프로젝트: zky001/ts2
    def initialize(self, simulationWindow):
        """Initializes the simulation.

        :param simulationWindow:
        """
        self.messageLogger.addMessage(self.tr("Simulation initializing"),
                                      logger.Message.SOFTWARE_MSG)
        self.simulationWindow = simulationWindow
        self.updatePlaces()
        for ti in self._trackItems.values():
            ti.initialize(self)
        if not self.checkTrackItemsLinks():
            self.messageLogger.addMessage(
                self.tr("Invalid simulation: Not all items are linked."),
                logger.Message.SOFTWARE_MSG)
            raise utils.FormatException(
                self.tr("Invalid simulation: Not all items are linked."))

        for rte in self.routes.values():
            rte.initialize(self)
        for rte in self.routes.values():
            # We need routes initialized before setting them up
            rte.setToInitialState()
        for ti in self.trackItems.values():
            # We need trackItems linked and routes set before setting triggers
            ti.setupTriggers()
        for trainType in self.trainTypes.values():
            trainType.initialize(self)
        for service in self.services.values():
            service.initialize(self)
        for train in self.trains:
            train.initialize(self)
        self._trains.sort(
            key=lambda x: x.currentService.lines and x.currentService.lines[
                0].scheduledDepartureTimeStr or x.currentService.serviceCode)
        self.messageLogger.initialize(self)

        self._scene.update()
        self._startTime = QtCore.QTime.fromString(self.option("currentTime"),
                                                  "hh:mm:ss")
        self._time = self._startTime
        self._timer.timeout.connect(self.timerOut)
        interval = 500
        self._timer.setInterval(interval)
        self._timer.start()
        self._scorer.score = self.option("currentScore")
        self.messageLogger.addMessage(self.tr("Simulation loaded"),
                                      logger.Message.SOFTWARE_MSG)
예제 #4
0
def load(editorWindow, jsonStream):
    """Loads the simulation from jsonStream and returns it as an Editor.

    The logic of loading is the following:
    1. We create the graph of objects from json.load(). When initialized,
    each object stores its JSON data.
    2. When all the objects are created, we call the initialize() method of the
    simulation which calls in turn the initialize() method of each object.
    This method will create all the missing links between the object and the
    simulation (and other objects)."""
    editor = json.load(jsonStream, object_hook=json_hook, encoding='utf-8')
    if not isinstance(editor, Editor):
        raise utils.FormatException(
            translate("simulation.load",
                      "Loaded file is not a TS2 simulation"))
    editor.initialize(editorWindow)
    return editor
예제 #5
0
 def trigger(signalItem):
     routeNums = []
     for rs in signalItem.routesSetParams.values():
         routeNums.extend(rs)
     for routeNum in routeNums:
         try:
             signalItem.simulation.routes[routeNum].routeSelected.connect(
                 signalItem.updateSignalState)
             signalItem.simulation.routes[routeNum].routeUnselected.connect(
                 signalItem.updateSignalState)
         except KeyError as err:
             raise utils.FormatException(
                 translate(
                     "RouteSetCondition",
                     "Error in simulation definition: SignalItem %s "
                     "references unknown route %s") %
                 (signalItem.tiId, str(err)))
예제 #6
0
 def trigger(signalItem):
     tiIds = []
     for tp in signalItem.trainPresentParams.values():
         tiIds.extend(tp)
     for tiId in tiIds:
         try:
             signalItem.simulation.trackItems[tiId].trainEntersItem.connect(
                 signalItem.updateSignalState)
             signalItem.simulation.trackItems[tiId].trainLeavesItem.connect(
                 signalItem.updateSignalState)
         except KeyError as err:
             raise utils.FormatException(
                 translate(
                     "TrainPresentOnItems",
                     "Error in simulation definition: SignalItem %s "
                     "references unknown track item %s") %
                 (signalItem.tiId, str(err)))
예제 #7
0
파일: simulation.py 프로젝트: zky001/ts2
def json_hook(dct):
    """Hook method for json.load()."""
    if not dct.get('__type__'):
        return dct
    elif dct['__type__'] == "Simulation":
        return Simulation(dct['options'], dct['trackItems'], dct['routes'],
                          dct['trainTypes'], dct['services'], dct['trains'],
                          dct['messageLogger'])
    elif dct['__type__'] == "SignalItem":
        return signalitem.SignalItem(parameters=dct)
    elif dct['__type__'] == "EndItem":
        return enditem.EndItem(parameters=dct)
    elif dct['__type__'] == "InvisibleLinkItem":
        return invisiblelinkitem.InvisibleLinkItem(parameters=dct)
    elif dct['__type__'] == "LineItem":
        return lineitem.LineItem(parameters=dct)
    elif dct['__type__'] == "Place":
        return placeitem.Place(parameters=dct)
    elif dct['__type__'] == "PlatformItem":
        return platformitem.PlatformItem(parameters=dct)
    elif dct['__type__'] == "PointsItem":
        return pointsitem.PointsItem(parameters=dct)
    elif dct['__type__'] == "TextItem":
        return textitem.TextItem(parameters=dct)
    elif dct['__type__'] == "Route":
        return route.Route(parameters=dct)
    elif dct['__type__'] == "Position":
        return position.Position(parameters=dct)
    elif dct['__type__'] == "TrainType":
        return trains.TrainType(parameters=dct)
    elif dct['__type__'] == "Service":
        return trains.Service(parameters=dct)
    elif dct['__type__'] == "ServiceLine":
        return trains.ServiceLine(parameters=dct)
    elif dct['__type__'] == "Train":
        return trains.Train(parameters=dct)
    elif dct['__type__'] == "MessageLogger":
        return logger.MessageLogger(parameters=dct)
    elif dct['__type__'] == "Message":
        return logger.Message(dct)
    else:
        raise utils.FormatException(
            translate("json_hook", "Unknown __type__ '%s' in JSON file") %
            dct['__type__'])