Browse Source

re-implented trailing calculations of train

lookup-tables
Stephan Richter 5 years ago
parent
commit
0ef617aa34
  1. 2
      pom.xml
  2. 4
      resources/translations/Application.de.translation
  3. 11
      src/main/java/de/srsoftware/web4rail/BaseClass.java
  4. 6
      src/main/java/de/srsoftware/web4rail/Plan.java
  5. 142
      src/main/java/de/srsoftware/web4rail/Route.java
  6. 17
      src/main/java/de/srsoftware/web4rail/actions/Action.java
  7. 12
      src/main/java/de/srsoftware/web4rail/actions/FreePreviousBlocks.java
  8. 166
      src/main/java/de/srsoftware/web4rail/moving/Train.java
  9. 48
      src/main/java/de/srsoftware/web4rail/tiles/Block.java
  10. 13
      src/main/java/de/srsoftware/web4rail/tiles/BlockH.java
  11. 7
      src/main/java/de/srsoftware/web4rail/tiles/BlockV.java
  12. 2
      src/main/java/de/srsoftware/web4rail/tiles/CrossH.java
  13. 11
      src/main/java/de/srsoftware/web4rail/tiles/StraightH.java
  14. 7
      src/main/java/de/srsoftware/web4rail/tiles/StraightV.java
  15. 33
      src/main/java/de/srsoftware/web4rail/tiles/StretchableTile.java
  16. 76
      src/main/java/de/srsoftware/web4rail/tiles/Tile.java

2
pom.xml

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>de.srsoftware</groupId> <groupId>de.srsoftware</groupId>
<artifactId>web4rail</artifactId> <artifactId>web4rail</artifactId>
<version>0.9.20</version> <version>0.10.1</version>
<name>Web4Rail</name> <name>Web4Rail</name>
<packaging>jar</packaging> <packaging>jar</packaging>
<description>Java Model Railway Control</description> <description>Java Model Railway Control</description>

4
resources/translations/Application.de.translation

@ -32,6 +32,7 @@ Emergency : Notfall
FinishRoute : Route abschließen FinishRoute : Route abschließen
FreeStartBlock : Start-Block freigeben FreeStartBlock : Start-Block freigeben
Hardware settings : Hardware-Einstellungen Hardware settings : Hardware-Einstellungen
Height : Höhe
Help : Hilfe Help : Hilfe
inverted : invertiert inverted : invertiert
learn : lernen learn : lernen
@ -103,4 +104,5 @@ Was not able to assign {} to {}! : Konnte {} nicht an {} zuweisen!
Was not able to lock {} : Konnte {} nicht reservieren Was not able to lock {} : Konnte {} nicht reservieren
Was not able to set all signals! : Konnte nicht alle Signale stellen! Was not able to set all signals! : Konnte nicht alle Signale stellen!
Was not able to set all turnouts! : Konnte nicht alle Weichen stellen! Was not able to set all turnouts! : Konnte nicht alle Weichen stellen!
WEST : Westen WEST : Westen
Width : Breite

11
src/main/java/de/srsoftware/web4rail/BaseClass.java

@ -0,0 +1,11 @@
package de.srsoftware.web4rail;
public class BaseClass implements Constants{
public static boolean isNull(Object o) {
return o==null;
}
public static boolean isSet(Object o) {
return o != null;
}
}

6
src/main/java/de/srsoftware/web4rail/Plan.java

