Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
Game.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 using System;
4 using System.Globalization;
5 using System.IO;
6 using System.Reflection;
7 using System.Threading.Tasks;
8 using SiliconStudio.Core.Mathematics;
9 using SiliconStudio.Paradox.Effects;
10 using SiliconStudio.Paradox.Engine;
11 using SiliconStudio.Paradox.EntityModel;
12 using SiliconStudio.Paradox.Games;
13 using SiliconStudio.Core.Storage;
14 using SiliconStudio.Paradox.Audio;
15 using SiliconStudio.Paradox.Graphics;
16 using SiliconStudio.Paradox.Graphics.Data;
17 using SiliconStudio.Core.Diagnostics;
18 using SiliconStudio.Core.IO;
19 using SiliconStudio.Core.Serialization.Assets;
20 using SiliconStudio.Paradox.Graphics.DataOld;
22 using SiliconStudio.Paradox.Input;
23 using SiliconStudio.Paradox.UI;
24 
26 
27 namespace SiliconStudio.Paradox
28 {
29  /// <summary>
30  /// Main Game class system.
31  /// </summary>
32  public class Game : GameBase
33  {
34  private readonly GameFontSystem gameFontSystem;
35 
36  private readonly LogListener logListener;
37 
38  /// <summary>
39  /// Gets the graphics device manager.
40  /// </summary>
41  /// <value>The graphics device manager.</value>
42  public GraphicsDeviceManager GraphicsDeviceManager { get; private set; }
43 
44  /// <summary>
45  /// Gets the render system.
46  /// </summary>
47  /// <value>The render system.</value>
48  public RenderSystem RenderSystem { get; private set; }
49 
50  /// <summary>
51  /// Gets the script system.
52  /// </summary>
53  /// <value>The script.</value>
54  public ScriptSystem Script { get; internal set; }
55 
56  /// <summary>
57  /// Gets the input manager.
58  /// </summary>
59  /// <value>The input.</value>
60  public InputManager Input { get; internal set; }
61 
62  /// <summary>
63  /// Gets the entity system.
64  /// </summary>
65  /// <value>The entity system.</value>
66  public EntitySystem Entities { get; internal set; }
67 
68  /// <summary>
69  /// Gets the effect system.
70  /// </summary>
71  /// <value>The effect system.</value>
72  public EffectSystem EffectSystem { get; private set; }
73 
74  /// <summary>
75  /// Gets the audio system.
76  /// </summary>
77  /// <value>The audio.</value>
78  public AudioSystem Audio { get; private set; }
79 
80  /// <summary>
81  /// Gets the UI system.
82  /// </summary>
83  /// <value>The UI.</value>
84  public UISystem UI { get; private set; }
85 
86  /// <summary>
87  /// Gets the sprite animation system.
88  /// </summary>
89  /// <value>The sprite animation system.</value>
90  public SpriteAnimationSystem SpriteAnimation { get; private set; }
91 
92  /// <summary>
93  /// Gets the font system.
94  /// </summary>
95  /// <value>The font system.</value>
96  /// <exception cref="System.InvalidOperationException">The font system is not initialized yet</exception>
97  public IFontSystem Font
98  {
99  get
100  {
101  if (gameFontSystem.FontSystem == null)
102  throw new InvalidOperationException("The font system is not initialized yet");
103 
104  return gameFontSystem.FontSystem;
105  }
106  }
107 
108  /// <summary>
109  /// Gets or sets the console log mode. See remarks.
110  /// </summary>
111  /// <value>The console log mode.</value>
112  /// <remarks>
113  /// Defines how the console will be displayed when running the game. By default, on Windows, It will open only on debug
114  /// if there are any messages logged.
115  /// </remarks>
117  {
118  get
119  {
120  var consoleLogListener = logListener as ConsoleLogListener;
121  return consoleLogListener != null ? consoleLogListener.LogMode : default(ConsoleLogMode);
122  }
123  set
124  {
125  var consoleLogListener = logListener as ConsoleLogListener;
126  if (consoleLogListener != null)
127  {
128  consoleLogListener.LogMode = value;
129  }
130  }
131  }
132 
133  /// <summary>
134  /// Gets or sets the default console log level.
135  /// </summary>
136  /// <value>The console log level.</value>
137  public LogMessageType ConsoleLogLevel
138  {
139  get
140  {
141  var consoleLogListener = logListener as ConsoleLogListener;
142  return consoleLogListener != null ? consoleLogListener.LogLevel : default(LogMessageType);
143  }
144  set
145  {
146  var consoleLogListener = logListener as ConsoleLogListener;
147  if (consoleLogListener != null)
148  {
149  consoleLogListener.LogLevel = value;
150  }
151  }
152  }
153 
154  /// <summary>
155  /// Initializes a new instance of the <see cref="Game"/> class.
156  /// </summary>
157  public Game()
158  {
159  // Register the logger backend before anything else
160  logListener = GetLogListener();
161 
162  if (logListener != null)
163  GlobalLogger.GlobalMessageLogged += logListener;
164 
165  // Create and register all core services
166  Input = new InputManager(Services);
167  Script = new ScriptSystem(Services);
168  Entities = new EntitySystem(Services);
169 
170  Audio = new AudioSystem(Services);
171  UI = new UISystem(Services);
172  gameFontSystem = new GameFontSystem(Services);
173  SpriteAnimation = new SpriteAnimationSystem(Services);
174 
175  // ---------------------------------------------------------
176  // Add common GameSystems - Adding order is important
177  // (Unless overriden by gameSystem.UpdateOrder)
178  // ---------------------------------------------------------
179 
180  // Add the input manager
181  GameSystems.Add(Input);
182 
183  // Add the scheduler system
184  // - Must be after Input, so that scripts are able to get latest input
185  // - Must be before Entities/Camera/Audio/UI, so that scripts can apply
186  // changes in the same frame they will be applied
187  GameSystems.Add(Script);
188 
189  // Add the UI System
190  GameSystems.Add(UI);
191 
192  // Add the entity manager
193  GameSystems.Add(Entities);
194 
195  // Add the Audio System
196  GameSystems.Add(Audio);
197 
198  // Add the Font system
199  GameSystems.Add(gameFontSystem);
200 
201  //Add the sprite animation System
202  GameSystems.Add(SpriteAnimation);
203 
204  Asset.Serializer.LowLevelSerializerSelector = ParameterContainerExtensions.DefaultSceneSerializerSelector;
205 
206  // Creates the graphics device manager
208  }
209 
210  protected override void Destroy()
211  {
212  base.Destroy();
213 
214  if (logListener != null)
215  GlobalLogger.GlobalMessageLogged -= logListener;
216  }
217 
218  protected override void Initialize()
219  {
220  base.Initialize();
221 
222  if (Context.InitializeDatabase)
223  {
224  InitializeAssetDatabase();
225  }
226 
227  EffectSystem = new EffectSystem(Services);
228  GameSystems.Add(EffectSystem);
229 
230  // Add RenderSystem
231  RenderSystem = new RenderSystem(Services);
232  GameSystems.Add(RenderSystem);
233 
234  using (var profile = Profiler.Begin(GameProfilingKeys.EntityProcessorInitialize))
235  {
236  // TODO: Do we need to make this list data-driven?
237  Entities.Processors.Add(new HierarchicalProcessor());
238  Entities.Processors.Add(new AnimationProcessor());
239  Entities.Processors.Add(new ModelNodeLinkProcessor());
240  Entities.Processors.Add(new TransformationProcessor());
241  Entities.Processors.Add(new MeshProcessor());
242  Entities.Processors.Add(new AudioListenerProcessor());
243  Entities.Processors.Add(new AudioEmitterProcessor());
244  Entities.Processors.Add(new SpriteProcessor());
245  }
246 
247  // TODO: data-driven?
248  Asset.Serializer.RegisterSerializer(new GpuTextureSerializer2<Graphics.Texture>(GraphicsDevice));
249  Asset.Serializer.RegisterSerializer(new GpuTextureSerializer2<Graphics.Texture1D>(GraphicsDevice));
250  Asset.Serializer.RegisterSerializer(new GpuTextureSerializer2<Graphics.Texture2D>(GraphicsDevice));
251  Asset.Serializer.RegisterSerializer(new GpuTextureSerializer2<Graphics.Texture3D>(GraphicsDevice));
252  Asset.Serializer.RegisterSerializer(new GpuTextureSerializer2<Graphics.TextureCube>(GraphicsDevice));
253  Asset.Serializer.RegisterSerializer(new GpuSamplerStateSerializer2(GraphicsDevice));
254  Asset.Serializer.RegisterSerializer(new GpuBlendStateSerializer(GraphicsDevice));
255  Asset.Serializer.RegisterSerializer(new GpuRasterizerStateSerializer(GraphicsDevice));
256  Asset.Serializer.RegisterSerializer(new GpuDepthStencilStateSerializer(GraphicsDevice));
257  Asset.Serializer.RegisterSerializer(new ImageSerializer());
258  Asset.Serializer.RegisterSerializer(new SoundEffectSerializer(Audio.AudioEngine));
259  Asset.Serializer.RegisterSerializer(new SoundMusicSerializer(Audio.AudioEngine));
260 
261  // determine the virtual resolution so that ratio is maintained
262  const int screenDesiredHeight = 1080;
263  var screenRatio = GraphicsDevice.BackBuffer.Width / (float)GraphicsDevice.BackBuffer.Height;
264  VirtualResolution = new Vector3((int)(screenRatio * screenDesiredHeight), screenDesiredHeight, screenDesiredHeight);
265 
266  // enable multi-touch by default
267  Input.MultiTouchEnabled = true;
268  }
269 
270  internal static void InitializeAssetDatabase()
271  {
272  using (var profile = Profiler.Begin(GameProfilingKeys.ObjectDatabaseInitialize))
273  {
274  // Create and mount database file system
275  var objDatabase = new ObjectDatabase("/data/db", "index", "/local/db");
276 
277  // Only set a mount path if not mounted already
278  var mountPath = VirtualFileSystem.ResolveProviderUnsafe("/asset", true).Provider == null ? "/asset" : null;
279  var databaseFileProvider = new DatabaseFileProvider(objDatabase, mountPath);
280 
281  AssetManager.GetFileProvider = () => databaseFileProvider;
282  }
283  }
284 
285  protected override void EndDraw(bool present)
286  {
287 #if SILICONSTUDIO_PLATFORM_WINDOWS_DESKTOP
288  // Allow to make a screenshot using CTRL+c+F12 (on release of F12)
289  if (Input.HasKeyboard)
290  {
291  if (Input.IsKeyDown(Keys.LeftCtrl)
292  && Input.IsKeyDown(Keys.C)
293  && Input.IsKeyReleased(Keys.F12))
294  {
295  var currentFilePath = Assembly.GetEntryAssembly().Location;
296  var timeNow = DateTime.Now.ToString("s", CultureInfo.InvariantCulture).Replace(':', '_');
297  var newFileName = Path.Combine(
298  Path.GetDirectoryName(currentFilePath),
299  Path.GetFileNameWithoutExtension(currentFilePath) + "_" + timeNow + ".png");
300 
301  Console.WriteLine("Saving screenshot: {0}", newFileName);
302 
303  using (var stream = System.IO.File.Create(newFileName))
304  {
305  GraphicsDevice.BackBuffer.Texture.Save(stream, ImageFileType.Png);
306  }
307  }
308  }
309 #endif
310  base.EndDraw(present);
311  }
312 
313  /// <summary>
314  /// Loads the content.
315  /// </summary>
316  protected virtual Task LoadContent()
317  {
318  return Task.FromResult(true);
319  }
320 
321  internal override void LoadContentInternal()
322  {
323  base.LoadContentInternal();
324  Script.Add(LoadContent);
325  }
326  protected virtual LogListener GetLogListener()
327  {
328  return new ConsoleLogListener();
329  }
330  }
331 }
override void EndDraw(bool present)
Ends the drawing of a frame. This method is preceeded by calls to Draw and BeginDraw.
Definition: Game.cs:285
ConsoleLogMode
Defines how the console is opened.
A system in charge of animating the sprites
Keys
Enumeration for keys.
Definition: Keys.cs:8
The interface to create and manage fonts.
Definition: IFontSystem.cs:8
virtual LogListener GetLogListener()
Definition: Game.cs:326
A TextureCube frontend to SharpDX.Direct3D11.Texture2D.
Definition: TextureCube.cs:37
RenderTarget BackBuffer
Gets the back buffer sets by the current Presenter setup on this device.
SiliconStudio.Paradox.Engine.MeshProcessor MeshProcessor
Definition: Game.cs:25
Represents a three dimensional mathematical vector.
Definition: Vector3.cs:42
The script system handles scripts scheduling in a game.
Definition: ScriptSystem.cs:16
SharpDX.DirectWrite.Font Font
This processor will take care of adding/removing children of every Entity added/removed in the Entity...
Main Game class system.
Definition: Game.cs:32
Performs primitive-based rendering, creates resources, handles system-level variables, adjusts gamma ramp levels, and creates shaders. See The+GraphicsDevice+class to learn more about the class.
Gives access to the object database.
Renders its RenderSystem.Pipeline, which will usually result in drawing all meshes, UI, etc...
Definition: RenderSystem.cs:18
virtual Task LoadContent()
Loads the content.
Definition: Game.cs:316
Manage a collection of entities.
Definition: EntitySystem.cs:22
LogMessageType
Type of a LogMessage.
A Texture 3D frontend to SharpDX.Direct3D11.Texture3D.
Definition: Texture3D.cs:37
A Texture 2D frontend to SharpDX.Direct3D11.Texture2D.
Definition: Texture2D.cs:37
A Texture 1D frontend to SharpDX.Direct3D11.Texture1D.
Definition: Texture1D.cs:37
Interface of the UI system.
Definition: UISystem.cs:20
override void Destroy()
Disposes of object resources.
Definition: Game.cs:210
int Height
Gets the height in texel.
Definition: RenderTarget.cs:29
Updates TransformationComponent.WorldMatrix of entities.
Game()
Initializes a new instance of the Game class.
Definition: Game.cs:157
A base class to implement a log listener
Definition: LogListener.cs:10
The Audio System. It creates an underlying instance of AudioEngine.
Definition: AudioSystem.cs:16
override void Initialize()
Called after the Game and GraphicsDevice are created, but before LoadContent. Reference page contains...
Definition: Game.cs:218
Processor in charge of creating and updating the AudioListener data associated to the scene AudioList...
Processor in charge of updating the AudioEmitterComponents.
Base class for texture resources.
Definition: Texture.cs:38
A LogListener implementation redirecting its output to the default OS console. If console is not supp...