当前位置: 首页>>代码示例>>C#>>正文


C# DataStream.Dispose方法代码示例

本文整理汇总了C#中DataStream.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# DataStream.Dispose方法的具体用法?C# DataStream.Dispose怎么用?C# DataStream.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在DataStream的用法示例。


在下文中一共展示了DataStream.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: TextureFromBitmap

        public static Texture2D TextureFromBitmap(Bitmap image)
        {
            BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
                                             ImageLockMode.ReadWrite, image.PixelFormat);
            int bytes = data.Stride*image.Height;
            DataStream stream = new DataStream(bytes, true, true);
            stream.WriteRange(data.Scan0, bytes);
            stream.Position = 0;
            DataRectangle dRect = new DataRectangle(data.Stride, stream);

            Texture2DDescription texDesc = new Texture2DDescription
                                               {
                                                   ArraySize = 1,
                                                   MipLevels = 1,
                                                   SampleDescription = new SampleDescription(1, 0),
                                                   Format = Format.B8G8R8A8_UNorm,
                                                   CpuAccessFlags = CpuAccessFlags.None,
                                                   BindFlags = BindFlags.ShaderResource,
                                                   Usage = ResourceUsage.Immutable,
                                                   Height = image.Height,
                                                   Width = image.Width
                                               };

            image.UnlockBits(data);
            image.Dispose();
            Texture2D texture = new Texture2D(Game.Context.Device, texDesc, dRect);
            stream.Dispose();
            return texture;
        }
开发者ID:yong-ja,项目名称:starodyssey,代码行数:29,代码来源:ImageHelper.cs

