AbstractWaypointMovementModel.java 13.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
 * Copyright (c) 2005-2011 KOM - Multimedia Communications Lab
 *
 * This file is part of PeerfactSim.KOM.
 * 
 * PeerfactSim.KOM is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 * 
 * PeerfactSim.KOM is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with PeerfactSim.KOM.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package de.tud.kom.p2psim.impl.topology.movement;

import java.util.LinkedHashSet;
import java.util.Random;
import java.util.Set;
import java.util.WeakHashMap;

28
import de.tud.kom.p2psim.api.topology.TopologyComponent;
29
import de.tud.kom.p2psim.api.topology.movement.MovementModel;
30
import de.tud.kom.p2psim.api.topology.movement.SimLocationActuator;
31
import de.tud.kom.p2psim.api.topology.movement.local.LocalMovementStrategy;
32
import de.tud.kom.p2psim.api.topology.placement.PlacementModel;
33
34
35
36
import de.tud.kom.p2psim.api.topology.waypoints.WaypointModel;
import de.tud.kom.p2psim.impl.scenario.simcfg2.annotations.After;
import de.tud.kom.p2psim.impl.scenario.simcfg2.annotations.Configure;
import de.tud.kom.p2psim.impl.topology.PositionVector;
37
import de.tud.kom.p2psim.impl.topology.TopologyFactory;
38
39
40
41
42
43
import de.tud.kom.p2psim.impl.util.Either;
import de.tud.kom.p2psim.impl.util.geo.maps.MapLoader;
import de.tudarmstadt.maki.simonstrator.api.Event;
import de.tudarmstadt.maki.simonstrator.api.EventHandler;
import de.tudarmstadt.maki.simonstrator.api.Monitor;
import de.tudarmstadt.maki.simonstrator.api.Monitor.Level;
44
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.AttractionPoint;
45
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.Location;
46
47
48
49
50
51
52
53
54
55
56
57
58
import de.tudarmstadt.maki.simonstrator.api.Randoms;
import de.tudarmstadt.maki.simonstrator.api.Time;

/**
 * The AbstractWaypointMovementModel can be used to implement movement models
 * based on way point data. It uses an implementation of LocalMovementStrategy
 * for the movement between selected way points.
 * 
 * @author Fabio Zöllner
 * @version 1.0, 27.03.2012
 */
public abstract class AbstractWaypointMovementModel implements MovementModel {

59
	private Set<SimLocationActuator> components = new LinkedHashSet<SimLocationActuator>();
60
61
62

	protected PositionVector worldDimensions;

63
	protected WeakHashMap<SimLocationActuator, PositionVector> destinations;
64

65
	protected WeakHashMap<SimLocationActuator, Long> pauseTimes;
66

67
	protected WeakHashMap<SimLocationActuator, Long> pauseInProgressTimes;
68
69
70
71
72
73
74
75
76
77
78
79
80
81

	protected WaypointModel waypointModel;

	protected LocalMovementStrategy localMovementStrategy;

	private int configurationCounter = 100;

	private long timeBetweenMovement = 1 * Time.SECOND;

	private double speedLimit = 1;

	private double unscaledSpeedLimit = speedLimit;

	private Random rnd = Randoms.getRandom(AbstractWaypointMovementModel.class);
82

83
84
	public AbstractWaypointMovementModel(double worldX, double worldY) {
		worldDimensions = new PositionVector(worldX, worldY);
85
86
87
		destinations = new WeakHashMap<SimLocationActuator, PositionVector>();
		pauseTimes = new WeakHashMap<SimLocationActuator, Long>();
		pauseInProgressTimes = new WeakHashMap<SimLocationActuator, Long>();
88
89
90
91
92
93
94
95
96
97
98
99
100

		// Simulator.registerAtEventBus(this);
	}

	@Configure()
	@After(required = { WaypointModel.class, MapLoader.class })
	public boolean configure() {
		if (this.waypointModel == null && configurationCounter > 0) {
			configurationCounter--;
			return false;
		}

		if (this.waypointModel == null) {
101
			Monitor.log(AbstractWaypointMovementModel.class, Level.INFO,
102
103
104
105
106
107
108
109
110
111
					"No waypoint model has been configured. Thus the movement speed won't be adjusted for the scale of the waypoint model.");
		}
		//
		// if (waypointModel.getScaleFactor() != 1.0) {
		// Simulator.postEvent(new ScaleWorldEvent(waypointModel
		// .getScaleFactor()));
		// }

		return true;
	}
112

113
114
115
116
117
118
119
120
	/**
	 * This default implementation relies on {@link PlacementModel}s to be
	 * configured in the {@link TopologyFactory}
	 */
	@Override
	public void placeComponent(SimLocationActuator actuator) {
		// not supported
	}
121
122
123
124
125
126
127
128
129
130
131
132
133
134

