Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
SpriteBatch.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 
4 using System;
5 using System.Runtime.InteropServices;
6 using System.Text;
7 using SiliconStudio.Core.Mathematics;
8 using SiliconStudio.Paradox.Effects.Modules;
9 
10 namespace SiliconStudio.Paradox.Graphics
11 {
12  /// <summary>
13  /// Renders a group of sprites.
14  /// </summary>
15  public partial class SpriteBatch : BatchBase<SpriteBatch.SpriteDrawInfo>
16  {
17  private static readonly Vector2[] CornerOffsets = { Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY };
18  private static Vector2 vector2Zero = Vector2.Zero;
19  private static RectangleF? nullRectangle;
20 
21  private Matrix userViewMatrix;
22  private Matrix userProjectionMatrix;
23 
24  private readonly Matrix defaultViewMatrix = Matrix.Identity;
25  private Matrix defaultProjectionMatrix;
26 
27  /// <summary>
28  /// Gets or sets the default depth value used by the <see cref="SpriteBatch"/> when the <see cref="VirtualResolution"/> is not set.
29  /// </summary>
30  /// <remarks>More precisely, this value represents the length "farPlane-nearPlane" used by the default projection matrix.</remarks>
31  public float DefaultDepth { get; set; }
32 
33  /// <summary>
34  /// Gets or sets the virtual resolution used for this <see cref="SpriteBatch"/>
35  /// </summary>
36  public Vector3? VirtualResolution { get; set; }
37 
38  /// <summary>
39  /// Initializes a new instance of the <see cref="SpriteBatch" /> class.
40  /// </summary>
41  /// <param name="graphicsDevice">The graphics device.</param>
42  /// <param name="bufferElementCount">The maximum number element that can be batched in one time.</param>
43  /// <param name="batchCapacity">The batch capacity default to 64.</param>
44  public SpriteBatch(GraphicsDevice graphicsDevice, int bufferElementCount = 1024, int batchCapacity = 64)
45  : base(graphicsDevice, Bytecode, StaticQuadBufferInfo.CreateQuadBufferInfo("SpriteBatch.VertexIndexBuffer", bufferElementCount, batchCapacity), VertexPositionColorTextureSwizzle.Layout)
46  {
47  DefaultDepth = 200f;
48  }
49 
50  /// <summary>
51  /// Calculate the default projection matrix for the provided virtual resolution.
52  /// </summary>
53  /// <returns>The default projection matrix for the provided virtual resolution</returns>
54  /// <remarks>The sprite batch default projection is an orthogonal matrix such as (0,0) is the Top/Left corner of the screen and
55  /// (VirtualResolution.X, VirtualResolution.Y) is the Bottom/Right corner of the screen.</remarks>
56  public static Matrix CalculateDefaultProjection(Vector3 virtualResolution)
57  {
58  Matrix matrix;
59 
60  CalculateDefaultProjection(ref virtualResolution, out matrix);
61 
62  return matrix;
63  }
64 
65  /// <summary>
66  /// Calculate the default projection matrix for the provided virtual resolution.
67  /// </summary>
68  public static void CalculateDefaultProjection(ref Vector3 virtualResolution, out Matrix projection)
69  {
70  var xRatio = 1f / virtualResolution.X;
71  var yRatio = -1f / virtualResolution.Y;
72  var zRatio = -1f / virtualResolution.Z;
73 
74  projection = new Matrix { M11 = 2f * xRatio, M22 = 2f * yRatio, M33 = zRatio, M44 = 1f, M41 = -1f, M42 = 1f, M43 = 0.5f };
75  }
76 
77  private Vector3 GetCurrentResolution()
78  {
79  return VirtualResolution.HasValue ? VirtualResolution.Value: new Vector3(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, DefaultDepth);
80  }
81 
82  private void UpdateDefaultProjectionMatrix()
83  {
84  var resolution = GetCurrentResolution();
85  CalculateDefaultProjection(ref resolution, out defaultProjectionMatrix);
86  }
87 
88  /// <summary>
89  /// Begins a sprite batch operation using deferred sort and default state objects (BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise).
90  /// </summary>
91  /// <param name="sortMode">The sprite drawing order to use for the batch session</param>
92  /// <param name="effect">The effect to use for the batch session</param>
93  public void Begin(SpriteSortMode sortMode, Effect effect)
94  {
95  UpdateDefaultProjectionMatrix();
96  Begin(defaultViewMatrix, defaultProjectionMatrix, sortMode, null, null, null, null, effect);
97  }
98 
99  /// <summary>
100  /// Begins a sprite batch rendering using the specified sorting mode and blend state, sampler, depth stencil and rasterizer state objects, plus a custom effect. Passing null for any of the state objects selects the default default state objects (BlendState.AlphaBlend, DepthStencilState.None, RasterizerState.CullCounterClockwise, SamplerState.LinearClamp). Passing a null effect selects the default SpriteBatch Class shader.
101  /// </summary>
102  /// <param name="sortMode">The sprite drawing order to use for the batch session</param>
103  /// <param name="effect">The effect to use for the batch session</param>
104  /// <param name="blendState">The blending state to use for the batch session</param>
105  /// <param name="samplerState">The sampling state to use for the batch session</param>
106  /// <param name="depthStencilState">The depth stencil state to use for the batch session</param>
107  /// <param name="rasterizerState">The rasterizer state to use for the batch session</param>
108  /// <param name="stencilValue">The value of the stencil buffer to take as reference for the batch session</param>
109  public void Begin(SpriteSortMode sortMode = SpriteSortMode.Deferred, BlendState blendState = null, SamplerState samplerState = null, DepthStencilState depthStencilState = null, RasterizerState rasterizerState = null, Effect effect = null, int stencilValue = 0)
110  {
111  UpdateDefaultProjectionMatrix();
112  Begin(defaultViewMatrix, defaultProjectionMatrix, sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, stencilValue);
113  }
114 
115  /// <summary>
116  /// Begins a sprite batch rendering using the specified sorting mode and blend state, sampler, depth stencil, rasterizer state objects, plus a custom effect and a 2D transformation matrix. Passing null for any of the state objects selects the default default state objects (BlendState.AlphaBlend, DepthStencilState.None, RasterizerState.CullCounterClockwise, SamplerState.LinearClamp). Passing a null effect selects the default SpriteBatch Class shader.
117  /// </summary>
118  /// <param name="sortMode">The sprite drawing order to use for the batch session</param>
119  /// <param name="effect">The effect to use for the batch session</param>
120  /// <param name="blendState">The blending state to use for the batch session</param>
121  /// <param name="samplerState">The sampling state to use for the batch session</param>
122  /// <param name="depthStencilState">The depth stencil state to use for the batch session</param>
123  /// <param name="rasterizerState">The rasterizer state to use for the batch session</param>
124  /// <param name="stencilValue">The value of the stencil buffer to take as reference for the batch session</param>
125  /// <param name="viewMatrix">The view matrix to use for the batch session</param>
126  public void Begin(Matrix viewMatrix, SpriteSortMode sortMode = SpriteSortMode.Deferred, BlendState blendState = null, SamplerState samplerState = null, DepthStencilState depthStencilState = null, RasterizerState rasterizerState = null, Effect effect = null, int stencilValue = 0)
127  {
128  UpdateDefaultProjectionMatrix();
129  Begin(viewMatrix, defaultProjectionMatrix, sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, stencilValue);
130  }
131 
132  /// <summary>
133  /// Begins a sprite batch rendering using the specified sorting mode and blend state, sampler, depth stencil, rasterizer state objects, plus a custom effect and a 2D transformation matrix. Passing null for any of the state objects selects the default default state objects (BlendState.AlphaBlend, DepthStencilState.None, RasterizerState.CullCounterClockwise, SamplerState.LinearClamp). Passing a null effect selects the default SpriteBatch Class shader.
134  /// </summary>
135  /// <param name="sortMode">The sprite drawing order to use for the batch session</param>
136  /// <param name="effect">The effect to use for the batch session</param>
137  /// <param name="blendState">The blending state to use for the batch session</param>
138  /// <param name="samplerState">The sampling state to use for the batch session</param>
139  /// <param name="depthStencilState">The depth stencil state to use for the batch session</param>
140  /// <param name="rasterizerState">The rasterizer state to use for the batch session</param>
141  /// <param name="stencilValue">The value of the stencil buffer to take as reference for the batch session</param>
142  /// <param name="viewMatrix">The view matrix to use for the batch session</param>
143  /// <param name="projectionMatrix">The projection matrix to use for the batch session</param>
144  public void Begin(Matrix viewMatrix, Matrix projectionMatrix, SpriteSortMode sortMode = SpriteSortMode.Deferred, BlendState blendState = null, SamplerState samplerState = null, DepthStencilState depthStencilState = null, RasterizerState rasterizerState = null, Effect effect = null, int stencilValue = 0)
145  {
146  CheckEndHasBeenCalled("begin");
147 
148  userViewMatrix = viewMatrix;
149  userProjectionMatrix = projectionMatrix;
150 
151  Begin(effect, sortMode, blendState, samplerState, depthStencilState, rasterizerState, stencilValue);
152  }
153 
154  /// <summary>
155  /// Adds a sprite to a batch of sprites for rendering using the specified texture, destination rectangle, and color.
156  /// </summary>
157  /// <param name="texture">A texture.</param>
158  /// <param name="destinationRectangle">A rectangle that specifies (in screen coordinates) the destination for drawing the sprite.</param>
159  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
160  /// <remarks>
161  /// Before making any calls to Draw, you must call Begin. Once all calls to Draw are complete, call End.
162  /// </remarks>
163  public void Draw(Texture texture, RectangleF destinationRectangle, Color color)
164  {
165  DrawSprite(texture, ref destinationRectangle, false, ref nullRectangle, color, 0f, ref vector2Zero, SpriteEffects.None, ImageOrientation.AsIs, 0f);
166  }
167 
168  /// <summary>
169  /// Adds a sprite to a batch of sprites for rendering using the specified texture, position and color.
170  /// </summary>
171  /// <param name="texture">A texture.</param>
172  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
173  public void Draw(Texture texture, Vector2 position)
174  {
175  Draw(texture, position, Color.White);
176  }
177 
178  /// <summary>
179  /// Adds a sprite to a batch of sprites for rendering using the specified texture, position and color.
180  /// </summary>
181  /// <param name="texture">A texture.</param>
182  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
183  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
184  public void Draw(Texture texture, Vector2 position, Color color)
185  {
186  var destination = new RectangleF(position.X, position.Y, 1f, 1f);
187  DrawSprite(texture, ref destination, true, ref nullRectangle, color, 0f, ref vector2Zero, SpriteEffects.None, ImageOrientation.AsIs, 0f);
188  }
189 
190  /// <summary>
191  /// Adds a sprite to a batch of sprites for rendering using the specified texture, destination rectangle, source rectangle, color, rotation, origin, effects and layer.
192  /// </summary>
193  /// <param name="texture">A texture.</param>
194  /// <param name="orientation">The source image orientation</param>
195  /// <param name="destinationRectangle">A rectangle that specifies (in screen coordinates) the destination for drawing the sprite. If this rectangle is not the same size as the source rectangle, the sprite will be scaled to fit.</param>
196  /// <param name="sourceRectangle">A rectangle that specifies (in texels) the source texels from a texture. Use null to draw the entire texture. </param>
197  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
198  /// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
199  /// <param name="origin">The sprite origin in the texture in pixels (dependent of image orientation). Default value is (0,0) which represents the upper-left corner.</param>
200  /// <param name="effects">Effects to apply.</param>
201  /// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
202  public void Draw(Texture texture, RectangleF destinationRectangle, RectangleF? sourceRectangle, Color color, float rotation, Vector2 origin,
203  SpriteEffects effects = SpriteEffects.None, ImageOrientation orientation = ImageOrientation.AsIs, float layerDepth = 0f)
204  {
205  DrawSprite(texture, ref destinationRectangle, false, ref sourceRectangle, color, rotation, ref origin, effects, orientation, layerDepth);
206  }
207 
208 
209  /// <summary>
210  /// Adds a sprite to a batch of sprites for rendering using the specified texture, position, source rectangle, color, rotation, origin, scale, effects, and layer.
211  /// </summary>
212  /// <param name="texture">A texture.</param>
213  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
214  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
215  /// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
216  /// <param name="origin">The sprite origin in the texture in pixels (dependent of image orientation). Default value is (0,0) which represents the upper-left corner.</param>
217  /// <param name="scale">Scale factor.</param>
218  /// <param name="effects">Effects to apply.</param>
219  /// <param name="orientation">The source image orientation</param>
220  /// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
221  public void Draw(Texture texture, Vector2 position, Color color, float rotation, Vector2 origin, float scale = 1.0f,
222  SpriteEffects effects = SpriteEffects.None, ImageOrientation orientation = ImageOrientation.AsIs, float layerDepth = 0)
223  {
224  Draw(texture, position, null, color, rotation, origin, scale, effects, orientation, layerDepth);
225  }
226 
227  /// <summary>
228  /// Adds a sprite to a batch of sprites for rendering using the specified texture, position, source rectangle, color, rotation, origin, scale, effects, and layer.
229  /// </summary>
230  /// <param name="texture">A texture.</param>
231  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
232  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
233  /// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
234  /// <param name="origin">The sprite origin in the texture in pixels (dependent of image orientation). Default value is (0,0) which represents the upper-left corner.</param>
235  /// <param name="scale">Scale factor.</param>
236  /// <param name="effects">Effects to apply.</param>
237  /// <param name="orientation">The source image orientation</param>
238  /// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
239  public void Draw(Texture texture, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale,
240  SpriteEffects effects = SpriteEffects.None, ImageOrientation orientation = ImageOrientation.AsIs, float layerDepth = 0)
241  {
242  Draw(texture, position, null, color, rotation, origin, scale, effects, orientation, layerDepth);
243  }
244 
245  /// <summary>
246  /// Adds a sprite to a batch of sprites for rendering using the specified texture, position, source rectangle, and color.
247  /// </summary>
248  /// <param name="texture">A texture.</param>
249  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
250  /// <param name="sourceRectangle">A rectangle that specifies (in texels) the source texels from a texture. Use null to draw the entire texture. </param>
251  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
252  public void Draw(Texture texture, Vector2 position, RectangleF? sourceRectangle, Color color)
253  {
254  var destination = new RectangleF(position.X, position.Y, 1f, 1f);
255  DrawSprite(texture, ref destination, true, ref sourceRectangle, color, 0f, ref vector2Zero, SpriteEffects.None, ImageOrientation.AsIs, 0f);
256  }
257 
258  /// <summary>
259  /// Adds a sprite to a batch of sprites for rendering using the specified texture, position, source rectangle, color, rotation, origin, scale, effects, and layer.
260  /// </summary>
261  /// <param name="texture">A texture.</param>
262  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
263  /// <param name="sourceRectangle">A rectangle that specifies (in texels) the source texels from a texture. Use null to draw the entire texture. </param>
264  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
265  /// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
266  /// <param name="origin">The sprite origin in the texture in pixels (dependent of image orientation). Default value is (0,0) which represents the upper-left corner.</param>
267  /// <param name="scale">Scale factor.</param>
268  /// <param name="effects">Effects to apply.</param>
269  /// <param name="orientation">The source image orientation</param>
270  /// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
271  public void Draw(Texture texture, Vector2 position, RectangleF? sourceRectangle, Color color, float rotation,
272  Vector2 origin, float scale = 1f, SpriteEffects effects = SpriteEffects.None, ImageOrientation orientation = ImageOrientation.AsIs, float layerDepth = 0)
273  {
274  var destination = new RectangleF(position.X, position.Y, scale, scale);
275  DrawSprite(texture, ref destination, true, ref sourceRectangle, color, rotation, ref origin, effects, orientation, layerDepth);
276  }
277 
278  /// <summary>
279  /// Adds a sprite to a batch of sprites for rendering using the specified texture, position, source rectangle, color, rotation, origin, scale, effects, and layer.
280  /// </summary>
281  /// <param name="texture">A texture.</param>
282  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
283  /// <param name="sourceRectangle">A rectangle that specifies (in texels) the source texels from a texture. Use null to draw the entire texture. </param>
284  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
285  /// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
286  /// <param name="origin">The sprite origin in the texture in pixels (dependent of image orientation). Default value is (0,0) which represents the upper-left corner.</param>
287  /// <param name="scale">Scale factor.</param>
288  /// <param name="effects">Effects to apply.</param>
289  /// <param name="orientation">The source image orientation</param>
290  /// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
291  public void Draw(Texture texture, Vector2 position, RectangleF? sourceRectangle, Color color, float rotation,
292  Vector2 origin, Vector2 scale, SpriteEffects effects = SpriteEffects.None, ImageOrientation orientation = ImageOrientation.AsIs, float layerDepth = 0)
293  {
294  var destination = new RectangleF(position.X, position.Y, scale.X, scale.Y);
295  DrawSprite(texture, ref destination, true, ref sourceRectangle, color, rotation, ref origin, effects, orientation, layerDepth);
296  }
297 
298  /// <summary>
299  /// Returns the size of the given text in virtual pixels.
300  /// </summary>
301  /// <param name="spriteFont">The font used to draw the text.</param>
302  /// <param name="text">The text to measure.</param>
303  /// <param name="targetSize">The size of the target to render in</param>
304  /// <returns>The size of the text in virtual pixels.</returns>
305  /// <exception cref="ArgumentNullException">The provided sprite font is null.</exception>
306  public Vector2 MeasureString(SpriteFont spriteFont, string text, Vector2 targetSize)
307  {
308  if (spriteFont == null) throw new ArgumentNullException("spriteFont");
309 
310  return MeasureString(spriteFont, text, spriteFont.Size, targetSize);
311  }
312 
313  /// <summary>
314  /// Returns the size of the given text in virtual pixels.
315  /// </summary>
316  /// <param name="spriteFont">The font used to draw the text.</param>
317  /// <param name="text">The text to measure.</param>
318  /// <param name="targetSize">The size of the target to render in</param>
319  /// <param name="fontSize">The font size (in pixels) used to draw the text.</param>
320  /// <returns>The size of the text in virtual pixels.</returns>
321  /// <exception cref="ArgumentNullException">The provided sprite font is null.</exception>
322  public Vector2 MeasureString(SpriteFont spriteFont, string text, float fontSize, Vector2 targetSize)
323  {
324  if (spriteFont == null) throw new ArgumentNullException("spriteFont");
325 
326  if (string.IsNullOrEmpty(text))
327  return Vector2.Zero;
328 
329  // calculate the size of the text that will be used to draw
330  var virtualResolution = VirtualResolution.HasValue? VirtualResolution.Value: new Vector3(targetSize, DefaultDepth);
331  var ratio = new Vector2(targetSize.X / virtualResolution.X, targetSize.Y / virtualResolution.Y);
332 
333  var realSize = spriteFont.MeasureString(text, fontSize * ratio);
334 
335  // convert pixel size into virtual pixel size (if needed)
336  var virtualSize = realSize;
337  virtualSize.X /= ratio.X;
338  virtualSize.Y /= ratio.Y;
339 
340  return virtualSize;
341  }
342 
343  /// <summary>Adds a string to a batch of sprites for rendering using the specified font, text, position, and color.</summary>
344  /// <param name="spriteFont">A font for displaying text.</param>
345  /// <param name="text">A text string.</param>
346  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
347  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
348  /// <param name="alignment">Describes how to align the text to draw</param>
349  public void DrawString(SpriteFont spriteFont, string text, Vector2 position, Color color, TextAlignment alignment = TextAlignment.Left)
350  {
351  var proxy = new SpriteFont.StringProxy(text);
352  DrawString(spriteFont, ref proxy, -1, ref position, ref color, 0, Vector2.Zero, Vector2.One, SpriteEffects.None, 0f, alignment);
353  }
354 
355  /// <summary>Adds a string to a batch of sprites for rendering using the specified font, text, position, and color.</summary>
356  /// <param name="spriteFont">A font for displaying text.</param>
357  /// <param name="text">Text string.</param>
358  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
359  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
360  /// <param name="alignment">Describes how to align the text to draw</param>
361  public void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2 position, Color color, TextAlignment alignment = TextAlignment.Left)
362  {
363  var proxy = new SpriteFont.StringProxy(text);
364  DrawString(spriteFont, ref proxy, -1, ref position, ref color, 0, Vector2.Zero, Vector2.One, SpriteEffects.None, 0f, alignment);
365  }
366 
367  /// <summary>Adds a string to a batch of sprites for rendering using the specified font, text, position, and color.</summary>
368  /// <param name="spriteFont">A font for displaying text.</param>
369  /// <param name="text">A text string.</param>
370  /// <param name="fontSize">The font size in pixels (ignored in the case of static fonts)</param>
371  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
372  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
373  /// <param name="alignment">Describes how to align the text to draw</param>
374  public void DrawString(SpriteFont spriteFont, string text, float fontSize, Vector2 position, Color color, TextAlignment alignment = TextAlignment.Left)
375  {
376  var proxy = new SpriteFont.StringProxy(text);
377  DrawString(spriteFont, ref proxy, fontSize, ref position, ref color, 0, Vector2.Zero, Vector2.One, SpriteEffects.None, 0f, alignment);
378  }
379 
380  /// <summary>Adds a string to a batch of sprites for rendering using the specified font, text, position, and color.</summary>
381  /// <param name="spriteFont">A font for displaying text.</param>
382  /// <param name="text">Text string.</param>
383  /// <param name="fontSize">The font size in pixels (ignored in the case of static fonts)</param>
384  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
385  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
386  /// <param name="alignment">Describes how to align the text to draw</param>
387  public void DrawString(SpriteFont spriteFont, StringBuilder text, float fontSize, Vector2 position, Color color, TextAlignment alignment = TextAlignment.Left)
388  {
389  var proxy = new SpriteFont.StringProxy(text);
390  DrawString(spriteFont, ref proxy, fontSize, ref position, ref color, 0, Vector2.Zero, Vector2.One, SpriteEffects.None, 0f, alignment);
391  }
392 
393  /// <summary>Adds a string to a batch of sprites for rendering using the specified font, text, position, color, rotation, origin, scale, effects and layer.</summary>
394  /// <param name="spriteFont">A font for displaying text.</param>
395  /// <param name="text">A text string.</param>
396  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
397  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
398  /// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
399  /// <param name="origin">The sprite origin in virtual pixels; the default is (0,0) which represents the upper-left corner.</param>
400  /// <param name="scale">Scale factor.</param>
401  /// <param name="effects">Effects to apply.</param>
402  /// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
403  /// <param name="alignment">Describes how to align the text to draw</param>
404  public void DrawString(SpriteFont spriteFont, string text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth, TextAlignment alignment)
405  {
406  var proxy = new SpriteFont.StringProxy(text);
407  DrawString(spriteFont, ref proxy, -1, ref position, ref color, rotation, ref origin, ref scale, effects, layerDepth, alignment);
408  }
409 
410  /// <summary>Adds a string to a batch of sprites for rendering using the specified font, text, position, color, rotation, origin, scale, effects and layer.</summary>
411  /// <param name="spriteFont">A font for displaying text.</param>
412  /// <param name="text">Text string.</param>
413  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
414  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
415  /// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
416  /// <param name="origin">The sprite origin in virtual pixels; the default is (0,0) which represents the upper-left corner.</param>
417  /// <param name="scale">Scale factor.</param>
418  /// <param name="effects">Effects to apply.</param>
419  /// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
420  /// <param name="alignment">Describes how to align the text to draw</param>
421  public void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth, TextAlignment alignment)
422  {
423  var proxy = new SpriteFont.StringProxy(text);
424  DrawString(spriteFont, ref proxy, -1, ref position, ref color, rotation, ref origin, ref scale, effects, layerDepth, alignment);
425  }
426 
427  /// <summary>Adds a string to a batch of sprites for rendering using the specified font, text, position, color, rotation, origin, scale, effects and layer.</summary>
428  /// <param name="spriteFont">A font for displaying text.</param>
429  /// <param name="text">A text string.</param>
430  /// <param name="fontSize">The font size in pixels (ignored in the case of static fonts)</param>
431  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
432  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
433  /// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
434  /// <param name="origin">The sprite origin in virtual pixels; the default is (0,0) which represents the upper-left corner.</param>
435  /// <param name="scale">Scale factor.</param>
436  /// <param name="effects">Effects to apply.</param>
437  /// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
438  /// <param name="alignment">Describes how to align the text to draw</param>
439  public void DrawString(SpriteFont spriteFont, string text, float fontSize, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth, TextAlignment alignment)
440  {
441  var proxy = new SpriteFont.StringProxy(text);
442  DrawString(spriteFont, ref proxy, fontSize, ref position, ref color, rotation, ref origin, ref scale, effects, layerDepth, alignment);
443  }
444 
445  /// <summary>Adds a string to a batch of sprites for rendering using the specified font, text, position, color, rotation, origin, scale, effects and layer.</summary>
446  /// <param name="spriteFont">A font for displaying text.</param>
447  /// <param name="text">Text string.</param>
448  /// <param name="fontSize">The font size in pixels (ignored in the case of static fonts)</param>
449  /// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
450  /// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
451  /// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
452  /// <param name="origin">The sprite origin in virtual pixels; the default is (0,0) which represents the upper-left corner.</param>
453  /// <param name="scale">Scale factor.</param>
454  /// <param name="effects">Effects to apply.</param>
455  /// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
456  /// <param name="alignment">Describes how to align the text to draw</param>
457  public void DrawString(SpriteFont spriteFont, StringBuilder text, float fontSize, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth, TextAlignment alignment)
458  {
459  var proxy = new SpriteFont.StringProxy(text);
460  DrawString(spriteFont, ref proxy, fontSize, ref position, ref color, rotation, ref origin, ref scale, effects, layerDepth, alignment);
461  }
462 
463  private void DrawString(SpriteFont spriteFont, ref SpriteFont.StringProxy text, float fontSize, ref Vector2 position, ref Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth, TextAlignment alignment)
464  {
465  DrawString(spriteFont, ref text, fontSize, ref position, ref color, rotation, ref origin, ref scale, effects, layerDepth, alignment);
466  }
467 
468  private void DrawString(SpriteFont spriteFont, ref SpriteFont.StringProxy text, float fontSize, ref Vector2 position, ref Color color, float rotation, ref Vector2 origin, ref Vector2 scale, SpriteEffects effects, float layerDepth, TextAlignment alignment)
469  {
470  if (spriteFont == null)
471  {
472  throw new ArgumentNullException("spriteFont");
473  }
474  if (text.IsNull)
475  {
476  throw new ArgumentNullException("text");
477  }
478  if (fontSize < 0)
479  fontSize = spriteFont.Size;
480 
481  // calculate the resolution ratio between the screen real size and the virtual resolution
482  var viewportSize = GraphicsDevice.Viewport;
483  var virtualResolution = GetCurrentResolution();
484  var resolutionRatio = new Vector2(viewportSize.Width / virtualResolution.X, viewportSize.Height / virtualResolution.Y);
485  scale.X = scale.X / resolutionRatio.X;
486  scale.Y = scale.Y / resolutionRatio.Y;
487 
488  var fontSize2 = fontSize * (spriteFont.IsDynamic ? resolutionRatio : Vector2.One);
489  var drawCommand = new SpriteFont.InternalDrawCommand(this, ref fontSize2, ref position, ref color, rotation, ref origin, ref scale, effects, layerDepth);
490 
491  // snap the position the closest 'real' pixel
492  Vector2.Modulate(ref drawCommand.Position, ref resolutionRatio, out drawCommand.Position);
493  drawCommand.Position.X = (float)Math.Round(drawCommand.Position.X);
494  drawCommand.Position.Y = (float)Math.Round(drawCommand.Position.Y);
495  drawCommand.Position.X /= resolutionRatio.X;
496  drawCommand.Position.Y /= resolutionRatio.Y;
497 
498  spriteFont.InternalDraw(ref text, ref drawCommand, alignment);
499  }
500 
501  internal unsafe void DrawSprite(Texture texture, ref RectangleF destination, bool scaleDestination, ref RectangleF? sourceRectangle, Color color,
502  float rotation, ref Vector2 origin, SpriteEffects effects, ImageOrientation orientation, float depth, SwizzleMode swizzle = SwizzleMode.None, bool realSize = false)
503  {
504  // Check that texture is not null
505  if (texture == null)
506  {
507  throw new ArgumentNullException("texture");
508  }
509 
510  // Put values in next ElementInfo
511  var elementInfo = new ElementInfo();
512  var spriteInfo = &elementInfo.DrawInfo;
513 
514  float width;
515  float height;
516 
517  // If the source rectangle has a value, then use it.
518  if (sourceRectangle.HasValue)
519  {
520  var rectangle = sourceRectangle.Value;
521  spriteInfo->Source.X = rectangle.X;
522  spriteInfo->Source.Y = rectangle.Y;
523  width = rectangle.Width;
524  height = rectangle.Height;
525  }
526  else
527  {
528  // Else, use directly the size of the texture
529  spriteInfo->Source.X = 0.0f;
530  spriteInfo->Source.Y = 0.0f;
531  width = texture.Width;
532  height = texture.Height;
533  }
534 
535  // Sets the width and height
536  spriteInfo->Source.Width = width;
537  spriteInfo->Source.Height = height;
538 
539  // Scale the destination box
540  if (scaleDestination)
541  {
542  if (orientation == ImageOrientation.Rotated90)
543  {
544  destination.Width *= height;
545  destination.Height *= width;
546  }
547  else
548  {
549  destination.Width *= width;
550  destination.Height *= height;
551  }
552  }
553 
554  // Sets the destination
555  spriteInfo->Destination = destination;
556 
557  // Copy all other values.
558  spriteInfo->Origin.X = origin.X;
559  spriteInfo->Origin.Y = origin.Y;
560  spriteInfo->Rotation = rotation;
561  spriteInfo->Depth = depth;
562  spriteInfo->SpriteEffects = effects;
563  spriteInfo->Color = color;
564  spriteInfo->Swizzle = swizzle;
565  spriteInfo->TextureSize.X = texture.Width;
566  spriteInfo->TextureSize.Y = texture.Height;
567  spriteInfo->Orientation = orientation;
568 
569  elementInfo.VertexCount = StaticQuadBufferInfo.VertexByElement;
570  elementInfo.IndexCount = StaticQuadBufferInfo.IndicesByElement;
571  elementInfo.Depth = depth;
572 
573  Draw(texture, null, ref elementInfo);
574  }
575 
576  protected override unsafe void UpdateBufferValuesFromElementInfo(ref ElementInfo elementInfo, IntPtr vertexPtr, IntPtr indexPtr, int vertexOffset)
577  {
578  var vertex = (VertexPositionColorTextureSwizzle*)vertexPtr;
579  fixed (SpriteDrawInfo* drawInfo = &elementInfo.DrawInfo)
580  {
581  var deltaX = 1f / drawInfo->TextureSize.X;
582  var deltaY = 1f / drawInfo->TextureSize.Y;
583 
584  var rotation = Math.Abs(drawInfo->Rotation) > MathUtil.ZeroTolerance ? new Vector2((float)Math.Cos(drawInfo->Rotation), (float)Math.Sin(drawInfo->Rotation)) : Vector2.UnitX;
585 
586  // Center scale down to the size of the source texture
587  var origin = drawInfo->Origin;
588  origin.X /= Math.Max(MathUtil.ZeroTolerance, drawInfo->Source.Width);
589  origin.Y /= Math.Max(MathUtil.ZeroTolerance, drawInfo->Source.Height);
590 
591  for (int j = 0; j < 4; j++)
592  {
593  // Gets the corner and take into account the Flip mode.
594  var corner = CornerOffsets[j];
595  // Calculate position on destination
596  var position = new Vector2((corner.X - origin.X) * drawInfo->Destination.Width, (corner.Y - origin.Y) * drawInfo->Destination.Height);
597 
598  // Apply rotation and destination offset
599  vertex->Position.X = drawInfo->Destination.X + (position.X * rotation.X) - (position.Y * rotation.Y);
600  vertex->Position.Y = drawInfo->Destination.Y + (position.X * rotation.Y) + (position.Y * rotation.X);
601  vertex->Position.Z = drawInfo->Depth;
602  vertex->Position.W = 1f;
603  vertex->Color = drawInfo->Color;
604 
605  corner = CornerOffsets[((j ^ (int)drawInfo->SpriteEffects) + (int)drawInfo->Orientation) % 4];
606  vertex->TextureCoordinate.X = (drawInfo->Source.X + corner.X * drawInfo->Source.Width) * deltaX;
607  vertex->TextureCoordinate.Y = (drawInfo->Source.Y + corner.Y * drawInfo->Source.Height) * deltaY;
608 
609  vertex->Swizzle = (int)drawInfo->Swizzle;
610 
611  vertex++;
612  }
613  }
614  }
615 
616  protected override void PrepareForRendering()
617  {
618  Matrix viewProjection;
619  Matrix.MultiplyTo(ref userViewMatrix, ref userProjectionMatrix, out viewProjection);
620 
621  // Setup effect states and parameters: SamplerState and MatrixTransform
622  // Sets the sampler state
623  Effect.Parameters.Set(SpriteBaseKeys.MatrixTransform, viewProjection);
624 
625  base.PrepareForRendering();
626  }
627 
628  [StructLayout(LayoutKind.Sequential)]
629  public struct SpriteDrawInfo
630  {
633  public Vector2 Origin;
634  public float Rotation;
635  public float Depth;
637  public Color Color;
641  }
642  }
643 }
void Begin(SpriteSortMode sortMode=SpriteSortMode.Deferred, BlendState blendState=null, SamplerState samplerState=null, DepthStencilState depthStencilState=null, RasterizerState rasterizerState=null, Effect effect=null, int stencilValue=0)
Begins a sprite batch rendering using the specified sorting mode and blend state, sampler...
Definition: SpriteBatch.cs:109
float Size
Gets the font size (resp. the default font size) for static fonts (resp. for dynamic fonts) in pixels...
Definition: SpriteFont.cs:62
SiliconStudio.Paradox.Games.Mathematics.Vector2 Vector2
static readonly Vector2 Zero
A SiliconStudio.Core.Mathematics.Vector2 with all of its components set to zero.
Definition: Vector2.cs:52
Represents a two dimensional mathematical vector.
Definition: Vector2.cs:42
void Draw(Texture texture, RectangleF destinationRectangle, Color color)
Adds a sprite to a batch of sprites for rendering using the specified texture, destination rectangle...
Definition: SpriteBatch.cs:163
void Begin(SpriteSortMode sortMode, Effect effect)
Begins a sprite batch operation using deferred sort and default state objects (BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise).
Definition: SpriteBatch.cs:93
void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth, TextAlignment alignment)
Adds a string to a batch of sprites for rendering using the specified font, text, position...
Definition: SpriteBatch.cs:421
Contains depth-stencil state for the device.
void DrawString(SpriteFont spriteFont, string text, float fontSize, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth, TextAlignment alignment)
Adds a string to a batch of sprites for rendering using the specified font, text, position...
Definition: SpriteBatch.cs:439
Describes a custom vertex format structure that contains position, color, texture and swizzle informa...
override unsafe void UpdateBufferValuesFromElementInfo(ref ElementInfo elementInfo, IntPtr vertexPtr, IntPtr indexPtr, int vertexOffset)
Update the mapped vertex and index buffer values using the provided element info. ...
Definition: SpriteBatch.cs:576
TextAlignment
Specify the available text alignment when rendering text.
Definition: TextAlignment.cs:8
const float ZeroTolerance
The value for which all absolute numbers smaller than are considered equal to zero.
Definition: MathUtil.cs:38
Represents a three dimensional mathematical vector.
Definition: Vector3.cs:42
SpriteEffects
Defines sprite mirroring options.
static Matrix CalculateDefaultProjection(Vector3 virtualResolution)
Calculate the default projection matrix for the provided virtual resolution.
Definition: SpriteBatch.cs:56
void DrawString(SpriteFont spriteFont, StringBuilder text, float fontSize, Vector2 position, Color color, TextAlignment alignment=TextAlignment.Left)
Adds a string to a batch of sprites for rendering using the specified font, text, position...
Definition: SpriteBatch.cs:387
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.
static readonly Vector2 One
A SiliconStudio.Core.Mathematics.Vector2 with all of its components set to one.
Definition: Vector2.cs:67
Define a RectangleF. This structure is slightly different from System.Drawing.RectangleF as it is int...
Definition: RectangleF.cs:36
Vector2 MeasureString(SpriteFont spriteFont, string text, Vector2 targetSize)
Returns the size of the given text in virtual pixels.
Definition: SpriteBatch.cs:306
void Draw(Texture texture, Vector2 position, Color color, float rotation, Vector2 origin, float scale=1.0f, SpriteEffects effects=SpriteEffects.None, ImageOrientation orientation=ImageOrientation.AsIs, float layerDepth=0)
Adds a sprite to a batch of sprites for rendering using the specified texture, position, source rectangle, color, rotation, origin, scale, effects, and layer.
Definition: SpriteBatch.cs:221
SpriteSortMode
Defines sprite sort-rendering options.
void Draw(Texture texture, Vector2 position, RectangleF?sourceRectangle, Color color, float rotation, Vector2 origin, float scale=1f, SpriteEffects effects=SpriteEffects.None, ImageOrientation orientation=ImageOrientation.AsIs, float layerDepth=0)
Adds a sprite to a batch of sprites for rendering using the specified texture, position, source rectangle, color, rotation, origin, scale, effects, and layer.
Definition: SpriteBatch.cs:271
void DrawString(SpriteFont spriteFont, string text, Vector2 position, Color color, TextAlignment alignment=TextAlignment.Left)
Adds a string to a batch of sprites for rendering using the specified font, text, position...
Definition: SpriteBatch.cs:349
SpriteFont to use with SpriteBatch. See SpriteFont to learn how to use it.
Definition: SpriteFont.cs:26
float Y
The Y component of the vector.
Definition: Vector2.cs:79
void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2 position, Color color, TextAlignment alignment=TextAlignment.Left)
Adds a string to a batch of sprites for rendering using the specified font, text, position...
Definition: SpriteBatch.cs:361
Represents a 32-bit color (4 bytes) in the form of RGBA (in byte order: R, G, B, A).
Definition: Color.cs:16
void Draw(Texture texture, Vector2 position, RectangleF?sourceRectangle, Color color)
Adds a sprite to a batch of sprites for rendering using the specified texture, position, source rectangle, and color.
Definition: SpriteBatch.cs:252
void DrawString(SpriteFont spriteFont, StringBuilder text, float fontSize, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth, TextAlignment alignment)
Adds a string to a batch of sprites for rendering using the specified font, text, position...
Definition: SpriteBatch.cs:457
Vector2 MeasureString(SpriteFont spriteFont, string text, float fontSize, Vector2 targetSize)
Returns the size of the given text in virtual pixels.
Definition: SpriteBatch.cs:322
void Draw(Texture texture, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects=SpriteEffects.None, ImageOrientation orientation=ImageOrientation.AsIs, float layerDepth=0)
Adds a sprite to a batch of sprites for rendering using the specified texture, position, source rectangle, color, rotation, origin, scale, effects, and layer.
Definition: SpriteBatch.cs:239
static void CalculateDefaultProjection(ref Vector3 virtualResolution, out Matrix projection)
Calculate the default projection matrix for the provided virtual resolution.
Definition: SpriteBatch.cs:68
void Draw(Texture texture, Vector2 position, Color color)
Adds a sprite to a batch of sprites for rendering using the specified texture, position and color...
Definition: SpriteBatch.cs:184
SwizzleMode
Specify how to swizzle a vector.
Definition: SwizzleMode.cs:8
float X
The X component of the vector.
Definition: Vector2.cs:73
void Draw(Texture texture, RectangleF destinationRectangle, RectangleF?sourceRectangle, Color color, float rotation, Vector2 origin, SpriteEffects effects=SpriteEffects.None, ImageOrientation orientation=ImageOrientation.AsIs, float layerDepth=0f)
Adds a sprite to a batch of sprites for rendering using the specified texture, destination rectangle...
Definition: SpriteBatch.cs:202
void DrawString(SpriteFont spriteFont, string text, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth, TextAlignment alignment)
Adds a string to a batch of sprites for rendering using the specified font, text, position...
Definition: SpriteBatch.cs:404
SiliconStudio.Core.Mathematics.Vector3 Vector3
static readonly Color White
White color.
void DrawString(SpriteFont spriteFont, string text, float fontSize, Vector2 position, Color color, TextAlignment alignment=TextAlignment.Left)
Adds a string to a batch of sprites for rendering using the specified font, text, position...
Definition: SpriteBatch.cs:374
void Draw(Texture texture, Vector2 position)
Adds a sprite to a batch of sprites for rendering using the specified texture, position and color...
Definition: SpriteBatch.cs:173
void Draw(Texture texture, Vector2 position, RectangleF?sourceRectangle, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects=SpriteEffects.None, ImageOrientation orientation=ImageOrientation.AsIs, float layerDepth=0)
Adds a sprite to a batch of sprites for rendering using the specified texture, position, source rectangle, color, rotation, origin, scale, effects, and layer.
Definition: SpriteBatch.cs:291
SiliconStudio.Core.Mathematics.RectangleF RectangleF
Definition: SpriteFont.cs:17
SpriteBatch(GraphicsDevice graphicsDevice, int bufferElementCount=1024, int batchCapacity=64)
Initializes a new instance of the SpriteBatch class.
Definition: SpriteBatch.cs:44
void Begin(Matrix viewMatrix, Matrix projectionMatrix, SpriteSortMode sortMode=SpriteSortMode.Deferred, BlendState blendState=null, SamplerState samplerState=null, DepthStencilState depthStencilState=null, RasterizerState rasterizerState=null, Effect effect=null, int stencilValue=0)
Begins a sprite batch rendering using the specified sorting mode and blend state, sampler...
Definition: SpriteBatch.cs:144
void Begin(Matrix viewMatrix, SpriteSortMode sortMode=SpriteSortMode.Deferred, BlendState blendState=null, SamplerState samplerState=null, DepthStencilState depthStencilState=null, RasterizerState rasterizerState=null, Effect effect=null, int stencilValue=0)
Begins a sprite batch rendering using the specified sorting mode and blend state, sampler...
Definition: SpriteBatch.cs:126
ImageOrientation
Defines the possible rotations to apply on image regions.
Base class for texture resources.
Definition: Texture.cs:38
Represents a 4x4 mathematical matrix.
Definition: Matrix.cs:47