示例2: Quad

        public Quad(int startX,int endX, int startZ, int endZ, Base.Content.Terrain.Terrain terrain, RenderManager renderer)
        {
            _bounds = new QuadBounds
            {
                MinX = startX / terrain.PointsPerMeter,
                MaxX = endX / terrain.PointsPerMeter,
                MinZ = startZ / terrain.PointsPerMeter,
                MaxZ = endZ / terrain.PointsPerMeter,
                MinY = terrain.Height[0],
                MaxY = terrain.Height[0]
            };
            HorizontalCenter = new Vector2(Bounds.MinX + (Bounds.MaxX - Bounds.MinX) / 2, Bounds.MinZ + (Bounds.MaxZ - Bounds.MinZ) / 2);

            int verticesX = endX - startX + 1;
            int verticesZ = endZ - startZ + 1;

            var dataStream = new DataStream(32 * verticesX * verticesZ, true, true);

            for (int i = 0; i < verticesX; i++)
            {
                for (int j = 0; j < verticesZ; j++)
                {
                    //Position
                    int xindex = Math.Min(i + startX, terrain.PointsX - 1);//Clamp to arraybounds if neccessary
                    int zindex = Math.Min(j + startZ, terrain.PointsZ - 1);//(Quadsize needs to be consistent for sharing IndexBuffers)
                    float x = xindex / terrain.PointsPerMeter;
                    float z = zindex / terrain.PointsPerMeter;
                    float y = terrain.Height[xindex * terrain.PointsZ + zindex];
                    dataStream.Write(new Vector3(x, y, z));

                    //Normal
                    float deltax = (terrain.Height[(xindex < terrain.PointsX - 1 ? xindex + 1 : xindex) * terrain.PointsZ + zindex]
                        - terrain.Height[(xindex != 0 ? xindex - 1 : xindex) * terrain.PointsZ + zindex]);

                    float deltaz = (terrain.Height[xindex * terrain.PointsZ + (zindex < terrain.PointsZ - 1 ? zindex + 1 : zindex)]
                        - terrain.Height[xindex * terrain.PointsZ + (zindex != 0 ? zindex - 1 : zindex)]);
                    if (xindex == 0 || xindex == terrain.PointsX - 1)
                        deltax *= 2;
                    if (zindex == 0 || zindex == terrain.PointsZ - 1)
                        deltaz *= 2;
                    var normal = new Vector3(-deltax, 2 / terrain.PointsPerMeter, deltaz);
                    normal.Normalize();
                    dataStream.Write(normal);

                    //TextureCoordinates
                    dataStream.Write(new Vector2(x / terrain.PointsX, z / terrain.PointsZ));

                    //Boundingbox-Params
                    if (y < _bounds.MinY)
                        _bounds.MinY = y;
                    if (y > _bounds.MaxY)
                        _bounds.MaxY = y;
                }
            }

            dataStream.Position = 0;
            VBuffer = new Buffer(renderer.D3DDevice, dataStream, 32 * verticesX * verticesZ, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            VertexBuffer = new VertexBufferBinding(VBuffer, 32, 0);
            dataStream.Dispose();
        }
开发者ID:hexd0t,项目名称:Garm_Net,代码行数:60,代码来源:TerrainQuad.cs

示例3: LoadByteCode

        private static DX11Effect LoadByteCode(byte[] bytecode)
        {
            DX11Effect shader = new DX11Effect();
            try
            {
                DataStream ds = new DataStream(bytecode.Length, true, true);
                ds.Write(bytecode, 0, bytecode.Length);
                shader.ByteCode = new ShaderBytecode(ds);

                //fs.Close();
                ds.Dispose();

                shader.IsCompiled = true;
                shader.ErrorMessage = "";

                shader.Preprocess();

            }
            catch (Exception ex)
            {
                shader.IsCompiled = false;
                shader.ErrorMessage = ex.Message;
                shader.DefaultEffect = null;
            }
            return shader;
        }
开发者ID:arturoc,项目名称:FeralTic,代码行数:26,代码来源:DX11Effect.cs

示例4: DX11IndexBuffer

        public DX11IndexBuffer(DX11RenderContext context, DataStream initial,bool dynamic, bool dispose)
        {
            this.context = context;
            format = SlimDX.DXGI.Format.R32_UInt;

            BindFlags flags = BindFlags.IndexBuffer;

            if (context.IsFeatureLevel11) { flags |= BindFlags.ShaderResource; }

            BufferDescription bd = new BufferDescription()
            {
                BindFlags = flags,
                CpuAccessFlags = dynamic ? CpuAccessFlags.Write : CpuAccessFlags.None,
                OptionFlags = context.IsFeatureLevel11 ? ResourceOptionFlags.RawBuffer : ResourceOptionFlags.None,
                SizeInBytes = (int)initial.Length,
                Usage = dynamic ? ResourceUsage.Dynamic : ResourceUsage.Default,
            };

            initial.Position = 0;
            this.IndicesCount = (int)initial.Length / 4;
            this.Buffer = new SlimDX.Direct3D11.Buffer(context.Device, initial, bd);

            this.CreateSRV();

            if (dispose) { initial.Dispose(); }
        }
开发者ID:kopffarben,项目名称:FeralTic,代码行数:26,代码来源:IndexBuffer.cs

示例5: LineStrip3d

        public DX11VertexGeometry LineStrip3d(List<Vector3> points, bool loop)
        {
            DX11VertexGeometry geom = new DX11VertexGeometry(context);

            int vcount = loop ? points.Count + 1 : points.Count;

            Pos3Tex2Vertex[] verts = new Pos3Tex2Vertex[vcount];

            float inc = loop ? 1.0f / (float)vcount : 1.0f / ((float)vcount + 1.0f);

            float curr = 0.0f;
            
                
            for (int i = 0; i < points.Count; i++)
            {
                verts[i].Position = points[i];
                verts[i].TexCoords.X = curr;
                curr += inc;
            }

            if (loop)
            {
                verts[points.Count].Position = points[0];
                verts[points.Count].TexCoords.X = 1.0f;
            }


            DataStream ds = new DataStream(vcount * Pos3Tex2Vertex.VertexSize, true, true);
            ds.Position = 0;
            ds.WriteRange(verts);
            ds.Position = 0;

            var vbuffer = new SlimDX.Direct3D11.Buffer(context.Device, ds, new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = (int)ds.Length,
                Usage = ResourceUsage.Default
            });

            ds.Dispose();

            geom.VertexBuffer = vbuffer;
            geom.InputLayout = Pos3Tex2Vertex.Layout;
            geom.Topology = PrimitiveTopology.LineStrip;
            geom.VerticesCount = vcount;
            geom.VertexSize = Pos3Tex2Vertex.VertexSize;

            geom.HasBoundingBox = false;

            return geom;
        }