	/**
	 * Gets called periodically (after timeBetweenMoveOperations) or by an
	 * application and should be used to recalculate positions
	 */
	public void move() {
		long nrOfSteps = timeBetweenMovement / Time.SECOND;

		for (int i = 0; i < nrOfSteps; i++) {
			step();
		}
	}

	private void step() {
135
136
		Set<SimLocationActuator> comps = getComponents();
		for (SimLocationActuator mcomp : comps) {
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173

			Long currentPause = pauseInProgressTimes.get(mcomp);
			if (currentPause != null) {
				if (Time.getCurrentTime() >= currentPause) {
					Monitor.log(AbstractWaypointMovementModel.class,
							Level.DEBUG, "Pause time ended...");
					pauseInProgressTimes.remove(mcomp);
				} else
					continue;
			}

			PositionVector dst = getDestination(mcomp);

			// If the movement model gave null as a destination no move is
			// executed
			if (dst == null) {
				Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
						"No destination before reachedPosition check... continuing");
				continue;
			}

			// If the position has been reached last round
			// set pause active and get a new destination
			if (reachedPosition(mcomp, dst)) {
				pauseAndGetNextPosition(mcomp);
				continue;
			}

			// Ask the local movement strategy for the next position.
			// It may return the next position or a boolean with true to notify
			// the
			// movement model that it can't get any closer to the current way
			// point.
			Either<PositionVector, Boolean> either = localMovementStrategy
					.nextPosition(mcomp, dst);

			if (either.hasLeft()) {
174
				updatePosition(mcomp, either.getLeft());
175
176
177
178
179
180
181
182
183
184
185
			} else {
				if (either.getRight().booleanValue()) {
					pauseAndGetNextPosition(mcomp);
					continue;
				} else {
					// Pause this round
					continue;
				}
			}
		}
	}
186

187
188
189
190
191
192
193
194
	/**
	 * Call this method to finally update the location of the given component.
	 * 
	 * @param actuator
	 * @param newPosition
	 */
	protected void updatePosition(SimLocationActuator actuator,
			PositionVector newPosition) {
195
		actuator.updateCurrentLocation(newPosition);
196
	}
197
198
199
200
201
202

	/**
	 * Sets the pause time for the given component and calls nextPosition on it.
	 * 
	 * @param comp
	 */
203
	private void pauseAndGetNextPosition(SimLocationActuator comp) {
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
		Long pt = pauseTimes.get(comp) * Time.SECOND;
		Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
				"Position reached... pause time is " + pt);
		if (pt != null) {
			Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
					"Simulator time: " + Time.getCurrentTime());
			Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
					"Pause time: " + pt);
			Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
					"Added up: " + (Time.getCurrentTime() + pt));
			pauseInProgressTimes.put(comp, Time.getCurrentTime() + pt);
		}

		nextPosition(comp);
	}

	/**
	 * Checks if the given component has reached its destination
	 * 
	 * @param comp
	 * @param dst
	 * @return Returns true if the destination was reached
	 */
227
228
	private boolean reachedPosition(SimLocationActuator comp,
			PositionVector dst) {
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
		PositionVector pos = comp.getRealPosition();

		double distance = pos.distanceTo(dst);

		// FIXME: Better detection?

		return (distance < getSpeedLimit() * 2);
	}

	/**
	 * Returns the current destination of the given component and calls
	 * nextPosition if it hasn't been set yet.
	 * 
	 * @param comp
	 * @return
	 */
245
	private PositionVector getDestination(SimLocationActuator comp) {
246
247
		PositionVector dst = destinations.get(comp);

248
249
250
251
		Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
				"Pos: " + comp.getRealPosition());
		Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
				"Dst: " + dst);
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272

		if (dst == null) {
			Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
					"No destination, calling nextPosition()");
			nextPosition(comp);
			dst = destinations.get(comp);
			Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
					"New destination is: " + dst);
		}

		return dst;
	}

	/**
	 * This method can be called by the concrete implementation to let the
	 * AbstractWaypointMovementModel know the next destination and pause time.
	 * 
	 * @param comp
	 * @param destination
	 * @param pauseTime
	 */
273
	protected void nextDestination(SimLocationActuator comp,
274
275
276
277
278
279
280
281
282
283
284
285
			PositionVector destination, long pauseTime) {
		destinations.put(comp, destination);
		pauseTimes.put(comp, pauseTime);
	}

	/**
	 * Is to be implemented by the concrete movement model and will be called by
	 * the AbstractWaypointMovementModel to ask the concrete implementation for
	 * a new destination.
	 * 
	 * @param component
	 */
286
	public abstract void nextPosition(SimLocationActuator component);
287
288
289
290
291
292

	/**
	 * Get all participating Components
	 * 
	 * @return
	 */