@ -237,7 +237,7 @@ public class Plan implements Constants{
private String analyze() { private String analyze() {
Vector<Route> routes = new Vector<Route>(); Vector<Route> routes = new Vector<Route>();
for (Block block : blocks) { for (Block block : blocks) {
for (Connector con : block.startPoints()) routes.addAll(follow(new Route().start(block,con.from.inverse()),con)); for (Connector con : block.startPoints()) routes.addAll(follow(new Route().begin(block,con.from.inverse()),con));
} }
this.routes.clear(); this.routes.clear();
for (Tile tile : tiles.values()) tile.routes().clear(); for (Tile tile : tiles.values()) tile.routes().clear();
@ -586,7 +586,7 @@ public class Plan implements Constants{
private void remove(Tile tile) { private void remove(Tile tile) {
removeTile(tile.x,tile.y); removeTile(tile.x,tile.y);
if (tile instanceof Block) blocks.remove(tile); if (tile instanceof Block) blocks.remove(tile);
for (int i=1; i<tile.len(); i++) removeTile(tile.x+i, tile.y); // remove shadow tiles for (int i=1; i<tile.width(); i++) removeTile(tile.x+i, tile.y); // remove shadow tiles
for (int i=1; i<tile.height(); i++) removeTile(tile.x, tile.y+i); // remove shadow tiles for (int i=1; i<tile.height(); i++) removeTile(tile.x, tile.y+i); // remove shadow tiles
if (tile != null) stream("remove "+tile.id()); if (tile != null) stream("remove "+tile.id());
} }
@ -649,7 +649,7 @@ public class Plan implements Constants{
public void set(int x,int y,Tile tile) throws IOException { public void set(int x,int y,Tile tile) throws IOException {
if (tile == null) return; if (tile == null) return;
if (tile instanceof Block) blocks.add((Block) tile); if (tile instanceof Block) blocks.add((Block) tile);
for (int i=1; i<tile.len(); i++) set(x+i,y,new Shadow(tile)); for (int i=1; i<tile.width(); i++) set(x+i,y,new Shadow(tile));
for (int i=1; i<tile.height(); i++) set(x,y+i,new Shadow(tile)); for (int i=1; i<tile.height(); i++) set(x,y+i,new Shadow(tile));
setIntern(x,y,tile); setIntern(x,y,tile);
place(tile); place(tile);

142
src/main/java/de/srsoftware/web4rail/Route.java

@ -4,7 +4,6 @@ import java.io.BufferedWriter;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -26,7 +25,6 @@ import de.srsoftware.web4rail.actions.Action.Context;
import de.srsoftware.web4rail.actions.ActionList; import de.srsoftware.web4rail.actions.ActionList;
import de.srsoftware.web4rail.actions.ActivateRoute; import de.srsoftware.web4rail.actions.ActivateRoute;
import de.srsoftware.web4rail.actions.FinishRoute; import de.srsoftware.web4rail.actions.FinishRoute;
import de.srsoftware.web4rail.actions.FreePreviousBlocks;
import de.srsoftware.web4rail.actions.SetSignalsToStop; import de.srsoftware.web4rail.actions.SetSignalsToStop;
import de.srsoftware.web4rail.actions.SetSpeed; import de.srsoftware.web4rail.actions.SetSpeed;
import de.srsoftware.web4rail.conditions.Condition; import de.srsoftware.web4rail.conditions.Condition;
@ -36,6 +34,7 @@ import de.srsoftware.web4rail.tags.Checkbox;
import de.srsoftware.web4rail.tags.Fieldset; import de.srsoftware.web4rail.tags.Fieldset;
import de.srsoftware.web4rail.tags.Form; import de.srsoftware.web4rail.tags.Form;
import de.srsoftware.web4rail.tags.Input; import de.srsoftware.web4rail.tags.Input;
import de.srsoftware.web4rail.tags.Label;
import de.srsoftware.web4rail.tiles.Block; import de.srsoftware.web4rail.tiles.Block;
import de.srsoftware.web4rail.tiles.Contact; import de.srsoftware.web4rail.tiles.Contact;
import de.srsoftware.web4rail.tiles.Shadow; import de.srsoftware.web4rail.tiles.Shadow;
@ -49,7 +48,7 @@ import de.srsoftware.web4rail.tiles.Turnout.State;
* @author Stephan Richter, SRSoftware * @author Stephan Richter, SRSoftware
* *
*/ */
public class Route implements Constants{ public class Route extends BaseClass{
private static final Logger LOG = LoggerFactory.getLogger(Route.class); private static final Logger LOG = LoggerFactory.getLogger(Route.class);
static final String NAME = "name"; static final String NAME = "name";
static final String PATH = "path"; static final String PATH = "path";
@ -88,14 +87,14 @@ public class Route implements Constants{
*/ */
public static Object action(HashMap<String, String> params,Plan plan) throws IOException { public static Object action(HashMap<String, String> params,Plan plan) throws IOException {
Route route = plan.route(Integer.parseInt(params.get(ID))); Route route = plan.route(Integer.parseInt(params.get(ID)));
if (route == null) return t("Unknown route: {}",params.get(ID)); if (isNull(route)) return t("Unknown route: {}",params.get(ID));
switch (params.get(ACTION)) { switch (params.get(ACTION)) {
case ACTION_DROP: case ACTION_DROP:
String message = plan.remove(route); String message = plan.remove(route);
String tileId = params.get(Tile.class.getSimpleName()); String tileId = params.get(Tile.class.getSimpleName());
if (tileId != null) { if (isSet(tileId)) {
Tile tile = plan.get(tileId, false); Tile tile = plan.get(tileId, false);
if (tile != null) { if (isSet(tile)) {
plan.stream(message); plan.stream(message);
return tile.propMenu(); return tile.propMenu();
} }
@ -113,7 +112,7 @@ public class Route implements Constants{
private Object dropCodition(HashMap<String, String> params) { private Object dropCodition(HashMap<String, String> params) {
String condId = params.get(REALM_CONDITION); String condId = params.get(REALM_CONDITION);
if (condId != null) { if (isSet(condId)) {
int cid = Integer.parseInt(condId); int cid = Integer.parseInt(condId);
for (Condition condition : conditions) { for (Condition condition : conditions) {
if (condition.id() == cid) { if (condition.id() == cid) {
@ -130,12 +129,7 @@ public class Route implements Constants{
* @throws IOException * @throws IOException
*/ */
public void activate() throws IOException { public void activate() throws IOException {
for (Tile tile : path) { // TODO
if (!(tile instanceof Block)) tile.trainHead(train);
}
train.heading(endDirection.inverse());
endBlock.trainHead(train);
startBlock.trailingTrain(train);
} }
/** /**
@ -167,7 +161,7 @@ public class Route implements Constants{
*/ */
public void add(String trigger, Action action) { public void add(String trigger, Action action) {
ActionList actions = triggers.get(trigger); ActionList actions = triggers.get(trigger);
if (actions == null) { if (isNull(actions)) {
actions = new ActionList(); actions = new ActionList();
triggers.put(trigger, actions); triggers.put(trigger, actions);
} }
@ -224,7 +218,7 @@ public class Route implements Constants{
for (Contact c : contacts) { for (Contact c : contacts) {
Tag link = Plan.addLink(c,c.toString(),list); Tag link = Plan.addLink(c,c.toString(),list);
ActionList actions = triggers.get(c.trigger()); ActionList actions = triggers.get(c.trigger());
if (actions == null) { if (isNull(actions)) {
actions = new ActionList(); actions = new ActionList();
triggers.put(c.trigger(), actions); triggers.put(c.trigger(), actions);
} }
@ -240,9 +234,7 @@ public class Route implements Constants{
new Input(REALM,REALM_ROUTE).hideIn(form); new Input(REALM,REALM_ROUTE).hideIn(form);
new Input(ID,id()).hideIn(form); new Input(ID,id()).hideIn(form);
if (params.containsKey(CONTEXT)) new Input(CONTEXT,params.get(CONTEXT)).hideIn(form); if (params.containsKey(CONTEXT)) new Input(CONTEXT,params.get(CONTEXT)).hideIn(form);
Tag label = new Tag("label").content(t("name:")+NBSP); new Input(NAME, name()).style("width: 80%").addTo(new Label(t("name:")+NBSP)).addTo(form);
new Input(NAME, name()).style("width: 80%").addTo(label);
label.addTo(form);
new Checkbox(DISABLED, t("disabled"), disabled).addTo(form); new Checkbox(DISABLED, t("disabled"), disabled).addTo(form);
new Button(t("Apply"),form).addTo(form).addTo(win); new Button(t("Apply"),form).addTo(form).addTo(win);
@ -281,6 +273,18 @@ public class Route implements Constants{
return true; return true;
} }
public Route begin(Block block,Direction from) {
// add those fields to clone, too!
contacts = new Vector<Contact>();
signals = new Vector<Signal>();
path = new Vector<Tile>();
turnouts = new HashMap<>();
startBlock = block;
startDirection = from;
path.add(block);
return this;
}
protected Route clone() { protected Route clone() {
Route clone = new Route(); Route clone = new Route();
clone.startBlock = startBlock; clone.startBlock = startBlock;
@ -305,7 +309,6 @@ public class Route implements Constants{
Contact lastContact = contacts.lastElement(); Contact lastContact = contacts.lastElement();
add(lastContact.trigger(), new SetSpeed()); add(lastContact.trigger(), new SetSpeed());
add(lastContact.trigger(), new FinishRoute()); add(lastContact.trigger(), new FinishRoute());
add(lastContact.trigger(), new FreePreviousBlocks());
} }
} }
@ -315,13 +318,14 @@ public class Route implements Constants{
* @param trainHead * @param trainHead
*/ */
public void contact(Contact contact) { public void contact(Contact contact) {
traceTrainFrom(contact);
LOG.debug("{} on {} activated {}.",train,this,contact); LOG.debug("{} on {} activated {}.",train,this,contact);
ActionList actions = triggers.get(contact.trigger()); ActionList actions = triggers.get(contact.trigger());
if (actions == null) return; if (isNull(actions)) return;
Context context = new Context(contact); Context context = new Context(contact);
actions.fire(context); actions.fire(context);
} }
public Vector<Contact> contacts() { public Vector<Contact> contacts() {
return new Vector<>(contacts); return new Vector<>(contacts);
} }
@ -335,8 +339,11 @@ public class Route implements Constants{
} }
public void finish() { public void finish() {
reset(); setSignals(Signal.STOP);
train.block(endBlock, false); for (Tile tile : path) tile.setRoute(null);
Tile lastTile = path.lastElement();
if (lastTile instanceof Contact) lastTile.set(null);
train.set(endBlock);
train.heading(endDirection.inverse()); train.heading(endDirection.inverse());
} }
@ -344,7 +351,7 @@ public class Route implements Constants{
return setupActions.fire(context); return setupActions.fire(context);
} }
public boolean free() { public boolean isFree() {
for (int i=1; i<path.size(); i++) { for (int i=1; i<path.size(); i++) {
if (!path.get(i).isFree()) return false; if (!path.get(i).isFree()) return false;
} }
@ -414,7 +421,7 @@ public class Route implements Constants{
if (!setupActions.isEmpty()) json.put(ACTIONS, setupActions.json()); if (!setupActions.isEmpty()) json.put(ACTIONS, setupActions.json());
String name = name(); String name = name();
if (name != null) json.put(NAME, name); if (isSet(name)) json.put(NAME, name);
if (disabled) json.put(DISABLED, true); if (disabled) json.put(DISABLED, true);
@ -428,8 +435,8 @@ public class Route implements Constants{
endDirection = Direction.valueOf(json.getString(END_DIRECTION)); endDirection = Direction.valueOf(json.getString(END_DIRECTION));
for (Object tileId : pathIds) { for (Object tileId : pathIds) {
Tile tile = plan.get((String) tileId,false); Tile tile = plan.get((String) tileId,false);
if (startBlock == null) { if (isNull(startBlock)) {
start((Block) tile, startDirection); begin((Block) tile, startDirection);
} else if (tile instanceof Block) { // make sure, endDirection is set on last block } else if (tile instanceof Block) { // make sure, endDirection is set on last block
add(tile,endDirection); add(tile,endDirection);
} else { } else {
@ -482,19 +489,25 @@ public class Route implements Constants{
for (int i=0; i<arr.length(); i++) { for (int i=0; i<arr.length(); i++) {
JSONObject json = arr.getJSONObject(i); JSONObject json = arr.getJSONObject(i);
Condition condition = Condition.create(json.getString(TYPE)); Condition condition = Condition.create(json.getString(TYPE));
if (condition != null) conditions.add(condition.load(json)); if (isSet(condition)) conditions.add(condition.load(json));
} }
} }
public boolean lock() { public boolean lock() {
ArrayList<Tile> lockedTiles = new ArrayList<Tile>(); Vector<Tile> alreadyLocked = new Vector<Tile>();
try { boolean success = true;
for (Tile tile : path) lockedTiles.add(tile.setRoute(this)); for (Tile tile : path) {
} catch (IllegalStateException e) { try {
for (Tile tile: lockedTiles) tile.unlock(); tile.setRoute(this);
return false; } catch (IllegalStateException e) {
success = false;
break;
}
} }
return true; if (!success) for (Tile tile :alreadyLocked) {
tile.setRoute(null);
}
return success;
} }
public List<Route> multiply(int size) { public List<Route> multiply(int size) {
@ -505,7 +518,7 @@ public class Route implements Constants{
public String name() { public String name() {
String name = names.get(id()); String name = names.get(id());
if (name == null) { if (isNull(name)) {
name = generateName(); name = generateName();
name(name); name(name);
} }
@ -518,7 +531,7 @@ public class Route implements Constants{
public Vector<Tile> path() { public Vector<Tile> path() {
Vector<Tile> result = new Vector<Tile>(); Vector<Tile> result = new Vector<Tile>();
if (path != null) result.addAll(path); if (isSet(path)) result.addAll(path);
return result; return result;
} }
@ -533,18 +546,9 @@ public class Route implements Constants{
return win; return win;
} }
public void reset() { public boolean reset() {
new SetSignalsToStop().fire(new Context(this)); // TODO
for (Tile tile : path) { return false;
if (!(tile instanceof Block)) tile.unlock();
}
if (endBlock.route() == this) endBlock.setRoute(null);
if (startBlock.route() == this) startBlock.setRoute(null);
if (train != null) {
train.heading(startDirection);
train.block(startBlock, false);
if (train.route == this) train.route = null;
}
} }
public static void saveAll(Collection<Route> routes, String filename) throws IOException { public static void saveAll(Collection<Route> routes, String filename) throws IOException {
@ -561,14 +565,14 @@ public class Route implements Constants{
} }
public void setLast(State state) { public void setLast(State state) {
if (state == null || state == State.UNDEF) return; if (isNull(state) || state == State.UNDEF) return;
Tile lastTile = path.lastElement(); Tile lastTile = path.lastElement();
if (lastTile instanceof Turnout) addTurnout((Turnout) lastTile,state); if (lastTile instanceof Turnout) addTurnout((Turnout) lastTile,state);
} }
public boolean setSignals(String state) { public boolean setSignals(String state) {
for (Signal signal : signals) { for (Signal signal : signals) {
if (!signal.state(state == null ? Signal.GO : state)) return false; if (!signal.state(isNull(state) ? Signal.GO : state)) return false;
} }
return true; return true;
} }
@ -588,18 +592,6 @@ public class Route implements Constants{
} }
return true; return true;
} }
public Route start(Block block,Direction from) {
// add those fields to clone, too!
contacts = new Vector<Contact>();
signals = new Vector<Signal>();
path = new Vector<Tile>();
turnouts = new HashMap<>();
startBlock = block;
startDirection = from;
path.add(block);
return this;
}
public Block startBlock() { public Block startBlock() {
return startBlock; return startBlock;
@ -614,27 +606,35 @@ public class Route implements Constants{
return getClass().getSimpleName()+"("+name()+")"; return getClass().getSimpleName()+"("+name()+")";
} }
public boolean train(Train train) { private void traceTrainFrom(Tile tile) {
if (this.train != null && this.train != train) return false; Vector<Tile> trace = new Vector<Tile>();
this.train = train; for (Tile t:path) {
trace.add(t);
if (t == tile) break;
}
train.addToTrace(trace);
}
public boolean train(Train newTrain) {
if (isSet(train) && newTrain != train) return false;
train = newTrain;
return true; return true;
} }
public Route unlock() throws IOException { public Route unlock() throws IOException {
setSignals(Signal.STOP); // TODO
for (Tile tile : path) tile.unlock();
return this; return this;
} }
public Object update(HashMap<String, String> params,Plan plan) { public Object update(HashMap<String, String> params,Plan plan) {
LOG.debug("update({})",params); LOG.debug("update({})",params);
String name = params.get(NAME); String name = params.get(NAME);
if (name != null) name(name); if (isSet(name)) name(name);
disabled = "on".equals(params.get(DISABLED)); disabled = "on".equals(params.get(DISABLED));
Condition condition = Condition.create(params.get(REALM_CONDITION)); Condition condition = Condition.create(params.get(REALM_CONDITION));
if (condition != null) { if (isSet(condition)) {
conditions.add(condition); conditions.add(condition);
return properties(params); return properties(params);
} }

17
src/main/java/de/srsoftware/web4rail/actions/Action.java

@ -14,7 +14,7 @@ import org.slf4j.LoggerFactory;
import de.keawe.tools.translations.Translation; import de.keawe.tools.translations.Translation;
import de.srsoftware.tools.Tag; import de.srsoftware.tools.Tag;
import de.srsoftware.web4rail.Application; import de.srsoftware.web4rail.Application;
import de.srsoftware.web4rail.Constants; import de.srsoftware.web4rail.BaseClass;
import de.srsoftware.web4rail.Plan; import de.srsoftware.web4rail.Plan;
import de.srsoftware.web4rail.Route; import de.srsoftware.web4rail.Route;
import de.srsoftware.web4rail.Window; import de.srsoftware.web4rail.Window;
@ -23,7 +23,7 @@ import de.srsoftware.web4rail.tags.Label;
import de.srsoftware.web4rail.tags.Select; import de.srsoftware.web4rail.tags.Select;
import de.srsoftware.web4rail.tiles.Contact; import de.srsoftware.web4rail.tiles.Contact;
public abstract class Action implements Constants { public abstract class Action extends BaseClass {
private static final HashMap<Integer,Action> actions = new HashMap<Integer, Action>(); private static final HashMap<Integer,Action> actions = new HashMap<Integer, Action>();
public static final Logger LOG = LoggerFactory.getLogger(Action.class); public static final Logger LOG = LoggerFactory.getLogger(Action.class);
private static final String PREFIX = Action.class.getPackageName(); private static final String PREFIX = Action.class.getPackageName();
@ -50,6 +50,17 @@ public abstract class Action implements Constants {
this.route = route; this.route = route;
train = route.train; train = route.train;
} }
@Override
public String toString() {
StringBuffer sb = new StringBuffer(getClass().getSimpleName());
sb.append("(");
sb.append(t("Train: {}",train));
if (isSet(route)) sb.append(", "+t("Route: {}",route));
if (isSet(contact)) sb.append(", "+t("Contact: {}",contact));
sb.append(")");
return sb.toString();
}
} }
public Action() { public Action() {
@ -59,7 +70,6 @@ public abstract class Action implements Constants {
public static Action create(String type) { public static Action create(String type) {
try { try {
if (type.equals("FreeStartBlock")) type = FreePreviousBlocks.class.getSimpleName();
return (Action) Class.forName(PREFIX+"."+type).getDeclaredConstructor().newInstance(); return (Action) Class.forName(PREFIX+"."+type).getDeclaredConstructor().newInstance();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -92,7 +102,6 @@ public abstract class Action implements Constants {
ConditionalAction.class, ConditionalAction.class,
SetSpeed.class, SetSpeed.class,
SetSignalsToStop.class, SetSignalsToStop.class,
FreePreviousBlocks.class,
FinishRoute.class, FinishRoute.class,
TurnTrain.class, TurnTrain.class,
StopAuto.class, StopAuto.class,

12
src/main/java/de/srsoftware/web4rail/actions/FreePreviousBlocks.java

@ -1,12 +0,0 @@
package de.srsoftware.web4rail.actions;
import java.io.IOException;
public class FreePreviousBlocks extends Action {
@Override
public boolean fire(Context context) throws IOException {
if (context.train != null) context.train.resetPreviousBlocks();
return false;
}
}

166
src/main/java/de/srsoftware/web4rail/moving/Train.java

@ -8,6 +8,7 @@ import java.io.IOException;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Random; import java.util.Random;
@ -22,7 +23,7 @@ import org.slf4j.LoggerFactory;
import de.keawe.tools.translations.Translation; import de.keawe.tools.translations.Translation;
import de.srsoftware.tools.Tag; import de.srsoftware.tools.Tag;
import de.srsoftware.web4rail.Application; import de.srsoftware.web4rail.Application;
import de.srsoftware.web4rail.Constants; import de.srsoftware.web4rail.BaseClass;
import de.srsoftware.web4rail.Plan; import de.srsoftware.web4rail.Plan;
import de.srsoftware.web4rail.Plan.Direction; import de.srsoftware.web4rail.Plan.Direction;
import de.srsoftware.web4rail.Route; import de.srsoftware.web4rail.Route;
@ -36,8 +37,9 @@ import de.srsoftware.web4rail.tags.Input;
import de.srsoftware.web4rail.tags.Label; import de.srsoftware.web4rail.tags.Label;
import de.srsoftware.web4rail.tags.Select; import de.srsoftware.web4rail.tags.Select;
import de.srsoftware.web4rail.tiles.Block; import de.srsoftware.web4rail.tiles.Block;
import de.srsoftware.web4rail.tiles.Tile;
public class Train implements Comparable<Train>,Constants { public class Train extends BaseClass implements Comparable<Train> {
private static final Logger LOG = LoggerFactory.getLogger(Train.class); private static final Logger LOG = LoggerFactory.getLogger(Train.class);
public static final String HEAD = "train_head"; public static final String HEAD = "train_head";
@ -71,7 +73,7 @@ public class Train implements Comparable<Train>,Constants {
private Block block = null; private Block block = null;
private Vector<Block> previousBlocks = new Vector<Block>(); LinkedList<Tile> trace = new LinkedList<Tile>();
private class Autopilot extends Thread{ private class Autopilot extends Thread{
boolean stop = false; boolean stop = false;
@ -81,7 +83,7 @@ public class Train implements Comparable<Train>,Constants {
try { try {
stop = false; stop = false;
while (true) { while (true) {
if (route == null) { if (isNull(route)) {
Thread.sleep(2000); Thread.sleep(2000);
if (stop) return; if (stop) return;
Train.this.start(); Train.this.start();
@ -107,7 +109,7 @@ public class Train implements Comparable<Train>,Constants {
} }
public Train(Locomotive loco, Integer id) { public Train(Locomotive loco, Integer id) {
if (id == null) id = Application.createId(); if (isNull(id)) id = Application.createId();
this.id = id; this.id = id;
add(loco); add(loco);
trains.put(id, this); trains.put(id, this);
@ -115,7 +117,7 @@ public class Train implements Comparable<Train>,Constants {
public static Object action(HashMap<String, String> params, Plan plan) throws IOException { public static Object action(HashMap<String, String> params, Plan plan) throws IOException {
String action = params.get(ACTION); String action = params.get(ACTION);
if (action == null) return t("No action passed to Train.action!"); if (isNull(action)) return t("No action passed to Train.action!");
if (!params.containsKey(Train.ID)) { if (!params.containsKey(Train.ID)) {
switch (action) { switch (action) {
case ACTION_PROPS: case ACTION_PROPS:
@ -127,7 +129,7 @@ public class Train implements Comparable<Train>,Constants {
} }
int id = Integer.parseInt(params.get(Train.ID)); int id = Integer.parseInt(params.get(Train.ID));
Train train = trains.get(id); Train train = trains.get(id);
if (train == null) return(t("No train with id {}!",id)); if (isNull(train)) return(t("No train with id {}!",id));
switch (action) { switch (action) {
case ACTION_ADD: case ACTION_ADD:
return train.addCar(params); return train.addCar(params);
@ -151,17 +153,18 @@ public class Train implements Comparable<Train>,Constants {
return t("Unknown action: {}",params.get(ACTION)); return t("Unknown action: {}",params.get(ACTION));
} }
private Route chooseRoute(Context context) { HashSet<Route> routes = block.routes(); private Route chooseRoute(Context context) {
HashSet<Route> routes = block.routes();
Vector<Route> availableRoutes = new Vector<Route>(); Vector<Route> availableRoutes = new Vector<Route>();
for (Route rt : routes) { for (Route rt : routes) {
if (rt == route) continue; // andere Route als zuvor wählen if (rt == route) continue; // andere Route als zuvor wählen
if (rt.path().firstElement() != block) continue; // keine Route wählen, die nicht vom aktuellen Block des Zuges startet if (rt.path().firstElement() != block) continue; // keine Route wählen, die nicht vom aktuellen Block des Zuges startet
if (direction != null && rt.startDirection != direction) { // Route ist entgegen der Startrichtung des Zuges if (isSet(direction) && rt.startDirection != direction) { // Route ist entgegen der Startrichtung des Zuges
if (!pushPull || !block.turnAllowed) { // Zug ist kein Wendezug oder Block erlaubt kein Wenden if (!pushPull || !block.turnAllowed) { // Zug ist kein Wendezug oder Block erlaubt kein Wenden
continue; continue;
} }
} }
if (!rt.free()) { // keine belegten Routen wählen if (!rt.isFree()) { // keine belegten Routen wählen
LOG.debug("{} is not free!",rt); LOG.debug("{} is not free!",rt);
continue; continue;
} }
@ -180,7 +183,7 @@ public class Train implements Comparable<Train>,Constants {
public String directedName() { public String directedName() {
String result = name(); String result = name();
if (direction == null) return result; if (isNull(direction)) return result;
switch (direction) { switch (direction) {
case NORTH: case NORTH:
case WEST: case WEST:
@ -194,9 +197,9 @@ public class Train implements Comparable<Train>,Constants {
private Object dropCar(HashMap<String, String> params) { private Object dropCar(HashMap<String, String> params) {
String carId = params.get(CAR_ID); String carId = params.get(CAR_ID);
if (carId != null) cars.remove(Car.get(carId)); if (isSet(carId)) cars.remove(Car.get(carId));
String locoId = params.get(LOCO_ID); String locoId = params.get(LOCO_ID);
if (locoId != null) locos.remove(Car.get(locoId)); if (isSet(locoId)) locos.remove(Car.get(locoId));
return props(); return props();
} }
@ -204,7 +207,7 @@ public class Train implements Comparable<Train>,Constants {
LOG.debug("addCar({})",params); LOG.debug("addCar({})",params);
if (!params.containsKey(CAR_ID)) return t("No car id passed to Train.addCar!"); if (!params.containsKey(CAR_ID)) return t("No car id passed to Train.addCar!");
Car car = Car.get(params.get(CAR_ID)); Car car = Car.get(params.get(CAR_ID));
if (car == null) return t("No car with id \"{}\" known!",params.get(CAR_ID)); if (isNull(car)) return t("No car with id \"{}\" known!",params.get(CAR_ID));
if (car instanceof Locomotive) { if (car instanceof Locomotive) {
locos.add((Locomotive) car); locos.add((Locomotive) car);
} else cars.add(car); } else cars.add(car);
@ -212,7 +215,7 @@ public class Train implements Comparable<Train>,Constants {
} }
public void add(Car car) { public void add(Car car) {
if (car == null) return; if (isNull(car)) return;
if (car instanceof Locomotive) { if (car instanceof Locomotive) {
locos.add((Locomotive) car); locos.add((Locomotive) car);
} else cars.add(car); } else cars.add(car);
@ -220,29 +223,13 @@ public class Train implements Comparable<Train>,Constants {
} }
private String automatic() { private String automatic() {
if (autopilot == null) { if (isNull(autopilot)) {
autopilot = new Autopilot(); autopilot = new Autopilot();
autopilot.start(); autopilot.start();
} }
return t("{} now in auto-mode",this); return t("{} now in auto-mode",this);
} }
public Block block() {
return block;
}
public Train block(Block block, boolean resetPreviousBlocks) {
if (this.block == block) return this; // nothing to update
if (this.block != null) {
this.block.trailingTrain(this);
previousBlocks.add(this.block);
}
this.block = block;
block.trainHead(this);
if (resetPreviousBlocks) resetPreviousBlocks();
return this;
}
private Tag carList() { private Tag carList() {
Tag locoProp = new Tag("li").content(t("Cars:")); Tag locoProp = new Tag("li").content(t("Cars:"));
Tag locoList = new Tag("ul").clazz("carlist"); Tag locoList = new Tag("ul").clazz("carlist");
@ -273,7 +260,7 @@ public class Train implements Comparable<Train>,Constants {
private static Object create(HashMap<String, String> params, Plan plan) { private static Object create(HashMap<String, String> params, Plan plan) {
Locomotive loco = (Locomotive) Locomotive.get(params.get(Train.LOCO_ID)); Locomotive loco = (Locomotive) Locomotive.get(params.get(Train.LOCO_ID));
if (loco == null) return t("unknown locomotive: {}",params.get(ID)); if (isNull(loco)) return t("unknown locomotive: {}",params.get(ID));
Train train = new Train(loco).plan(plan); Train train = new Train(loco).plan(plan);
if (params.containsKey(NAME)) train.name(params.get(NAME)); if (params.containsKey(NAME)) train.name(params.get(NAME));
return train; return train;
@ -286,7 +273,7 @@ public class Train implements Comparable<Train>,Constants {
public Train heading(Direction dir) { public Train heading(Direction dir) {
direction = dir; direction = dir;
if (block != null) plan.place(block); if (isSet(block)) plan.place(block);
return this; return this;
} }
@ -294,10 +281,10 @@ public class Train implements Comparable<Train>,Constants {
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
json.put(ID, id); json.put(ID, id);
json.put(NAME,name); json.put(NAME,name);
if (route != null) json.put(ROUTE, route.id()); if (isSet(route)) json.put(ROUTE, route.id());
if (direction != null) json.put(DIRECTION, direction); if (isSet(direction)) json.put(DIRECTION, direction);
json.put(PUSH_PULL, pushPull); json.put(PUSH_PULL, pushPull);
if (name != null)json.put(NAME, name); if (isSet(name))json.put(NAME, name);
Vector<Integer> locoIds = new Vector<Integer>(); Vector<Integer> locoIds = new Vector<Integer>();
for (Locomotive loco : locos) locoIds.add(loco.id()); for (Locomotive loco : locos) locoIds.add(loco.id());
json.put(LOCOS, locoIds); json.put(LOCOS, locoIds);
@ -326,7 +313,7 @@ public class Train implements Comparable<Train>,Constants {
public static void loadAll(String filename, Plan plan) throws IOException { public static void loadAll(String filename, Plan plan) throws IOException {
BufferedReader file = new BufferedReader(new FileReader(filename)); BufferedReader file = new BufferedReader(new FileReader(filename));
String line = file.readLine(); String line = file.readLine();
while (line != null) { while (isSet(line)) {
JSONObject json = new JSONObject(line); JSONObject json = new JSONObject(line);
int id = json.getInt(ID); int id = json.getInt(ID);
@ -405,7 +392,7 @@ public class Train implements Comparable<Train>,Constants {
} }
public String name() { public String name() {
return (name != null ? name : locos.firstElement().name()); return (isSet(name) ? name : locos.firstElement().name());
} }
private Train name(String newName) { private Train name(String newName) {
@ -441,11 +428,11 @@ public class Train implements Comparable<Train>,Constants {
carList().addTo(propList); carList().addTo(propList);
new Tag("li").content(t("length: {}",length())).addTo(propList); new Tag("li").content(t("length: {}",length())).addTo(propList);
if (block != null) { if (isSet(block)) {
new Tag("li").content(t("Current location: {}",block)).addTo(propList); new Tag("li").content(t("Current location: {}",block)).addTo(propList);
Tag actions = new Tag("li").clazz().content(t("Actions:")+NBSP); Tag actions = new Tag("li").clazz().content(t("Actions:")+NBSP);
new Button(t("start"),"train("+id+",'"+ACTION_START+"')").addTo(actions); new Button(t("start"),"train("+id+",'"+ACTION_START+"')").addTo(actions);
if (autopilot == null) { if (isNull(autopilot)) {
new Button(t("auto"),"train("+id+",'"+ACTION_AUTO+"')").addTo(actions); new Button(t("auto"),"train("+id+",'"+ACTION_AUTO+"')").addTo(actions);
} else { } else {
new Button(t("quit autopilot"),"train("+id+",'"+ACTION_QUIT+"')").addTo(actions); new Button(t("quit autopilot"),"train("+id+",'"+ACTION_QUIT+"')").addTo(actions);
@ -453,10 +440,10 @@ public class Train implements Comparable<Train>,Constants {
actions.addTo(propList); actions.addTo(propList);
} }
if (route != null) { if (isSet(route)) {
new Tag("li").content(t("Current route: {}",route)).addTo(propList); new Tag("li").content(t("Current route: {}",route)).addTo(propList);
} }
if (direction != null) new Tag("li").content(t("Direction: heading {}",direction)).addTo(propList); if (isSet(direction)) new Tag("li").content(t("Direction: heading {}",direction)).addTo(propList);
Tag tagList = new Tag("ul"); Tag tagList = new Tag("ul");
for (String tag : tags()) new Tag("li").content(tag).addTo(tagList); for (String tag : tags()) new Tag("li").content(tag).addTo(tagList);
@ -474,26 +461,13 @@ public class Train implements Comparable<Train>,Constants {
} }
public Object quitAutopilot() { public Object quitAutopilot() {
if (autopilot != null) { if (isSet(autopilot)) {
autopilot.stop = true; autopilot.stop = true;
autopilot = null; autopilot = null;
return t("{} stopping at next block.",this); return t("{} stopping at next block.",this);
} else return t("autopilot not active."); } else return t("autopilot not active.");
} }
public void removeFromBlock(Block block) {
if (block.trainHead() == this) block.trainHead(null);
if (this.block == block) this.block = null;
previousBlocks.remove(block);
}
public void resetPreviousBlocks() {
for (Block block : previousBlocks) {
if (block.trainHead() == this || block.trailingTrain() == this) block.unlock();
}
previousBlocks.clear();
}
public static void saveAll(String filename) throws IOException { public static void saveAll(String filename) throws IOException {
BufferedWriter file = new BufferedWriter(new FileWriter(filename)); BufferedWriter file = new BufferedWriter(new FileWriter(filename));
for (Entry<Integer, Train> entry:trains.entrySet()) { for (Entry<Integer, Train> entry:trains.entrySet()) {
@ -504,7 +478,7 @@ public class Train implements Comparable<Train>,Constants {
} }
public static Select selector(Train preselected,Collection<Train> exclude) { public static Select selector(Train preselected,Collection<Train> exclude) {
if (exclude == null) exclude = new Vector<Train>(); if (isNull(exclude)) exclude = new Vector<Train>();
Select select = new Select(Train.HEAD); Select select = new Select(Train.HEAD);
new Tag("option").attr("value","0").content(t("unset")).addTo(select); new Tag("option").attr("value","0").content(t("unset")).addTo(select);
for (Train train : Train.list()) { for (Train train : Train.list()) {
@ -522,21 +496,23 @@ public class Train implements Comparable<Train>,Constants {
} }
public String start() throws IOException { public String start() throws IOException {
if (block == null) return t("{} not in a block",this); if (isNull(block)) return t("{} not in a block",this);
if (route != null) route.reset(); // reset route previously chosen Context context = isSet(route) ? new Context( route ) : new Context( this);
Context context = new Context(this);
route = chooseRoute(context);
if (route == null) return t("No free routes from {}",block);
if (isSet(context.route)) context.route.reset(); // reset route previously chosen
route = chooseRoute(context);
if (isNull(route)) return t("No free routes from {}",block);
if (!route.lock()) return t("Was not able to lock {}",route); if (!route.lock()) return t("Was not able to lock {}",route);
if (direction != route.startDirection) turn(); if (direction != route.startDirection) turn();
String error = null; String error = null;
if (!route.setTurnouts()) error = t("Was not able to set all turnouts!"); if (!route.setTurnouts()) error = t("Was not able to set all turnouts!");
if (error == null && !route.fireSetupActions(context)) error = t("Was not able to fire all setup actions of route!"); if (isNull(error) && !route.fireSetupActions(context)) error = t("Was not able to fire all setup actions of route!");
if (error == null && !route.setSignals(null)) error = t("Was not able to set all signals!"); if (isNull(error) && !route.setSignals(null)) error = t("Was not able to set all signals!");
if (error == null && !route.train(this)) error = t("Was not able to assign {} to {}!",this,route); if (isNull(error) && !route.train(this)) error = t("Was not able to assign {} to {}!",this,route);
if (error != null) { if (isSet(error)) {
route.reset(); route.reset();
return error; return error;
} }
@ -547,13 +523,6 @@ public class Train implements Comparable<Train>,Constants {
private Object stopNow() { private Object stopNow() {
quitAutopilot(); quitAutopilot();
setSpeed(0); setSpeed(0);
if (route != null) try {
route.unlock();
route.endBlock().trainHead(null);
route.startBlock().trainHead(this);
} catch (IOException e) {
e.printStackTrace();
}
route = null; route = null;
return t("Stopped {}.",this); return t("Stopped {}.",this);
} }
@ -564,16 +533,15 @@ public class Train implements Comparable<Train>,Constants {
@Override @Override
public String toString() { public String toString() {
return name != null ? name : locos.firstElement().name(); return isSet(name) ? name : locos.firstElement().name();
} }
public Object turn() { public Object turn() {
LOG.debug("train.turn()"); LOG.debug("train.turn()");
if (direction != null) { if (isSet(direction)) {
direction = direction.inverse(); direction = direction.inverse();
for (Locomotive loco : locos) loco.turn(); for (Locomotive loco : locos) loco.turn();
} }
if (block != null) plan.place(block.trainHead(this));
return t("{} turned.",this); return t("{} turned.",this);
} }
@ -593,4 +561,48 @@ public class Train implements Comparable<Train>,Constants {
return this; return this;
} }
public void set(Block newBlock) {
block = newBlock;
if (isSet(block)) block.set(this);
}
public Tile headPos() {
return trace.getFirst();
}
public void addToTrace(Vector<Tile> newTiles) {
boolean active = trace.isEmpty();
for (Tile tile : newTiles) {
if (active) {
trace.addFirst(tile);
System.err.println(trace);
} else {
Tile dummy = trace.getFirst();
if (dummy == tile) {
active = true;
};
}
}
showTrace();
}
public void showTrace() {
int remainingLength = length();
for (int i=0; i<trace.size(); i++) {
Tile tile = trace.get(i);
if (remainingLength>0) {
remainingLength-=tile.length();
tile.set(this);
} else {
tile.set(null);
trace.remove(i);
i--; // do not move to next index: remove shifted the next index towards us
}
}
}
public void dropTrace() {
while (!trace.isEmpty()) trace.removeFirst().set(null);
}
} }

48
src/main/java/de/srsoftware/web4rail/tiles/Block.java

@ -22,7 +22,6 @@ public abstract class Block extends StretchableTile{
private static final String ALLOW_TURN = "allowTurn"; private static final String ALLOW_TURN = "allowTurn";
public boolean turnAllowed = false; public boolean turnAllowed = false;
private Train trailingTrain = null;
@Override @Override
public JSONObject config() { public JSONObject config() {
@ -30,11 +29,6 @@ public abstract class Block extends StretchableTile{
config.put(NAME, name); config.put(NAME, name);
return config; return config;
} }
@Override
public boolean isFree() {
return super.isFree() && trailingTrain == null;
}
@Override @Override
public JSONObject json() { public JSONObject json() {
@ -61,7 +55,7 @@ public abstract class Block extends StretchableTile{
new Checkbox(ALLOW_TURN,t("Turn allowed"),turnAllowed).addTo(new Tag("p")).addTo(form); new Checkbox(ALLOW_TURN,t("Turn allowed"),turnAllowed).addTo(new Tag("p")).addTo(form);
Select select = Train.selector(trainHead, null); Select select = Train.selector(train, null);
select.addTo(new Label(t("Train:")+NBSP)).addTo(new Tag("p")).addTo(form); select.addTo(new Label(t("Train:")+NBSP)).addTo(new Tag("p")).addTo(form);
return form; return form;
@ -71,10 +65,10 @@ public abstract class Block extends StretchableTile{
public Tag propMenu() { public Tag propMenu() {
Tag window = super.propMenu(); Tag window = super.propMenu();
if (trainHead != null) { if (isSet(train)) {
window.children().insertElementAt(new Button(t("stop"),"train("+trainHead.id+",'"+ACTION_STOP+"')"), 1); window.children().insertElementAt(new Button(t("stop"),"train("+train.id+",'"+ACTION_STOP+"')"), 1);
window.children().insertElementAt(new Button(t("start"),"train("+trainHead.id+",'"+ACTION_START+"')"), 1); window.children().insertElementAt(new Button(t("start"),"train("+train.id+",'"+ACTION_START+"')"), 1);
window.children().insertElementAt(trainHead.link("span"), 1); window.children().insertElementAt(train.link("span"), 1);
window.children().insertElementAt(new Tag("h4").content(t("Train:")), 1); window.children().insertElementAt(new Tag("h4").content(t("Train:")), 1);
} }
return window; return window;
@ -84,12 +78,11 @@ public abstract class Block extends StretchableTile{
@Override @Override
public Tag tag(Map<String, Object> replacements) throws IOException { public Tag tag(Map<String, Object> replacements) throws IOException {
if (replacements == null) replacements = new HashMap<String, Object>(); if (isNull(replacements)) replacements = new HashMap<String, Object>();
replacements.put("%text%",name); replacements.put("%text%",name);
if (trailingTrain != null) replacements.put("%text%","("+trailingTrain.name()+")"); if (isSet(train)) replacements.put("%text%",train.directedName());
if (trainHead != null) replacements.put("%text%",trainHead.directedName());
Tag tag = super.tag(replacements); Tag tag = super.tag(replacements);
if (trainHead != null || trailingTrain != null) tag.clazz(tag.get("class")+" occupied"); if (isSet(train)) tag.clazz(tag.get("class")+" occupied");
return tag; return tag;
} }
@ -103,32 +96,19 @@ public abstract class Block extends StretchableTile{
return getClass().getSimpleName()+"("+name+") @ ("+x+","+y+")"; return getClass().getSimpleName()+"("+name+") @ ("+x+","+y+")";
} }
public void trailingTrain(Train train) {
trailingTrain = train;
this.trainHead = null;
plan.place(this);
}
public Train trailingTrain() {
return trailingTrain;
}
@Override
public void unlock() {
trailingTrain = null;
super.unlock();
}
@Override @Override
public Tile update(HashMap<String, String> params) throws IOException { public Tile update(HashMap<String, String> params) throws IOException {
if (params.containsKey(NAME)) name=params.get(NAME); if (params.containsKey(NAME)) name=params.get(NAME);
if (params.containsKey(Train.HEAD)) { if (params.containsKey(Train.HEAD)) {
int trainId = Integer.parseInt(params.get(Train.HEAD)); int trainId = Integer.parseInt(params.get(Train.HEAD));
if (trainId == 0) { if (trainId == 0) {
trainHead(null); train = null;
} else { } else {
Train t = Train.get(trainId); Train dummy = Train.get(trainId);
if (t != null) trainHead = t.block(this,true); if (isSet(dummy) && dummy != train) {
dummy.set(this);
dummy.dropTrace();
}
} }
} }
turnAllowed = params.containsKey(ALLOW_TURN) && params.get(ALLOW_TURN).equals("on"); turnAllowed = params.containsKey(ALLOW_TURN) && params.get(ALLOW_TURN).equals("on");

13
src/main/java/de/srsoftware/web4rail/tiles/BlockH.java

@ -15,7 +15,7 @@ public class BlockH extends Block{
public Map<Connector, State> connections(Direction from) { public Map<Connector, State> connections(Direction from) {
switch (from) { switch (from) {
case WEST: case WEST:
return Map.of(new Connector(x+len(),y,Direction.WEST),State.UNDEF); return Map.of(new Connector(x+width(),y,Direction.WEST),State.UNDEF);
case EAST: case EAST:
return Map.of(new Connector(x-1,y,Direction.EAST),State.UNDEF); return Map.of(new Connector(x-1,y,Direction.EAST),State.UNDEF);
default: default:
@ -24,12 +24,17 @@ public class BlockH extends Block{
} }
@Override @Override
public int len() { public int width() {
return length; return stretch;
} }
@Override @Override
public List<Connector> startPoints() { public List<Connector> startPoints() {
return List.of(new Connector(x-1, y, Direction.EAST),new Connector(x+len(), y, Direction.WEST)); return List.of(new Connector(x-1, y, Direction.EAST),new Connector(x+width(), y, Direction.WEST));
}
@Override
protected String stretchType() {
return t("Width");
} }
} }

7
src/main/java/de/srsoftware/web4rail/tiles/BlockV.java

@ -25,11 +25,16 @@ public class BlockV extends Block{
@Override @Override
public int height() { public int height() {
return length; return stretch;
} }
@Override @Override
public List<Connector> startPoints() { public List<Connector> startPoints() {
return List.of(new Connector(x,y-1,Direction.SOUTH),new Connector(x,y+height(),Direction.NORTH)); return List.of(new Connector(x,y-1,Direction.SOUTH),new Connector(x,y+height(),Direction.NORTH));
}
@Override
protected String stretchType() {
return t("Height");
} }
} }

2
src/main/java/de/srsoftware/web4rail/tiles/CrossH.java

@ -24,7 +24,7 @@ public class CrossH extends Cross{
} }
@Override @Override
public int len() { public int width() {
return 2; return 2;
} }

11
src/main/java/de/srsoftware/web4rail/tiles/StraightH.java

@ -15,7 +15,7 @@ public class StraightH extends StretchableTile{
if (oneWay == from) return new HashMap<>(); if (oneWay == from) return new HashMap<>();
switch (from) { switch (from) {
case WEST: case WEST:
return Map.of(new Connector(x+len(),y,Direction.WEST),State.UNDEF); return Map.of(new Connector(x+width(),y,Direction.WEST),State.UNDEF);
case EAST: case EAST:
return Map.of(new Connector(x-1,y,Direction.EAST),State.UNDEF); return Map.of(new Connector(x-1,y,Direction.EAST),State.UNDEF);
default: default:
@ -24,12 +24,17 @@ public class StraightH extends StretchableTile{
} }
@Override @Override
public int len() { public int width() {
return length; return stretch;
} }
@Override @Override
public List<Direction> possibleDirections() { public List<Direction> possibleDirections() {
return List.of(Direction.EAST,Direction.WEST); return List.of(Direction.EAST,Direction.WEST);
} }
@Override
protected String stretchType() {
return t("Width");
}
} }

7
src/main/java/de/srsoftware/web4rail/tiles/StraightV.java

@ -25,11 +25,16 @@ public class StraightV extends StretchableTile{
@Override @Override
public int height() { public int height() {
return length; return stretch;
} }
@Override @Override
public List<Direction> possibleDirections() { public List<Direction> possibleDirections() {
return List.of(Direction.NORTH,Direction.SOUTH); return List.of(Direction.NORTH,Direction.SOUTH);
} }
@Override
protected String stretchType() {
return t("Height");
}
} }

33
src/main/java/de/srsoftware/web4rail/tiles/StretchableTile.java

@ -7,61 +7,64 @@ import java.util.Map.Entry;
import org.json.JSONObject; import org.json.JSONObject;
import de.srsoftware.tools.Tag; import de.srsoftware.tools.Tag;
import de.srsoftware.web4rail.tags.Input;
import de.srsoftware.web4rail.tags.Label;
public abstract class StretchableTile extends Tile { public abstract class StretchableTile extends Tile {
private static final String LENGTH = "length"; private static final String STRETCH_LENGTH = "stretch";
public int length = 1; public int stretch = 1;
@Override @Override
public JSONObject config() { public JSONObject config() {
JSONObject config = super.config(); JSONObject config = super.config();
if (length != 1) config.put(LENGTH, length); if (stretch != 1) config.put(STRETCH_LENGTH, stretch);
return config; return config;
} }
@Override @Override
public JSONObject json() { public JSONObject json() {
JSONObject json = super.json(); JSONObject json = super.json();
if (length > 1) json.put(LENGTH, length); if (stretch > 1) json.put(STRETCH_LENGTH, stretch);
return json; return json;
} }
@Override @Override
protected Tile load(JSONObject json) throws IOException { protected Tile load(JSONObject json) throws IOException {
super.load(json); super.load(json);
if (json.has(LENGTH)) length = json.getInt(LENGTH); if (json.has(STRETCH_LENGTH)) stretch = json.getInt(STRETCH_LENGTH);
return this; return this;
} }
@Override @Override
public Tag propForm(String id) { public Tag propForm(String id) {
Tag form = super.propForm(id); Tag form = super.propForm(id);
new Tag("h4").content(t("Length")).addTo(form); new Tag("h4").content(stretchType()).addTo(form);
Tag label = new Tag("label").content(t("length:")+NBSP);
new Tag("input").attr("type", "number").attr("name","length").attr("value", length).addTo(label); new Input(STRETCH_LENGTH, stretch).numeric().addTo(new Label(stretchType()+":"+NBSP)).addTo(new Tag("p")).addTo(form);
label.addTo(new Tag("p")).addTo(form);
return form; return form;
} }
private void setLength(String value) { private void stretch(String value) {
try { try {
setLength(Integer.parseInt(value)); stretch(Integer.parseInt(value));
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
LOG.warn("{} is not a valid length!",value); LOG.warn("{} is not a valid length!",value);
} }
} }
public void setLength(int len) { public void stretch(int len) {
this.length = Math.max(1, len); this.stretch = Math.max(1, len);
} }
protected abstract String stretchType();
@Override @Override
public Tile update(HashMap<String, String> params) throws IOException { public Tile update(HashMap<String, String> params) throws IOException {
for (Entry<String, String> entry : params.entrySet()) { for (Entry<String, String> entry : params.entrySet()) {
switch (entry.getKey()) { switch (entry.getKey()) {
case LENGTH: case STRETCH_LENGTH:
setLength(entry.getValue()); stretch(entry.getValue());
break; break;
} }
} }

76
src/main/java/de/srsoftware/web4rail/tiles/Tile.java

@ -23,8 +23,8 @@ import org.slf4j.LoggerFactory;
import de.keawe.tools.translations.Translation; import de.keawe.tools.translations.Translation;
import de.srsoftware.tools.Tag; import de.srsoftware.tools.Tag;
import de.srsoftware.web4rail.Application; import de.srsoftware.web4rail.Application;
import de.srsoftware.web4rail.BaseClass;
import de.srsoftware.web4rail.Connector; import de.srsoftware.web4rail.Connector;
import de.srsoftware.web4rail.Constants;
import de.srsoftware.web4rail.Plan; import de.srsoftware.web4rail.Plan;
import de.srsoftware.web4rail.Plan.Direction; import de.srsoftware.web4rail.Plan.Direction;
import de.srsoftware.web4rail.Route; import de.srsoftware.web4rail.Route;
@ -36,10 +36,12 @@ import de.srsoftware.web4rail.tags.Form;
import de.srsoftware.web4rail.tags.Input; import de.srsoftware.web4rail.tags.Input;
import de.srsoftware.web4rail.tags.Radio; import de.srsoftware.web4rail.tags.Radio;
public abstract class Tile implements Constants{ public abstract class Tile extends BaseClass{
protected static Logger LOG = LoggerFactory.getLogger(Tile.class); protected static Logger LOG = LoggerFactory.getLogger(Tile.class);
private static int DEFAUT_LENGTH = 5;
public static final String ID = "id"; public static final String ID = "id";
private static final String LENGTH = "length";
private static final String LOCKED = "locked"; private static final String LOCKED = "locked";
private static final String OCCUPIED = "occupied"; private static final String OCCUPIED = "occupied";
private static final String ONEW_WAY = "one_way"; private static final String ONEW_WAY = "one_way";
@ -48,16 +50,17 @@ public abstract class Tile implements Constants{
private static final String TYPE = "type"; private static final String TYPE = "type";
private static final String X = "x"; private static final String X = "x";
private static final String Y = "y"; private static final String Y = "y";
private boolean disabled = false; private boolean disabled = false;
private int length = DEFAUT_LENGTH;
protected Direction oneWay = null; protected Direction oneWay = null;
protected Plan plan = null;; protected Plan plan = null;;
protected Route route = null; protected Route route = null;
private HashSet<Route> routes = new HashSet<>(); private HashSet<Route> routes = new HashSet<>();
protected HashSet<Shadow> shadows = new HashSet<>(); protected HashSet<Shadow> shadows = new HashSet<>();
protected Train trainHead = null; protected Train train = null;
protected Train trainTail = null;
public Integer x = null; public Integer x = null;
public Integer y = null; public Integer y = null;
@ -66,8 +69,8 @@ public abstract class Tile implements Constants{
classes.add("tile"); classes.add("tile");
classes.add(getClass().getSimpleName()); classes.add(getClass().getSimpleName());
if (isSet(route)) classes.add(LOCKED); if (isSet(route)) classes.add(LOCKED);
if (isSet(trainHead) || isSet(trainTail)) classes.add(OCCUPIED); if (isSet(train)) classes.add(OCCUPIED);
if (disabled) classes.add(DISABLED); if (disabled) classes.add(DISABLED);
return classes; return classes;
} }
@ -93,7 +96,7 @@ public abstract class Tile implements Constants{
} }
public boolean isFree() { public boolean isFree() {
return !(disabled || isSet(route) || isSet(trainHead) || isSet(trainTail)); return !(disabled || isSet(route) || isSet(train));
} }
public int height() { public int height() {
@ -115,14 +118,6 @@ public abstract class Tile implements Constants{
tile.load(json); tile.load(json);
plan.set(tile.x, tile.y, tile); plan.set(tile.x, tile.y, tile);
} }
protected static boolean isNull(Object o) {
return o==null;
}
protected static boolean isSet(Object o) {
return o != null;
}
public JSONObject json() { public JSONObject json() {
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
@ -132,13 +127,18 @@ public abstract class Tile implements Constants{
if (isSet(route)) json.put(ROUTE, route.id()); if (isSet(route)) json.put(ROUTE, route.id());
if (isSet(oneWay)) json.put(ONEW_WAY, oneWay); if (isSet(oneWay)) json.put(ONEW_WAY, oneWay);
if (disabled) json.put(DISABLED, true); if (disabled) json.put(DISABLED, true);
if (isSet(trainHead)) json.put(Train.HEAD, trainHead.id); if (isSet(train)) json.put(REALM_TRAIN, train.id);
if (isSet(trainTail)) json.put(Train.TAIL, trainTail.id); json.put(LENGTH, length);
return json; return json;
} }
public int len() { public int length() {
return 1; return length;
}
public Tile length(int newLength) {
length = newLength;
return this;
} }
public static void loadAll(String filename, Plan plan) throws IOException { public static void loadAll(String filename, Plan plan) throws IOException {
@ -163,10 +163,10 @@ public abstract class Tile implements Constants{
JSONObject pos = json.getJSONObject(POS); JSONObject pos = json.getJSONObject(POS);
x = pos.getInt(X); x = pos.getInt(X);
y = pos.getInt(Y); y = pos.getInt(Y);
if (json.has(ONEW_WAY)) oneWay = Direction.valueOf(json.getString(ONEW_WAY)); if (json.has(DISABLED)) disabled = json.getBoolean(DISABLED);
if (json.has(DISABLED)) disabled = json.getBoolean(DISABLED); if (json.has(LENGTH)) length = json.getInt(LENGTH);
if (json.has(Train.HEAD)) trainHead = Train.get(json.getInt(Train.HEAD)); if (json.has(ONEW_WAY)) oneWay = Direction.valueOf(json.getString(ONEW_WAY));
if (json.has(Train.TAIL)) trainTail = Train.get(json.getInt(Train.TAIL)); if (json.has(REALM_TRAIN)) train = Train.get(json.getInt(REALM_TRAIN));
return this; return this;
} }
@ -195,7 +195,6 @@ public abstract class Tile implements Constants{
new Input(REALM, REALM_PLAN).hideIn(form); new Input(REALM, REALM_PLAN).hideIn(form);
new Input(ID,id()).hideIn(form); new Input(ID,id()).hideIn(form);
List<Direction> pd = possibleDirections(); List<Direction> pd = possibleDirections();
if (!pd.isEmpty()) { if (!pd.isEmpty()) {
new Tag("h4").content(t("One way:")).addTo(form); new Tag("h4").content(t("One way:")).addTo(form);
@ -211,6 +210,8 @@ public abstract class Tile implements Constants{
Window window = new Window("tile-properties",t("Properties of {} @ ({},{})",title(),x,y)); Window window = new Window("tile-properties",t("Properties of {} @ ({},{})",title(),x,y));
String formId = "tile-properties-"+id(); String formId = "tile-properties-"+id();
Tag form = propForm(formId); Tag form = propForm(formId);
new Tag("h4").content(t("Length")).addTo(form);
new Input(LENGTH,length).numeric().addTo(form);
new Tag("h4").content(t("Availability")).addTo(form); new Tag("h4").content(t("Availability")).addTo(form);
new Checkbox(DISABLED, t("disabled"), disabled).addTo(form); new Checkbox(DISABLED, t("disabled"), disabled).addTo(form);
new Button(t("Apply"),"submitForm('"+formId+"')").addTo(form); new Button(t("Apply"),"submitForm('"+formId+"')").addTo(form);
@ -285,7 +286,7 @@ public abstract class Tile implements Constants{
} }
public Tag tag(Map<String,Object> replacements) throws IOException { public Tag tag(Map<String,Object> replacements) throws IOException {
int width = 100*len(); int width = 100*width();
int height = 100*height(); int height = 100*height();
if (isNull(replacements)) replacements = new HashMap<String, Object>(); if (isNull(replacements)) replacements = new HashMap<String, Object>();
replacements.put("%width%",width); replacements.put("%width%",width);
@ -298,7 +299,7 @@ public abstract class Tile implements Constants{
.attr("name", getClass().getSimpleName()) .attr("name", getClass().getSimpleName())
.attr("viewbox", "0 0 "+width+" "+height); .attr("viewbox", "0 0 "+width+" "+height);
if (isSet(x)) style="left: "+(30*x)+"px; top: "+(30*y)+"px;"; if (isSet(x)) style="left: "+(30*x)+"px; top: "+(30*y)+"px;";
if (len()>1) style+=" width: "+(30*len())+"px;"; if (width()>1) style+=" width: "+(30*width())+"px;";
if (height()>1) style+=" height: "+(30*height())+"px;"; if (height()>1) style+=" height: "+(30*height())+"px;";
if (!style.isEmpty()) svg.style(style); if (!style.isEmpty()) svg.style(style);
@ -355,20 +356,19 @@ public abstract class Tile implements Constants{
return t("{}({},{})",getClass().getSimpleName(),x,y) ; return t("{}({},{})",getClass().getSimpleName(),x,y) ;
} }
public Train trainHead() { public Train train() {
return trainHead; return train;
} }
public Tile trainHead(Train train) { public Tile set(Train newTrain) {
if (this.trainHead == train) return this; // nothing to update if (newTrain == train) return this; // nothing to update
this.trainHead = train; this.train = newTrain;
return plan.place(this); return plan.place(this);
} }
public void unlock() { public void unlock() {
route = null; route = null;
trainHead = null; train = null;
trainTail = null;
plan.place(this); plan.place(this);
} }
@ -383,7 +383,13 @@ public abstract class Tile implements Constants{
} }
} }
disabled = "on".equals(params.get(DISABLED)); disabled = "on".equals(params.get(DISABLED));
String len = params.get(LENGTH);
if (isSet(len)) length(Integer.parseInt(len));
plan.stream(tag(null).toString()); plan.stream(tag(null).toString());
return this; return this;
} }
public int width() {
return 1;
}
} }

Loading…
Cancel
Save