开发者ID:arturoc,项目名称:FeralTic,代码行数:53,代码来源:DX11Primitive_Line.cs

示例6: DXTreeSkeleton

        public DXTreeSkeleton(CS_Tree tree, CS_Params csParams)
        {
            InitShaders();

            DXTreeSkeleton_TreeTraversal traversal = new DXTreeSkeleton_TreeTraversal(csParams);
            tree.traverseTree(traversal);
            BBox = traversal.BBox;

            for (int i = 0; i < 5; i++)
            {
                if (traversal.Vertices2[i].Count != 0)
                {

                    var stream = new DataStream(traversal.Vertices2[i].Count * Marshal.SizeOf(typeof(DXSKV)), true, true);

                    stream.WriteRange(traversal.Vertices2[i].ToArray());
                    stream.Position = 0;
                    _vertexBuffer2[i] = new Buffer(DXDevice, stream, new BufferDescription()
                    {
                        BindFlags = BindFlags.VertexBuffer,
                        CpuAccessFlags = CpuAccessFlags.None,
                        OptionFlags = ResourceOptionFlags.None,
                        SizeInBytes = traversal.Vertices2[i].Count * Marshal.SizeOf(typeof(DXSKV)),
                        Usage = ResourceUsage.Default
                    });
                    stream.Dispose();

                    List<UInt32> indices = new List<UInt32>();
                    for (int k = 0; k < traversal.Vertices2[i].Count; k++) { indices.Add((UInt32)k); }

                    stream = new DataStream(indices.Count * sizeof(UInt32), true, true);
                    stream.WriteRange(indices.ToArray());

                    stream.Position = 0;

                    _indexBuffer2[i] = new Buffer(DXDevice, stream, new BufferDescription()
                    {
                        BindFlags = BindFlags.IndexBuffer,
                        CpuAccessFlags = CpuAccessFlags.None,
                        OptionFlags = ResourceOptionFlags.None,
                        SizeInBytes = indices.Count * sizeof(UInt32),
                        Usage = ResourceUsage.Default
                    });
                    stream.Dispose();

                    IndexCount2[i] = indices.Count;
                }
            }
        }
开发者ID:khazanJM,项目名称:arbaro-csharp,代码行数:49,代码来源:DXTreeSkeleton.cs

