]> Dogcows Code - chaz/carfire/blob - CarFire/CarFire/CarFire/Map.cs
New property IEntity.IsCollidable so entities can let the collision code know whether...
[chaz/carfire] / CarFire / CarFire / CarFire / Map.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.IO;
6 using System.Runtime.Serialization;
7 using System.Diagnostics;
8 using Microsoft.Xna.Framework;
9 using Microsoft.Xna.Framework.Graphics;
10 using System.Reflection;
11
12 namespace CarFire
13 {
14 /// <summary>
15 /// A map object represents the map or virtual world where players and other
16 /// game entities exist. The map consists of a grid where each grid space can
17 /// contain static scenery and/or game entities which can move and interact
18 /// with other game entities.
19 /// </summary>
20 public class Map
21 {
22 #region Public Constants
23
24 public const float PixelsToUnitSquares = 64.0f;
25
26 #endregion
27
28
29 #region Public Types
30
31 /// <summary>
32 /// The type of a map helps determine how the map is intended to be used.
33 /// </summary>
34 public enum Mode
35 {
36 None,
37 Campaign,
38 Battle
39 }
40
41 /// <summary>
42 /// The container class for map metadata.
43 /// </summary>
44 public class Metadata
45 {
46 public string Name;
47 public Mode Type;
48 public string Author;
49 public HashSet<int> NumPlayers = new HashSet<int>();
50 public string Tileset;
51 public int GridWidth;
52 public int GridHeight;
53 }
54
55 /// <summary>
56 /// The container class for information about an entity defined in the map.
57 /// </summary>
58 public class RawEntity
59 {
60 public char Id;
61 public Point Position;
62 public Dictionary<string, string> Attributes = new Dictionary<string, string>();
63 }
64
65 #endregion
66
67
68 #region Public Properties
69
70 /// <summary>
71 /// Get the name of the map.
72 /// </summary>
73 public string Name { get { return mData.Metadata.Name; } }
74
75 /// <summary>
76 /// Get the type of the map.
77 /// </summary>
78 public Mode Type { get { return mData.Metadata.Type; } }
79
80 /// <summary>
81 /// Get the author of the map.
82 /// </summary>
83 public string Author { get { return mData.Metadata.Author; } }
84
85 /// <summary>
86 /// Get a set of integers containing each allowable number of players.
87 /// </summary>
88 public HashSet<int> NumPlayers { get { return mData.Metadata.NumPlayers; } }
89
90 /// <summary>
91 /// Get the width of the map, in grid units.
92 /// </summary>
93 public int Width { get { return mData.Metadata.GridWidth; } }
94
95 /// <summary>
96 /// Get the height of the map, in grid units.
97 /// </summary>
98 public int Height { get { return mData.Metadata.GridHeight; } }
99
100 /// <summary>
101 /// Get the name of the tileset.
102 /// </summary>
103 public string Tileset { get { return mData.Metadata.Tileset; } }
104
105 /// <summary>
106 /// Get the current grid of open cells. On the grid, true means
107 /// the cell is open (i.e. an entity can occupy that cell), and false
108 /// means the cell is closed. Note that, just like Map.IsCellOpen,
109 /// only static scenery is considered; the grid cannot tell you
110 /// whether or not an entity is already occupying the cell.
111 /// </summary>
112 public bool[,] Grid { get { return mData.Grid; } }
113
114 /// <summary>
115 /// Get a list of the raw entity containers loaded with the map. If you
116 /// want to get the actual entity objects, use Map.GetEntities and
117 /// Map.GetAllEntities instead.
118 /// </summary>
119 public List<RawEntity> RawEntities { get { return mData.Entities; } }
120
121
122 /// <summary>
123 /// Get and set the coordinate of the grid cell that should be in
124 /// the center of the screen when the map is drawn. Setting this
125 /// will change the viewport of the map and will effect the return
126 /// values of Map.GetPointFromCoordinates and Map.GetRectangleFromCoordinates.
127 /// </summary>
128 public Vector2 CenterCell
129 {
130 get { return mView.CenterCell; }
131 set { mView.CenterCell = value; }
132 }
133
134 /// <summary>
135 /// Get and set the tilemap with its associated texture and tile
136 /// character to coordinate mappings. This effects what the map looks
137 /// like when it is drawn. You will need to reset any map instances
138 /// after setting a new tilemap. You should also set a tilemap before
139 /// instantiating any maps.
140 /// </summary>
141 public static Tilemap Tilemap;
142
143 /// <summary>
144 /// Get and set the zoom of the map view. The default zoom is
145 /// Map.PixelsToUnitSquares.
146 /// </summary>
147 public float Zoom
148 {
149 get { return mView.Zoom; }
150 set { mView.Zoom = value; }
151 }
152
153 #endregion
154
155
156 #region Public Methods
157
158 /// <summary>
159 /// Construct a map with the provided map data.
160 /// </summary>
161 /// <param name="metadata">The metadata.</param>
162 /// <param name="grid">The grid.</param>
163 /// <param name="entities">The entities.</param>
164 public Map(Metadata metadata, char[,] grid, char defaultTile,
165 List<RawEntity> entities, Point[] playerPositions)
166 {
167 mData = new Model(metadata, grid, defaultTile, entities, playerPositions);
168 mView = new View(mData);
169 }
170
171
172 /// <summary>
173 /// Draw a representation of the map to the screen.
174 /// </summary>
175 /// <param name="spriteBatch">The jeewiz.</param>
176 public void Draw(SpriteBatch spriteBatch)
177 {
178 mView.Draw(spriteBatch);
179 }
180
181
182 /// <summary>
183 /// Get a point in screen-space from a coordinate in gridspace.
184 /// </summary>
185 /// <param name="x">X-coordinate.</param>
186 /// <param name="y">Y-coordinate.</param>
187 /// <returns>Transformed point.</returns>
188 public Point GetPointFromCoordinates(float x, float y)
189 {
190 return mView.GetPointFromCoordinates(x, y);
191 }
192
193 /// <summary>
194 /// Get a point in screen-space from a coordinate in gridspace.
195 /// </summary>
196 /// <param name="point">X,Y-coordinates.</param>
197 /// <returns>Transformed point.</returns>
198 public Point GetPointFromCoordinates(Vector2 point)
199 {
200 return mView.GetPointFromCoordinates(point.X, point.Y);
201 }
202
203 /// <summary>
204 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
205 /// </summary>
206 /// <param name="x">X-coordinate.</param>
207 /// <param name="y">Y-coordinate.</param>
208 /// <returns>Transformed rectangle.</returns>
209 public Rectangle GetRectangleFromCoordinates(float x, float y)
210 {
211 return mView.GetRectangleFromCoordinates(x, y);
212 }
213
214 /// <summary>
215 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
216 /// </summary>
217 /// <param name="point">X,Y-coordinates.</param>
218 /// <returns>Transformed rectangle.</returns>
219 public Rectangle GetRectangleFromCoordinates(Vector2 point)
220 {
221 return mView.GetRectangleFromCoordinates(point.X, point.Y);
222 }
223
224
225 /// <summary>
226 /// Determine whether or not a cell can be occupied by a game entity.
227 /// </summary>
228 /// <param name="x">X-coordinate.</param>
229 /// <param name="y">Y-coordinate.</param>
230 /// <returns>True if cell can be occupied, false otherwise.</returns>
231 public bool IsCellOpen(int x, int y)
232 {
233 return mData.IsCellOpen(x, y);
234 }
235
236 /// <summary>
237 /// created by Brady for AI precalculations
238 /// </summary>
239 /// <param name="x">X-coordinate.</param>
240 /// <param name="y">Y-coordinate.</param>
241 public bool IsWall(int x, int y)
242 {
243 return mData.IsWall(x, y);
244 }
245
246 /// <summary>
247 /// Determine whether or not a cell can be occupied by a game entity.
248 /// </summary>
249 /// <param name="point">X,Y-coordinates.</param>
250 /// <returns>True if cell can be occupied, false otherwise.</returns>
251 public bool IsCellOpen(Point point)
252 {
253 return mData.IsCellOpen(point.X, point.Y);
254 }
255
256
257 /// <summary>
258 /// Get the starting position of a player.
259 /// </summary>
260 /// <param name="playerNumber">The number of the player (i.e. 1-4).
261 /// This number must be a valid player number.</param>
262 /// <returns>The starting position of the player.</returns>
263 public Point GetStartingPositionForPlayer(int playerNumber)
264 {
265 Debug.Assert(1 <= playerNumber && playerNumber <= NumPlayers.Max());
266 return mData.PlayerPositions[playerNumber];
267 }
268
269
270 /// <summary>
271 /// Get all the entities loaded from the map file. Exceptions could be
272 /// thrown if there are entities without associated classes.
273 /// </summary>
274 /// <param name="game">The game reference to be passed to entities.</param>
275 /// <returns>List of entity objects loaded.</returns>
276 public List<IEntity> GetAllEntities(Game game)
277 {
278 return mData.GetAllEntities(game);
279 }
280
281 /// <summary>
282 /// Get the entities of a certain type loaded from the map file. Exceptions
283 /// could be thrown if there are entities without associated classes.
284 /// </summary>
285 /// <param name="game">The game reference to be passed to entities.</param>
286 /// <typeparam name="T">Type of the entity you want a list of.</typeparam>
287 /// <returns>List of entity objects loaded.</returns>
288 public List<T> GetEntities<T>(Game game)
289 {
290 return mData.GetEntities<T>(game);
291 }
292
293
294 /// <summary>
295 /// Set the tile of a cell.
296 /// </summary>
297 /// <param name="x">X-coordinate.</param>
298 /// <param name="y">Y-coordinate.</param>
299 /// <param name="tile">The character representing the tile.</param>
300 public void SetCell(int x, int y, char tile)
301 {
302 mData.SetCell(x, y, tile);
303 }
304
305 /// <summary>
306 /// Set the tile of a cell.
307 /// </summary>
308 /// <param name="point">X,Y-coordinates.</param>
309 /// <param name="tile">The character representing the tile.</param>
310 public void SetCell(Point point, char tile)
311 {
312 mData.SetCell(point.X, point.Y, tile);
313 }
314
315
316 /// <summary>
317 /// Clear a cell to the default tile.
318 /// </summary>
319 /// <param name="x">X-coordinate.</param>
320 /// <param name="y">Y-coordinate.</param>
321 public void ClearCell(int x, int y)
322 {
323 mData.ClearCell(x, y);
324 }
325
326 /// <summary>
327 /// Clear a cell to the default tile.
328 /// </summary>
329 /// <param name="point">X,Y-coordinates.</param>
330 public void ClearCell(Point point)
331 {
332 mData.ClearCell(point.X, point.Y);
333 }
334
335
336 /// <summary>
337 /// Reset the map to the state it was at right after loading.
338 /// </summary>
339 public void Reset()
340 {
341 mData.Reset();
342 mView.Reset();
343 }
344
345 #endregion
346
347
348 #region Private Types
349
350 class Model
351 {
352 public Metadata Metadata { get { return mMetadata; } }
353 public List<RawEntity> Entities { get { return mEntities; } }
354 public Point[] PlayerPositions { get { return mPlayerPositions; } }
355 public bool[,] Grid { get { return mBooleanGrid; } }
356
357
358 public Model(Metadata metadata, char[,] grid, char defaultTile,
359 List<RawEntity> entities, Point[] playerPositions)
360 {
361 Debug.Assert(metadata != null);
362 Debug.Assert(grid != null);
363 Debug.Assert(entities != null);
364 Debug.Assert(metadata.GridWidth * metadata.GridHeight == grid.Length);
365 Debug.Assert(Tilemap != null);
366
367 mMetadata = metadata;
368 mCleanGrid = grid;
369 mDefaultTile = defaultTile;
370 mEntities = entities;
371 mPlayerPositions = playerPositions;
372
373 Reset();
374
375 #if DEBUG
376 Console.WriteLine("Loaded map {0} of type {1} written by {2}.",
377 metadata.Name,
378 metadata.Type,
379 metadata.Author);
380 #endif
381 }
382
383
384 public void Reset()
385 {
386 mGrid = (char[,])mCleanGrid.Clone();
387
388 mBooleanGrid = new bool[mMetadata.GridWidth, mMetadata.GridHeight];
389 for (int x = 0; x < mMetadata.GridWidth; x++)
390 {
391 for (int y = 0; y < mMetadata.GridHeight; y++)
392 {
393 mBooleanGrid[x, y] = IsCellOpen(x, y);
394 }
395 }
396 }
397
398
399 public bool IsCellOpen(int x, int y)
400 {
401 if (!IsOnMap(x, y)) return false;
402 return (Tilemap.GetTileFlags(mGrid[x, y]) & TileFlags.Open) == TileFlags.Open;
403 }
404
405 //created by Brady for AI precalculations
406 public bool IsWall(int x, int y)
407 {
408 if (!IsOnMap(x, y)) return false;
409 return (Tilemap.GetTileFlags(mGrid[x, y]) & TileFlags.Wall) == TileFlags.Wall;
410 }
411
412 public void SetCell(int x, int y, char tile)
413 {
414 if (IsOnMap(x, y))
415 {
416 mGrid[x, y] = tile;
417 mBooleanGrid[x, y] = IsCellOpen(x, y);
418 }
419 }
420
421 public char GetCell(int x, int y)
422 {
423 if (IsOnMap(x, y)) return mGrid[x, y];
424 return mDefaultTile;
425 }
426
427 public void ClearCell(int x, int y)
428 {
429 SetCell(x, y, mDefaultTile);
430 }
431
432 public bool IsOnMap(int x, int y)
433 {
434 return 0 <= x && x < Metadata.GridWidth && 0 <= y && y < Metadata.GridHeight;
435 }
436
437
438 public List<IEntity> GetAllEntities(Game game)
439 {
440 List<IEntity> list = new List<IEntity>();
441
442 foreach (RawEntity raw in mEntities)
443 {
444 if (raw.Attributes.ContainsKey("type"))
445 {
446 string typename = raw.Attributes["type"];
447
448 object[] args = new object[4];
449 args[0] = raw.Id;
450 args[1] = raw.Position;
451 args[2] = raw.Attributes;
452 args[3] = game;
453
454 try
455 {
456 IEntity entity = (IEntity)Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
457 if (entity != null)
458 {
459 entity.LoadContent(game.ContentManager);
460 list.Add(entity);
461 }
462 else throw new Exception();
463 }
464 #pragma warning disable 0168
465 catch (System.Exception ex)
466 #pragma warning restore 0168
467 {
468 throw new Exception("Entity of type " + typename + " not loaded because an entity class can't be found.");
469 }
470 }
471 else
472 {
473 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
474 }
475 }
476
477 return list;
478 }
479
480 public List<T> GetEntities<T>(Game game)
481 {
482 System.Type type = typeof(T);
483 List<T> list = new List<T>();
484
485 string typename = typeof(T).Name;
486 foreach (RawEntity raw in mEntities)
487 {
488 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
489 {
490 object[] args = new object[4];
491 args[0] = raw.Id;
492 args[1] = raw.Position;
493 args[2] = raw.Attributes;
494 args[3] = game;
495
496 T entity = (T)Activator.CreateInstance(type, args);
497 if (entity != null)
498 {
499 ((IEntity)entity).LoadContent(game.ContentManager);
500 list.Add(entity);
501 }
502 else throw new Exception("Entity of type " + typename + " not loaded because an entity class can't be found.");
503 }
504 }
505
506 return list;
507 }
508
509
510 Metadata mMetadata;
511 char[,] mGrid;
512 char[,] mCleanGrid;
513 bool[,] mBooleanGrid;
514 char mDefaultTile;
515 List<RawEntity> mEntities;
516 Point[] mPlayerPositions;
517 }
518
519 class View
520 {
521 public Vector2 CenterCell;
522 public float Zoom;
523
524
525 public View(Model data)
526 {
527 Debug.Assert(data != null);
528 mData = data;
529
530 Reset();
531 }
532
533
534 public void Reset()
535 {
536 CenterCell = Vector2.Zero;
537 Zoom = PixelsToUnitSquares;
538 }
539
540
541 public void Draw(SpriteBatch spriteBatch)
542 {
543 if (Tilemap == null) throw new Exception("Cannot draw map without first setting the tilemap.");
544 mViewport = spriteBatch.GraphicsDevice.Viewport;
545
546 for (int y = 0; y < mData.Metadata.GridHeight; y++)
547 {
548 for (int x = 0; x < mData.Metadata.GridWidth; x++)
549 {
550 Tilemap.Draw(spriteBatch, mData.GetCell(x, y), GetRectangleFromCoordinates(x, y));
551 }
552 }
553 }
554
555
556 public Point GetPointFromCoordinates(float x, float y)
557 {
558 Matrix transform = GetTransformation(CenterCell);
559 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
560
561 return new Point((int)point.X, (int)point.Y);
562 }
563
564 public Rectangle GetRectangleFromCoordinates(float x, float y)
565 {
566 Matrix transform = GetTransformation(CenterCell);
567 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
568
569 return new Rectangle((int)Math.Round(point.X, 0), (int)Math.Round(point.Y, 0), (int)Math.Round(Zoom, 0), (int)Math.Round(Zoom, 0));
570 }
571
572
573
574 Matrix GetTransformation(Vector2 center)
575 {
576 float halfRatio = Zoom * 0.5f;
577 Matrix transform = Matrix.CreateTranslation(-center.X, -center.Y, 0.0f);
578 transform *= Matrix.CreateScale(Zoom);
579 transform *= Matrix.CreateTranslation(mViewport.Width * 0.5f - halfRatio,
580 mViewport.Height * 0.5f - halfRatio, 0.0f);
581
582 Vector2 topLeft = Vector2.Transform(new Vector2(0.0f, 0.0f), transform);
583 topLeft.X = Math.Max(mViewport.X, topLeft.X);
584 topLeft.Y = Math.Max(mViewport.Y, topLeft.Y);
585 transform *= Matrix.CreateTranslation(-topLeft.X, -topLeft.Y, 0.0f);
586
587 Vector2 bottomRight = Vector2.Transform(new Vector2((float)mData.Metadata.GridWidth,
588 (float)mData.Metadata.GridHeight), transform);
589 float right = mViewport.X + mViewport.Width;
590 float bottom = mViewport.Y + mViewport.Height;
591 bottomRight.X = Math.Min(right, bottomRight.X) - right;
592 bottomRight.Y = Math.Min(bottom, bottomRight.Y) - bottom;
593 transform *= Matrix.CreateTranslation(-bottomRight.X, -bottomRight.Y, 0.0f);
594
595 return transform;
596 }
597
598
599 Model mData;
600 Viewport mViewport;
601 }
602
603 #endregion
604
605
606 #region Private Variables
607
608 Model mData;
609 View mView;
610
611 #endregion
612 }
613 }
This page took 0.062293 seconds and 5 git commands to generate.