I'm trying to render 3D over 2D in Monogame, but can't figure out why it won't work!
Here's the drawing callback:
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
Resolution.BeginDraw();
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, DepthStencilState.Default,
RasterizerState.CullCounterClockwise, null, Resolution.getTransformationMatrix());
m_ScrManager.Draw();
spriteBatch.End();
//Reset device to defaults before rendering...
GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
GraphicsDevice.Viewport = new Viewport(0, 0, GlobalSettings.Default.ScreenWidth, GlobalSettings.Default.ScreenHeight);
m_ScrManager.Draw3D();
HitVM.Step();
base.Draw(gameTime);
}
}
Here is Resolution.cs:
//////////////////////////////////////////////////////////////////////////
////License: The MIT License (MIT)
////Copyright (c) 2010 David Amador (http://www.david-amador.com)
////
////Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
////
////The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
////
////THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Gonzo
{
public static class Resolution
{
static private GraphicsDeviceManager _Device = null;
//From: http://www.discussiongenerator.com/2012/09/15/resolution-independent-2d-rendering-in-xna-4/
static private int virtualViewportX;
static private int virtualViewportY;
static private int _Width = 800;
static private int _Height = 600;
static private int _VWidth = 1024;
static private int _VHeight = 768;
static private Matrix _ScaleMatrix;
static private bool _FullScreen = false;
static private bool _dirtyMatrix = true;
public static int VirtualViewportX { get { return virtualViewportX; } }
public static int VirtualViewportY { get { return virtualViewportY; } }
static public void Init(ref GraphicsDeviceManager device)
{
_Width = device.PreferredBackBufferWidth;
_Height = device.PreferredBackBufferHeight;
_Device = device;
_dirtyMatrix = true;
ApplyResolutionSettings();
}
static public Matrix getTransformationMatrix()
{
if (_dirtyMatrix) RecreateScaleMatrix();
return _ScaleMatrix;
}
static public void SetResolution(int Width, int Height, bool FullScreen)
{
_Width = Width;
_Height = Height;
_FullScreen = FullScreen;
ApplyResolutionSettings();
}
static public void SetVirtualResolution(int Width, int Height)
{
_VWidth = Width;
_VHeight = Height;
_dirtyMatrix = true;
}
static private void ApplyResolutionSettings()
{
#if XBOX360
_FullScreen = true;
#endif
// If we aren't using a full screen mode, the height and width of the window can
// be set to anything equal to or smaller than the actual screen size.
if (_FullScreen == false)
{
if ((_Width <= GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width)
&& (_Height <= GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height))
{
_Device.PreferredBackBufferWidth = _Width;
_Device.PreferredBackBufferHeight = _Height;
_Device.IsFullScreen = _FullScreen;
_Device.ApplyChanges();
}
}
else
{
// If we are using full screen mode, we should check to make sure that the display
// adapter can handle the video mode we are trying to set. To do this, we will
// iterate through the display modes supported by the adapter and check them against
// the mode we want to set.
foreach (DisplayMode dm in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes)
{
// Check the width and height of each mode against the passed values
if ((dm.Width == _Width) && (dm.Height == _Height))
{
// The mode is supported, so set the buffer formats, apply changes and return
_Device.PreferredBackBufferWidth = _Width;
_Device.PreferredBackBufferHeight = _Height;
_Device.IsFullScreen = _FullScreen;
_Device.ApplyChanges();
}
}
}
_dirtyMatrix = true;
_Width = _Device.PreferredBackBufferWidth;
_Height = _Device.PreferredBackBufferHeight;
}
/// <summary>
/// Sets the device to use the draw pump
/// Sets correct aspect ratio
/// </summary>
static public void BeginDraw()
{
// Start by reseting viewport to (0,0,1,1)
FullViewport();
// Clear to Black
_Device.GraphicsDevice.Clear(Color.Black);
// Calculate Proper Viewport according to Aspect Ratio
ResetViewport();
// and clear that
// This way we are gonna have black bars if aspect ratio requires it and
// the clear color on the rest
_Device.GraphicsDevice.Clear(Color.CornflowerBlue);
}
static private void RecreateScaleMatrix()
{
_dirtyMatrix = false;
_ScaleMatrix = Matrix.CreateScale(
(float)_Device.GraphicsDevice.Viewport.Width / _VWidth,
(float)_Device.GraphicsDevice.Viewport.Width / _VWidth,
1f);
}
static public void FullViewport()
{
Viewport vp = new Viewport();
vp.X = vp.Y = 0;
vp.Width = _Width;
vp.Height = _Height;
_Device.GraphicsDevice.Viewport = vp;
}
/// <summary>
/// Get virtual Mode Aspect Ratio
/// </summary>
/// <returns>aspect ratio</returns>
static public float getVirtualAspectRatio()
{
return (float)_VWidth / (float)_VHeight;
}
static public void ResetViewport()
{
float targetAspectRatio = getVirtualAspectRatio();
// figure out the largest area that fits in this resolution at the desired aspect ratio
int width = _Device.PreferredBackBufferWidth;
int height = (int)(width / targetAspectRatio + .5f);
bool changed = false;
if (height > _Device.PreferredBackBufferHeight)
{
height = _Device.PreferredBackBufferHeight;
// PillarBox
width = (int)(height * targetAspectRatio + .5f);
changed = true;
}
// set up the new viewport centered in the backbuffer
Viewport viewport = new Viewport();
viewport.X = (_Device.PreferredBackBufferWidth / 2) - (width / 2);
viewport.Y = (_Device.PreferredBackBufferHeight / 2) - (height / 2);
viewport.Width = width;
viewport.Height = height;
viewport.MinDepth = 0;
viewport.MaxDepth = 1;
virtualViewportX = viewport.X;
virtualViewportY = viewport.Y;
if (changed)
{
_dirtyMatrix = true;
}
_Device.GraphicsDevice.Viewport = viewport;
}
}
}
Here is the 3D rendering:
public void Render(Matrix ViewMatrix, Matrix WorldMatrix, Matrix ProjectionMatrix)
{
//This sets DepthBufferEnable and DepthBufferWriteEnable.
m_Devc.DepthStencilState = DepthStencilState.Default;
m_Devc.BlendState = BlendState.AlphaBlend;
m_Devc.RasterizerState = RasterizerState.CullNone;
// Configure effects
m_HeadEffect.World = WorldMatrix;
m_HeadEffect.View = ViewMatrix;
m_HeadEffect.Projection = ProjectionMatrix;
m_HeadEffect.EnableDefaultLighting();
if (HeadTexture != null)
{
m_HeadEffect.Texture = HeadTexture;
m_HeadEffect.TextureEnabled = true;
}
m_BodyEffect.World = WorldMatrix;
m_BodyEffect.View = ViewMatrix;
m_BodyEffect.Projection = ProjectionMatrix;
m_BodyEffect.EnableDefaultLighting();
if (m_BodyEffect != null)
{
m_BodyEffect.Texture = BodyTexture;
m_BodyEffect.TextureEnabled = true;
}
// Configure effects
m_LeftHandEffect.World = WorldMatrix;
m_LeftHandEffect.View = ViewMatrix;
m_LeftHandEffect.Projection = ProjectionMatrix;
m_LeftHandEffect.EnableDefaultLighting();
if (LeftHandTexture != null)
{
m_LeftHandEffect.Texture = LeftHandTexture;
m_LeftHandEffect.TextureEnabled = true;
}
if (HeadMesh != null)
{
foreach (EffectPass Pass in m_HeadEffect.CurrentTechnique.Passes)
{
Pass.Apply();
foreach (Vector3 Fce in HeadMesh.Faces)
{
// Draw
VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3];
Vertex[0] = HeadMesh.TransformedVertices[(int)Fce.X];
Vertex[1] = HeadMesh.TransformedVertices[(int)Fce.Y];
Vertex[2] = HeadMesh.TransformedVertices[(int)Fce.Z];
Vertex[0].TextureCoordinate = HeadMesh.TransformedVertices[(int)Fce.X].TextureCoordinate;
Vertex[1].TextureCoordinate = HeadMesh.TransformedVertices[(int)Fce.Y].TextureCoordinate;
Vertex[2].TextureCoordinate = HeadMesh.TransformedVertices[(int)Fce.Z].TextureCoordinate;
Vertex[0].Normal = HeadMesh.TransformedVertices[(int)Fce.X].Normal;
Vertex[1].Normal = HeadMesh.TransformedVertices[(int)Fce.Y].Normal;
Vertex[2].Normal = HeadMesh.TransformedVertices[(int)Fce.Z].Normal;
m_Devc.DrawUserPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList, Vertex, 0, 1);
}
TransformVertices(HeadMesh, null, MeshType.Head);
}
}
if (BodyMesh != null)
{
foreach (EffectPass Pass in m_BodyEffect.CurrentTechnique.Passes)
{
Pass.Apply();
foreach (Vector3 Fce in BodyMesh.Faces)
{
// Draw
VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3];
Vertex[0] = BodyMesh.TransformedVertices[(int)Fce.X];
Vertex[1] = BodyMesh.TransformedVertices[(int)Fce.Y];
Vertex[2] = BodyMesh.TransformedVertices[(int)Fce.Z];
Vertex[0].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.X].TextureCoordinate;
Vertex[1].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.Y].TextureCoordinate;
Vertex[2].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.Z].TextureCoordinate;
Vertex[0].Normal = BodyMesh.TransformedVertices[(int)Fce.X].Normal;
Vertex[1].Normal = BodyMesh.TransformedVertices[(int)Fce.Y].Normal;
Vertex[2].Normal = BodyMesh.TransformedVertices[(int)Fce.Z].Normal;
m_Devc.DrawUserPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList, Vertex, 0, 1);
}
TransformVertices(BodyMesh, Skel.Bones[0], MeshType.Body);
}
}
if (LeftHandMesh != null)
{
foreach (EffectPass Pass in m_LeftHandEffect.CurrentTechnique.Passes)
{
Pass.Apply();
foreach (Vector3 Fce in LeftHandMesh.Faces)
{
// Draw
VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3];
Vertex[0] = LeftHandMesh.TransformedVertices[(int)Fce.X];
Vertex[1] = LeftHandMesh.TransformedVertices[(int)Fce.Y];
Vertex[2] = LeftHandMesh.TransformedVertices[(int)Fce.Z];
m_Devc.DrawUserPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList, Vertex, 0, 1);
}
TransformVertices(LeftHandMesh, null, MeshType.LHand);
}
}
if (RightHandMesh != null)
{
foreach (EffectPass Pass in m_LeftHandEffect.CurrentTechnique.Passes)
{
Pass.Apply();
foreach (Vector3 Fce in RightHandMesh.Faces)
{
// Draw
VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3];
Vertex[0] = RightHandMesh.TransformedVertices[(int)Fce.X];
Vertex[1] = RightHandMesh.TransformedVertices[(int)Fce.Y];
Vertex[2] = RightHandMesh.TransformedVertices[(int)Fce.Z];
m_Devc.DrawUserPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList, Vertex, 0, 1);
}
TransformVertices(RightHandMesh, null, MeshType.RHand);
}
}
}
/// <summary>
/// Transforms all vertices in a given mesh to their correct positions.
/// </summary>
/// <param name="Msh">The mesh to transform.</param>
/// <param name="bone">The bone to transform to.</param>
private void TransformVertices(Mesh Msh, Bone bone, MeshType MshType)
{
switch (MshType)
{
case MeshType.Head:
for (int i = 0; i < Msh.TotalVertexCount; i++)
{
//Transform the head vertices' position by the absolute transform
//for the headbone (which is always bone 17) to render the head in place.
Msh.TransformedVertices[i].Position = Vector3.Transform(Msh.RealVertices[i].Position,
Skel.Bones[16].AbsoluteMatrix);
Msh.TransformedVertices[i].TextureCoordinate = Msh.RealVertices[i].TextureCoordinate;
//Transform the head normals' position by the absolute transform
//for the headbone (which is always bone 17) to render the head in place.
Msh.TransformedVertices[i].Normal = Vector3.Transform(Msh.RealVertices[i].Normal,
Skel.Bones[16].AbsoluteMatrix);
}
return;
case MeshType.Body:
BoneBinding boneBinding = Msh.BoneBindings.FirstOrDefault(x => Msh.Bones[(int)x.BoneIndex] == bone.Name);
if (boneBinding != null)
{
for (int i = 0; i < boneBinding.RealVertexCount; i++)
{
int vertexIndex = (int)boneBinding.FirstRealVertexIndex + i;
VertexPositionNormalTexture relativeVertex = Msh.RealVertices[vertexIndex];
Matrix translatedMatrix = Matrix.CreateTranslation(new Vector3(relativeVertex.Position.X, relativeVertex.Position.Y, relativeVertex.Position.Z)) * bone.AbsoluteMatrix;
Msh.TransformedVertices[vertexIndex].Position = Vector3.Transform(Vector3.Zero, translatedMatrix);
Msh.TransformedVertices[vertexIndex].TextureCoordinate = relativeVertex.TextureCoordinate;
//Normals...
translatedMatrix = Matrix.CreateTranslation(new Vector3(relativeVertex.Normal.X, relativeVertex.Normal.Y, relativeVertex.Normal.Z)) * bone.AbsoluteMatrix;
Msh.TransformedVertices[vertexIndex].Normal = Vector3.Transform(Vector3.Zero, translatedMatrix);
}
}
foreach (var child in bone.Children)
TransformVertices(Msh, child, MshType);
break;
case MeshType.LHand:
for (int i = 0; i < Msh.TotalVertexCount; i++)
{
//Transform the left hand vertices' position by the absolute transform
//for the left handbone (which is always bone 10) to render the left hand in place.
Msh.TransformedVertices[i].Position = Vector3.Transform(Msh.RealVertices[i].Position,
Skel.Bones[9].AbsoluteMatrix);
//Transform the left hand normals' position by the absolute transform
//for the left handbone (which is always bone 10) to render the left hand in place.
Msh.TransformedVertices[i].Normal = Vector3.Transform(Msh.RealVertices[i].Normal,
Skel.Bones[9].AbsoluteMatrix);
}
return;
case MeshType.RHand:
for (int i = 0; i < Msh.TotalVertexCount; i++)
{
//Transform the right hand vertices' position by the absolute transform
//for the right handbone (which is always bone 15) to render the right hand in place.
Msh.TransformedVertices[i].Position = Vector3.Transform(Msh.RealVertices[i].Position,
Skel.Bones[14].AbsoluteMatrix);
//Transform the right hand normals' position by the absolute transform
//for the right handbone (which is always bone 15) to render the right hand in place.
Msh.TransformedVertices[i].Normal = Vector3.Transform(Msh.RealVertices[i].Normal,
Skel.Bones[14].AbsoluteMatrix);
}
return;
}
}
The 3D rendering works fine when I comment out the 2D rendering from the drawing callback. Why? :\