示例7: GetData

 /// <summary>	
 /// Get data from the GPU asynchronously.	
 /// </summary>	
 /// <remarks>	
 /// GetData retrieves the data collected between calls to <see cref="SharpDX.Direct3D10.Asynchronous.Begin"/> and <see cref="SharpDX.Direct3D10.Asynchronous.End"/>.  Certain queries only require a call to ID3D10Asynchronous::End in which case the data returned by GetData is accurate up to the last call to ID3D10Asynchronous::End (See <see cref="SharpDX.Direct3D10.Query"/>). If DataSize is 0, GetData is only used to check status where a return value of S_OK indicates that data is available to give to an application, and a return value of S_FALSE indicates data is not yet available. It is invalid to invoke this function on a predicate created with the flag D3D10_QUERY_MISCFLAG_PREDICATEHINT. If the asynchronous interface that calls this function is <see cref="SharpDX.Direct3D10.Query"/>, then the following table applies.  Query TypeOutput Data TypeSupports Begin Method EVENTBOOLNO OCCLUSIONUINT64YES TIMESTAMPUINT64NO TIMESTAMP_DISJOINTQUERYDATA_TIMESTAMP_DISJOINTYES PIPELINE_STATISTICSQUERYDATA_PIPELINE_STATISTICSYES OCCLUSION_PREDICATEBOOLYES SO_STATISTICSQUERYDATA_SO_STATISTICSYES SO_OVERFLOW_PREDICATEBOOLYES  ? If the asynchronous interface that calls this API is <see cref="SharpDX.Direct3D10.Counter"/>, then the following applies.  Counter TypeOutput Data TypeUnits GPU_IDLEFLOAT32fraction of time VERTEX_PROCESSINGFLOAT32fraction of time GEOMETRY_PROCESSINGFLOAT32fraction of time PIXEL_PROCESSINGFLOAT32fraction of time OTHER_GPU_PROCESSINGFLOAT32fraction of time HOST_ADAPTER_BANDWIDTH_UTILIZATIONFLOAT32fraction of theoretical maximum LOCAL_VIDMEM_BANDWIDTH_UTILIZATIONFLOAT32fraction of theoretical maximum VERTEX_THROUGHPUT_UTILIZATIONFLOAT32fraction of theoretical maximum TRISETUP_THROUGHPUT_UTILIZATIONFLOAT32fraction of theoretical maximum FILLRATE_THROUGHPUT_UTILIZATIONFLOAT32fraction of theoretical maximum VERTEXSHADER_MEMORY_LIMITEDFLOAT32fraction of time VERTEXSHADER_COMPUTATION_LIMITEDFLOAT32fraction of time GEOMETRYSHADER_MEMORY_LIMITEDFLOAT32fraction of time GEOMETRYSHADER_COMPUTATION_LIMITEDFLOAT32fraction of time PIXELSHADER_MEMORY_LIMITEDFLOAT32fraction of time PIXELSHADER_COMPUTATION_LIMITEDFLOAT32fraction of time POST_TRANSFORM_CACHE_HIT_RATEFLOAT32fraction TEXTURE_CACHE_HIT_RATEFLOAT32fraction  ? The value returned by a GPU_IDLE, VERTEX_PROCESSING, GEOMETRY_PROCESSING, PIXEL_PROCESSING, or OTHER_GPU_PROCESSING counter may be different depending on the number of parallel counters that exist on a video card, and those values can be interpreted with the following equation:  ?  Equation to interpret the number of parallel counters ? The number of parallel counters that a video card has is available from NumDetectableParallelUnits in <see cref="CounterMetadata"/>, and it can be retrieved by calling <see cref="Device.CheckCounter"/>. 	
 /// </remarks>	
 /// <param name="flags">Optional flags. Can be 0 or any combination of the flags enumerated by <see cref="SharpDX.Direct3D10.AsynchronousFlags"/>. </param>
 /// <returns>If this function succeeds, returns a <see cref="SharpDX.DataStream"/> containing the asynchronous data sent from the GPU. </returns>
 /// <unmanaged>HRESULT ID3D10Asynchronous::GetData([Out, Buffer, Optional] void* pData,[In] int DataSize,[In] int GetDataFlags)</unmanaged>
 public DataStream GetData(AsynchronousFlags flags)
 {
     int dataSize = GetDataSize();
     DataStream dataStream = new DataStream(dataSize, true, true);
     try
     {
         GetData(dataStream.DataPointer, dataSize, (int)flags);
     }
     catch (Exception)
     {
         dataStream.Dispose();
         throw;
     }
     return dataStream;
 }
开发者ID:Nezz,项目名称:SharpDX,代码行数:24,代码来源:Asynchronous.cs

