AbstractWaypointMovementModel.java 14.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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
 * 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.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.WeakHashMap;

import com.google.common.eventbus.Subscribe;

import de.tud.kom.p2psim.api.topology.movement.MovementListener;
import de.tud.kom.p2psim.api.topology.movement.MovementModel;
import de.tud.kom.p2psim.api.topology.movement.MovementSupported;
import de.tud.kom.p2psim.api.topology.movement.local.LocalMovementStrategy;
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;
import de.tud.kom.p2psim.impl.topology.events.ScaleWorldEvent;
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;
45
46
import de.tudarmstadt.maki.simonstrator.api.Monitor;
import de.tudarmstadt.maki.simonstrator.api.Monitor.Level;
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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 {

	private Set<MovementSupported> components = new LinkedHashSet<MovementSupported>();

	protected PositionVector worldDimensions;

	protected WeakHashMap<MovementSupported, PositionVector> destinations;

	protected WeakHashMap<MovementSupported, Long> pauseTimes;

	protected WeakHashMap<MovementSupported, Long> pauseInProgressTimes;

	private List<MovementListener> listeners;

	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);

	public AbstractWaypointMovementModel(double worldX, double worldY) {
		worldDimensions = new PositionVector(worldX, worldY);
		listeners = new LinkedList<MovementListener>();
		destinations = new WeakHashMap<MovementSupported, PositionVector>();
		pauseTimes = new WeakHashMap<MovementSupported, Long>();
		pauseInProgressTimes = new WeakHashMap<MovementSupported, Long>();

		// 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) {
105
106
107
108
			Monitor.log(
					AbstractWaypointMovementModel.class,
					Level.INFO,
					"No waypoint model has been configured. Thus the movement speed won't be adjusted for the scale of the waypoint model.");
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
		}
		//
		// if (waypointModel.getScaleFactor() != 1.0) {
		// Simulator.postEvent(new ScaleWorldEvent(waypointModel
		// .getScaleFactor()));
		// }

		return true;
	}

	@Subscribe
	public void scaleWorld(ScaleWorldEvent event) {
		double scaleFactor = event.getFactor();

		speedLimit = unscaledSpeedLimit * scaleFactor;
124
125
126
127
		Monitor.log(
				AbstractWaypointMovementModel.class,
				Level.INFO,
				"Movement speed of the local movement strategy has been adjusted for the waypoint model scale and is now "
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
				+ speedLimit + "m/s");
	}

	/**
	 * 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();
		}

		notifyRoundEnd();
	}

	private void step() {
		Set<MovementSupported> comps = getComponents();
		for (MovementSupported mcomp : comps) {
			if (!mcomp.movementActive()) {
				continue;
			}

			Long currentPause = pauseInProgressTimes.get(mcomp);
			if (currentPause != null) {
				if (Time.getCurrentTime() >= currentPause) {
155
156
					Monitor.log(AbstractWaypointMovementModel.class,
							Level.DEBUG, "Pause time ended...");
157
158
159
160
161
162
163
164
165
166
					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) {
167
168
				Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
						"No destination before reachedPosition check... continuing");
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
				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()) {
				mcomp.getRealPosition().replace(either.getLeft());
				notifyPositionChange(mcomp);
			} else {
				if (either.getRight().booleanValue()) {
					pauseAndGetNextPosition(mcomp);
					continue;
				} else {
					// Pause this round
					continue;
				}
			}
		}
	}

	/**
	 * Sets the pause time for the given component and calls nextPosition on it.
	 * 
	 * @param comp
	 */
	private void pauseAndGetNextPosition(MovementSupported comp) {
		Long pt = pauseTimes.get(comp) * Time.SECOND;
209
210
		Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
				"Position reached... pause time is " + pt);
211
		if (pt != null) {
212
213
214
215
216
217
			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));
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
			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
	 */
	private boolean reachedPosition(MovementSupported comp, PositionVector dst) {
		PositionVector pos = comp.getRealPosition();

		double distance = pos.getDistance(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
	 */
	private PositionVector getDestination(MovementSupported comp) {
		PositionVector dst = destinations.get(comp);

251
252
253
254
		Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG, "Pos: "
				+ comp.getRealPosition());
		Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG, "Dst: "
				+ dst);
255
256

		if (dst == null) {
257
258
			Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
					"No destination, calling nextPosition()");
259
260
			nextPosition(comp);
			dst = destinations.get(comp);
261
262
			Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
					"New destination is: " + dst);
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
		}

		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
	 */
	protected void nextDestination(MovementSupported comp,
			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
	 */
	public abstract void nextPosition(MovementSupported component);

	/**
	 * Get all participating Components
	 * 
	 * @return
	 */
	protected Set<MovementSupported> getComponents() {
		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
	public void addComponent(MovementSupported component) {
309
310
		Monitor.log(AbstractWaypointMovementModel.class, Level.DEBUG,
				"AbstractMovementModel: Adding component to the movement model");
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
		components.add(component);
	}

	@Override
	public void addMovementListener(MovementListener listener) {
		if (!listeners.contains(listener)) {
			listeners.add(listener);
		}
	}

	@Override
	public void removeMovementListener(MovementListener listener) {
		listeners.remove(listener);
	}

	/**
	 * Notify Listeners
	 */
	protected void notifyRoundEnd() {
		for (MovementListener listener : listeners) {
			listener.afterComponentsMoved();
		}
	}

	protected void notifyPositionChange(MovementSupported comp) {
		for (MovementListener listener : listeners) {
			listener.afterComponentMoved(comp);
		}
		comp.positionChanged();
	}

	/**
	 * 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();
		}

	}

}