293
	protected Set<SimLocationActuator> getComponents() {
294
295
296
297
298
299
300
301
302
303
304
		return components;
	}

	/**
	 * Add a component to this movement-Model (used to keep global information
	 * about all participants in a movement model). Each Component acts as a
	 * callback upon movement of this component
	 * 
	 * @param component
	 */
	@Override
305
	public void addComponent(SimLocationActuator component) {
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
		Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
				"AbstractMovementModel: Adding component to the movement model");
		components.add(component);
	}

	/**
	 * Get a valid delta-Vector (does not cross world-boundaries and does not
	 * exceed moveSpeedLimit)
	 * 
	 * @param oldPosition
	 * @return
	 */
	protected PositionVector getRandomDelta(PositionVector oldPosition) {
		return getRandomDelta(oldPosition, getSpeedLimit());
	}

	/**
	 * Get a valid delta-Vector, where each abs(entry) must not exceed maxLength
	 * 
	 * @param oldPosition
	 * @param maxLength
	 * @return
	 */
	protected PositionVector getRandomDelta(PositionVector oldPosition,
			double maxLength) {
		double[] delta = new double[oldPosition.getDimensions()];
		for (int i = 0; i < oldPosition.getDimensions(); i++) {
			int tries = 0;
			do {
				delta[i] = getRandomDouble(-maxLength, maxLength);
				if (++tries > 50) {
					delta[i] = 0;
					break;
				}
				// delta[i] = (r.nextInt(2 * getMoveSpeedLimit() + 1) -
				// getMoveSpeedLimit());
			} while (oldPosition.getEntry(i) + delta[i] > getWorldDimension(i)
					|| oldPosition.getEntry(i) + delta[i] < 0);
		}
		PositionVector deltaVector = new PositionVector(delta);
		return deltaVector;
	}

	/**
	 * Returns if this is a valid position within the boundaries
	 * 
	 * @return
	 */
	protected boolean isValidPosition(PositionVector vector) {
		for (int i = 0; i < vector.getDimensions(); i++) {
			if (vector.getEntry(i) > getWorldDimension(i)
					|| vector.getEntry(i) < 0) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Returns a random int between from and to, including both interval ends!
	 * 
	 * @param from
	 * @param to
	 * @return
	 */
	protected int getRandomInt(int from, int to) {
		int intervalSize = Math.abs(to - from);
		return (rnd.nextInt(intervalSize + 1) + from);
	}

	protected double getRandomDouble(double from, double to) {
		double intervalSize = Math.abs(to - from);
		return (rnd.nextDouble() * intervalSize + from);
	}

	/**
	 * Move models can periodically calculate new positions and notify
	 * listeners, if a position changed. Here you can specify the interval
	 * between these notifications/calculations. If this is set to zero, there
	 * is no periodical execution, which may be useful if you want to call
	 * move() from within an application.
	 * 
	 * @param timeBetweenMoveOperations
	 */
	public void setTimeBetweenMoveOperations(long timeBetweenMoveOperations) {

		this.timeBetweenMovement = timeBetweenMoveOperations;

		if (timeBetweenMoveOperations > 0) {
			reschedule();
		}
	}

	protected void reschedule() {
		Event.scheduleWithDelay(timeBetweenMovement, new PeriodicMove(), this,
				0);
	}

	@Deprecated
	public void setSpeedLimit(double speedLimit) {
		this.speedLimit = speedLimit;
		this.unscaledSpeedLimit = speedLimit;
	}

	@Deprecated
	public double getSpeedLimit() {
		return speedLimit;
	}

	public void setWorldX(double dimension) {
		this.worldDimensions.setEntry(0, dimension);
	}

	public void setWorldY(double dimension) {
		this.worldDimensions.setEntry(1, dimension);
	}

	public double getWorldDimension(int dim) {
		return worldDimensions.getEntry(dim);
	}

	public void setWorldZ(double dimension) {
		this.worldDimensions.setEntry(2, dimension);
	}

	public void setWaypointModel(WaypointModel model) {
		this.waypointModel = model;

		if (localMovementStrategy != null)
			localMovementStrategy.setWaypointModel(getWaypointModel());
	}

	public WaypointModel getWaypointModel() {
		return this.waypointModel;
	}

	public void setLocalMovementStrategy(LocalMovementStrategy strategy) {
		strategy.setWaypointModel(getWaypointModel());
		this.localMovementStrategy = strategy;
	}

	/**
	 * Triggers the periodic move
	 * 
	 * @author Bjoern Richerzhagen
	 * @version 1.0, 20.03.2012
	 */
	protected class PeriodicMove implements EventHandler {

		@Override
		public void eventOccurred(Object content, int type) {
			move();
			reschedule();
		}

	}

}