示例8: GSSprite

        public GSSprite(Device device, DVector3 Position)
        {
            //float3 Position //12
            //half2 Size //16
            //half4 AABBTexCoord //24
            //half4 AditiveColor //32
            InputElement[] elements = new[] {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new InputElement("TEXCOORD", 0, Format.R16G16_Float, 12, 0),
                new InputElement("TEXCOORD", 1, Format.R16G16B16A16_Float, 16, 0),
                new InputElement("TEXCOORD", 2, Format.R16G16B16A16_Float, 24, 0),
            };

            BytesPerVertex = 32;
            VertexsCount = 1;

            var vertices = new DataStream(BytesPerVertex * VertexsCount, true, true);

            vertices.Write(Conversion.ToVector3(Position));
            vertices.Write(new Half2(10, 10));
            vertices.Write(new Half4(0, 0, 1, 1));
            vertices.Write(new Half4(1, 0, 0, 1));
            vertices.Position = 0;

            Vertexs = new Buffer(device, vertices, BytesPerVertex * VertexsCount, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);
            binding = new VertexBufferBinding(Vertexs, BytesPerVertex, 0);
            vertices.Dispose();

            this.Position = Position;
            EEEM = ContentManager.LoadEffect("Content/Shaders/GSSprite", elements);
            TexCont = ContentManager.LoadTexture2D("Content/Textures/Particl");
            // Подготовка константного буффера
            BufferDescription bd = new BufferDescription();
            bd.SizeInBytes = Marshal.SizeOf(typeof(ShaderConstants));
            bd.Usage = ResourceUsage.Dynamic;
            bd.BindFlags = BindFlags.ConstantBuffer;
            bd.CpuAccessFlags = CpuAccessFlags.Write;
            bd.OptionFlags = ResourceOptionFlags.None;
            bd.StructureByteStride = 0;

            constantsBuffer = new Buffer(device, bd);
            constants = new ShaderConstants();
        }
开发者ID:MagistrAVSH,项目名称:my-spacegame-engine,代码行数:43,代码来源:GSSprite.cs

示例9: CreateDynamicVertexBuffer

        public static Buffer CreateDynamicVertexBuffer(DX11RenderContext context, DataStream ds, bool dispose = false)
        {
            ds.Position = 0;
            var vertices = new SlimDX.Direct3D11.Buffer(context.Device, ds, new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = (int)ds.Length,
                Usage = ResourceUsage.Dynamic
            });

            if (dispose)
            {
                ds.Dispose();
            }

            return vertices;
        }
开发者ID:kopffarben,项目名称:FeralTic,代码行数:19,代码来源:BufferHelper.cs

示例10: DX11VertexBuffer

        public DX11VertexBuffer(DX11RenderContext context, DataStream initial,int verticescount,int vertexsize, bool dynamic, bool dispose)
        {
            this.context = context;

            BufferDescription bd = new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = dynamic ? CpuAccessFlags.Write : CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = (int)initial.Length,
                Usage = dynamic ? ResourceUsage.Dynamic : ResourceUsage.Immutable,
            };

            initial.Position = 0;
            this.Buffer = new SlimDX.Direct3D11.Buffer(context.Device, initial, bd);
            this.VertexSize = vertexsize;
            this.VerticesCount = verticescount;

            if (dispose) { initial.Dispose(); }
        }
开发者ID:arturoc,项目名称:FeralTic,代码行数:20,代码来源:VertexBuffer.cs

示例11: GetBitmap

        public static unsafe WriteableBitmap GetBitmap(this SharpDX.Direct3D11.Texture2D tex)
        {
            DataRectangle db;
            DataStream data = new DataStream(tex.Description.Height * tex.Description.Width * 4, true, true);
            using(var copy = tex.GetCopy())
            using (var surface = copy.QueryInterface<SharpDX.DXGI.Surface>())
            {
                db = surface.Map(SharpDX.DXGI.MapFlags.Read, out data);
                // can't destroy the surface now with WARP driver

                int w = tex.Description.Width;
                int h = tex.Description.Height;
                var wb = new WriteableBitmap(w, h, 96.0, 96.0, PixelFormats.Bgra32, null);
                wb.Lock();
                try
                {
                    uint* wbb = (uint*)wb.BackBuffer;

                    data.Position = 0;
                    for (int y = 0; y < h; y++)
                    {
                        data.Position = y * db.Pitch;
                        for (int x = 0; x < w; x++)
                        {
                            var c = data.Read<uint>();
                            wbb[y * w + x] = c;
                        }
                    }
                }
                finally
                {
                    wb.AddDirtyRect(new Int32Rect(0, 0, w, h));
                    wb.Unlock();
                    data.Dispose();

                }
                return wb;
            }
        }
