]> Dogcows Code - chaz/carfire/blob - CarFire/CarFire/CarFire/Map.cs
f3d59d4a705a6e2e341a0177cf4e87f23fb46f7f
[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 // DEBUG: Tilesets not implemented at all.
23 public static Texture2D DefaultTile;
24
25 #region Public Exceptions
26
27 /// <summary>
28 /// This exception is thrown during the loading of a map if any
29 /// part of the map file is inconsistent with the expected format
30 /// and order.
31 /// </summary>
32 public class RuntimeException : System.ApplicationException
33 {
34 public RuntimeException() { }
35
36 public RuntimeException(string message) :
37 base(message) { }
38
39 public RuntimeException(string message, System.Exception inner) :
40 base(message, inner) { }
41
42 protected RuntimeException(SerializationInfo info, StreamingContext context) :
43 base(info, context) { }
44 }
45
46 #endregion
47
48
49 #region Public Constants
50
51 public const float PixelsToUnitSquares = 60.0f;
52
53 #endregion
54
55
56 #region Public Types
57
58 /// <summary>
59 /// The type of a map helps determine how the map is intended to be used.
60 /// </summary>
61 public enum Mode
62 {
63 None,
64 Campaign,
65 Battle
66 }
67
68 /// <summary>
69 /// The container class for map metadata.
70 /// </summary>
71 public class Metadata
72 {
73 public string Name;
74 public Mode Type;
75 public string Author;
76 public HashSet<int> NumPlayers = new HashSet<int>();
77 public string Tileset;
78 public int GridWidth;
79 public int GridHeight;
80 }
81
82 /// <summary>
83 /// The container class for information about an entity defined in the map.
84 /// </summary>
85 public class RawEntity
86 {
87 public char Id;
88 public Point Position;
89 public Dictionary<string, string> Attributes = new Dictionary<string, string>();
90 }
91
92 #endregion
93
94
95 #region Public Attributes
96
97 /// <summary>
98 /// Get the name of the map.
99 /// </summary>
100 public string Name { get { return mData.Metadata.Name; } }
101
102 /// <summary>
103 /// Get the type of the map.
104 /// </summary>
105 public Mode Type { get { return mData.Metadata.Type; } }
106
107 /// <summary>
108 /// Get the author of the map.
109 /// </summary>
110 public string Author { get { return mData.Metadata.Author; } }
111
112 /// <summary>
113 /// Get a set of integers containing each allowable number of players.
114 /// </summary>
115 public HashSet<int> NumPlayers { get { return mData.Metadata.NumPlayers; } }
116
117 /// <summary>
118 /// Get the width of the map, in grid units.
119 /// </summary>
120 public int Width { get { return mData.Metadata.GridWidth; } }
121
122 /// <summary>
123 /// Get the height of the map, in grid units.
124 /// </summary>
125 public int Height { get { return mData.Metadata.GridHeight; } }
126
127 // TODO: This should return whatever object we end up using for tilesets.
128 public string Tileset { get { return mData.Metadata.Tileset; } }
129
130 /// <summary>
131 /// Get a list of the raw entity containers loaded with the map.
132 /// </summary>
133 public List<RawEntity> RawEntities { get { return mData.Entities; } }
134
135
136 /// <summary>
137 /// Get and set the coordinate of the grid cell that should be in
138 /// the center of the screen when the map is drawn.
139 /// </summary>
140 public Vector2 CenterCell
141 {
142 get { return mView.CenterCell; }
143 set { mView.CenterCell = value; }
144 }
145
146 #endregion
147
148
149 #region Public Methods
150
151 /// <summary>
152 /// Construct a map with the provided map data.
153 /// </summary>
154 /// <param name="metadata">The metadata.</param>
155 /// <param name="grid">The grid.</param>
156 /// <param name="entities">The entities.</param>
157 public Map(Metadata metadata, char[,] grid, List<RawEntity> entities, Point[] playerPositions)
158 {
159 mData = new Modal(metadata, grid, entities, playerPositions);
160 mView = new View(mData);
161 }
162
163
164 /// <summary>
165 /// Draw a representation of the map to the screen.
166 /// </summary>
167 /// <param name="spriteBatch">The jeewiz.</param>
168 public void Draw(SpriteBatch spriteBatch)
169 {
170 mView.Draw(spriteBatch);
171 }
172
173
174 /// <summary>
175 /// Get a point in screen-space from a coordinate in gridspace.
176 /// </summary>
177 /// <param name="x">X-coordinate.</param>
178 /// <param name="y">Y-coordinate.</param>
179 /// <returns>Transformed point.</returns>
180 public Point GetPointFromCoordinates(float x, float y)
181 {
182 return mView.GetPointFromCoordinates(x, y);
183 }
184
185 /// <summary>
186 /// Get a point in screen-space from a coordinate in gridspace.
187 /// </summary>
188 /// <param name="point">X,Y-coordinates.</param>
189 /// <returns>Transformed point.</returns>
190 public Point GetPointFromCoordinates(Vector2 point)
191 {
192 return mView.GetPointFromCoordinates(point.X, point.Y);
193 }
194
195 /// <summary>
196 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
197 /// </summary>
198 /// <param name="x">X-coordinate.</param>
199 /// <param name="y">Y-coordinate.</param>
200 /// <returns>Transformed rectangle.</returns>
201 public Rectangle GetRectangleFromCoordinates(float x, float y)
202 {
203 return mView.GetRectangleFromCoordinates(x, y);
204 }
205
206 /// <summary>
207 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
208 /// </summary>
209 /// <param name="point">X,Y-coordinates.</param>
210 /// <returns>Transformed rectangle.</returns>
211 public Rectangle GetRectangleFromCoordinates(Vector2 point)
212 {
213 return mView.GetRectangleFromCoordinates(point.X, point.Y);
214 }
215
216
217 /// <summary>
218 /// Determine whether or not a cell can be occupied by a game entity.
219 /// </summary>
220 /// <param name="x">X-coordinate.</param>
221 /// <param name="y">Y-coordinate.</param>
222 /// <returns>True if cell can be occupied, false otherwise.</returns>
223 public bool IsCellOpen(int x, int y)
224 {
225 return mData.IsCellOpen(x, y);
226 }
227
228 /// <summary>
229 /// Determine whether or not a cell can be occupied by a game entity.
230 /// </summary>
231 /// <param name="point">X,Y-coordinates.</param>
232 /// <returns>True if cell can be occupied, false otherwise.</returns>
233 public bool IsCellOpen(Point point)
234 {
235 return mData.IsCellOpen(point.X, point.Y);
236 }
237
238
239 /// <summary>
240 /// Get the starting position of a player.
241 /// </summary>
242 /// <param name="playerNumber">The number of the player (i.e. 1-4).
243 /// This number must be a valid player number.</param>
244 /// <returns>The starting position of the player.</returns>
245 public Point GetStartingPositionForPlayer(int playerNumber)
246 {
247 Debug.Assert(1 <= playerNumber && playerNumber <= NumPlayers.Max());
248 return mData.PlayerPositions[playerNumber];
249 }
250
251
252 /// <summary>
253 /// Get all the entities loaded from the map file. Exceptions could be
254 /// thrown if there are entities without associated classes.
255 /// </summary>
256 /// <returns>List of entity objects loaded.</returns>
257 public List<object> GetAllEntities()
258 {
259 return mData.GetAllEntities();
260 }
261
262 /// <summary>
263 /// Get the entities of a certain type loaded from the map file. Exceptions
264 /// could be thrown if there are entities without associated classes.
265 /// </summary>
266 /// <typeparam name="T">Type of the entity you want a list of.</typeparam>
267 /// <returns>List of entity objects loaded.</returns>
268 public List<T> GetEntities<T>()
269 {
270 return mData.GetEntities<T>();
271 }
272
273 #endregion
274
275
276 #region Private Types
277
278 class Modal
279 {
280 Metadata mMetadata;
281 char[,] mGrid;
282 List<RawEntity> mEntities;
283 Point[] mPlayerPositions;
284
285 public Modal(Metadata metadata, char[,] grid, List<RawEntity> entities, Point[] playerPositions)
286 {
287 Debug.Assert(metadata != null);
288 Debug.Assert(grid != null);
289 Debug.Assert(entities != null);
290 Debug.Assert(metadata.GridWidth * metadata.GridHeight == grid.Length);
291
292 mMetadata = metadata;
293 mGrid = grid;
294 mEntities = entities;
295 mPlayerPositions = playerPositions;
296
297 #if DEBUG
298 Console.WriteLine("Loaded map {0} of type {1} written by {2}.",
299 metadata.Name,
300 metadata.Type,
301 metadata.Author);
302 #endif
303 }
304
305
306 public Metadata Metadata { get { return mMetadata; } }
307 public List<RawEntity> Entities { get { return mEntities; } }
308 public Point[] PlayerPositions { get { return mPlayerPositions; } }
309
310
311 public bool IsCellOpen(int x, int y)
312 {
313 // TODO: Still need to define characters for types of scenery.
314 return mGrid[x, y] == ' ';
315 }
316
317
318 public List<object> GetAllEntities()
319 {
320 List<object> list = new List<object>();
321
322 foreach (RawEntity raw in mEntities)
323 {
324 if (raw.Attributes.ContainsKey("type"))
325 {
326 string typename = raw.Attributes["type"];
327
328 object[] args = new object[3];
329 args[0] = raw.Id;
330 args[1] = raw.Position;
331 args[2] = raw.Attributes;
332
333 try
334 {
335
336 object entity = Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
337 if (entity != null) list.Add(entity);
338 else throw new RuntimeException();
339 }
340 #pragma warning disable 0168
341 catch (System.Exception ex)
342 #pragma warning restore 0168
343 {
344 throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
345 }
346 }
347 else
348 {
349 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
350 }
351 }
352
353 return list;
354 }
355
356 public List<T> GetEntities<T>()
357 {
358 System.Type type = typeof(T);
359 List<T> list = new List<T>();
360
361 string typename = typeof(T).Name;
362 foreach (RawEntity raw in mEntities)
363 {
364 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
365 {
366 object[] args = new object[3];
367 args[0] = raw.Id;
368 args[1] = raw.Position;
369 args[2] = raw.Attributes;
370
371 T entity = (T)Activator.CreateInstance(type, args);
372 if (entity != null) list.Add(entity);
373 else throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
374 }
375 }
376
377 return list;
378 }
379 }
380
381 class View
382 {
383 Modal mData;
384
385 public Vector2 CenterCell;
386 Viewport mViewport;
387
388
389 public View(Modal data)
390 {
391 Debug.Assert(data != null);
392 mData = data;
393 }
394
395 public void Draw(SpriteBatch spriteBatch)
396 {
397 mViewport = spriteBatch.GraphicsDevice.Viewport;
398
399 // TODO: There is no culling yet, but it runs so fast that it probably won't ever need it.
400 for (int y = 0; y < mData.Metadata.GridHeight; y++)
401 {
402 for (int x = 0; x < mData.Metadata.GridWidth; x++)
403 {
404 if (mData.IsCellOpen(x, y))
405 {
406 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.White);
407 }
408 else
409 {
410 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.DarkBlue);
411 }
412 }
413 }
414 }
415
416 /// <summary>
417 /// Get a matrix to transform a point from grid-space to screen coordinates. This
418 /// method uses the viewport to bound the edges of the map such that the camera
419 /// will not show anything outside of the grid.
420 /// </summary>
421 /// <param name="center">The point to put in the center.</param>
422 /// <returns>The transformation matrix.</returns>
423 Matrix GetTransformation(Vector2 center)
424 {
425 float halfRatio = PixelsToUnitSquares * 0.5f;
426 Matrix transform = Matrix.CreateTranslation(-center.X, -center.Y, 0.0f);
427 transform *= Matrix.CreateScale(PixelsToUnitSquares);
428 transform *= Matrix.CreateTranslation(mViewport.Width * 0.5f - halfRatio,
429 mViewport.Height * 0.5f - halfRatio, 0.0f);
430
431 Vector2 topLeft = Vector2.Transform(new Vector2(0.0f, 0.0f), transform);
432 topLeft.X = Math.Max(mViewport.X, topLeft.X);
433 topLeft.Y = Math.Max(mViewport.Y, topLeft.Y);
434 transform *= Matrix.CreateTranslation(-topLeft.X, -topLeft.Y, 0.0f);
435
436 Vector2 bottomRight = Vector2.Transform(new Vector2((float)mData.Metadata.GridWidth,
437 (float)mData.Metadata.GridHeight), transform);
438 float right = mViewport.X + mViewport.Width;
439 float bottom = mViewport.Y + mViewport.Height;
440 bottomRight.X = Math.Min(right, bottomRight.X) - right;
441 bottomRight.Y = Math.Min(bottom, bottomRight.Y) - bottom;
442 transform *= Matrix.CreateTranslation(-bottomRight.X, -bottomRight.Y, 0.0f);
443
444 return transform;
445 }
446
447
448 public Point GetPointFromCoordinates(float x, float y)
449 {
450 Matrix transform = GetTransformation(CenterCell);
451 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
452
453 return new Point((int)point.X, (int)point.Y);
454 }
455
456 public Rectangle GetRectangleFromCoordinates(float x, float y)
457 {
458 Matrix transform = GetTransformation(CenterCell);
459 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
460
461 return new Rectangle((int)point.X, (int)point.Y, (int)PixelsToUnitSquares, (int)PixelsToUnitSquares);
462 }
463 }
464
465 #endregion
466
467
468 #region Private Variables
469
470 Modal mData;
471 View mView;
472
473 #endregion
474 }
475 }
This page took 0.051965 seconds and 3 git commands to generate.