]> Dogcows Code - chaz/carfire/blob - CarFire/CarFire/CarFire/Map.cs
getting entity lists not more consistent with throwing exceptions
[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 = 8.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 Type
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 Type 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 Type Type { get { return mData.mMetadata.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="data">Map data.</param>
155 public Map(Metadata metadata, char[,] grid, List<RawEntity> entities)
156 {
157 mData = new Modal(metadata, grid, entities);
158 mView = new View(mData);
159 }
160
161
162 /// <summary>
163 /// Draw a representation of the map to the screen.
164 /// </summary>
165 /// <param name="spriteBatch">The jeewiz.</param>
166 public void Draw(SpriteBatch spriteBatch)
167 {
168 mView.Draw(spriteBatch);
169 }
170
171
172 /// <summary>
173 /// Get a point in screen-space from a coordinate in gridspace.
174 /// </summary>
175 /// <param name="x">X-coordinate.</param>
176 /// <param name="y">Y-coordinate.</param>
177 /// <returns>Transformed point.</returns>
178 public Point GetPointFromCoordinates(float x, float y)
179 {
180 return mView.GetPointFromCoordinates(x, y);
181 }
182
183 /// <summary>
184 /// Get a point in screen-space from a coordinate in gridspace.
185 /// </summary>
186 /// <param name="point">X,Y-coordinates.</param>
187 /// <returns>Transformed point.</returns>
188 public Point GetPointFromCoordinates(Vector2 point)
189 {
190 return mView.GetPointFromCoordinates(point.X, point.Y);
191 }
192
193 /// <summary>
194 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
195 /// </summary>
196 /// <param name="x">X-coordinate.</param>
197 /// <param name="y">Y-coordinate.</param>
198 /// <returns>Transformed rectangle.</returns>
199 public Rectangle GetRectangleFromCoordinates(float x, float y)
200 {
201 return mView.GetRectangleFromCoordinates(x, y);
202 }
203
204 /// <summary>
205 /// Get a rectangle in screen-space centered around a coordinate in gridspace.
206 /// </summary>
207 /// <param name="point">X,Y-coordinates.</param>
208 /// <returns>Transformed rectangle.</returns>
209 public Rectangle GetRectangleFromCoordinates(Vector2 point)
210 {
211 return mView.GetRectangleFromCoordinates(point.X, point.Y);
212 }
213
214
215 /// <summary>
216 /// Determine whether or not a cell can be occupied by a game entity.
217 /// </summary>
218 /// <param name="x">X-coordinate.</param>
219 /// <param name="y">Y-coordinate.</param>
220 /// <returns>True if cell can be occupied, false otherwise.</returns>
221 public bool IsCellOpen(int x, int y)
222 {
223 return mData.IsCellOpen(x, y);
224 }
225
226 /// <summary>
227 /// Determine whether or not a cell can be occupied by a game entity.
228 /// </summary>
229 /// <param name="point">X,Y-coordinates.</param>
230 /// <returns>True if cell can be occupied, false otherwise.</returns>
231 public bool IsCellOpen(Point point)
232 {
233 return mData.IsCellOpen(point.X, point.Y);
234 }
235
236
237 /// <summary>
238 /// Get all the entities loaded from the map file. Exceptions could be
239 /// thrown if there are entities without associated classes.
240 /// </summary>
241 /// <returns>List of entity objects loaded.</returns>
242 public List<object> GetAllEntities()
243 {
244 return mData.GetAllEntities();
245 }
246
247 /// <summary>
248 /// Get the entities of a certain type loaded from the map file. Exceptions
249 /// could be thrown if there are entities without associated classes.
250 /// </summary>
251 /// <typeparam name="T">Type of the entity you want a list of.</typeparam>
252 /// <returns>List of entity objects loaded.</returns>
253 public List<T> GetEntities<T>()
254 {
255 return mData.GetEntities<T>();
256 }
257
258 #endregion
259
260
261 #region Private Types
262
263 class Modal
264 {
265 Metadata mMetadata;
266 char[,] mGrid;
267 List<RawEntity> mEntities;
268
269 public Modal(Metadata metadata, char[,] grid, List<RawEntity> entities)
270 {
271 Debug.Assert(metadata != null);
272 Debug.Assert(grid != null);
273 Debug.Assert(entities != null);
274 Debug.Assert(metadata.GridWidth * metadata.GridHeight == grid.Length);
275
276 mMetadata = metadata;
277 mGrid = grid;
278 mEntities = entities;
279
280 #if DEBUG
281 Console.WriteLine("Loaded map {0} of type {1} written by {2}.",
282 metadata.Name,
283 metadata.Type,
284 metadata.Author);
285 #endif
286 }
287
288
289 public Metadata Metadata { get { return mMetadata; } }
290 public List<RawEntity> Entities { get { return mEntities; } }
291
292
293 public bool IsCellOpen(int x, int y)
294 {
295 // TODO: Still need to define characters for types of scenery.
296 return mGrid[x, y] == ' ';
297 }
298
299
300 public List<object> GetAllEntities()
301 {
302 List<object> list = new List<object>();
303
304 foreach (RawEntity raw in mEntities)
305 {
306 if (raw.Attributes.ContainsKey("type"))
307 {
308 string typename = raw.Attributes["type"];
309
310 object[] args = new object[3];
311 args[0] = raw.Id;
312 args[1] = raw.Position;
313 args[2] = raw.Attributes;
314
315 try
316 {
317
318 object entity = Activator.CreateInstance(System.Type.GetType("CarFire." + typename), args);
319 if (entity != null) list.Add(entity);
320 else throw new RuntimeException();
321 }
322 #pragma warning disable 0168
323 catch (System.Exception ex)
324 #pragma warning restore 0168
325 {
326 throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
327 }
328 }
329 else
330 {
331 Console.WriteLine("Ignoring entity with identifier " + raw.Id + " since it has no type key.");
332 }
333 }
334
335 return list;
336 }
337
338 public List<T> GetEntities<T>()
339 {
340 System.Type type = typeof(T);
341 List<T> list = new List<T>();
342
343 string typename = typeof(T).Name;
344 foreach (RawEntity raw in mEntities)
345 {
346 if (raw.Attributes.ContainsKey("type") && typename == raw.Attributes["type"])
347 {
348 object[] args = new object[3];
349 args[0] = raw.Id;
350 args[1] = raw.Position;
351 args[2] = raw.Attributes;
352
353 T entity = (T)Activator.CreateInstance(type, args);
354 if (entity != null) list.Add(entity);
355 else throw new RuntimeException("Entity of type " + typename + " not loaded because an entity class can't be found.");
356 }
357 }
358
359 return list;
360 }
361 }
362
363 class View
364 {
365 Modal mData;
366
367 public Vector2 CenterCell;
368 Viewport mViewport;
369
370
371 public View(Modal data)
372 {
373 Debug.Assert(data != null);
374 mData = data;
375 }
376
377 public void Draw(SpriteBatch spriteBatch)
378 {
379 mViewport = spriteBatch.GraphicsDevice.Viewport;
380
381 // TODO: There is no culling yet, but it runs so fast that it probably won't ever need it.
382 for (int y = 0; y < mData.Metadata.GridHeight; y++)
383 {
384 for (int x = 0; x < mData.Metadata.GridWidth; x++)
385 {
386 if (mData.IsCellOpen(x, y))
387 {
388 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.White);
389 }
390 else
391 {
392 spriteBatch.Draw(Map.DefaultTile, GetRectangleFromCoordinates(x, y), Color.DarkBlue);
393 }
394 }
395 }
396 }
397
398 /// <summary>
399 /// Get a matrix to transform a point from grid-space to screen coordinates. This
400 /// method uses the viewport to bound the edges of the map such that the camera
401 /// will not show anything outside of the grid.
402 /// </summary>
403 /// <param name="center">The point to put in the center.</param>
404 /// <returns>The transformation matrix.</returns>
405 Matrix GetTransformation(Vector2 center)
406 {
407 float halfRatio = PixelsToUnitSquares * 0.5f;
408 Matrix transform = Matrix.CreateTranslation(-center.X, -center.Y, 0.0f);
409 transform *= Matrix.CreateScale(PixelsToUnitSquares);
410 transform *= Matrix.CreateTranslation(mViewport.Width * 0.5f - halfRatio,
411 mViewport.Height * 0.5f - halfRatio, 0.0f);
412
413 Vector2 topLeft = Vector2.Transform(new Vector2(0.0f, 0.0f), transform);
414 topLeft.X = Math.Max(mViewport.X, topLeft.X);
415 topLeft.Y = Math.Max(mViewport.Y, topLeft.Y);
416 transform *= Matrix.CreateTranslation(-topLeft.X, -topLeft.Y, 0.0f);
417
418 Vector2 bottomRight = Vector2.Transform(new Vector2((float)mData.Metadata.GridWidth,
419 (float)mData.Metadata.GridHeight), transform);
420 float right = mViewport.X + mViewport.Width;
421 float bottom = mViewport.Y + mViewport.Height;
422 bottomRight.X = Math.Min(right, bottomRight.X) - right;
423 bottomRight.Y = Math.Min(bottom, bottomRight.Y) - bottom;
424 transform *= Matrix.CreateTranslation(-bottomRight.X, -bottomRight.Y, 0.0f);
425
426 return transform;
427 }
428
429
430 public Point GetPointFromCoordinates(float x, float y)
431 {
432 Matrix transform = GetTransformation(CenterCell);
433 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
434
435 return new Point((int)point.X, (int)point.Y);
436 }
437
438 public Rectangle GetRectangleFromCoordinates(float x, float y)
439 {
440 Matrix transform = GetTransformation(CenterCell);
441 Vector2 point = Vector2.Transform(new Vector2(x, y), transform);
442
443 return new Rectangle((int)point.X, (int)point.Y, (int)PixelsToUnitSquares, (int)PixelsToUnitSquares);
444 }
445 }
446
447 #endregion
448
449
450 #region Private Variables
451
452 Modal mData;
453 View mView;
454
455 #endregion
456 }
457 }
This page took 0.050848 seconds and 5 git commands to generate.