开发者ID:KFlaga,项目名称:Cam3D,代码行数:39,代码来源:DXWPFExt.cs

示例12: GetVertexBuffer

        public SlimDX.Direct3D11.Buffer GetVertexBuffer()
        {
            // dynamically create buffer
            if (m_DeviceBuffer == null)
            {
                ResourceUsage resourceUsage = ResourceUsage.Default;
                CpuAccessFlags cpuAccessFlags = CpuAccessFlags.None;

                if(m_Usage == Type.DYNAMIC )
                {
                    resourceUsage = ResourceUsage.Dynamic;
                    cpuAccessFlags = CpuAccessFlags.Write;
                }

                BufferDescription desc = new BufferDescription()
                {
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = cpuAccessFlags,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = (int)m_RawData.Length,
                    Usage = resourceUsage
                };

                if (m_Usage == Type.DYNAMIC)
                {
                    m_DeviceBuffer = new SlimDX.Direct3D11.Buffer(m_D3dDevice, desc);
                }
                else
                {
                    DataStream dataStream = new DataStream(m_RawData.ToArray(), true, true);
                    m_DeviceBuffer = new SlimDX.Direct3D11.Buffer(m_D3dDevice, dataStream, desc);
                    dataStream.Dispose();
                }
            }

            return m_DeviceBuffer;
        }
开发者ID:aik6980,项目名称:GameFramework,代码行数:37,代码来源:VertexBufferD3d11.cs

示例13: Optimize

        /// <summary>	
        /// Generates a new mesh with reordered faces and vertices to optimize drawing performance.	
        /// </summary>	
        /// <remarks>	
        /// This method generates a new mesh. Before running Optimize, an application must generate an adjacency buffer by calling <see cref="SharpDX.Direct3D10.Mesh.GenerateAdjacencyAndPointRepresentation"/>. The adjacency buffer contains adjacency data, such as a list of edges and the faces that are adjacent to each other. This method is very similar to the <see cref="SharpDX.Direct3D10.Mesh.CloneMesh"/> method, except that it can perform optimization while generating the new clone of the mesh. The output mesh inherits all of the creation parameters of the input mesh. 	
        /// </remarks>	
        /// <param name="flags">Specifies the type of optimization to perform. This parameter can be set to a combination of one or more flags from D3DXMESHOPT and D3DXMESH (except D3DXMESH_32BIT, D3DXMESH_IB_WRITEONLY, and D3DXMESH_WRITEONLY). </param>
        /// <param name="faceRemap">An array of UINTs, one per face, that identifies the original mesh face that corresponds to each face in the optimized mesh.</param>
        /// <param name="vertexRemap">An array of index for each vertex that specifies how the new vertices map to the old vertices. This remap is useful if you need to alter external data based on the new vertex mapping. </param>
        /// <returns>The return value is one of the values listed in {{Direct3D 10 Return Codes}}. </returns>
        /// <unmanaged>HRESULT ID3DX10Mesh::Optimize([None] int Flags,[Out, Buffer, Optional] int* pFaceRemap,[In] LPD3D10BLOB* ppVertexRemap)</unmanaged>
        public void Optimize(MeshOptimizeFlags flags, out int[] faceRemap, out int[] vertexRemap)
        {

            IntPtr blobPtr;
            DataStream dataStream = null;
            unsafe
            {
                try
                {
                    faceRemap = new int[FaceCount];
                    Optimize((int)flags, faceRemap, new IntPtr(&blobPtr));
                    dataStream = new DataStream(new Blob(blobPtr));
                    vertexRemap = dataStream.ReadRange<int>(VertexCount);
                    dataStream.Dispose();
                }
                catch (Exception)
                {
                    faceRemap = null;
                    vertexRemap = null;
                    if (dataStream!=null)
                        dataStream.Dispose();
                    throw;
                }
            }
        }
