public ToolTipInstance(Board board, XNA.Rectangle rect, string title, string desc, int originalNum = -1) : base(board, rect) { this.title = title; this.desc = desc; this.originalNum = originalNum; }
public static Dictionary<string, int> SerializePoint(XNA.Point p) { Dictionary<string, int> result = new Dictionary<string, int>(2); result.Add("x", p.X); result.Add("y", p.Y); return result; }
public override void Begin(GraphicsDevice device, SpriteBlendMode blendMode, SpriteSortMode sortMode, SaveStateMode stateMode, Local.Matrix transformMatrix) { _childRenderer = GetCurrentRenderer(); _childRenderer.Begin(device, blendMode, sortMode, stateMode, transformMatrix); currentSortMode = sortMode; base.Begin(device, blendMode, sortMode, stateMode, transformMatrix); }
/// <summary> /// Calculates the logical position from a given physical position, using the current device orientation. /// </summary> /// <param name="result">The resulting corrected values in logical space.</param> /// <param name="physicalPosition">The original physical position.</param> public static void CalculateLogicalPosition(Vector2 result, Xna.Vector2 physicalPosition) { // get the physical screen dimensions var physicalScreenWidth = (float)DeviceInfo.Current.PhysicalScreenWidth; var physicalScreenHeight = (float)DeviceInfo.Current.PhysicalScreenHeight; // variables float x; float y; // determine how we need to convert the physical x and y coordinates // into logical ones if (DeviceInfo.Current.Orientation == PageOrientation.LandscapeLeft) { x = physicalPosition.Y; y = physicalScreenWidth - physicalPosition.X; } else { // assume PageOrientation.LandscapeRight since we don't support portrait mode at all x = physicalScreenHeight - physicalPosition.Y; y = physicalPosition.X; } // set values result.X = x; result.Y = y; }
private Rectangle[] CreatePatches(Rectangle rectangle) { var x = rectangle.X; var y = rectangle.Y; var w = rectangle.Width; var h = rectangle.Height; var middleWidth = w - LeftPadding - RightPadding; var middleHeight = h - TopPadding - BottomPadding; var bottomY = y + h - BottomPadding; var rightX = x + w - RightPadding; var leftX = x + LeftPadding; var topY = y + TopPadding; var patches = new[] { new Rectangle(x, y, LeftPadding, TopPadding), // top left new Rectangle(leftX, y, middleWidth, TopPadding), // top middle new Rectangle(rightX, y, RightPadding, TopPadding), // top right new Rectangle(x, topY, LeftPadding, middleHeight), // left middle new Rectangle(leftX, topY, middleWidth, middleHeight), // middle new Rectangle(rightX, topY, RightPadding, middleHeight), // right middle new Rectangle(x, bottomY, LeftPadding, BottomPadding), // bottom left new Rectangle(leftX, bottomY, middleWidth, BottomPadding), // bottom middle new Rectangle(rightX, bottomY, RightPadding, BottomPadding) // bottom right }; return patches; }
public BuffZone(Board board, XNA.Rectangle rect, int itemID, int interval, int duration, string zoneName) : base(board, rect) { this.itemID = itemID; this.interval = interval; this.duration = duration; this.zoneName = zoneName; }
public DesktopContext (XNA.GraphicsDeviceManager gdm, SpriteBatch sb, SpriteFont vf, double width, double height) : base(width, height) { this.width = width; this.height = height; spriteBatch = sb; font = vf; graphicsDeviceManager = gdm; imageCache = new Dictionary<string, Texture2D> (); }
static ShadowHullVertex() { var elements = new[] { new VertexElement(0, VertexElementFormat.Vector2, VertexElementUsage.Position, 0), new VertexElement(8, VertexElementFormat.Vector2, VertexElementUsage.Normal,0), new VertexElement(16, VertexElementFormat.Color, VertexElementUsage.Color,0), }; VertexDec = new VertexDeclaration(elements); }
public static void Draw( PrimitiveDrawer primitiveDrawer, Matrix cameraView, Matrix cameraProjection, Vector3 start, Vector3 end, Color color) { var vertices = new[] { new VertexPositionColor(start, Color.White), new VertexPositionColor(end, Color.White) }; primitiveDrawer.Draw(Matrix.Identity, cameraView, cameraProjection, color, null, PrimitiveType.LineList, vertices, false); }
/// <summary> /// Takes a vector and switches/adjusts the X and Y coordinates as required to match /// the logical axis alignment of the device. The result is stored in the <paramref name="result"/> argument. /// </summary> /// <param name="result">Contains the adjusted X and Y coordinates of the physical coordinates.</param> /// <param name="physicalPosition">The original values, using the physical dimensions of the device screen.</param> public static void AdjustLogicalAxis(Vector2 result, Xna.Vector2 physicalPosition) { // determine how we need to convert the physical x and y coordinates // into logical ones if (DeviceInfo.Current.Orientation == PageOrientation.LandscapeLeft) { result.X = physicalPosition.Y; result.Y = -physicalPosition.X; } else { // assume PageOrientation.LandscapeRight since we don't support portrait mode at all result.X = -physicalPosition.Y; result.Y = physicalPosition.X; } }
public void Polygon_Transform_Rotation_Test() { var vertices = new[] { new Vector2(-5, -5), new Vector2(5, 10), new Vector2(-5, 10) }; var polygon = new PolygonF(vertices); polygon.Rotate(MathHelper.ToRadians(90)); const float tolerance = 0.01f; Assert.IsTrue(new Vector2(5, -5).EqualsWithTolerance(polygon.Vertices[0], tolerance)); Assert.IsTrue(new Vector2(-10, 5).EqualsWithTolerance(polygon.Vertices[1], tolerance)); Assert.IsTrue(new Vector2(-10, -5).EqualsWithTolerance(polygon.Vertices[2], tolerance)); }
public void Polygon_Transform_Scale_Test() { var vertices = new[] { new Vector2(0, -1), new Vector2(1, 1), new Vector2(-1, 1) }; var polygon = new PolygonF(vertices); polygon.Scale(new Vector2(1, -0.5f)); const float tolerance = 0.01f; Assert.IsTrue(new Vector2(0, -0.5f).EqualsWithTolerance(polygon.Vertices[0], tolerance), "0"); Assert.IsTrue(new Vector2(2f, 0.5f).EqualsWithTolerance(polygon.Vertices[1], tolerance), "1"); Assert.IsTrue(new Vector2(-2f, 0.5f).EqualsWithTolerance(polygon.Vertices[2], tolerance), "2"); }
public void Polygon_Contains_Point_Test() { var vertices = new[] { new Vector2(0, 0), new Vector2(10, 0), new Vector2(10, 10), new Vector2(0, 10) }; var polygon = new PolygonF(vertices); Assert.IsTrue(polygon.Contains(new Vector2(5, 5))); Assert.IsTrue(polygon.Contains(new Vector2(0.01f, 0.01f))); Assert.IsTrue(polygon.Contains(new Vector2(9.99f, 9.99f))); Assert.IsFalse(polygon.Contains(new Vector2(-1f, -1f))); Assert.IsFalse(polygon.Contains(new Vector2(-11f, -11f))); }
/// <summary> /// Constructor fills in the menu contents. /// </summary> public MainMenuScreen() : base(zh_cn.���˵�) { // Create our menu entries. MenuEntry playGameMenuEntry = new MenuEntry(zh_cn.��ʼ��Ϸ); MenuEntry optionsMenuEntry = new MenuEntry(zh_cn.����ѡ��); MenuEntry exitMenuEntry = new MenuEntry(zh_cn.�˳�); // Hook up menu event handlers. playGameMenuEntry.Selected += PlayGameMenuEntrySelected; optionsMenuEntry.Selected += OptionsMenuEntrySelected; exitMenuEntry.Selected += OnCancel; // Add entries to the menu. MenuEntries.Add(playGameMenuEntry); MenuEntries.Add(optionsMenuEntry); MenuEntries.Add(exitMenuEntry); }
public void Polygon_Transform_Translation_Test() { var vertices = new[] { new Vector2(0, 0), new Vector2(10, 0), new Vector2(10, 10), new Vector2(0, 10) }; var polygon = new PolygonF(vertices); polygon.Offset(new Vector2(2, 3)); Assert.AreEqual(new Vector2(2, 3), polygon.Vertices[0]); Assert.AreEqual(new Vector2(12, 3), polygon.Vertices[1]); Assert.AreEqual(new Vector2(12, 13), polygon.Vertices[2]); Assert.AreEqual(new Vector2(2, 13), polygon.Vertices[3]); }
internal void BlitText(Vector2 position, Local.Rectangle source) { WriteableBitmap SourceImage = Font.SourceData; int[] sourcePixels = Font.SourceData.Pixels; int[] targetPixels = renderedText.Pixels; int sourcePixelWidth = Font.SourceData.PixelWidth; int targetPixelWidth = pixelWidth; for (int i = 0; i < source.Width; i++) { for (int j = 0; j < source.Height; j++) { int sourceIndex = (source.X + i) + ((source.Y + j) * sourcePixelWidth); uint sourcePixel = (uint)sourcePixels[sourceIndex]; int targetIndex = ((int)position.X + i) + (((int)position.Y + j) * targetPixelWidth); uint targetPixel = (uint)targetPixels[targetIndex]; int sa = (byte)((sourcePixel >> 24) & 0xff); byte da = (byte)((targetPixel >> 24) & 0xff); if (sa >= 255 || da == 0) { targetPixels[targetIndex] = (int)sourcePixel; } else if (sa == 0) { } else { // not sure if this compositing algorithm is correct, // there is a good chance it needs to be fixed. byte sr = (byte)((sourcePixel >> 16) & 0xff); byte sg = (byte)((sourcePixel >> 8) & 0xff); byte sb = (byte)((sourcePixel) & 0xff); byte dr = (byte)((targetPixel >> 16) & 0xff); byte dg = (byte)((targetPixel >> 8) & 0xff); byte db = (byte)((targetPixel) & 0xff); int ra = 255 - (255 - sa) * (255 - da) / 255; targetPixels[targetIndex] = (ra << 24) | (blend(sr, dr) << 16) | (blend(sg, dg) << 8) | (blend(sb, db)); } } } }
/// <summary> /// Constructor. /// </summary> public PauseMenuScreen() : base(zh_cn.��ͣ��Ϸ) { // Flag that there is no need for the game to transition // off when the pause menu is on top of it. IsPopup = true; // Create our menu entries. MenuEntry resumeGameMenuEntry = new MenuEntry(zh_cn.������Ϸ); MenuEntry quitGameMenuEntry = new MenuEntry(zh_cn.�˳���Ϸ); // Hook up menu event handlers. resumeGameMenuEntry.Selected += OnCancel; quitGameMenuEntry.Selected += QuitGameMenuEntrySelected; // Add entries to the menu. MenuEntries.Add(resumeGameMenuEntry); MenuEntries.Add(quitGameMenuEntry); }
public void Begin(GraphicsDevice device, SpriteBlendMode blendMode, SpriteSortMode sortMode, SaveStateMode stateMode, Local.Matrix transformMatrix) { //transformMatrix = Matrix.Identity; Rect rect = new Rect( (device.Viewport.X), (device.Viewport.Y), device.Viewport.Width, device.Viewport.Height); if (rect != lastRect || !MatricesAreEqual(transformMatrix, lastMatrix)) { transformMatrix.M41 += device.Viewport.X; transformMatrix.M42 += device.Viewport.Y; MatrixTransform matrixTransform = new MatrixTransform(); System.Windows.Media.Matrix matrix = new System.Windows.Media.Matrix( transformMatrix.M11, transformMatrix.M12, transformMatrix.M21, transformMatrix.M22, transformMatrix.M41, transformMatrix.M42); matrixTransform.Matrix = matrix; System.Windows.Media.RectangleGeometry rectangleGeometry = new System.Windows.Media.RectangleGeometry(); rectangleGeometry.Rect = rect; MatrixTransform inverse = matrixTransform.Inverse as MatrixTransform; rectangleGeometry.Transform = inverse; Canvas.Clip = rectangleGeometry; matrixTransform.Matrix = matrix; TransformMatrix = transformMatrix; lastRect = rect; lastMatrix = transformMatrix; Canvas.Width = rect.Width; Canvas.Height = rect.Height; } InUse = true; Begin(); }
private int[] FindSafety() { UnitSectorManager unitSectorManager = GameLogic.GetInstance().SectorManager; Point sector = unitSectorManager.GetSector(mUnit.Position); int[] fleeSector = new[] {sector.X, sector.Y}; int[] bounds = unitSectorManager.GetSurroundingIndexes(sector.X, sector.Y, 1); float maxRelation = 0; for (int y = bounds[1]; y <= bounds[3]; y++) for (int x = bounds[0]; x <= bounds[2]; x++) if (x != sector.X || y != sector.Y) { float relation = mParent.GetComputerPlayerRelation(x, y); if (relation > maxRelation) { maxRelation = relation; fleeSector[0] = x; fleeSector[1] = y; } } return fleeSector; }
public static CollisionResult CollidesWithSat(this BoundingBox boundingBox, BoundingBox other) { var axis = new[] { Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ }; var shortestAxis = Vector3.Zero; var shortestOverlap = float.MaxValue; for (var i = 0; i < axis.Length; i++) { var currentAxis = axis[i]; var p1 = GetProjectedPoints(boundingBox, currentAxis); var p2 = GetProjectedPoints(other, currentAxis); var overlapValue = p1.OverlapSize(p2); if (overlapValue > 0.0f) { if (overlapValue < shortestOverlap) { shortestOverlap = overlapValue; shortestAxis = p1.Min < p2.Min ? currentAxis : -currentAxis; } } else { return CollisionResult.Empty; } } return new CollisionResult { Collides = true, Axis = shortestAxis * shortestOverlap }; }
public SideBar(ScreenManager screenManager, ContentManager content, Metronome metronome, Rectangle rect) : base(screenManager, metronome, rect) { mContent = content; // Initialize other screens const int width = 300; const int height = 200; var rectangle = new Rectangle(Game.mScreenWidth / 2 - width / 2, Game.mScreenHeight / 2 - height / 2, width, height); mCreateSpeedTemplateHud = new CreateSpeedTemplateHud(mScreenManager, mMetronome, rectangle); mCreateRudimentHud = new CreateRudimentHud(mScreenManager, mMetronome, rectangle); mEditSpeedTemplateHud = new EditSpeedTemplateHud(mScreenManager, mMetronome, rectangle); // Initialize Create buttons var labels = new[] {"New Template", "New Rudiment"}; var actions = new MetronomeScreen.RunAction[] {CreateNewTemplate, CreateNewRudiment}; mButtons = new Button[labels.Length + mMetronome.mSpeedTemplates.Count]; for (var i = 0; i < labels.Length; i++) { mButtons[i].mLabel = labels[i]; mButtons[i].mTexName = "TextButton"; mButtons[i].mState = OwnButtonState.Normal; mButtons[i].mAction = actions[i]; mButtons[i].mTextures = new Texture2D[3]; } mButtons[0].mRectangle = new Rectangle(mRectangle.X + 10, mRectangle.Y + 40 + mMetronome.mSpeedTemplates.Count*30, 100, 25); mButtons[1].mRectangle = new Rectangle(mRectangle.X + 10, mButtons[0].mRectangle.Y + 80 + mMetronome.mRudiments.Count*30, 100, 25); // Initialize Speed Template buttons for (var i = 2; i - 2 < mMetronome.mSpeedTemplates.Count; i++) { mButtons[i].mLabel = mMetronome.mSpeedTemplates[i - 2].mName; mButtons[i].mTexName = "TextButtonBlue"; mButtons[i].mState = OwnButtonState.Normal; mButtons[i].mParameterAction = StartTemplate; mButtons[i].mParameterActionRight = EditTemplate; mButtons[i].mParameter = i - 2; mButtons[i].mTextures = new Texture2D[3]; mButtons[i].mRectangle = new Rectangle(10, 40 + (i - 2) * 30, 100, 20); } }
public MapleEmptyRectangle(Board board, XNA.Rectangle rect) { this.board = board; lock (board.ParentControl) { a = CreateDot(rect.Left, rect.Top); b = CreateDot(rect.Right, rect.Top); c = CreateDot(rect.Right, rect.Bottom); d = CreateDot(rect.Left, rect.Bottom); PlaceDots(); // Make lines ab = CreateLine(a, b); bc = CreateLine(b, c); cd = CreateLine(c, d); da = CreateLine(d, a); ab.yBind = true; bc.xBind = true; cd.yBind = true; da.xBind = true; } }
protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); Vector3 cameraPosition = Vector3.Backward * 2; Matrix cameraView = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up); Matrix cameraProjection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(55), GraphicsDevice.Viewport.AspectRatio, 1, 100); float rotationAngle = (float)gameTime.TotalGameTime.TotalSeconds / 3.0f; Quaternion rotation = Quaternion.CreateFromYawPitchRoll(rotationAngle, 0, 0); switch (_activeShape) { case 0: ShapeVisualizer.DrawWireframeBox(cameraPosition, cameraView, cameraProjection, Vector3.Zero, Vector3.One, rotation, Color.Red); break; case 1: { var matrix = Matrix.CreateLookAt(new Vector3(-5, 1, -5), new Vector3(0, 0, -10), Vector3.Up) * Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 1, 1, 10); var frustum = new BoundingFrustum(matrix); ShapeVisualizer.DrawWireframeFrustum(cameraView, cameraProjection, frustum, Color.Gray); break; } case 2 : { var corners = new[] { new Vector3(-1, -1, 0), new Vector3(1, -1, -1), new Vector3(-1, 1, 0), new Vector3(1, 1, -3) }; ShapeVisualizer.DrawSolidRectangle(cameraView, cameraProjection, corners, Color.Blue); break; } case 3: { for (int i = 0; i < 360; i += 30) ShapeVisualizer.DrawLine(cameraView, cameraProjection, Vector3.Zero, Vector3.TransformNormal(Vector3.Up, Matrix.CreateRotationZ(MathHelper.ToRadians(i))), Color.Yellow); break; } case 4 : { ShapeVisualizer.DrawWireframeDisc(cameraPosition, cameraView, cameraProjection, Vector3.Zero, Vector3.Forward, 0.8f, Color.White, false); break; } case 5 : { ShapeVisualizer.DrawWireframeSphere(cameraPosition, cameraView, cameraProjection, Vector3.Zero, Vector3.Forward, 0.8f, rotation * Quaternion.CreateFromYawPitchRoll(0.2f, 0.4f, 0.1f), Color.White); break; } } DrawOverlayText(); base.Draw(gameTime); }
public void PostDeserializationActions(bool? selected, XNA.Point? offset) { // Nothing to do here, we cant be offset nor selected. }
public Texture2D GetEmote(out XNA.Rectangle emoteRect) { emoteRect = new XNA.Rectangle(); if (_data.emoteFrame < 0) return null; const int NUM_EMOTES = 15; const int NUM_FRAMES = 4; int convertedEmote = 0; switch (_data.emote) { case Emote.Happy: /*0*/break; case Emote.Depressed: convertedEmote = 7; break; case Emote.Sad: convertedEmote = 1; break; case Emote.Angry: convertedEmote = 5; break; case Emote.Confused: convertedEmote = 3; break; case Emote.Surprised: convertedEmote = 2; break; case Emote.Hearts: convertedEmote = 6; break; case Emote.Moon: convertedEmote = 4; break; case Emote.Suicidal: convertedEmote = 9; break; case Emote.Embarassed: convertedEmote = 8; break; case Emote.Drunk: case Emote.Trade: case Emote.LevelUp: case Emote.Playful: convertedEmote = (int)_data.emote - 1; break; default: throw new ArgumentOutOfRangeException(); } Texture2D emote = _gfxManager.TextureFromResource(GFXTypes.PostLoginUI, 38, true); int eachSet = emote.Width/NUM_EMOTES; int eachFrame = emote.Width/(NUM_EMOTES*NUM_FRAMES); emoteRect = new XNA.Rectangle((convertedEmote * eachSet) + (_data.emoteFrame * eachFrame), 0, eachFrame, emote.Height); return emote; }
public Texture2D GetFace(out XNA.Rectangle faceRect) { if (_data.emoteFrame < 0 || _data.emote == Emote.Trade || _data.emote == Emote.LevelUp) { faceRect = new XNA.Rectangle(); return null; } //14 rows (7 female - 7 male) / 11 columns const int ROWS = 14; const int COLS = 11; Texture2D face = _gfxManager.TextureFromResource(GFXTypes.SkinSprites, 8, true); int widthDelta = face.Width/COLS; int heightDelta = face.Height/ROWS; int genderOffset = (face.Height/2)*_data.gender; //'playful' is the last face in the gfx (ndx 10), even though it has enum value of 14 (ndx 13) int emote = _data.emote == Emote.Playful || _data.emote == Emote.Drunk ? 10 : (int)_data.emote - 1; faceRect = new XNA.Rectangle(widthDelta*emote, heightDelta*_data.race + genderOffset, widthDelta, heightDelta); return face; }
public Texture2D GetSkin(bool isBow, out XNA.Rectangle skinRect) { const byte sheetRows = 7; byte sheetColumns = 4; byte gfxNum = 1; //change up which gfx resource to load, and the size of the resource, based on the _data if (_charRef.State == CharacterActionState.Walking && _data.walkFrame > 0) { //walking gfxNum = 2; sheetColumns = 16; } else if (_charRef.State == CharacterActionState.Attacking && _data.attackFrame > 0) { if (!isBow) { //attacking gfxNum = 3; sheetColumns = 8; } else if(_data.attackFrame == 1) //only 1 frame of bow/gun animation { gfxNum = 7; //4 columns in this one too } } else if (_charRef.State == CharacterActionState.SpellCast) { gfxNum = 4; } else if (_charRef.State == CharacterActionState.Sitting) { if (_data.sitting == SitState.Floor) gfxNum = 6; else if (_data.sitting == SitState.Chair) gfxNum = 5; } //similar if statements for spell, emote, etc bool rotated = _data.facing == EODirection.Left || _data.facing == EODirection.Up; Texture2D sheet = _gfxManager.TextureFromResource(GFXTypes.SkinSprites, gfxNum, true); int heightDelta = sheet.Height / sheetRows; //the height of one 'row' in the sheet int widthDelta = sheet.Width / sheetColumns; //the width of one 'column' in the sheet int section = sheet.Width/4; //each 'section' for a different set of graphics int walkExtra = _data.walkFrame > 0 ? widthDelta * (_data.walkFrame - 1) : 0; walkExtra = !isBow && _data.attackFrame > 0 ? widthDelta*(_data.attackFrame - 1) : walkExtra; skinRect = new XNA.Rectangle( _data.gender * widthDelta * (sheetColumns / 2) + (rotated ? section : 0) + walkExtra, _data.race * heightDelta, widthDelta, heightDelta); return sheet; }
public override void Draw(SpriteBatch sprite, XNA.Color color, int xShift, int yShift) { XNA.Rectangle destinationRectangle = new XNA.Rectangle((int)X + xShift - Origin.X, (int)Y + yShift - Origin.Y, Width, Height); sprite.Draw(baseInfo.GetTexture(sprite), destinationRectangle, null, color, 0f, new XNA.Vector2(0, 0), Flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, 0 /*Layer.LayerNumber / 10f + Z / 1000f*/); if (ApplicationSettings.InfoMode) { int xBase = (int)X + xShift; int yBase = (int)Y + yShift; ObjectInfo oi = (ObjectInfo)baseInfo; if (oi.RopeOffsets != null) DrawOffsetMap(sprite, oi.RopeOffsets, xBase, yBase); if (oi.LadderOffsets != null) DrawOffsetMap(sprite, oi.LadderOffsets, xBase, yBase); } base.Draw(sprite, color, xShift, yShift); }
private static void ExtractData(ref Vector3[] vert, ref int[] ind, ref Vector2[] tex, IModelo model, XNA.Vector3 scale) { List<Vector3> vertices = new List<Vector3>(); List<Vector2> texcoords = new List<Vector2>(); List<int> indices = new List<int>(); for (int i = 0; i < model.MeshNumber; i++) { BatchInformation[] bi = model.GetBatchInformation(i); for (int j = 0; j < bi.Length; j++) { BatchInformation info = bi[j]; int offset = vertices.Count; Microsoft.Xna.Framework.Vector3[] a = new Microsoft.Xna.Framework.Vector3[info.NumVertices]; // Read the format of the vertex buffer VertexDeclaration declaration = bi[j].VertexBuffer.VertexDeclaration; VertexElement[] vertexElements = declaration.GetVertexElements(); // Find the element that holds the position VertexElement vertexPosition = new VertexElement(); foreach (VertexElement elem in vertexElements) { if (elem.VertexElementUsage == VertexElementUsage.Position && elem.VertexElementFormat == VertexElementFormat.Vector3) { vertexPosition = elem; // There should only be one break; } } // Check the position element found is valid if (vertexPosition == null || vertexPosition.VertexElementUsage != VertexElementUsage.Position || vertexPosition.VertexElementFormat != VertexElementFormat.Vector3) { throw new Exception("Model uses unsupported vertex format!"); } // This where we store the vertices until transformed // Read the vertices from the buffer in to the array bi[j].VertexBuffer.GetData<Microsoft.Xna.Framework.Vector3>( bi[j].BaseVertex * declaration.VertexStride + vertexPosition.Offset, a, 0, bi[j].NumVertices, declaration.VertexStride); for (int k = 0; k != a.Length; ++k) { XNA.Matrix tra = info.ModelLocalTransformation * XNA.Matrix.CreateScale(scale); Microsoft.Xna.Framework.Vector3.Transform(ref a[k], ref tra, out a[k]); vertices.Add(a[k].AsPhysX()); } foreach (VertexElement elem in vertexElements) { if (elem.VertexElementUsage == VertexElementUsage.TextureCoordinate && elem.VertexElementFormat == VertexElementFormat.Vector2) { vertexPosition = elem; // There should only be one break; } } Microsoft.Xna.Framework.Vector2[] b = new Microsoft.Xna.Framework.Vector2[info.NumVertices]; // This where we store the vertices until transformed // Read the vertices from the buffer in to the array bi[j].VertexBuffer.GetData<Microsoft.Xna.Framework.Vector2>( bi[j].BaseVertex * declaration.VertexStride + vertexPosition.Offset, b, 0, bi[j].NumVertices, declaration.VertexStride); for (int k = 0; k != b.Length; ++k) { texcoords.Add(b[k].AsPhysX()); } if (info.IndexBuffer.IndexElementSize != IndexElementSize.SixteenBits) { int[] s = new int[info.PrimitiveCount * 3]; info.IndexBuffer.GetData<int>(info.StartIndex * 2, s, 0, info.PrimitiveCount * 3); for (int k = 0; k != info.PrimitiveCount; ++k) { indices.Add(s[k * 3 + 2] + offset); indices.Add(s[k * 3 + 1] + offset); indices.Add(s[k * 3 + 0] + offset); } } else { short[] s = new short[info.PrimitiveCount * 3]; info.IndexBuffer.GetData<short>(info.StartIndex * 2, s, 0, info.PrimitiveCount * 3); for (int k = 0; k != info.PrimitiveCount; ++k) { indices.Add(s[k * 3 + 2] + offset); indices.Add(s[k * 3 + 1] + offset); indices.Add(s[k * 3 + 0] + offset); } } } } ind = indices.ToArray(); vert = vertices.ToArray(); tex = texcoords.ToArray(); }
public ClothModel(GraphicFactory factory, PhysxPhysicWorld PhysxPhysicWorld, ClothMeshDescription clothMeshDesc, XNA.Vector3[] Points, XNA.Vector2[] TextCoords, int[] Indices, String diffuseTextureName = null) : base(factory, "Cloth", false) { this._diffuseName = diffuseTextureName; VerticesNum = Points.Length; IndicesNum = Indices.Length; clothMeshDesc.AllocateVertices<Vector3>(VerticesNum); clothMeshDesc.AllocateTriangles<int>(IndicesNum / 3); clothMeshDesc.VertexCount = VerticesNum; clothMeshDesc.TriangleCount = IndicesNum / 3; BatchInformation = new PloobsEngine.Modelo.BatchInformation(0, VerticesNum, IndicesNum / 3, 0, 0, VertexPositionNormalTexture.VertexDeclaration, VertexPositionNormalTexture.VertexDeclaration.VertexStride, PrimitiveType.TriangleList); BatchInformation.ModelLocalTransformation = XNA.Matrix.Identity; vertexPositionNormalTexture = new VertexPositionNormalTexture[VerticesNum]; BatchInformation.VertexBuffer = factory.CreateDynamicVertexBuffer(VertexPositionNormalTexture.VertexDeclaration, VerticesNum + (int)(1.2 * VerticesNum), BufferUsage.WriteOnly); BatchInformation.IndexBuffer = factory.CreateDynamicIndexBuffer(IndexElementSize.ThirtyTwoBits, IndicesNum + (int)(1.2 * IndicesNum), BufferUsage.WriteOnly); BatchInformation.IndexBuffer.SetData<int>(Indices); clothMeshDesc.VerticesStream.SetData(Points); clothMeshDesc.TriangleStream.SetData(Indices); for (int i = 0; i < BatchInformation.NumVertices; i++) { vertexPositionNormalTexture[i].TextureCoordinate = TextCoords[i]; vertexPositionNormalTexture[i].Position = Points[i]; } // We are using 32 bit integers for our indices, so make sure the 16 bit flag is removed. // 32 bits are the default, so this isn't technically needed, but it's good to show in a sample clothMeshDesc.Flags &= ~MeshFlag.Indices16Bit; //clothMeshDesc.Flags |= (MeshFlag)((int)clothMeshDesc.Flags | (int)ClothMeshFlag.Tearable); // Write the cooked data to memory using (var memoryStream = new MemoryStream()) { Cooking.InitializeCooking(); Cooking.CookClothMesh(clothMeshDesc, memoryStream); Cooking.CloseCooking(); // Need to reset the position of the stream to the beginning memoryStream.Position = 0; ClothMesh = PhysxPhysicWorld.Core.CreateClothMesh(memoryStream); } modelRadius = Microsoft.Xna.Framework.BoundingSphere.CreateFromPoints(Points).Radius; LoadModel(factory, out BatchInformations, out TextureInformations); }