public static CreateGatheringByUserIdRequest FromDict(JsonData data) { return(new CreateGatheringByUserIdRequest { namespaceName = data.Keys.Contains("namespaceName") && data["namespaceName"] != null ? data["namespaceName"].ToString(): null, userId = data.Keys.Contains("userId") && data["userId"] != null ? data["userId"].ToString(): null, player = data.Keys.Contains("player") && data["player"] != null?global::Gs2.Gs2Matchmaking.Model.Player.FromDict(data["player"]) : null, attributeRanges = data.Keys.Contains("attributeRanges") && data["attributeRanges"] != null ? data["attributeRanges"].Cast <JsonData>().Select(value => { return AttributeRange.FromDict(value); } ).ToList() : null, capacityOfRoles = data.Keys.Contains("capacityOfRoles") && data["capacityOfRoles"] != null ? data["capacityOfRoles"].Cast <JsonData>().Select(value => { return CapacityOfRole.FromDict(value); } ).ToList() : null, allowUserIds = data.Keys.Contains("allowUserIds") && data["allowUserIds"] != null ? data["allowUserIds"].Cast <JsonData>().Select(value => { return value.ToString(); } ).ToList() : null, expiresAt = data.Keys.Contains("expiresAt") && data["expiresAt"] != null ? (long?)long.Parse(data["expiresAt"].ToString()) : null, duplicationAvoider = data.Keys.Contains("duplicationAvoider") && data["duplicationAvoider"] != null ? data["duplicationAvoider"].ToString(): null, }); }
private ExtendedMaterial[] InitMaterialArray(Dictionary <IPXVertex, int> vDic) { ExtendedMaterial[] ExMaterialArray = new ExtendedMaterial[Pmx.Material.Count]; ARangeArray = new AttributeRange[Pmx.Material.Count]; ExMaterialArray = new ExtendedMaterial[Pmx.Material.Count]; int faceOffset = 0; for (int i = 0; i < Pmx.Material.Count; i++) { IPXMaterial m = Pmx.Material[i]; ARangeArray[i] = new AttributeRange { AttribId = i, FaceCount = m.Faces.Count, FaceStart = faceOffset, VertexCount = VIndices[i].Count, VertexStart = vDic[m.Faces[0].Vertex1] }; faceOffset += m.Faces.Count; ExMaterialArray[i] = new ExtendedMaterial { MaterialD3D = new Material { //Ambient = new Color4(1,m.Ambient.R,m.Ambient.G,m.Ambient.B), Emissive = new Color4(1, m.Ambient.R, m.Ambient.G, m.Ambient.B), Diffuse = m.Diffuse.ToColor4(), Power = m.Power, Specular = new Color4(m.Specular.ToColor3()) }, TextureFileName = m.Tex }; } return(ExMaterialArray); }
private void BuildMesh() { SortAtributes(); var at = new AttributeRange[_cantLayers]; for (int i = 0; i < _cantLayers; i++) { var ar = new AttributeRange { AttributeId = i }; int fi = -1, li = -1; for (int j = 0; j < _cantFaces; j++) { if (_atributos[j] == i) { if (fi == -1) { fi = j; } li = j; } } if (fi != -1) { ar.FaceCount = li - fi + 1; ar.FaceStart = fi; ar.VertexStart = 0; ar.VertexCount = _cantVertices; } at[i] = ar; } var m = new Mesh(_cantFaces, _cantVertices, MeshFlags.Use32Bit | MeshFlags.Managed, TgcSceneLoader.DiffuseMapVertexElements, GuiController.Instance.D3dDevice); m.SetAttributeTable(at); var atrib = m.LockAttributeBufferArray(LockFlags.None); _atributos.CopyTo(atrib, 0); m.UnlockAttributeBuffer(atrib); m.SetVertexBufferData(_vertices, LockFlags.None); m.SetIndexBufferData(_indices, LockFlags.None); _mesh = new TgcMesh(m, "mesh", TgcMesh.MeshRenderType.DIFFUSE_MAP) { Materials = _materialData, DiffuseMaps = _textures, Enabled = true, AlphaBlendEnable = false, }; _mesh.BoundingBox = new TgcBoundingBox(minVert, maxVert); }
public static UpdateGatheringRequest FromDict(JsonData data) { return(new UpdateGatheringRequest { namespaceName = data.Keys.Contains("namespaceName") && data["namespaceName"] != null ? data["namespaceName"].ToString(): null, gatheringName = data.Keys.Contains("gatheringName") && data["gatheringName"] != null ? data["gatheringName"].ToString(): null, attributeRanges = data.Keys.Contains("attributeRanges") && data["attributeRanges"] != null ? data["attributeRanges"].Cast <JsonData>().Select(value => { return AttributeRange.FromDict(value); } ).ToList() : null, duplicationAvoider = data.Keys.Contains("duplicationAvoider") && data["duplicationAvoider"] != null ? data["duplicationAvoider"].ToString(): null, }); }
public AttributeRange[] GenerateAttributeTable(int vertex_start, int vertex_count) { AttributeRange[] da = new AttributeRange[at.Count]; for (int i = 0; i < at.Count; i++) { MqoAttributeRange ar = at[i]; da[i].AttributeId = ar.AttributeId; da[i].FaceStart = ar.FaceStart; da[i].FaceCount = ar.FaceCount; da[i].VertexStart = vertex_start; da[i].VertexCount = vertex_count; } return(da); }
private void CreateMesh() { AttributeRange attributeRange = new AttributeRange(); meshTerrain = new Mesh(indicesMesh.Length / 3, vertices.Length, MeshFlags.SystemMemory, CustomVertex.PositionColored.Format, map.device); attributeRange.AttributeId = 0; attributeRange.FaceStart = 0; attributeRange.FaceCount = indicesMesh.Length / 3; attributeRange.VertexStart = 0; attributeRange.VertexCount = vertices.Length; meshTerrain.VertexBuffer.SetData(vertices, 0, LockFlags.None); meshTerrain.IndexBuffer.SetData(indicesMesh, 0, LockFlags.None); meshTerrain.SetAttributeTable(new AttributeRange[] { attributeRange }); }
public static void AddAttribute(Dictionary <Attributes, AttributeRange> attributes, string[] rawAttributes) { if (rawAttributes == null) { return; } attributes.Clear(); for (int i = 0; i < rawAttributes.Length / FIELD_COUNT; i++) { int rowIndex = i * FIELD_COUNT; var attribute = (Attributes)Enum.Parse(typeof(Attributes), rawAttributes[rowIndex]); var minValue = float.Parse(rawAttributes[rowIndex + 1], System.Globalization.CultureInfo.InvariantCulture); var maxValue = float.Parse(rawAttributes[rowIndex + 2], System.Globalization.CultureInfo.InvariantCulture); var attributeRange = new AttributeRange(minValue, maxValue); attributes.Add(attribute, attributeRange); } }
/// <summary> /// Invalidates the CompositionAdorner render. /// Used in TextServicesDisplayAttributePropertyRanges (for composition display attribute) /// </summary> internal void InvalidateAdorner() { for (int i = 0; i < _attributeRanges.Count; i++) { // Get the composition attribute range from the attribute range lists AttributeRange attributeRange = (AttributeRange)_attributeRanges[i]; // Add the composition lines for rendering the composition lines attributeRange.AddCompositionLines(); } // Invalidate the CompositionAdorner to update the rendering. AdornerLayer adornerLayer = VisualTreeHelper.GetParent(this) as AdornerLayer; if (adornerLayer != null) { adornerLayer.Update(AdornedElement); adornerLayer.InvalidateArrange(); } }
public static void Hook0600002E(Mesh mesh, int i, ref Material mat) { mat = mesh.GetMaterials()[i].MaterialD3D; mat.Ambient = mat.Diffuse; Color4 col = new Color4(0.0f, 0.0f, 0.0f, 0.0f); if ((mesh.VertexFormat & VertexFormat.Texture1) != VertexFormat.None) { int index = 0; int count = mesh.VertexCount; if (mesh.GetAttributeTable() != null && i < mesh.GetAttributeTable().Length) { AttributeRange attr = mesh.GetAttributeTable()[i]; if (attr != null) { index = attr.VertexStart; count = attr.VertexCount; } } int stride = mesh.VertexBuffer.Description.SizeInBytes / mesh.VertexCount; count = Math.Min(count, mesh.VertexCount - index); if (count > 0 && mesh.VertexBuffer != null) { DataStream stream = mesh.VertexBuffer.Lock(stride * index, stride * count, LockFlags.ReadOnly); for (int j = 0; j < count; ++j) { stream.Seek(stride - 8, SeekOrigin.Current); Vector2 vec = stream.Read <Vector2>(); col.Red = Math.Min(col.Red, vec.X); col.Green = Math.Max(col.Green, vec.X); col.Blue = Math.Min(col.Blue, vec.Y); col.Alpha = Math.Max(col.Alpha, vec.Y); } mesh.VertexBuffer.Unlock(); } } mat.Specular = col; }
//------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Render override to render the composition adorner here. /// </summary> protected override void OnRender(DrawingContext drawingContext) { // Get the matrix from AdornedElement to the visual parent to get the transformed // start/end point Visual parent2d = VisualTreeHelper.GetParent(this.AdornedElement) as Visual; if (parent2d == null) { return; } GeneralTransform transform = AdornedElement.TransformToAncestor(parent2d); if (transform == null) { return; } // Please note that we do the highlight adornment for the CONVERTED text only // for Simplified Chinese IMEs. Doing this uniformly across all IMEs wasnt possible // because it was noted that some of them (viz. Japanese) werent being consistent // about this attribute. bool isChinesePinyin = chinesePinyin.Equals(InputLanguageManager.Current.CurrentInputLanguage.IetfLanguageTag); // Render the each of the composition string attribute from the attribute ranges. for (int i = 0; i < _attributeRanges.Count; i++) { DoubleCollection dashArray; // Get the composition attribute range from the attribute range lists AttributeRange attributeRange = (AttributeRange)_attributeRanges[i]; // Skip the rendering composition lines if the composition line doesn't exist. if (attributeRange.CompositionLines.Count == 0) { continue; } // Set the line bold and squiggle bool lineBold = attributeRange.TextServicesDisplayAttribute.IsBoldLine ? true : false; bool squiggle = false; bool hasVirtualSelection = (attributeRange.TextServicesDisplayAttribute.AttrInfo & UnsafeNativeMethods.TF_DA_ATTR_INFO.TF_ATTR_TARGET_CONVERTED) != 0; Brush selectionBrush = null; double selectionOpacity = -1; Pen selectionPen = null; if (isChinesePinyin && hasVirtualSelection) { DependencyObject owner = _textView.TextContainer.Parent; selectionBrush = (Brush)owner.GetValue(TextBoxBase.SelectionBrushProperty); selectionOpacity = (double)owner.GetValue(TextBoxBase.SelectionOpacityProperty); } // Set the line height and cluse gap value that base on the ratio of text height double height = attributeRange.Height; double lineHeight = height * (lineBold ? BoldLineHeightRatio : NormalLineHeightRatio); double clauseGap = height * ClauseGapRatio; // Create Pen for drawing the composition lines with the specified line color Pen pen = new Pen(new SolidColorBrush(Colors.Black), lineHeight); // Set the pen style that based on IME's composition line style switch (attributeRange.TextServicesDisplayAttribute.LineStyle) { case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_DOT: // Add the dot length and specify the start/end line cap as the round dashArray = new DoubleCollection(); dashArray.Add(DotLength); dashArray.Add(DotLength); pen.DashStyle = new DashStyle(dashArray, 0); pen.DashCap = System.Windows.Media.PenLineCap.Round; pen.StartLineCap = System.Windows.Media.PenLineCap.Round; pen.EndLineCap = System.Windows.Media.PenLineCap.Round; // Update the line height for the dot line. Dot line will be more thickness than // other line to show it clearly. lineHeight = height * (lineBold ? BoldDotLineHeightRatio : NormalDotLineHeightRatio); break; case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_DASH: double dashLength = height * (lineBold ? BoldDashRatio : NormalDashRatio); double dashGapLength = height * (lineBold ? BoldDashGapRatio : NormalDashGapRatio); // Add the dash and dash gap legth dashArray = new DoubleCollection(); dashArray.Add(dashLength); dashArray.Add(dashGapLength); pen.DashStyle = new DashStyle(dashArray, 0); pen.DashCap = System.Windows.Media.PenLineCap.Round; pen.StartLineCap = System.Windows.Media.PenLineCap.Round; pen.EndLineCap = System.Windows.Media.PenLineCap.Round; break; case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_SOLID: pen.StartLineCap = System.Windows.Media.PenLineCap.Round; pen.EndLineCap = System.Windows.Media.PenLineCap.Round; break; case UnsafeNativeMethods.TF_DA_LINESTYLE.TF_LS_SQUIGGLE: squiggle = true; break; } double halfLineHeight = lineHeight / 2; // Draw the each of the composition line for (int j = 0; j < attributeRange.CompositionLines.Count; j++) { CompositionLine compositionLine = (CompositionLine)attributeRange.CompositionLines[j]; // Get the start/end point for composition adorner. // Currently Text doesn't aware of the spaceroom for the drawing of the composition // adorner(like as normal/bold dot/line/squggle), so we should draw the composition adorners // to the closest area of the bottom text. Point startPoint = new Point(compositionLine.StartPoint.X + clauseGap, compositionLine.StartPoint.Y - halfLineHeight); Point endPoint = new Point(compositionLine.EndPoint.X - clauseGap, compositionLine.EndPoint.Y - halfLineHeight); // Apply composition line color which is actually the foreground of text as well pen.Brush = new SolidColorBrush(compositionLine.LineColor); // Apply matrix to start/end point // transform.TryTransform(startPoint, out startPoint); transform.TryTransform(endPoint, out endPoint); if (isChinesePinyin && hasVirtualSelection) { Rect rect = Rect.Union(compositionLine.StartRect, compositionLine.EndRect); rect = transform.TransformBounds(rect); drawingContext.PushOpacity(selectionOpacity); drawingContext.DrawRectangle(selectionBrush, selectionPen, rect); drawingContext.Pop(); } if (squiggle) { // Draw the squiggle line with using of the PathFigure and DrawGemetry. // We may revisit this logic to render the smooth squiggle line. Point pathPoint = new Point(startPoint.X, startPoint.Y - halfLineHeight); double squiggleGap = halfLineHeight; PathFigure pathFigure = new PathFigure(); pathFigure.StartPoint = pathPoint; int indexPoint = 0; while (indexPoint < ((endPoint.X - startPoint.X) / (squiggleGap))) { if (indexPoint % 4 == 0 || indexPoint % 4 == 3) { pathPoint = new Point(pathPoint.X + squiggleGap, pathPoint.Y + halfLineHeight); pathFigure.Segments.Add(new LineSegment(pathPoint, true)); } else if (indexPoint % 4 == 1 || indexPoint % 4 == 2) { pathPoint = new Point(pathPoint.X + squiggleGap, pathPoint.Y - halfLineHeight); pathFigure.Segments.Add(new LineSegment(pathPoint, true)); } indexPoint++; } PathGeometry pathGeometry = new PathGeometry(); pathGeometry.Figures.Add(pathFigure); // Draw the composition line with the squiggle drawingContext.DrawGeometry(null, pen, pathGeometry); } else { drawingContext.DrawLine(pen, startPoint, endPoint); } } } }
/// <summary> /// Generates a mesh from the parsed /// information of the file /// </summary> private void GenerateMesh(Device d3dDevice) { if(m_alNormals.Count == 0) throw new System.Exception("No normals were found for this mesh."); if(m_intNumFaces == 0) throw new System.Exception("No faces were found for this mesh."); if(m_intNumVerts == 0) throw new System.Exception("No vertices were found for this mesh."); //create a mesh with Poisiton, Normal, and Texture info. Even if it doesn't contain TextCoords m_d3dMesh = new Mesh(m_intNumFaces, m_intNumVerts, MeshFlags.Managed, CustomVertex.PositionNormalTextured.Format, d3dDevice); //index array short[] aryIndices = new short[m_alVertFormat.Count]; CustomVertex.PositionNormalTextured[] aryVerts = new CustomVertex.PositionNormalTextured[m_intNumVerts]; Vector3 v, t, n; CustomVertex.PositionNormalTextured cvVert; //loop through each face and apply the format for(int i=0; i<m_intNumFaces * 3; i++) { //parse the vertex information string[] aryVertInfo = (string[])m_alVertFormat[i]; //first one is vertex index short index = short.Parse(aryVertInfo[0]); //OBJ format starts at 1 not 0 index--; //set the index arry aryIndices[i] = index; v = (Vector3)m_alVertices[index]; t = new Vector3(0,0,0); //parse the texture coords if( aryVertInfo.Length == 3) { index = short.Parse(aryVertInfo[1]); index--; //set the texture coordinate t = (Vector3)m_alTextCoords[index]; index = short.Parse(aryVertInfo[2]); index--; //set the normal n = (Vector3)m_alNormals[index]; } else { index = short.Parse(aryVertInfo[1]); index--; //set the normal n = (Vector3)m_alNormals[index]; } cvVert = aryVerts[aryIndices[i]]; cvVert.Position = v; cvVert.Normal = n; cvVert.Tu = t.X; cvVert.Tv = t.Y; aryVerts[aryIndices[i]] = cvVert; }//end for loop m_d3dMesh.VertexBuffer.SetData(aryVerts,0, LockFlags.None); m_d3dMesh.IndexBuffer.SetData(aryIndices,0,LockFlags.None); AttributeRange ar = new AttributeRange(); ar.AttributeId = 0; ar.FaceCount = m_intNumFaces; ar.FaceStart = 0; ar.VertexCount = m_intNumVerts; ar.VertexStart = 0; m_d3dMesh.SetAttributeTable(new AttributeRange[] {ar}); int[] adj = new int[m_intNumFaces * 3]; m_d3dMesh.GenerateAdjacency(0.01f, adj); m_d3dMesh.OptimizeInPlace(MeshFlags.OptimizeVertexCache | MeshFlags.OptimizeIgnoreVerts, adj); m_d3dMesh.ComputeNormals(); m_bLoaded = true; }
/// <summary> /// Loads a mesh from the given stream /// </summary> /// <param name="device">A d3d mobile device which will be displaying /// the mesh</param> /// <param name="stream">The stream containing serialized mesh data /// </param> /// <param name="flags">Option flags</param> /// <param name="materials">Output array is filled with any needed /// materials</param> /// <param name="textures">Output array is filled with the filenames /// of any needed textures</param> /// <returns></returns> public static Mesh LoadMesh(Device device, Stream stream, MeshFlags flags, out Material [] materials, out string [] textures) { if (device == null) { throw new ArgumentException("Argument device was invalid"); } if (stream == null) { throw new ArgumentException("Argument stream was invalid"); } byte [] rgb; byte [] rgbIb; byte [] rgbVb; Mesh meshRet; VertexBuffer vb; IndexBuffer ib; int fileMagicNumber; int fileVersion; VertexFormats flexibleVertexFormat; int numberVertices; int numberIndices; int is16BitIndices; int numberMaterials; int numberAttrRanges; int offsetVertex; int offsetIndices; int offsetAttrRange; int offsetMaterial; int bytesMaterials; int bytesIndices; int [] attributeTable; AttributeRange [] attributeRanges; rgb = new byte [512]; stream.Seek(0, SeekOrigin.Begin); // Read header, any errors will be propagated up stream.Read(rgb, 0, sizeofHeader); // read and verify magic number fileMagicNumber = BitConverter.ToInt32(rgb, 0); if (fileMagicNumber != magicNumber) { throw new MeshSerializationException( "The serialized data does not represent a mesh"); } // read and verify version fileVersion = BitConverter.ToInt32(rgb, 4); if (fileVersion != versionNumber) { throw new MeshSerializationException( "The format version was not recognized"); } flexibleVertexFormat = (VertexFormats) BitConverter.ToInt32(rgb, 8); numberVertices = BitConverter.ToInt32(rgb, 12); numberIndices = BitConverter.ToInt32(rgb, 16); is16BitIndices = BitConverter.ToInt32(rgb, 20); numberMaterials = BitConverter.ToInt32(rgb, 24); numberAttrRanges = BitConverter.ToInt32(rgb, 28); offsetVertex = BitConverter.ToInt32(rgb, 32); offsetIndices = BitConverter.ToInt32(rgb, 36); offsetAttrRange = BitConverter.ToInt32(rgb, 40); offsetMaterial = BitConverter.ToInt32(rgb, 44); bytesMaterials = BitConverter.ToInt32(rgb, 48); // verify number of vertices if (numberVertices < 0) { throw new MeshSerializationException( String.Format(CultureInfo.InvariantCulture, "Invalid number of vertices: {0}", numberVertices)); } // verify number of indices if (numberIndices < 0 || numberIndices % 3 != 0) { throw new MeshSerializationException( String.Format(CultureInfo.InvariantCulture, "Invalid number of indices: {0}", numberIndices)); } // verify number of materials if (numberMaterials < 0) { throw new MeshSerializationException( String.Format(CultureInfo.InvariantCulture, "Invalid number of materials: {0}", numberMaterials)); } // verify number of attribute ranges if (numberAttrRanges < 0) { throw new MeshSerializationException( String.Format(CultureInfo.InvariantCulture, "Invalid number of attribute ranges: {0}", numberAttrRanges)); } // determine number of index bytes and verify Is16BitIndices if (is16BitIndices == 1) { bytesIndices = numberIndices * 2; } else if (is16BitIndices == 0) { bytesIndices = numberIndices * 4; } else { throw new MeshSerializationException( String.Format(CultureInfo.InvariantCulture, "Invalid value for is16BitIndices: {0}", is16BitIndices)); } // Managed Direct3D mobile uses different Fvf defines than // managed Direct3D for the desktop // when this code is linked against the desktop version // this will convert the Fvf to match MD3DM constants // when this code is linked against MD3DM this section will // not have changed anything. // determine the necessary Fvf int sourceFormat = (int)flexibleVertexFormat; int textureCount; flexibleVertexFormat = VertexFormats.Position; if ((sourceFormat & md3dmFvfNormal) != 0) { flexibleVertexFormat |= VertexFormats.Normal; } if ((sourceFormat & md3dmFvfDiffuse) != 0) { flexibleVertexFormat |= VertexFormats.Diffuse; } if ((sourceFormat & md3dmFvfSpecular) != 0) { flexibleVertexFormat |= VertexFormats.Specular; } // determine number of textures textureCount = (sourceFormat & (int)VertexFormats.TextureCountMask) >> (int)md3dmFvfTextureCountShift; //limit to 4 textures if (textureCount > 4) { textureCount = 4; } // continue setting up necessary Fvf flexibleVertexFormat |= (VertexFormats)( textureCount << (int)VertexFormats.TextureCountShift); int bytesVertices = VertexInformation.GetFormatSize(flexibleVertexFormat) * numberVertices; // Verify none of the data regions overlap // the material section is variable size so we can't check // that one yet if (!((offsetVertex >= sizeofHeader) && (offsetIndices >= offsetVertex + bytesVertices) && (offsetAttrRange >= offsetIndices + bytesIndices) && (offsetMaterial >= offsetAttrRange + numberAttrRanges * sizeofAttributeRange) && (stream.Length >= offsetMaterial + bytesMaterials))) { throw new MeshSerializationException( "The data regions are not " + "within the stream or overlap"); } // create our data tables materials = new Material[numberMaterials]; textures = new string[numberMaterials]; attributeRanges = new AttributeRange[numberAttrRanges]; attributeTable = new int[numberIndices / 3]; // move to the attribute range section, propagate up // any exception stream.Seek(offsetAttrRange, SeekOrigin.Begin); // parse attribute ranges for (int i = 0; i < numberAttrRanges; i++) { int attribId; int faceStart; int faceCount; int vertexStart; int vertexCount; // read in the attribute range data stream.Read(rgb, 0, sizeofAttributeRange); attribId = BitConverter.ToInt32(rgb, 0); faceStart = BitConverter.ToInt32(rgb, 4); faceCount = BitConverter.ToInt32(rgb, 8); vertexStart = BitConverter.ToInt32(rgb, 12); vertexCount = BitConverter.ToInt32(rgb, 16); // verify the data if ((vertexStart < 0 || vertexCount < 0 || vertexStart + vertexCount > numberVertices) || (faceStart < 0 || faceCount < 0 || (faceStart + faceCount) * 3 > numberIndices)) { throw new ApplicationException( "Invalid attribute range"); } // store the validated data attributeRanges[i].AttributeId = attribId; attributeRanges[i].FaceStart = faceStart; attributeRanges[i].FaceCount = faceCount; attributeRanges[i].VertexStart = vertexStart; attributeRanges[i].VertexCount = vertexCount; for (int j = faceStart; j < faceStart + faceCount; j++) { attributeTable[j] = attribId; } } // move to the material section stream.Seek(offsetMaterial, SeekOrigin.Begin); // parse materials for (int i = 0; i < numberMaterials; i++) { int cbTexture; // verify that we aren't reading past the end of the stream // its possible an invalid filename length the if (stream.Position + sizeofMaterial > stream.Length) { throw new MeshSerializationException( "Material data region is" + " corrupt"); } // read in the material color data stream.Read(rgb, 0, sizeofMaterial); materials[i].DiffuseColor = new ColorValue( BitConverter.ToSingle(rgb, 0), BitConverter.ToSingle(rgb, 4), BitConverter.ToSingle(rgb, 8), BitConverter.ToSingle(rgb, 12)); materials[i].AmbientColor = new ColorValue( BitConverter.ToSingle(rgb, 16), BitConverter.ToSingle(rgb, 20), BitConverter.ToSingle(rgb, 24), BitConverter.ToSingle(rgb, 28)); materials[i].SpecularColor = new ColorValue( BitConverter.ToSingle(rgb, 32), BitConverter.ToSingle(rgb, 36), BitConverter.ToSingle(rgb, 40), BitConverter.ToSingle(rgb, 44)); materials[i].SpecularSharpness = BitConverter.ToSingle(rgb, 48); // read in the size of the texture filename cbTexture = BitConverter.ToInt32(rgb, 52); // verify that the texture filename has a valid length if (cbTexture < 0 || stream.Position + cbTexture > stream.Length) { throw new MeshSerializationException( "Material data region is corrupt"); } // read the texture filename if (cbTexture > 0) { stream.Read(rgb, 0, cbTexture); textures[i] = Encoding.Unicode.GetString(rgb, 0, cbTexture); } } // create data buffers rgbIb = new byte[bytesIndices]; rgbVb = new byte[bytesVertices]; // read in the index data stream.Seek(offsetIndices, SeekOrigin.Begin); stream.Read(rgbIb, 0, rgbIb.Length); // read in the vertex data stream.Seek(offsetVertex, SeekOrigin.Begin); stream.Read(rgbVb, 0, rgbVb.Length); // set the use 32 bit flag appropriately flags = (flags & ~(MeshFlags.Use32Bit)) | ((is16BitIndices == 0) ? MeshFlags.Use32Bit : 0); // create a new empty mesh meshRet = new Mesh(numberIndices / 3, numberVertices, flags, flexibleVertexFormat, device); try { // create the index and vertex buffer vb = meshRet.VertexBuffer; ib = meshRet.IndexBuffer; // write the vertex data vb.Lock(0, bytesVertices, LockFlags.None).Write(rgbVb, 0, bytesVertices); vb.Unlock(); // write the index data ib.Lock(0, rgbIb.Length, LockFlags.None).Write(rgbIb, 0, rgbIb.Length); ib.Unlock(); // set the attributes meshRet.LockAttributeBuffer(LockFlags.None); meshRet.UnlockAttributeBuffer(attributeTable); meshRet.SetAttributeTable(attributeRanges); } catch (DirectXException e) { // release the mesh if anything went wrong meshRet.Dispose(); meshRet = null; throw e; } return(meshRet); }
private void RebuildAsync(Object deviceObj) { try { Device device = (Device)deviceObj; // Rebuild if (_line.Equals("")) { _lineSprite = null; _valid = true; } else { try { int firstTick = Environment.TickCount; System.Drawing.Font font = new System.Drawing.Font(_fontFace, _fontSize); Bitmap b = new Bitmap(_lineWidth, _lineHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(b); g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; g.FillRectangle(new SolidBrush(Color.Black), new Rectangle(0, 0, b.Width, b.Height)); g.DrawString(_displayString, font, new SolidBrush(Color.White), new PointF(0, 0)); //TextRenderer.DrawText(g, _displayString, font, new Point(0, 0), Color.White); _lineTexture = Texture.FromBitmap(device, b, Usage.None, Pool.Managed); //_lineTexture = new Texture(device, (int)_lineWidth * (int)Math.Pow(2.0, (double)mipLevels), (int)_lineHeight * (int)Math.Pow(2.0, (double)mipLevels), mipLevels + 1, Usage.RenderTarget, Format.Unknown, Pool.Default); //Surface s = _lineTexture.GetSurfaceLevel(mipLevels); //SurfaceLoader.FromSurface(s, Surface.FromBitmap(device, b, Pool.Default), Filter.Box, 0xFF0000); g.Dispose(); //for (int i = 1; i <= mipLevels; i++) //{ // int width = _lineWidth * (int)Math.Pow(2.0, (double)i); // int height = _lineHeight * (int)Math.Pow(2, (double)i); // b = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); // font = new System.Drawing.Font(_fontFace, _fontSize * (float)Math.Pow(2, (double)i)); // g = Graphics.FromImage(b); // g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; // g.FillRectangle(new SolidBrush(Color.Black), new Rectangle(0, 0, b.Width, b.Height)); // g.DrawString(displayString, font, new SolidBrush(Color.White), new PointF(0, 0)); // s = _lineTexture.GetSurfaceLevel(mipLevels - i); // SurfaceLoader.FromSurface(s, Surface.FromBitmap(device, b, Pool.Default), Filter.Box, 0xFF0000); // g.Dispose(); //} // Set up the material _lineMaterial = new Material(); _lineMaterial.Diffuse = _line.Color; //_lineMaterial.Ambient = GetColor(_line.Type); // Set up the rectangular mesh CustomVertex.PositionNormalTextured[] verts = new CustomVertex.PositionNormalTextured[4]; verts[0].Position = new Vector3(0, 0, -_lineHeight); verts[0].Normal = new Vector3(0, 1, 0); verts[0].Tu = 0; verts[0].Tv = 1; verts[1].Position = new Vector3(_lineWidth, 0, -_lineHeight); verts[1].Normal = new Vector3(0, 1, 0); verts[1].Tu = 1; verts[1].Tv = 1; verts[2].Position = new Vector3(_lineWidth, 0, 0); verts[2].Normal = new Vector3(0, 1, 0); verts[2].Tu = 1; verts[2].Tv = 0; verts[3].Position = new Vector3(0, 0, 0); verts[3].Normal = new Vector3(0, 1, 0); verts[3].Tu = 0; verts[3].Tv = 0; AttributeRange[] attributes = new AttributeRange[1]; attributes[0].AttributeId = 0; attributes[0].FaceCount = 2; attributes[0].FaceStart = 0; attributes[0].VertexCount = 4; attributes[0].VertexStart = 0; short[] indices = new short[] { 0, 1, 2, 0, 2, 3 }; _lineSprite = new Mesh(2, 4, 0, CustomVertex.PositionNormalTextured.Format, device); _lineSprite.SetVertexBufferData(verts, LockFlags.Discard); _lineSprite.SetIndexBufferData(indices, LockFlags.Discard); _lineSprite.SetAttributeTable(attributes); //int[] adjacency = new int[_lineSprite.NumberFaces * 3]; //_lineSprite.GenerateAdjacency(0.01F, adjacency); //_lineSprite.OptimizeInPlace(MeshFlags.OptimizeVertexCache, adjacency); _valid = true; } catch (Exception) { _valid = false; _lineTexture = null; _lineSprite = null; return; } } } catch (Exception) { _valid = false; _lineTexture = null; _lineSprite = null; } finally { Animate(0); _building = false; } }
public static Mesh CreateConeLimit(Microsoft.DirectX.Direct3D.Device d3dDevice, float fltHalfAngle, float fltHeight, int iSides) { Mesh mesh; AttributeRange ar = new AttributeRange(); float fltRotAmnt = Geometry.DegreeToRadian(360.0f/iSides); //create indices short[] aryIndices = new short[iSides * 3]; //create vertices CustomVertex.PositionNormal[] aryVerts = new CustomVertex.PositionNormal[iSides + 1]; //create mesh with desired vertex format and desired size mesh = new Mesh(aryIndices.Length/3, aryVerts.Length, MeshFlags.SystemMemory, CustomVertex.PositionNormal.Format, d3dDevice); //caclulate the bottom radius vertices Vector3 v3Current = new Vector3(0, 0,0); aryVerts[0].Position = v3Current; v3Current.Z = fltHeight; v3Current.TransformCoordinate(Matrix.RotationX(fltHalfAngle)); aryVerts[1].Position = v3Current; for(int i=2; i<iSides + 1; i++) { v3Current.TransformCoordinate(Matrix.RotationZ(fltRotAmnt)); aryVerts[i].Position = v3Current; } //calculate the indices int j =0; for(int i=0; i<aryIndices.Length; i+=3) { //get first triangle aryIndices[i] = (short)(0); aryIndices[i+1] = (short)(j + 2); aryIndices[i+2] = (short)(j + 1); if(i == aryIndices.Length - 3) { aryIndices[i] = (short)(0); aryIndices[i+1] = (short)(1); aryIndices[i+2] = (short)(j + 1); /* TODO: Remove when done Debug.WriteLine("\nj = " + j.ToString()); Debug.WriteLine(aryIndices[i]); Debug.WriteLine(aryIndices[i+1]); Debug.WriteLine(aryIndices[i+2]); Debug.WriteLine(aryIndices[i+3]); Debug.WriteLine(aryIndices[i+4]); Debug.WriteLine(aryIndices[i+5]); */ } j++; } // aryIndices[0] = 0; // aryIndices[1] = 2; // aryIndices[2] = 1; // aryIndices[3] = 0; // aryIndices[4] = 3; // aryIndices[5] = 2; // aryIndices[6] = 0; // aryIndices[7] = 4; // aryIndices[8] = 3; // aryIndices[9] = 0; // aryIndices[10] = 1; // aryIndices[11] = 4; ar.AttributeId = 0; ar.FaceStart = 0; ar.FaceCount = aryIndices.Length/3; ar.VertexStart = 0; ar.VertexCount = aryVerts.Length; //set the mesh mesh.VertexBuffer.SetData(aryVerts, 0, LockFlags.None); mesh.IndexBuffer.SetData(aryIndices, 0, LockFlags.None); mesh.SetAttributeTable(new AttributeRange[]{ar}); mesh.ComputeNormals(); return (mesh); }
void SaveTexture(string filename) { //this.frames.Sort(FrameCompare); int tWidth = 1; // frames[0].avatar.Label.Image.Width; int tHeight = 1; // frames[0].avatar.Label.Image.Height; bool flag = true; Texture outputTexture = null; CustomVertex.PositionColoredTextured[] vertexes = new CustomVertex.PositionColoredTextured[4 * frames.Count]; short[] indexes = new short[frames.Count * 6]; for (int j = 0; j < frames.Count * 4; j++) { vertexes[j].Color = Color.White.ToArgb(); vertexes[j].Position = new Vector3(0, 0, 0); } //int maxWidth, maxHeight; if (frames.Count > 1) { while (flag) { if (OTNode.wFlag) { tWidth += OTNode.widthNeed; } else { tHeight += OTNode.heightNeed; } //tWidth *= 2; // tHeight *= 2; if (outputTexture != null) { outputTexture.Dispose(); } outputTexture = new Texture(d3dDevice, tWidth, tHeight, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default); Surface outputTextureSurface = outputTexture.GetSurfaceLevel(0); d3dDevice.ColorFill(outputTextureSurface, new Rectangle(0, 0, tWidth, tHeight), Color.Magenta); OTNode.target = outputTextureSurface; OTNode node = new OTNode(new Rectangle(0, 0, tWidth, tHeight)); //maxHeight = maxWidth = 0; for (int i = 0; i < frames.Count; i++) { toolStripProgressBar1.Value = (int)((float)(i + 1) / frames.Count * 100); this.Update(); Rectangle rect = node.Insert(frames[i]); if (rect == Rectangle.Empty) { flag = true; break; } else { flag = false; } //if (rect.Right > maxWidth) // maxWidth = rect.Right; //if (rect.Bottom > maxHeight) // maxHeight = rect.Bottom; vertexes[i * 4].X = -frames[i].centerPoint.X; vertexes[i * 4].Y = frames[i].centerPoint.Y - frames[i].avatar.Label.Image.Height; vertexes[i * 4 + 1].X = vertexes[i * 4].X; vertexes[i * 4 + 1].Y = frames[i].centerPoint.Y; vertexes[i * 4 + 2].X = frames[i].avatar.Label.Image.Width - frames[i].centerPoint.X;; vertexes[i * 4 + 2].Y = vertexes[i * 4 + 1].Y; vertexes[i * 4 + 3].X = vertexes[i * 4 + 2].X; vertexes[i * 4 + 3].Y = vertexes[i * 4].Y; vertexes[i * 4].Tu = (rect.Left + 1) / (float)tWidth; vertexes[i * 4].Tv = (rect.Bottom - 1) / (float)tHeight; vertexes[i * 4 + 1].Tu = vertexes[i * 4].Tu; vertexes[i * 4 + 1].Tv = (rect.Top + 1) / (float)tHeight; vertexes[i * 4 + 2].Tu = (rect.Right - 1) / (float)tWidth; vertexes[i * 4 + 2].Tv = vertexes[i * 4 + 1].Tv; vertexes[i * 4 + 3].Tu = vertexes[i * 4 + 2].Tu; vertexes[i * 4 + 3].Tv = vertexes[i * 4].Tv; indexes[i * 6 + 0] = (short)(i * 4 + 0); indexes[i * 6 + 1] = (short)(i * 4 + 1); indexes[i * 6 + 2] = (short)(i * 4 + 2); indexes[i * 6 + 3] = (short)(i * 4 + 3); indexes[i * 6 + 4] = (short)(i * 4 + 0); indexes[i * 6 + 5] = (short)(i * 4 + 2); } } } else { int i = 0; tWidth = frames[0].avatar.Label.Image.Width; tHeight = frames[0].avatar.Label.Image.Height; Rectangle rect = new Rectangle(0, 0, frames[0].avatar.Label.Image.Width, frames[0].avatar.Label.Image.Height); vertexes[i * 4].X = -frames[i].centerPoint.X; vertexes[i * 4].Y = frames[i].centerPoint.Y - frames[i].avatar.Label.Image.Height; vertexes[i * 4 + 1].X = vertexes[i * 4].X; vertexes[i * 4 + 1].Y = frames[i].centerPoint.Y; vertexes[i * 4 + 2].X = frames[i].avatar.Label.Image.Width - frames[i].centerPoint.X;; vertexes[i * 4 + 2].Y = vertexes[i * 4 + 1].Y; vertexes[i * 4 + 3].X = vertexes[i * 4 + 2].X; vertexes[i * 4 + 3].Y = vertexes[i * 4].Y; vertexes[i * 4].Tu = (rect.Left + 1) / (float)tWidth; vertexes[i * 4].Tv = (rect.Bottom - 1) / (float)tHeight; vertexes[i * 4 + 1].Tu = vertexes[i * 4].Tu; vertexes[i * 4 + 1].Tv = (rect.Top + 1) / (float)tHeight; vertexes[i * 4 + 2].Tu = (rect.Right - 1) / (float)tWidth; vertexes[i * 4 + 2].Tv = vertexes[i * 4 + 1].Tv; vertexes[i * 4 + 3].Tu = vertexes[i * 4 + 2].Tu; vertexes[i * 4 + 3].Tv = vertexes[i * 4].Tv; indexes[i * 6 + 0] = (short)(i * 4 + 0); indexes[i * 6 + 1] = (short)(i * 4 + 1); indexes[i * 6 + 2] = (short)(i * 4 + 2); indexes[i * 6 + 3] = (short)(i * 4 + 3); indexes[i * 6 + 4] = (short)(i * 4 + 0); indexes[i * 6 + 5] = (short)(i * 4 + 2); outputTexture = frames[0].texture; } Mesh mesh = new Mesh(2 * frames.Count, 4 * frames.Count, MeshFlags.Managed, CustomVertex.PositionColoredTextured.Format, d3dDevice); mesh.SetVertexBufferData(vertexes, LockFlags.None); mesh.SetIndexBufferData(indexes, LockFlags.None); //--------------------------- //Setting one of these does NOT work. You MUST set both. AttributeRange[] attributeTable = new AttributeRange[frames.Count]; int[] attributes = mesh.LockAttributeBufferArray(LockFlags.None); for (int i = 0; i < frames.Count; i++) { attributes[i * 2] = i; attributes[i * 2 + 1] = i; attributeTable[i].AttributeId = i; //ID is the value passed into the DrawSubset function of Mesh. attributeTable[i].FaceCount = 2; //Our subsets only have 1 face. attributeTable[i].FaceStart = i * 2; attributeTable[i].VertexCount = 4; //We need 3 vertices to make a face. attributeTable[i].VertexStart = i * 4; } mesh.UnlockAttributeBuffer(attributes); mesh.SetAttributeTable(attributeTable); //--------------------------- ExtendedMaterial[] em = new ExtendedMaterial[frames.Count]; em[0].TextureFilename = System.IO.Path.GetFileNameWithoutExtension(filename) + ".dds"; for (int i = 0; i < frames.Count; i++) { Material mat = new Material(); mat.Diffuse = Color.White; mat.Ambient = mat.Diffuse; mat.Specular = mat.Diffuse; mat.Emissive = Color.Black; em[i].Material3D = mat; } mesh.Save(System.IO.Path.GetFileNameWithoutExtension(filename) + ".sht", (int[])null, em, null, XFileFormat.Binary); TextureLoader.Save(System.IO.Path.GetFileNameWithoutExtension(filename) + ".dds", ImageFileFormat.Dds, outputTexture); }
private void RebuildAsync(Object deviceObj) { try { Device device = (Device)deviceObj; // Rebuild if (_bitmap == null) { _bitmap = new Bitmap(1, 1); _valid = true; } else { try { _imageTexture = Texture.FromBitmap(device, _bitmap, Usage.Dynamic, Pool.Default); // Set up the material _imageMaterial = new Material(); _imageMaterial.Diffuse = _color; // Set up the rectangular mesh CustomVertex.PositionNormalTextured[] verts = new CustomVertex.PositionNormalTextured[4]; verts[0].Position = new Vector3(0, 0, -_height); verts[0].Normal = new Vector3(0, 1, 0); verts[0].Tu = 0; verts[0].Tv = 1; verts[1].Position = new Vector3(_width, 0, -_height); verts[1].Normal = new Vector3(0, 1, 0); verts[1].Tu = 1; verts[1].Tv = 1; verts[2].Position = new Vector3(_width, 0, 0); verts[2].Normal = new Vector3(0, 1, 0); verts[2].Tu = 1; verts[2].Tv = 0; verts[3].Position = new Vector3(0, 0, 0); verts[3].Normal = new Vector3(0, 1, 0); verts[3].Tu = 0; verts[3].Tv = 0; AttributeRange[] attributes = new AttributeRange[1]; attributes[0].AttributeId = 0; attributes[0].FaceCount = 2; attributes[0].FaceStart = 0; attributes[0].VertexCount = 4; attributes[0].VertexStart = 0; short[] indices = new short[] { 0, 1, 2, 0, 2, 3 }; _imageSprite = new Mesh(2, 4, 0, CustomVertex.PositionNormalTextured.Format, device); _imageSprite.SetVertexBufferData(verts, LockFlags.Discard); _imageSprite.SetIndexBufferData(indices, LockFlags.Discard); _imageSprite.SetAttributeTable(attributes); _valid = true; } catch (Exception) { _valid = false; _imageTexture = null; _imageSprite = null; return; } } } catch (Exception) { _valid = false; _imageTexture = null; _imageSprite = null; } finally { _building = false; } }
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(AttributeRange obj) { return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr); }
/// <summary> /// The create hill object. /// </summary> /// <param name="device">The device.</param> /// <param name="hillPoints">The hill points.</param> /// <returns></returns> /// <remarks></remarks> public static Mesh createHillObject(Device device, List<Vector3> hillPoints) { Mesh mesh; short[] arrayIndices = new short[(hillPoints.Count * 2 - 1) * 6]; CustomVertex.PositionTextured[] arrayVertices = new CustomVertex.PositionTextured[hillPoints.Count * 2]; AttributeRange attributeRange = new AttributeRange(); // Create mesh with desired vertex format and desired size mesh = new Mesh( arrayIndices.Length / 3, arrayVertices.Length, MeshFlags.SystemMemory, CustomVertex.PositionTextured.Format, device); // For each point in the height field calculate the x, y, z and // texture coordinates. for (int y = 0; y < hillPoints.Count; y++) { CustomVertex.PositionTextured vertex = new CustomVertex.PositionTextured( hillPoints[y].X, hillPoints[y].Y, hillPoints[y].Z, 0, 0); arrayVertices[y * 2] = vertex; vertex = new CustomVertex.PositionTextured( hillPoints[y].X, hillPoints[y].Y, hillPoints[y].Z + hillHeight, 0, 0); arrayVertices[y * 2 + 1] = vertex; } // Calculate the index buffer. for (int y = 0; y < hillPoints.Count; y++) { int arrayIndex = (y * 2) * 6; int vertexIndex = y * 2; if (y != hillPoints.Count - 1) { arrayIndices[arrayIndex + 0] = (short)vertexIndex; arrayIndices[arrayIndex + 1] = (short)(vertexIndex + 1); arrayIndices[arrayIndex + 2] = (short)(vertexIndex + 2); arrayIndices[arrayIndex + 3] = (short)(vertexIndex + 2); arrayIndices[arrayIndex + 4] = (short)(vertexIndex + 1); arrayIndices[arrayIndex + 5] = (short)(vertexIndex + 3); } else { arrayIndices[arrayIndex + 0] = (short)vertexIndex; arrayIndices[arrayIndex + 1] = (short)(vertexIndex + 1); arrayIndices[arrayIndex + 2] = 0; arrayIndices[arrayIndex + 3] = 0; arrayIndices[arrayIndex + 4] = (short)(vertexIndex + 1); arrayIndices[arrayIndex + 5] = 1; } } // There is only one attribute value for this mesh. // By specifying an attribute range the DrawSubset function // does not have to scan the entire mesh for all faces that are // are marked with a particular attribute id. attributeRange.AttributeId = 0; attributeRange.FaceStart = 0; attributeRange.FaceCount = arrayIndices.Length / 3; attributeRange.VertexStart = 0; attributeRange.VertexCount = arrayVertices.Length; mesh.VertexBuffer.SetData(arrayVertices, 0, LockFlags.None); mesh.IndexBuffer.SetData(arrayIndices, 0, LockFlags.None); mesh.SetAttributeTable(new[] { attributeRange }); return mesh; }
public SceneImportResult LoadStaticMesh(string filename) { var file = new FileInfo(filename); VertexDescriptor vd = VertexDescriptor.Get <ModelVertex>(); List <MeshLayer> layers = new List <MeshLayer>(); int[] adjacency; ExtendedMaterial[] meshMaterials; Mesh mesh = new Mesh(vd); List <MeshMaterial> material = new List <MeshMaterial>(); using (SlimDX.Direct3D9.Mesh d3dMesh = SlimDX.Direct3D9.Mesh.FromFile(Engine.Graphics, filename, MeshFlags.Managed)) { adjacency = d3dMesh.GetAdjacency(); meshMaterials = d3dMesh.GetMaterials(); for (int i = 0; i < meshMaterials.Length; i++) { var matd3d = meshMaterials[i].MaterialD3D; string textureFilename = meshMaterials[i].TextureFileName; if (textureFilename != null && !Path.IsPathRooted(textureFilename)) { textureFilename = Path.Combine(Path.GetDirectoryName(filename), textureFilename); } material.Add(new MeshMaterial() { Name = file.Name + "_material" + i, Alpha = matd3d.Diffuse.Alpha, Diffuse = matd3d.Diffuse.ToVector3(), Specular = matd3d.Specular.ToVector3(), SpecularPower = Math.Max(1, matd3d.Power), Reflectivity = 0, Refractitity = 0, EmissiveColor = matd3d.Emissive.ToVector3(), DiffuseMap = textureFilename != null && File.Exists(textureFilename) ? textureFilename : null }); } ModelVertex[] vertexes = new ModelVertex[d3dMesh.VertexCount]; Array indices; if (d3dMesh.IndexBuffer.Description.Format == Format.Index16) { indices = new ushort[d3dMesh.FaceCount * 3]; } else { indices = new uint[d3dMesh.FaceCount * 3]; } DataStream vertexStream = d3dMesh.LockVertexBuffer(0); VertexDescriptor meshVD = new VertexDescriptor(d3dMesh.GetDeclaration()); int positionOffset = meshVD.GetOffset(DeclarationUsage.Position, 0); int normalOffset = meshVD.GetOffset(DeclarationUsage.Normal, 0); int texCoordOffset = meshVD.GetOffset(DeclarationUsage.TextureCoordinate, 0); byte[] buffer; unsafe { buffer = new byte[vertexStream.Length]; vertexStream.Read(buffer, 0, (int)vertexStream.Length); fixed(byte *_pter = buffer) { byte *pter = _pter; for (int i = 0; i < d3dMesh.VertexCount; i++) { vertexes[i].Position = *((Vector3 *)(pter + positionOffset)); if (normalOffset > 0) { vertexes[i].Normal = *((Vector3 *)(pter + normalOffset)); } if (texCoordOffset > 0) { vertexes[i].TexCoord = *((Vector2 *)(pter + texCoordOffset)); } pter += d3dMesh.BytesPerVertex; } } d3dMesh.UnlockVertexBuffer(); DataStream indexStream = d3dMesh.LockIndexBuffer(0); GCHandle handler = GCHandle.Alloc(indices, GCHandleType.Pinned); byte * indexPter = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(indices, 0); buffer = new byte[indexStream.Length]; indexStream.Read(buffer, 0, (int)indexStream.Length); for (int i = 0; i < indexStream.Length; i++) { indexPter[i] = buffer[i]; } handler.Free(); d3dMesh.UnlockIndexBuffer(); } mesh.CreateVertexBuffer(vertexes); if (d3dMesh.IndexBuffer.Description.Format == Format.Index16) { mesh.CreateIndexBuffer((ushort[])indices); } else { mesh.CreateIndexBuffer((uint[])indices); } var d3dComponents = d3dMesh.GetAttributeTable(); if (d3dComponents == null) { MeshLayer component = new MeshLayer(); layers.Add(component); material.Add(MeshMaterial.CreateDefaultMaterial(file.Name + "_default")); component.materialIndex = 0; component.primitiveCount = mesh.FaceCount; component.startIndex = 0; component.startVertex = 0; component.vertexCount = mesh.VertexCount; } else { for (int i = 0; i < d3dComponents.Length; i++) { AttributeRange ar = d3dComponents[i]; MeshLayer component = new MeshLayer(); layers.Add(component); component.materialIndex = ar.AttribId; component.primitiveCount = ar.FaceCount; component.startIndex = ar.FaceStart * 3; component.startVertex = ar.VertexStart; component.vertexCount = ar.VertexCount; } } mesh.Materials = material.ToArray(); mesh.SetLayers(layers.ToArray()); if (normalOffset < 0) { mesh.ComputeNormals(); } if (texCoordOffset < 0) { mesh.ComputeTextureCoords(CoordMappingType.Spherical); } mesh.ComputeTangents(); meshVD.Dispose(); } StaticMeshSceneNode meshNode = new StaticMeshSceneNode(file.Name, mesh); return(new SceneImportResult { VisualSceneRoot = meshNode, VisualMaterials = material }); }
/// <summary> /// The create hill object. /// </summary> /// <param name="device">The device.</param> /// <param name="hillPoints">The hill points.</param> /// <returns></returns> /// <remarks></remarks> public static Mesh createHillObject(Device device, List <Vector3> hillPoints) { Mesh mesh; short[] arrayIndices = new short[(hillPoints.Count * 2 - 1) * 6]; CustomVertex.PositionTextured[] arrayVertices = new CustomVertex.PositionTextured[hillPoints.Count * 2]; AttributeRange attributeRange = new AttributeRange(); // Create mesh with desired vertex format and desired size mesh = new Mesh( arrayIndices.Length / 3, arrayVertices.Length, MeshFlags.SystemMemory, CustomVertex.PositionTextured.Format, device); // For each point in the height field calculate the x, y, z and // texture coordinates. for (int y = 0; y < hillPoints.Count; y++) { CustomVertex.PositionTextured vertex = new CustomVertex.PositionTextured( hillPoints[y].X, hillPoints[y].Y, hillPoints[y].Z, 0, 0); arrayVertices[y * 2] = vertex; vertex = new CustomVertex.PositionTextured( hillPoints[y].X, hillPoints[y].Y, hillPoints[y].Z + hillHeight, 0, 0); arrayVertices[y * 2 + 1] = vertex; } // Calculate the index buffer. for (int y = 0; y < hillPoints.Count; y++) { int arrayIndex = (y * 2) * 6; int vertexIndex = y * 2; if (y != hillPoints.Count - 1) { arrayIndices[arrayIndex + 0] = (short)vertexIndex; arrayIndices[arrayIndex + 1] = (short)(vertexIndex + 1); arrayIndices[arrayIndex + 2] = (short)(vertexIndex + 2); arrayIndices[arrayIndex + 3] = (short)(vertexIndex + 2); arrayIndices[arrayIndex + 4] = (short)(vertexIndex + 1); arrayIndices[arrayIndex + 5] = (short)(vertexIndex + 3); } else { arrayIndices[arrayIndex + 0] = (short)vertexIndex; arrayIndices[arrayIndex + 1] = (short)(vertexIndex + 1); arrayIndices[arrayIndex + 2] = 0; arrayIndices[arrayIndex + 3] = 0; arrayIndices[arrayIndex + 4] = (short)(vertexIndex + 1); arrayIndices[arrayIndex + 5] = 1; } } // There is only one attribute value for this mesh. // By specifying an attribute range the DrawSubset function // does not have to scan the entire mesh for all faces that are // are marked with a particular attribute id. attributeRange.AttributeId = 0; attributeRange.FaceStart = 0; attributeRange.FaceCount = arrayIndices.Length / 3; attributeRange.VertexStart = 0; attributeRange.VertexCount = arrayVertices.Length; mesh.VertexBuffer.SetData(arrayVertices, 0, LockFlags.None); mesh.IndexBuffer.SetData(arrayIndices, 0, LockFlags.None); mesh.SetAttributeTable(new[] { attributeRange }); return(mesh); }