开发者ID:Nezz,项目名称:SharpDX,代码行数:36,代码来源:Mesh.cs

示例14: Render

        /// <summary>
        /// Renders the bounding box for debugging purposes.
        /// </summary>
        /// <param name="box">The box to render.</param>
        /// <param name="graphicsDevice">The graphics device to use when rendering.</param>
        /// <param name="view">The current view matrix.</param>
        /// <param name="projection">The current projection matrix.</param>
        /// <param name="color">The color to use for drawing the lines of the box.</param>
        public static void Render(
            BoundingBox box,
            Device graphicsDevice,
            Matrix world,
            Matrix view,
            Matrix projection,
            Color4 color)
        {
            if (effect == null)
            {
                effect = Ressources.EffectCache.Get("Shaders\\basic_effect.fx");
                vertexBuffer = new Buffer(Scene.GetGraphicsDevice(), 8 * sizeof(float) * 4, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);
                /*
                 *
            vBuffer = new SlimDX.Direct3D11.Buffer(Scene.GetGraphicsDevice(), vBuffStream, new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = (int)vBuffStream.Length,
                Usage = ResourceUsage.Default
            });*/

                DataStream stream = new DataStream(sizeof(int) * indices.Length, false, true);
                stream.WriteRange<int>(indices);
                stream.Position = 0;
                indexBuffer = new SlimDX.Direct3D11.Buffer(Scene.GetGraphicsDevice(), stream, new BufferDescription()
                {
                    BindFlags = BindFlags.IndexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = (int)stream.Length,
                    Usage = ResourceUsage.Default
                });
                stream.Dispose();
                var sign = effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature;
                inLayout = new InputLayout(
                    Scene.GetGraphicsDevice(),
                    effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature,
                    new InputElement[] {
                        new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0)
                    });
            }
            effect.GetVariableByName("xColor").AsVector().Set(color);

            Vector3[] corners = box.GetCorners();

            for (int i = 0; i < 8; i++)
            {
                verts[i] = new Vector4(corners[i], 1.0f);
            }

            var data = Scene.GetGraphicsDevice().ImmediateContext.MapSubresource(vertexBuffer, 0,  MapMode.WriteDiscard, SlimDX.Direct3D11.MapFlags.None);
            data.Data.WriteRange(verts);
            Scene.GetGraphicsDevice().ImmediateContext.UnmapSubresource(vertexBuffer, 0);

            Scene.GetGraphicsDevice().ImmediateContext.InputAssembler.InputLayout = inLayout;
            Scene.GetGraphicsDevice().ImmediateContext.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);
            Scene.GetGraphicsDevice().ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 16, 0));
            Scene.GetGraphicsDevice().ImmediateContext.InputAssembler.PrimitiveTopology = (PrimitiveTopology.LineList);

            effect.GetVariableByName("World").AsMatrix().SetMatrix(world);
            effect.GetVariableByName("View").AsMatrix().SetMatrix(view);
            effect.GetVariableByName("Projection").AsMatrix().SetMatrix(projection);

            for (int i = 0; i < effect.GetTechniqueByIndex(0).Description.PassCount; i++)
            {
                effect.GetTechniqueByIndex(0).GetPassByIndex(i).Apply(Scene.GetGraphicsDevice().ImmediateContext);
                Scene.GetGraphicsDevice().ImmediateContext.DrawIndexed(indexBuffer.Description.SizeInBytes / sizeof(int), 0, 0);
            }
        }
开发者ID:crissian,项目名称:planets,代码行数:79,代码来源:BoundingBoxRenderer.cs

示例15: Segment

        public DX11IndexedGeometry Segment(Segment settings)
        {
            float phase = settings.Phase;
            float cycles = settings.Cycles; 
            float inner = settings.InnerRadius; 
            int res = settings.Resolution;
            bool flat = settings.Flat;

            DX11IndexedGeometry geom = new DX11IndexedGeometry(context);
            geom.Tag = settings;
            geom.PrimitiveType = settings.PrimitiveType;
            int vcount = res * 2;
            int icount = (res - 1) * 6;

            DataStream ds = new DataStream(vcount * Pos4Norm3Tex2Vertex.VertexSize, true, true);
            ds.Position = 0;

            float inc = Convert.ToSingle((Math.PI * 2.0 * cycles) / (res - 1.0));
            float phi = Convert.ToSingle(phase * (Math.PI * 2.0));

            Pos4Norm3Tex2Vertex innerv = new Pos4Norm3Tex2Vertex();
            innerv.Normals = new Vector3(0.0f, 0.0f, 1.0f);

            Pos4Norm3Tex2Vertex outerv = new Pos4Norm3Tex2Vertex();
            outerv.Normals = new Vector3(0.0f, 0.0f, 1.0f);

            Pos4Norm3Tex2Vertex[] vertices = new Pos4Norm3Tex2Vertex[res * 2];

            for (int i = 0; i < res; i++)
            {
                float x = Convert.ToSingle(0.5 * inner * Math.Cos(phi));
                float y = Convert.ToSingle(0.5 * inner * Math.Sin(phi));

                innerv.Position = new Vector4(x, y, 0.0f, 1.0f);

                if (flat)
                {
                    innerv.TexCoords = new Vector2(0.5f - x, 0.5f - y);
                }
                else
                {
                    innerv.TexCoords = new Vector2((1.0f * (float)i) / ((float)res - 1.0f), 0.0f);
                }

                x = Convert.ToSingle(0.5 * Math.Cos(phi));
                y = Convert.ToSingle(0.5 * Math.Sin(phi));

                outerv.Position = new Vector4(x, y, 0.0f, 1.0f);

                if (flat)
                {
                    outerv.TexCoords = new Vector2(0.5f - x, 0.5f - y);
                }
                else
                {
                    outerv.TexCoords = new Vector2((1.0f * (float)i) / ((float)res - 1.0f), 1.0f);
                }

                vertices[i] = innerv;
                vertices[i + res] = outerv;
                phi += inc;
            }

            float minx = float.MaxValue, miny = float.MaxValue, minz = float.MaxValue;
            float maxx = float.MinValue, maxy = float.MinValue, maxz = float.MinValue;

            foreach (Pos4Norm3Tex2Vertex v in vertices)
            {
                minx = v.Position.X < minx ? v.Position.X : minx;
                miny = v.Position.Y < miny ? v.Position.Y : miny;
                minz = v.Position.Z < minz ? v.Position.Z : minz;

                maxx = v.Position.X > maxx ? v.Position.X : maxx;
                maxy = v.Position.Y > maxy ? v.Position.Y : maxy;
                maxz = v.Position.Z > maxz ? v.Position.Z : maxz;
            }

            ds.WriteRange(vertices);

            ds.Position = 0;

            var vbuffer = new SlimDX.Direct3D11.Buffer(context.Device, ds, new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = (int)ds.Length,
                Usage = ResourceUsage.Default
            });

            ds.Dispose();

            int indstep = 0;
            int[] indices = new int[icount];
            for (int i = 0; i < res - 1; i++)
            {
                //Triangle from low to high
                indices[indstep] = i;
                indices[indstep + 2] = res + i;
                indices[indstep + 1] = i + 1;
//.........这里部分代码省略.........
开发者ID:arturoc,项目名称:FeralTic,代码行数:101,代码来源:DX11Primitive_Segment.cs


注:本文中的DataStream.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。