Exemplo n.º 1
0
        /// <summary>
        /// Renders all of our geometry each frame.
        /// </summary>
        public void DrawTriangleList(SlimDX.Vector3 loc)
        {
            _SB.Capture();

            // Create the vertex buffer and fill with the triangle vertices.
            Vertices = new VertexBuffer(D3D.Device, 3 * D3D.Vertex.SizeBytes, Usage.WriteOnly, VertexFormat.None, Pool.Managed);
            SlimDX.DataStream stream = Vertices.Lock(0, 0, LockFlags.None);
            stream.WriteRange(D3D.BuildVertexData());
            Vertices.Unlock();

            var worldMatrix = SlimDX.Matrix.Translation(loc);

            D3D.Device.SetTransform(TransformState.World, worldMatrix);

            D3D.Device.VertexFormat = D3D.Vertex.Format;

            // Render the vertex buffer.
            D3D.Device.SetStreamSource(0, Vertices, 0, D3D.Vertex.SizeBytes);

            //D3D.Device.DrawPrimitives(PrimitiveType.LineStrip, 0, 1);
            D3D.Device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);

            if (Vertices != null)
            {
                Vertices.Dispose();
            }

            _SB.Apply();
        }
        /// <summary>
        /// Creates a new instance of <see cref="D3D10VertexBufferImplementation"/> initialized with the interleaved data.
        /// </summary>
        /// <param name="renderer">The D3D10 renderer.</param>
        /// <param name="decl">The vertex declaration.</param>
        /// <param name="usage">The resource usage.</param>
        /// <param name="data">The interleaved data.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying D3D10 buffer or writing to it failed.</exception>
        internal D3D10VertexBufferImplementation(D3D10Renderer renderer, VertexDeclaration decl, ResourceUsage usage, DataBuffer data)
            : base(decl, usage, data)
        {
            _renderer       = renderer;
            _graphicsDevice = _renderer.GraphicsDevice;

            //Determine appropiate buffer, let any exceptions bubble up.
            try {
                using (SDX.DataStream ds = new SDX.DataStream(data.ByteDataCopy, true, false)) {
                    //Now create and populate appropiate D3D10 buffer
                    if (base.BufferUsage == ResourceUsage.Static)
                    {
                        D3D.ResourceUsage  rUsage    = D3D.ResourceUsage.Default;
                        D3D.CpuAccessFlags cpuAccess = D3D.CpuAccessFlags.None;
                        _buffer = new D3D.Buffer(_graphicsDevice, ds, new D3D.BufferDescription(data.SizeInBytes, rUsage, D3D.BindFlags.VertexBuffer, cpuAccess, D3D.ResourceOptionFlags.None));
                    }
                    else if (base.BufferUsage == ResourceUsage.Dynamic)
                    {
                        D3D.ResourceUsage  rUsage    = D3D.ResourceUsage.Dynamic;
                        D3D.CpuAccessFlags cpuAccess = D3D.CpuAccessFlags.Write;
                        _buffer = new D3D.Buffer(_graphicsDevice, ds, new D3D.BufferDescription(data.SizeInBytes, rUsage, D3D.BindFlags.VertexBuffer, cpuAccess, D3D.ResourceOptionFlags.None));
                    }
                }

                //Add to tracker
                _renderer.Resources.AddTrackedObject(_buffer.ComPointer, this);
            } catch (Exception e) {
                Dispose();
                throw new TeslaException("Error creating D3D10 buffer: \n" + e.Message, e);
            }
        }
Exemplo n.º 3
0
        static Texture2D ConvertFromBitmap(Bitmap image)
        {
            System.Drawing.Imaging.BitmapData data = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
                                        System.Drawing.Imaging.ImageLockMode.ReadWrite, image.PixelFormat);
            int bytes = data.Stride * image.Height;
            DataStream stream = new SlimDX.DataStream(bytes, true, true);
            stream.WriteRange(data.Scan0,bytes);
            stream.Position = 0;
            DataRectangle dRect = new SlimDX.DataRectangle(data.Stride, stream);

            SlimDX.DXGI.SampleDescription sampleDesc = new SlimDX.DXGI.SampleDescription();
            sampleDesc.Count = 1;
            sampleDesc.Quality = 0;

            Texture2DDescription texDesc = new Texture2DDescription()
            {
                ArraySize = 1,
                MipLevels = 1,
                SampleDescription = sampleDesc,
                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                CpuAccessFlags = CpuAccessFlags.Write,
                BindFlags = BindFlags.ShaderResource,
                Usage = ResourceUsage.Dynamic,
                Height = image.Height,
                Width = image.Width
            };

            image.UnlockBits(data);
            image.Dispose();

            return new Texture2D(RenderForm11.Device, texDesc, dRect);
        }
Exemplo n.º 4
0
        Mesh CreateConvexHullShape(ConvexHullShape shape)
        {
            ShapeHull hull = new ShapeHull(shape);

            hull.BuildHull(shape.Margin);

            UIntArray    hullIndices = hull.Indices;
            Vector3Array points      = hull.Vertices;


            int vertexCount = hull.NumIndices;
            int faceCount   = hull.NumTriangles;

            bool index32 = vertexCount > 65536;

            Mesh mesh = new Mesh(device, faceCount, vertexCount,
                                 MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0), VertexFormat.Position | VertexFormat.Normal);


            SlimDX.DataStream indices = mesh.LockIndexBuffer(LockFlags.Discard);
            int i;

            if (index32)
            {
                for (i = 0; i < vertexCount; i++)
                {
                    indices.Write(i);
                }
            }
            else
            {
                for (i = 0; i < vertexCount; i++)
                {
                    indices.Write((short)i);
                }
            }
            mesh.UnlockIndexBuffer();

            SlimDX.DataStream verts = mesh.LockVertexBuffer(LockFlags.Discard);
            Vector3           scale = Vector3.Multiply(shape.LocalScaling, 1.0f + shape.Margin);

            for (i = 0; i < vertexCount; i += 3)
            {
                verts.Write(Vector3.Modulate(points[(int)hullIndices[i]], scale));
                verts.Position += 12;
                verts.Write(Vector3.Modulate(points[(int)hullIndices[i + 1]], scale));
                verts.Position += 12;
                verts.Write(Vector3.Modulate(points[(int)hullIndices[i + 2]], scale));
                verts.Position += 12;
            }
            mesh.UnlockVertexBuffer();

            mesh.ComputeNormals();
            shapes.Add(shape, mesh);

            return(mesh);
        }
Exemplo n.º 5
0
        Mesh CreateStaticPlaneShape(StaticPlaneShape shape)
        {
            // Load shader
            if (planeShader == null)
            {
                Assembly assembly     = Assembly.GetExecutingAssembly();
                Stream   shaderStream = assembly.GetManifestResourceStream("DemoFramework.checker_shader.fx");

                planeShader = Effect.FromStream(device, shaderStream, ShaderFlags.None);
            }


            Vector3[] vertices = new Vector3[4 * 2];

            Mesh mesh = new Mesh(device, 2, 4, MeshFlags.SystemMemory, VertexFormat.Position | VertexFormat.Normal);

            Vector3 planeOrigin = shape.PlaneNormal * shape.PlaneConstant;
            Vector3 vec0, vec1;

            PlaneSpace1(shape.PlaneNormal, out vec0, out vec1);
            float size = 1000;

            Vector3[] verts = new Vector3[4]
            {
                planeOrigin + vec0 * size,
                planeOrigin - vec0 * size,
                planeOrigin + vec1 * size,
                planeOrigin - vec1 * size
            };

            SlimDX.DataStream vertexBuffer = mesh.LockVertexBuffer(LockFlags.Discard);
            vertexBuffer.Write(verts[0]);
            vertexBuffer.Position += 12;
            vertexBuffer.Write(verts[1]);
            vertexBuffer.Position += 12;
            vertexBuffer.Write(verts[2]);
            vertexBuffer.Position += 12;
            vertexBuffer.Write(verts[3]);
            vertexBuffer.Position += 12;
            mesh.UnlockVertexBuffer();

            SlimDX.DataStream indexBuffer = mesh.LockIndexBuffer(LockFlags.Discard);
            indexBuffer.Write((short)1);
            indexBuffer.Write((short)2);
            indexBuffer.Write((short)0);
            indexBuffer.Write((short)1);
            indexBuffer.Write((short)3);
            indexBuffer.Write((short)0);
            mesh.UnlockIndexBuffer();

            mesh.ComputeNormals();

            complexShapes.Add(shape, mesh);

            return(mesh);
        }
        public void Evaluate(int SpreadMax)
        {
            this.FOutput.SliceCount = 1;
            this.FInvalidate        = false;

            if (this.FOutput[0] == null)
            {
                this.FOutput[0] = new DX11Resource <DX11DynamicRawBuffer>();
            }

            if (this.FApply[0] || this.FFirst)
            {
                this.streamInput.Sync();

                if (this.streamInput[0] != null)
                {
                    var inStream = this.streamInput[0];

                    if (this.dataStream != null && this.dataStream.Length != inStream.Length)
                    {
                        this.dataStream.Dispose();
                        this.dataStream = null;
                    }

                    if (this.dataStream == null && inStream.Length > 0)
                    {
                        this.dataStream = new DataStream(inStream.Length, true, true);
                    }


                    if (this.dataStream != null)
                    {
                        inStream.Position   = 0;
                        dataStream.Position = 0;

                        inStream.CopyTo(dataStream);
                        dataStream.Position = 0;
                    }
                }
                else
                {
                    if (this.dataStream != null)
                    {
                        this.dataStream.Dispose();
                        this.dataStream = null;
                    }
                }

                this.FInvalidate = true;
                this.FFirst      = false;
                this.FOutput.Stream.IsChanged = true;
            }
        }
Exemplo n.º 7
0
        private static DX11Effect CompileSharpDX(string content, bool isfile, Include include, ShaderMacro[] defines, bool library = false)
        {
            DX11Effect shader = new DX11Effect();

            var profile = library ? "lib_5_0" : "fx_5_0";

            SharpDX.D3DCompiler.Include sdxInclude = include != null ? new SharpDXIncludeWrapper(include) : null;
            var sdxDefines = defines != null?defines.AsSharpDXMacro() : null;

            string errors;

            try
            {
                SharpDX.D3DCompiler.ShaderFlags flags = SharpDX.D3DCompiler.ShaderFlags.OptimizationLevel1;

                if (isfile)
                {
                    SharpDX.D3DCompiler.CompilationResult result = SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile(content, profile, flags, SharpDX.D3DCompiler.EffectFlags.None, sdxDefines, sdxInclude);

                    if (result.Bytecode != null)
                    {
                        SlimDX.DataStream ds = new SlimDX.DataStream(result.Bytecode, true, true);
                        shader.ByteCode = new ShaderBytecode(ds);
                        shader.Preprocess();
                    }
                    errors = result.Message;
                }
                else
                {
                    //shader.ByteCode = ShaderBytecode.Compile(content, "fx_5_0", flags, EffectFlags.None, defines, include, out errors);
                    SharpDX.D3DCompiler.CompilationResult result = SharpDX.D3DCompiler.ShaderBytecode.Compile(content, profile, flags, SharpDX.D3DCompiler.EffectFlags.None, sdxDefines, sdxInclude);

                    if (result.Bytecode != null)
                    {
                        SlimDX.DataStream ds = new SlimDX.DataStream(result.Bytecode, true, true);
                        shader.ByteCode = new ShaderBytecode(ds);
                        shader.Preprocess();
                    }
                    errors = result.Message;
                }

                //Compilation worked, but we can still have warning
                shader.IsCompiled   = shader.ByteCode != null;
                shader.ErrorMessage = errors;
            }
            catch (Exception ex)
            {
                shader.IsCompiled    = false;
                shader.ErrorMessage  = ex.Message;
                shader.DefaultEffect = null;
            }
            return(shader);
        }
Exemplo n.º 8
0
        public void RenderSoftBodyTextured(SoftBody softBody)
        {
            if (!(softBody.UserObject is Array))
            {
                return;
            }

            object[]   userObjArr   = softBody.UserObject as object[];
            FloatArray vertexBuffer = userObjArr[0] as FloatArray;
            IntArray   indexBuffer  = userObjArr[1] as IntArray;

            int vertexCount = (vertexBuffer.Count / 8);

            if (vertexCount > 0)
            {
                int faceCount = indexBuffer.Count / 2;

                bool index32 = vertexCount > 65536;

                Mesh mesh = new Mesh(device, faceCount, vertexCount,
                                     MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0),
                                     VertexFormat.Position | VertexFormat.Normal | VertexFormat.Texture1);

                SlimDX.DataStream indices = mesh.LockIndexBuffer(LockFlags.Discard);
                if (index32)
                {
                    foreach (int i in indexBuffer)
                    {
                        indices.Write(i);
                    }
                }
                else
                {
                    foreach (int i in indexBuffer)
                    {
                        indices.Write((short)i);
                    }
                }
                mesh.UnlockIndexBuffer();

                SlimDX.DataStream verts = mesh.LockVertexBuffer(LockFlags.Discard);
                foreach (float f in vertexBuffer)
                {
                    verts.Write(f);
                }
                mesh.UnlockVertexBuffer();

                mesh.ComputeNormals();
                mesh.DrawSubset(0);
                mesh.Dispose();
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Reads data from the index buffer into the array.
        /// </summary>
        /// <typeparam name="T">The type of data in the index buffer - int or short.</typeparam>
        /// <param name="data">Array to write the data to</param>
        /// <param name="startIndex">Starting index in the array at which to start writing to</param>
        /// <param name="elementCount">Number of indices to read</param>
        /// <param name="offsetInBytes">Offset from the start of the index buffer at which to start copying from</param>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public override void GetData <T>(T[] data, int startIndex, int elementCount, int offsetInBytes)
        {
            if (_buffer == null || _buffer.Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            //Throws null or out of range exception
            D3D10Helper.CheckArrayBounds(data, startIndex, elementCount);

            int numBytes = MemoryHelper.SizeOf <T>();

            int ibSize   = base.IndexCount * ((base.IndexFormat == IndexFormat.SixteenBits) ? 2 : 4);
            int dataSize = elementCount * numBytes;

            if (offsetInBytes < 0 || offsetInBytes > ibSize)
            {
                throw new ArgumentOutOfRangeException("offsetInBytes", "Byte offset is out of range.");
            }

            if ((offsetInBytes + dataSize) > ibSize)
            {
                throw new ArgumentOutOfRangeException("data", "Byte offset and the number of elements to read will cause a buffer overflow.");
            }

            CreateStaging();

            try {
                //If we're reading from the entire VB just copy the whole thing
                if (offsetInBytes == 0 && startIndex == 0 && dataSize == ibSize)
                {
                    _graphicsDevice.CopyResource(_buffer, _staging);
                }
                else
                {
                    D3D.ResourceRegion region = new D3D.ResourceRegion();
                    region.Left  = offsetInBytes;
                    region.Right = offsetInBytes + dataSize;
                    region.Front = region.Top = 0;
                    region.Back  = region.Bottom = 1;
                    _graphicsDevice.CopySubresourceRegion(_buffer, 0, region, _staging, 0, offsetInBytes, 0, 0);
                }

                using (SDX.DataStream ds = _staging.Map(D3D.MapMode.Read, D3D.MapFlags.None)) {
                    ds.Position = offsetInBytes;
                    ds.ReadRange <T>(data, startIndex, elementCount);
                    _staging.Unmap();
                }
            } catch (Exception e) {
                throw new TeslaException("Error reading from D3D10 Buffer.", e);
            }
        }
Exemplo n.º 10
0
        Mesh CreateTriangleMeshShape(TriangleMeshShape shape)
        {
            StridingMeshInterface meshInterface = shape.MeshInterface;

            BulletSharp.DataStream verts, indices;
            int           numVerts, numFaces;
            PhyScalarType vertsType, indicesType;
            int           vertexStride, indexStride;

            meshInterface.GetLockedReadOnlyVertexIndexData(out verts, out numVerts, out vertsType, out vertexStride,
                                                           out indices, out indexStride, out numFaces, out indicesType);

            bool index32 = numVerts > 65536;

            Mesh mesh = new Mesh(device, numFaces, numVerts,
                                 MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0), VertexFormat.Position | VertexFormat.Normal);

            SlimDX.DataStream data = mesh.LockVertexBuffer(LockFlags.None);
            while (verts.Position < verts.Length)
            {
                Vector3 v = verts.Read <Vector3>();
                data.Write(v);

                verts.Position += vertexStride - 12;

                // Normals will be calculated later
                data.Position += 12;
            }
            mesh.UnlockVertexBuffer();

            data = mesh.LockIndexBuffer(LockFlags.None);
            while (indices.Position < indices.Length)
            {
                int index = indices.Read <int>();
                if (index32)
                {
                    data.Write(index);
                }
                else
                {
                    data.Write((short)index);
                }
            }
            mesh.UnlockVertexBuffer();

            mesh.ComputeNormals();

            shapes.Add(shape, mesh);
            return(mesh);
        }
        /// <summary>
        /// Creates a new instance of <see cref="D3D10VertexBufferImplementation"/> initialized with the vertex data array.
        /// </summary>
        /// <param name="renderer">The D3D10 renderer.</param>
        /// <param name="decl">The vertex declaration.</param>
        /// <param name="usage">The resource usage.</param>
        /// <param name="data">The array of vertex data.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying D3D10 buffer or writing to it failed.</exception>
        internal D3D10VertexBufferImplementation(D3D10Renderer renderer, VertexDeclaration decl, ResourceUsage usage, params DataBuffer[] data)
            : base(decl, usage, data)
        {
            _renderer       = renderer;
            _graphicsDevice = renderer.GraphicsDevice;

            int totalSizeInBytes = base.VertexCount * decl.VertexStride;
            int vertexStride     = decl.VertexStride;

            try {
                //Now initialize the buffer with the supplied vertex store
                using (SDX.DataStream interleaved = new SDX.DataStream(totalSizeInBytes, true, true)) {
                    //Create the interleaved buffer
                    byte[] vertex = new byte[vertexStride];
                    for (int i = 0; i < base.VertexCount; i++)
                    {
                        int offset = 0;
                        for (int j = 0; j < data.Length; j++)
                        {
                            DataBuffer db          = data[j];
                            int        elementSize = db.ElementSizeInBytes;
                            db.Get(vertex, offset, elementSize);
                            offset += elementSize;
                        }
                        interleaved.Write(vertex, 0, vertexStride);
                    }
                    interleaved.Position = 0;
                    //Now create and populate appropiate D3D10 buffer
                    if (base.BufferUsage == ResourceUsage.Static)
                    {
                        D3D.ResourceUsage  rUsage    = D3D.ResourceUsage.Default;
                        D3D.CpuAccessFlags cpuAccess = D3D.CpuAccessFlags.None;
                        _buffer = new D3D.Buffer(_graphicsDevice, interleaved, new D3D.BufferDescription(totalSizeInBytes, rUsage, D3D.BindFlags.VertexBuffer, cpuAccess, D3D.ResourceOptionFlags.None));
                    }
                    else if (base.BufferUsage == ResourceUsage.Dynamic)
                    {
                        D3D.ResourceUsage  rUsage    = D3D.ResourceUsage.Dynamic;
                        D3D.CpuAccessFlags cpuAccess = D3D.CpuAccessFlags.Write;
                        _buffer = new D3D.Buffer(_graphicsDevice, interleaved, new D3D.BufferDescription(totalSizeInBytes, rUsage, D3D.BindFlags.VertexBuffer, cpuAccess, D3D.ResourceOptionFlags.None));
                    }
                }

                //Add to tracker
                _renderer.Resources.AddTrackedObject(_buffer.ComPointer, this);
            } catch (Exception e) {
                Dispose();
                throw new TeslaException("Error creating D3D10 buffer: \n" + e.Message, e);
            }
        }
Exemplo n.º 12
0
 public static Buffer CreateVertexBuffer(SlimDX.Direct3D11.Device graphicsDevice, System.Array vertices)
 {
     using (SlimDX.DataStream vertexStream = new SlimDX.DataStream(vertices, true, true))
     {
         return(new Buffer(
                    graphicsDevice,
                    vertexStream,
                    new BufferDescription
         {
             SizeInBytes = (int)vertexStream.Length,
             BindFlags = BindFlags.VertexBuffer,
         }
                    ));
     }
 }
Exemplo n.º 13
0
 /// <summary>
 /// インデックスバッファ作成
 /// </summary>
 public static SlimDX.Direct3D11.Buffer CreateIndexBuffer(System.Array indexes)
 {
     using (SlimDX.DataStream indexStream
                = new SlimDX.DataStream(indexes, true, true))
     {
         return(new SlimDX.Direct3D11.Buffer(
                    Instance._device,
                    indexStream,
                    new BufferDescription
         {
             SizeInBytes = (int)indexStream.Length,
             BindFlags = BindFlags.IndexBuffer,
         }
                    ));
     }
 }
Exemplo n.º 14
0
 public static Buffer CreateIndexBuffer(SlimDX.Direct3D11.Device graphicsDevice, uint[] indices)
 {
     using (SlimDX.DataStream indicesStream = new SlimDX.DataStream(indices, true, true))
     {
         return(new Buffer(
                    graphicsDevice,
                    indicesStream,
                    new BufferDescription
         {
             SizeInBytes = (int)indicesStream.Length,
             BindFlags = BindFlags.IndexBuffer,
             StructureByteStride = sizeof(uint)
         }
                    ));
     }
 }
Exemplo n.º 15
0
        Mesh CreateGImpactMeshShape(GImpactMeshShape shape)
        {
            BulletSharp.DataStream verts, indices;
            int           numVerts, numFaces;
            PhyScalarType vertsType, indicesType;
            int           vertexStride, indexStride;

            shape.MeshInterface.GetLockedReadOnlyVertexIndexData(out verts, out numVerts, out vertsType, out vertexStride,
                                                                 out indices, out indexStride, out numFaces, out indicesType);

            bool index32 = numVerts > 65536;

            Mesh mesh = new Mesh(device, numFaces, numVerts,
                                 MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0), VertexFormat.Position | VertexFormat.Normal);

            SlimDX.DataStream vertexBuffer = mesh.LockVertexBuffer(LockFlags.Discard);
            while (vertexBuffer.Position < vertexBuffer.Length)
            {
                vertexBuffer.Write(verts.Read <Vector3>());
                vertexBuffer.Position += 12;
            }
            mesh.UnlockVertexBuffer();

            SlimDX.DataStream indexBuffer = mesh.LockIndexBuffer(LockFlags.Discard);
            if (index32)
            {
                while (indexBuffer.Position < indexBuffer.Length)
                {
                    indexBuffer.Write(indices.Read <int>());
                }
            }
            else
            {
                while (indexBuffer.Position < indexBuffer.Length)
                {
                    indexBuffer.Write((short)indices.Read <int>());
                }
            }
            mesh.UnlockIndexBuffer();

            mesh.ComputeNormals();
            shapes.Add(shape, mesh);

            return(mesh);
        }
Exemplo n.º 16
0
        public override void Init()
        {
            // 頂点情報のフォーマットを設定
            vertexLayout = new InputLayout(
                Context.Device,
                Effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature,
                VertexPositionColor.VertexElements
                );

            // 頂点バッファに頂点を追加
            using (SlimDX.DataStream vertexStream = new SlimDX.DataStream(
                       new[] {
                new VertexPositionColor
                {
                    Position = new Vector3(0, 0, 0),
                    Color = new Vector3(1, 1, 1)
                },
                new VertexPositionColor
                {
                    Position = new Vector3(0, 1, 0),
                    Color = new Vector3(0, 0, 1)
                },
                new VertexPositionColor
                {
                    Position = new Vector3(1, 0, 0),
                    Color = new Vector3(1, 0, 0)
                }
            },
                       true,
                       true
                       ))
            {
                vertexBuffer = new SlimDX.Direct3D11.Buffer(
                    Context.Device,
                    vertexStream,
                    new BufferDescription
                {
                    SizeInBytes = (int)vertexStream.Length,
                    BindFlags   = BindFlags.VertexBuffer,
                }
                    );
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Creates a new instance of <see cref="D3D10IndexBufferImplementation"/>.
        /// </summary>
        /// <param name="renderer">The D3D renderer.</param>
        /// <param name="indices">The index data</param>
        /// <param name="usage">The buffer usage specifying what type of memory the buffer should be created in.</param>
        internal D3D10IndexBufferImplementation(D3D10Renderer renderer, DataBuffer <int> indices, ResourceUsage usage)
            : base(indices, usage)
        {
            if (indices == null)
            {
                throw new ArgumentNullException("indices", "Indices cannot be null.");
            }

            _renderer       = renderer;
            _graphicsDevice = _renderer.GraphicsDevice;

            try {
                //Determine appropiate vertex buffer to create
                if (usage == ResourceUsage.Static)
                {
                    D3D.ResourceUsage  rUsage    = D3D.ResourceUsage.Default;
                    D3D.CpuAccessFlags cpuAccess = D3D.CpuAccessFlags.None;
                    using (SDX.DataStream ds = new SDX.DataStream(indices.Buffer, true, true)) {
                        _buffer = new D3D.Buffer(_graphicsDevice, ds, new D3D.BufferDescription(indices.SizeInBytes, rUsage, D3D.BindFlags.IndexBuffer, cpuAccess, D3D.ResourceOptionFlags.None));
                    }
                }
                else if (usage == ResourceUsage.Dynamic)
                {
                    D3D.ResourceUsage  rUsage    = D3D.ResourceUsage.Dynamic;
                    D3D.CpuAccessFlags cpuAccess = D3D.CpuAccessFlags.Write;
                    using (SDX.DataStream ds = new SDX.DataStream(indices.Buffer, true, true)) {
                        _buffer = new D3D.Buffer(_graphicsDevice, ds, new D3D.BufferDescription(indices.SizeInBytes, rUsage, D3D.BindFlags.IndexBuffer, cpuAccess, D3D.ResourceOptionFlags.None));
                    }
                }

                //Add to tracker
                _renderer.Resources.AddTrackedObject(_buffer.ComPointer, this);
            } catch (D3D.Direct3D10Exception e) {
                Dispose();
                throw new TeslaException("Error creating D3D10 buffer.", e);
            }
        }
        protected void InitializePrimitive()
        {
            if (materialShader == null)
                materialShader = MaterialShader.DefaultMaterial(Renderer);
            if (this.GetType() == typeof(SkinnedMeshPrimitive))
                GeometryData.VertexDefinition = MaterialShader.SkinnedMeshVertexDefinition;
            else
                GeometryData.VertexDefinition = MaterialShader.StaticMeshVertexDefinition;
            GeometryData.VertexStride = GeometryData.VertexDefinition.SizeInBytes;
            GeometryData.VertexCount = GeometryData.Vertices.Count;
            GeometryData.IndexCount = GeometryData.Indices.Count;

            DataStream VerticesStream = new DataStream(GeometryData.VertexCount * GeometryData.VertexStride, true, true);
            Vector3[] Tangent;
            Vector3[] Bitangent;
            GenerateTangentFrame(out Tangent, out Bitangent);
            for (int j = 0; j < GeometryData.Vertices.Count; j++)
            {
                Vertex v = GeometryData.Vertices[j];
                for (int i = 0; i < GeometryData.VertexDefinition.Parameters.Count; i++)
                {
                    VertexParameterType vp = GeometryData.VertexDefinition.Parameters[i];
                    if (vp == VertexParameterType.Position)
                        VerticesStream.Write(v.GetVertex<Vector3>(vp).Value);
                    else if (vp == VertexParameterType.Normal)
                        VerticesStream.Write(v.GetVertex<Vector3>(vp).Value);
                    else if (vp == VertexParameterType.TextureCoordinate)
                        VerticesStream.Write(v.GetVertex<Vector2>(vp).Value);
                    else if (vp == VertexParameterType.Tangent)
                    {
                        //VerticesStream.Write(Vector3.Normalize(Tangent[j]));
                        VerticesStream.Write(MathHelper.CalculateTangent(v.GetVertex<Vector3>(VertexParameterType.Normal).Value));
                        /*if ((j + (GeometryData.Vertices.Count % 3)) % 3 == 0 & GeometryData.Vertices.Count - (j + (GeometryData.Vertices.Count % 3)) > 2)
                        {
                            tan = MathHelper.CalculateTangent(
                            v.GetVertex<Vector3>(VertexParameterType.Position).Value,
                            GeometryData.Vertices[j + 1].GetVertex<Vector3>(VertexParameterType.Position).Value,
                            GeometryData.Vertices[j + 2].GetVertex<Vector3>(VertexParameterType.Position).Value,
                            v.GetVertex<Vector2>(VertexParameterType.TextureCoordinate).Value,
                            GeometryData.Vertices[j + 1].GetVertex<Vector2>(VertexParameterType.TextureCoordinate).Value,
                            GeometryData.Vertices[j + 2].GetVertex<Vector2>(VertexParameterType.TextureCoordinate).Value
                            );
                        }
                        Vector3 val = v.GetVertex<Vector3>(VertexParameterType.Normal).Value;
                        Vector3 vec = MathHelper.ToVector3(Vector3.Transform(val, Matrix.RotationX(MathHelper.PiOver2)));
                        if (v is VertexPosNorTexTanBin)
                        {
                            VerticesStream.Write(v.GetVertex<Vector3>(vp).Value);
                        }
                        else
                        {
                            VerticesStream.Write(MathHelper.CalculateTangent(v.GetVertex<Vector3>(VertexParameterType.Normal).Value));
                        }*/
                    }
                    else if (vp == VertexParameterType.Binormal)
                    {
                        //VerticesStream.Write(Vector3.Normalize(Bitangent[j]));
                        VerticesStream.Write(-MathHelper.CalculateTangent(v.GetVertex<Vector3>(VertexParameterType.Normal).Value));
                        /*if ((j + (GeometryData.Vertices.Count % 3)) % 3 == 0 & GeometryData.Vertices.Count - (j + (GeometryData.Vertices.Count % 3)) > 2)
                        {
                            bin = MathHelper.CalculateBitangent(
                                v.GetVertex<Vector3>(VertexParameterType.Position).Value,
                                GeometryData.Vertices[j + 1].GetVertex<Vector3>(VertexParameterType.Position).Value,
                                GeometryData.Vertices[j + 2].GetVertex<Vector3>(VertexParameterType.Position).Value,
                                v.GetVertex<Vector2>(VertexParameterType.TextureCoordinate).Value,
                                GeometryData.Vertices[j + 1].GetVertex<Vector2>(VertexParameterType.TextureCoordinate).Value,
                                GeometryData.Vertices[j + 2].GetVertex<Vector2>(VertexParameterType.TextureCoordinate).Value
                                );
                        }
                        Vector3 val = v.GetVertex<Vector3>(VertexParameterType.Normal).Value;
                        Vector3 vec = MathHelper.ToVector3(Vector3.Transform(val, Matrix.RotationZ(MathHelper.PiOver2)));
                        if (v is VertexPosNorTexTanBin)
                        {
                            VerticesStream.Write(v.GetVertex<Vector3>(vp).Value);
                        }
                        else
                        {
                            VerticesStream.Write(MathHelper.CalculateBitangent(v.GetVertex<Vector3>(VertexParameterType.Normal).Value));
                        }*/
                    }
                    else if (vp == VertexParameterType.Bones32Bit)
                    {
                        Vector4 vec = (v.GetVertex<Vector4>(vp).Value);
                        VerticesStream.Write((uint)vec.X);
                        VerticesStream.Write((uint)vec.Y);
                        VerticesStream.Write((uint)vec.Z);
                        VerticesStream.Write((uint)vec.W);
                    }
                    else if (vp == VertexParameterType.Weights)
                    {
                        Vector4 vec = (v.GetVertex<Vector4>(vp).Value);
                        VerticesStream.Write(v.GetVertex<Vector4>(vp).Value);
                    }
                    else if (vp == VertexParameterType.ColorRGB)
                        VerticesStream.Write(v.GetVertex<Vector3>(vp).Value);
                }
            }
            VerticesStream.Position = 0;
            GeometryData.VertexBuffer = new Buffer(Renderer.Device, VerticesStream, GeometryData.VertexStride * GeometryData.VertexCount,
                ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, GeometryData.VertexStride);

            DataStream IndicesStream = new DataStream(GeometryData.Indices.ToArray(), true, true);
            IndicesStream.Position = 0;

            GeometryData.IndexBuffer = new Buffer(Renderer.Device, IndicesStream, sizeof(ushort) * GeometryData.IndexCount,
                ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, sizeof(ushort));

            IndicesStream.Close();
            VerticesStream.Close();
        }
Exemplo n.º 19
0
        /// <summary>
        /// Sets the data to the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array.</typeparam>
        /// <param name="data">Array of data.</param>
        /// <param name="mipLevel">Mip map level to access.</param>
        /// <param name="subimage">Rectangle representing a sub-image of the 2D texture to write to, if null the whole image is written to.</param>
        /// <param name="startIndex">Starting index in the array to start reading from.</param>
        /// <param name="elementCount">Number of elements to write.</param>
        /// <exception cref="System.ArgumentException">Thrown if the format byte size of the type to write and the texture do not match, the subimage
        /// dimensions are invalid, or if the total size to write and the total size in the texture do not match</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there was an error writing to the texture.</exception>
        public override void SetData <T>(T[] data, int mipLevel, Math.Rectangle?subimage, int startIndex, int elementCount)
        {
            if (_texture2D == null || _texture2D.Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (mipLevel < 0 || mipLevel >= _mipCount)
            {
                throw new ArgumentOutOfRangeException("mipLevel", String.Format("Mip level is out of range. Must be between 0 and {0}.", _mipCount.ToString()));
            }

            //Throws null or out of range exception
            D3D10Helper.CheckArrayBounds(data, startIndex, elementCount);

            int           formatSize = D3D10Helper.FormatSize(base.Format);
            SurfaceFormat format     = base.Format;
            int           elemSize   = MemoryHelper.SizeOf <T>();

            CheckSizes(formatSize, elemSize);

            //Calc subresource dimensions
            int width  = (int)MathHelper.Max(1, base.Width >> mipLevel);
            int height = (int)MathHelper.Max(1, base.Height >> mipLevel);

            //Get the dimensions, if its null we copy the whole texture
            Rectangle rect;

            if (subimage.HasValue)
            {
                rect = subimage.Value;
                CheckRectangle(rect, ref width, ref height);
            }
            else
            {
                rect = new Rectangle(0, 0, width, height);
            }

            CheckTotalSize(base.Format, ref formatSize, ref width, ref height, elemSize, elementCount);

            //Create staging for non-dynamic textures
            if (_usage == D3D.ResourceUsage.Default)
            {
                CreateStaging();
            }

            try {
                if (_usage == D3D.ResourceUsage.Default)
                {
                    SDX.DataRectangle dataRect = _staging.Map(mipLevel, D3D.MapMode.Write, D3D.MapFlags.None);
                    SDX.DataStream    ds       = dataRect.Data;
                    int row   = rect.Y;
                    int col   = rect.X;
                    int pitch = dataRect.Pitch;

                    int index = startIndex;
                    int count = elementCount;
                    //Compute the actual number of elements based on the format size and the element size we're copying the bytes into
                    int actWidth = (int)MathHelper.Floor(width * (formatSize / elemSize));
                    //Go row by row
                    for (int i = row; i < height; i++)
                    {
                        //Set the position
                        ds.Position = (i * pitch) + (col * formatSize);
                        //Break if we've run out of elements or on the very last row that isn't complete
                        if (count <= 0)
                        {
                            break;
                        }
                        else if (count < actWidth)
                        {
                            ds.WriteRange <T>(data, index, count);
                            break;
                        }
                        //Otherwise, copy the whole row and increment/decrement the index and count
                        ds.WriteRange <T>(data, index, actWidth);
                        index += actWidth;
                        count -= actWidth;
                    }
                    _staging.Unmap(mipLevel);

                    //Do resource copy
                    if (format == SurfaceFormat.DXT1 || format == SurfaceFormat.DXT3 || format == SurfaceFormat.DXT5)
                    {
                        _graphicsDevice.CopyResource(_staging, _texture2D);
                    }
                    else
                    {
                        D3D.ResourceRegion region = new D3D.ResourceRegion();
                        region.Left   = col;
                        region.Right  = col + width;
                        region.Top    = row;
                        region.Bottom = row + height;
                        region.Front  = 0;
                        region.Back   = 1;
                        _graphicsDevice.CopySubresourceRegion(_staging, mipLevel, region, _texture2D, mipLevel, col, row, 0);
                    }
                }
                else
                {
                    SDX.DataRectangle dataRect = _texture2D.Map(mipLevel, D3D.MapMode.WriteDiscard, D3D.MapFlags.None);
                    SDX.DataStream    ds       = dataRect.Data;
                    int row   = rect.Y;
                    int col   = rect.X;
                    int pitch = dataRect.Pitch;

                    int index = startIndex;
                    int count = elementCount;
                    //Compute the actual number of elements based on the format size and the element size we're copying the bytes into
                    int actWidth = (int)MathHelper.Floor(width * (formatSize / elemSize));
                    //Go row by row
                    for (int i = row; i < height; i++)
                    {
                        //Set the position
                        ds.Position = (i * pitch) + (col * formatSize);
                        //Break if we've run out of elements or on the very last row that isn't complete
                        if (count <= 0)
                        {
                            break;
                        }
                        else if (count < actWidth)
                        {
                            ds.WriteRange <T>(data, index, count);
                            break;
                        }
                        //Otherwise, copy the whole row and increment/decrement the index and count
                        ds.WriteRange <T>(data, index, actWidth);
                        index += actWidth;
                        count -= actWidth;
                    }
                    _texture2D.Unmap(mipLevel);
                }
            } catch (Exception e) {
                throw new TeslaException("Error writing to D3D10 Texture2D.", e);
            }
        }
Exemplo n.º 20
0
 public static Buffer CreateVertexBuffer(
     SlimDX.Direct3D11.Device graphicsDevice,
     System.Array vertices
     )
 {
     using (SlimDX.DataStream vertexStream
         = new SlimDX.DataStream(vertices, true, true))
     {
         return new Buffer(
             graphicsDevice,
             vertexStream,
             new BufferDescription
             {
                 SizeInBytes = (int)vertexStream.Length,
                 BindFlags = BindFlags.VertexBuffer,
             }
             );
     }
 }
Exemplo n.º 21
0
        /// <summary>
        /// Sets the data from the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array</typeparam>
        /// <param name="data">The array of data</param>
        /// <param name="mipLevel">Mip map level to read from</param>
        /// <param name="left">Right-most width position in the texture at which to acess. (0 or greater)</param>
        /// <param name="right">Right-most width position in the texture at which to acess. (width or less)</param>
        /// <param name="top">Top-most height position in the texture at which to acess. (0 or greater)</param>
        /// <param name="bottom">Bottom-most height position in the texture at which to acess. (height or less)</param>
        /// <param name="front">Front-most depth position in the texture at which to acess. (0 or greater)</param>
        /// <param name="back">Back-most depth position in the texture at which to acess. (depth or less)</param>
        /// <param name="startIndex">Starting index in the array to start reading from.</param>
        /// <param name="elementCount">Number of elements to write.</param>
        /// <exception cref="System.ArgumentException">Thrown if the format byte size of the type to write and the texture do not match, the subimage
        /// dimensions are invalid, or if the total size to write and the total size in the texture do not match</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there was an error writing to the texture.</exception>
        public override void SetData <T>(T[] data, int mipLevel, int left, int right, int top, int bottom, int front, int back, int startIndex, int elementCount)
        {
            if (_texture3D == null || _texture3D.Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (mipLevel < 0 || mipLevel >= _mipCount)
            {
                throw new ArgumentOutOfRangeException("mipLevel", String.Format("Mip level is out of range. Must be between 0 and {0}.", _mipCount.ToString()));
            }

            //Throws null or out of range exception
            D3D10Helper.CheckArrayBounds(data, startIndex, elementCount);

            int formatSize = D3D10Helper.FormatSize(base.Format);
            int elemSize   = MemoryHelper.SizeOf <T>();

            CheckSizes(formatSize, elemSize);

            //Calc subresource dimensions
            int width  = (int)MathHelper.Max(1, base.Width >> mipLevel);
            int height = (int)MathHelper.Max(1, base.Height >> mipLevel);
            int depth  = (int)MathHelper.Max(1, base.Depth >> mipLevel);

            //Ensure box dimensions
            CheckBox(left, right, top, bottom, front, back, ref width, ref height, ref depth);

            CheckTotalSize(base.Format, ref formatSize, ref width, ref height, ref depth, elemSize, elementCount);

            //Create staging for non-dynamic textures
            if (_usage == D3D.ResourceUsage.Default)
            {
                CreateStaging();
            }

            try {
                if (_usage == D3D.ResourceUsage.Default)
                {
                    SDX.DataBox    dataBox    = _staging.Map(mipLevel, D3D.MapMode.Write, D3D.MapFlags.None);
                    SDX.DataStream ds         = dataBox.Data;
                    int            row        = left;
                    int            col        = top;
                    int            slice      = front;
                    int            rowPitch   = dataBox.RowPitch;
                    int            slicePitch = dataBox.SlicePitch;

                    int index = startIndex;
                    int count = elementCount;
                    //Compute the actual number of elements based on the format size and the element size we're copying the bytes into
                    int actWidth = (int)MathHelper.Floor(width * (formatSize / elemSize));
                    //Go slice by slice
                    for (int k = slice; k < back; k++)
                    {
                        //Go row by row
                        for (int i = row; i < bottom; i++)
                        {
                            //Set the position
                            ds.Position = (k * slicePitch) + (i * rowPitch) + (col * formatSize);
                            //Break if we've run out of elements or on the very last row that isn't complete
                            if (count <= 0)
                            {
                                break;
                            }
                            else if (count < actWidth)
                            {
                                ds.WriteRange <T>(data, index, count);
                                break;
                            }
                            //Otherwise, copy the whole row and increment/decrement the index and count
                            ds.WriteRange <T>(data, index, actWidth);
                            index += actWidth;
                            count -= actWidth;
                        }
                    }
                    _staging.Unmap(mipLevel);

                    //Do resource copy
                    if (base.Format == SurfaceFormat.DXT1 || base.Format == SurfaceFormat.DXT3 || base.Format == SurfaceFormat.DXT5)
                    {
                        _graphicsDevice.CopyResource(_staging, _texture3D);
                    }
                    else
                    {
                        D3D.ResourceRegion region = new D3D.ResourceRegion();
                        region.Left   = col;
                        region.Right  = right;
                        region.Top    = row;
                        region.Bottom = bottom;
                        region.Front  = slice;
                        region.Back   = back;
                        _graphicsDevice.CopySubresourceRegion(_staging, mipLevel, region, _texture3D, mipLevel, col, row, slice);
                    }
                }
                else
                {
                    SDX.DataBox    dataBox    = _texture3D.Map(mipLevel, D3D.MapMode.Write, D3D.MapFlags.None);
                    SDX.DataStream ds         = dataBox.Data;
                    int            row        = left;
                    int            col        = top;
                    int            slice      = front;
                    int            rowPitch   = dataBox.RowPitch;
                    int            slicePitch = dataBox.SlicePitch;

                    int index = startIndex;
                    int count = elementCount;
                    //Compute the actual number of elements based on the format size and the element size we're copying the bytes into
                    int actWidth = (int)MathHelper.Floor(width * (formatSize / elemSize));
                    //Go slice by slice
                    for (int k = slice; k < back; k++)
                    {
                        //Go row by row
                        for (int i = row; i < bottom; i++)
                        {
                            //Set the position
                            ds.Position = (k * slicePitch) + (i * rowPitch) + (col * formatSize);
                            //Break if we've run out of elements or on the very last row that isn't complete
                            if (count <= 0)
                            {
                                break;
                            }
                            else if (count < actWidth)
                            {
                                ds.WriteRange <T>(data, index, count);
                                break;
                            }
                            //Otherwise, copy the whole row and increment/decrement the index and count
                            ds.WriteRange <T>(data, index, actWidth);
                            index += actWidth;
                            count -= actWidth;
                        }
                    }
                    _texture3D.Unmap(mipLevel);
                }
            } catch (Exception e) {
                throw new TeslaException("Error writing to D3D10 Texture3D.", e);
            }
        }
        /// <summary>
        /// Gets the back buffer data.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="subimage">The rectangle representing the sub-image. Null value means to grab the whole back buffer.</param>
        /// <param name="data">The data.</param>
        /// <param name="startIndex">The starting index in the array.</param>
        /// <param name="elementCount">The number of eleemnts to read</param>
        public override void GetBackBufferData <T>(Rectangle?subimage, T[] data, int startIndex, int elementCount)
        {
            if (_backBuffer.Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            //Throws null or out of range exception
            D3D10Helper.CheckArrayBounds(data, startIndex, elementCount);

            //Calc subresource dimensions
            int width  = _presentParams.BackBufferWidth;
            int height = _presentParams.BackBufferHeight;

            //Get the dimensions, if its null we copy the whole texture
            Rectangle rect;

            if (subimage.HasValue)
            {
                rect = subimage.Value;
                CheckRectangle(rect, width, height);
            }
            else
            {
                rect = new Rectangle(0, 0, width, height);
            }

            if (elementCount > rect.Width * rect.Height)
            {
                throw new ArgumentOutOfRangeException("elementCount", "Number of elements to read is larger than contained in the specified subimage.");
            }

            //Create staging
            CreateStaging();

            try {
                int row        = rect.Y;
                int col        = rect.X;
                int rectWidth  = rect.Width;
                int rectHeight = rect.Height;

                //Do resource copy
                if (row == 0 && col == 0 && rectWidth == width && rectHeight == height)
                {
                    _graphicsDevice.CopyResource(_backBuffer, _staging);
                }
                else
                {
                    D3D.ResourceRegion region = new D3D.ResourceRegion();
                    region.Left   = col;
                    region.Right  = col + rectWidth;
                    region.Top    = row;
                    region.Bottom = row + rectHeight;
                    region.Front  = 0;
                    region.Back   = 1;
                    _graphicsDevice.CopySubresourceRegion(_backBuffer, 0, region, _staging, 0, col, row, 0);
                }

                SDX.DataRectangle dataRect = _staging.Map(0, D3D.MapMode.Read, D3D.MapFlags.None);
                SDX.DataStream    ds       = dataRect.Data;
                int elemSize   = MemoryHelper.SizeOf <T>();
                int formatSize = D3D10Helper.FormatSize(_presentParams.BackBufferFormat);
                int pitch      = dataRect.Pitch;

                int index = startIndex;
                int count = elementCount;

                //Compute the actual number of elements based on the format size and the element size we're copying the bytes into
                int actWidth = (int)MathHelper.Floor(rectWidth * (formatSize / elemSize));
                //Go row by row
                for (int i = row; i < height; i++)
                {
                    //Set the position
                    ds.Position = (i * pitch) + (col * formatSize);
                    //Break if we've run out of elements or on the very last row that isn't complete
                    if (count <= 0)
                    {
                        break;
                    }
                    else if (count < actWidth)
                    {
                        ds.ReadRange <T>(data, index, count);
                        break;
                    }
                    //Otherwise, copy the whole row and increment/decrement the index and count
                    ds.ReadRange <T>(data, index, actWidth);
                    index += actWidth;
                    count -= actWidth;
                }
                _staging.Unmap(0);
            } catch (Exception e) {
                throw new TeslaException("Error reading from D3D10 Texture2D.", e);
            }
        }
        /// <summary>
        /// Gets the data from the vertex buffer and copies it into specified array.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array to copy contents to from the vertex buffer into</param>
        /// <param name="startIndex">Index of the element in the array at each to start writing to</param>
        /// <param name="elementCount">Number of elements to copy</param>
        /// <param name="offsetInBytes">Offset in bytes from the beginning of the vertex buffer to the data.</param>
        /// <param name="vertexStride">Size of an element in bytes</param>
        /// <exception cref="System.ObjectDisposedException">Thrown if Dispose() has been called.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown if the write options are incompatible with the resource usage of the buffer.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the data's vertex stride is too small, the offset in bytes is out of range,
        /// or the byte offset and number of elements to read will cause overflow.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there was an error reading from the buffer.</exception>
        public override void GetData <T>(T[] data, int startIndex, int elementCount, int offsetInBytes, int vertexStride)
        {
            if (_buffer == null || _buffer.Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            //Check if array bounds are out of range
            D3D10Helper.CheckArrayBounds(data, startIndex, elementCount);

            VertexDeclaration vertexDecl = base.VertexDeclaration;
            int vertexCount = base.VertexCount;

            int vbSize     = vertexCount * vertexDecl.VertexStride;
            int elemSize   = MemoryHelper.SizeOf <T>();
            int dataSize   = elementCount * elemSize;
            int vertexStep = vertexStride;

            if (vertexStride != 0)
            {
                vertexStep -= elemSize;
                if (vertexStep < 0)
                {
                    throw new ArgumentException("vertexStride", "Vertex stride is too small for requested data size.");
                }
                //If we get this far, we need to make sure the actual bytes we're going to look at matches up,
                //since we can grab specific parts of a vertex and not the whole thing
                if (elementCount > 1)
                {
                    dataSize = ((elementCount - 1) * vertexStep) + dataSize;
                }
            }

            //Prevent overflow out of range errors
            if ((offsetInBytes < 0) || (offsetInBytes > vbSize))
            {
                throw new ArgumentOutOfRangeException("offsetInBytes", "Byte offset is out of range.");
            }

            if ((offsetInBytes + dataSize) > vbSize)
            {
                throw new ArgumentOutOfRangeException("data", "Byte offset and elements to read will cause in buffer overflow.");
            }

            //Create scratch buffer, if it hasn't been created already
            CreateStaging();

            try {
                //If we're reading from the entire VB just copy the whole thing
                if (offsetInBytes == 0 && startIndex == 0 && vertexCount == data.Length)
                {
                    _graphicsDevice.CopyResource(_buffer, _staging);
                }
                else
                {
                    D3D.ResourceRegion region = new D3D.ResourceRegion();
                    region.Left  = offsetInBytes;
                    region.Right = offsetInBytes + dataSize;
                    region.Front = region.Top = 0;
                    region.Back  = region.Bottom = 1;
                    _graphicsDevice.CopySubresourceRegion(_buffer, 0, region, _staging, 0, offsetInBytes, 0, 0);
                }

                using (SDX.DataStream ds = _staging.Map(D3D.MapMode.Read, D3D.MapFlags.None)) {
                    //If the step is zero, that means we're dealing with the entire vertex and not a subset of it
                    if (vertexStep == 0)
                    {
                        ds.Position = offsetInBytes;
                        ds.ReadRange <T>(data, startIndex, elementCount);
                    }
                    else
                    {
                        ds.Position = offsetInBytes;
                        int count = elementCount - 1;
                        int index = startIndex;
                        data[index++] = ds.Read <T>();
                        while (count > 0)
                        {
                            ds.Position += vertexStep;
                            data[index]  = ds.Read <T>();
                            count--;
                            index++;
                        }
                    }
                    _staging.Unmap();
                }
            } catch (Exception e) {
                throw new TeslaException("Error reading from D3D10 Buffer.", e);
            }
        }
        /// <summary>
        /// Convienence method that takes an array of data buffers, each representing a vertex element (in the order
        /// declared by the vertex declaration), and writes all of the data to the vertex buffer. The buffers must match
        /// the vertex declaration as well as the byte sizes of each element and all be of the same length.
        /// </summary>
        /// <param name="data">Array of databuffers representing the vertex data.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the number of buffers do not match the number
        /// of vertex elements, or if the number of vertices in each buffer does not match the vertex count,
        /// or if there is a byte size mismatch of any kind.</exception>
        public override void SetInterleavedData(params DataBuffer[] data)
        {
            if (_buffer == null || _buffer.Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException("data", "Data cannot be null.");
            }

            VertexDeclaration vertexDecl = base.VertexDeclaration;
            int vertexCount = base.VertexCount;

            //Verify if the incoming vertex streams match right with the supplied vertex declaration
            VertexElement[] elems = vertexDecl.VertexElements;
            if (elems.Length != data.Length)
            {
                throw new ArgumentOutOfRangeException("data", "Number of vertex streams do not match up the number of declared vertex elements.");
            }

            int totalSizeInBytes = 0;
            int vertexStride     = 0;

            for (int i = 0; i < data.Length; i++)
            {
                DataBuffer    db           = data[i];
                VertexElement element      = elems[i];
                int           vSizeInBytes = db.ElementSizeInBytes;
                int           vCount       = db.SizeInBytes / vSizeInBytes;

                if (vCount != vertexCount)
                {
                    throw new ArgumentOutOfRangeException("data", "Vertex count mismatch, buffers must be of same length.");
                }
                if (vSizeInBytes != VertexDeclaration.GetVertexElementSize(element.Format))
                {
                    throw new ArgumentOutOfRangeException("data", "Supplied vertex buffer element size mismatch with actual vertex element size.");
                }

                totalSizeInBytes += db.SizeInBytes;
                vertexStride     += vSizeInBytes;
                db.Position       = 0;
            }

            if (totalSizeInBytes != vertexDecl.VertexStride * vertexCount)
            {
                throw new ArgumentOutOfRangeException("data", "Vertex data must match the size of the vertex buffer in bytes!");
            }

            CreateStaging();

            try {
                using (SDX.DataStream interleaved = _staging.Map(D3D.MapMode.Write, D3D.MapFlags.None)) {
                    byte[] vertex = new byte[vertexStride];
                    for (int i = 0; i < vertexCount; i++)
                    {
                        int startIndex = 0;
                        for (int j = 0; j < data.Length; j++)
                        {
                            DataBuffer db          = data[j];
                            int        elementSize = db.ElementSizeInBytes;
                            db.Get(vertex, startIndex, elementSize);
                            startIndex += elementSize;
                        }
                        interleaved.Write(vertex, 0, vertexStride);
                    }
                    _staging.Unmap();
                    //Copy entire resource
                    _graphicsDevice.CopyResource(_staging, _buffer);
                }
            } catch (Exception e) {
                throw new TeslaException("Error writing to D3D10 Buffer.", e);
            }
        }
        /// <summary>
        /// Sets the vertex data from an array source.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array that holds the vertex data</param>
        /// <param name="startIndex">Starting index of the element in the array at which to start copying from</param>
        /// <param name="elementCount">Number of elements to copy from the array</param>
        /// <param name="offsetInBytes">Offset in bytes from the beginning of the vertex buffer to the data.</param>
        /// <param name="vertexStride">Size of an element in bytes.</param>
        /// <param name="writeOptions">Writing options for the vertex buffer. None, discard, or no overwrite.</param>
        /// <exception cref="System.ObjectDisposedException">Thrown if Dispose() has been called.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown if the write options are incompatible with the resource usage of the buffer.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the data's vertex stride is too small, the offset in bytes is out of range,
        /// or the byte offset and number of elements to write will cause overflow.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there was an error writing to the buffer.</exception>
        public override void SetData <T>(T[] data, int startIndex, int elementCount, int offsetInBytes, int vertexStride, DataWriteOptions writeOptions)
        {
            if (_buffer == null || _buffer.Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            //Throw an error if an invalid write options is specified
            if (base.BufferUsage == ResourceUsage.Static && writeOptions != DataWriteOptions.None)
            {
                throw new InvalidOperationException("Can only specify write options other than DataWriteOptions.None for dynamic vertex buffers.");
            }

            //Check if array bounds are out of range
            D3D10Helper.CheckArrayBounds(data, startIndex, elementCount);

            VertexDeclaration vertexDecl = base.VertexDeclaration;
            int vertexCount = base.VertexCount;

            int vbSize     = vertexCount * vertexDecl.VertexStride;
            int elemSize   = MemoryHelper.SizeOf <T>();
            int dataSize   = elementCount * elemSize;
            int vertexStep = vertexStride;

            if (vertexStride != 0)
            {
                vertexStep -= elemSize;
                if (vertexStep < 0)
                {
                    throw new ArgumentOutOfRangeException("vertexStride", "Vertex stride is too small for requested data size.");
                }
                //If we get this far, we need to make sure the actual bytes we're going to look at matches up,
                //since we can grab specific parts of a vertex and not the whole thing
                if (elementCount > 1)
                {
                    dataSize = ((elementCount - 1) * vertexStep) + dataSize;
                }
            }

            //Prevent overflow out of range errors
            if ((offsetInBytes < 0) || (offsetInBytes > vbSize))
            {
                throw new ArgumentOutOfRangeException("offsetInbytes", "Byte offset is out of range.");
            }

            if ((offsetInBytes + dataSize) > vbSize)
            {
                throw new ArgumentOutOfRangeException("data", "Byte offset and elements to write will cause in buffer overflow.");
            }

            //Create scratch buffer, if it hasn't been created already
            bool usesStaging = false;

            if (base.BufferUsage == ResourceUsage.Static || writeOptions == DataWriteOptions.None)
            {
                CreateStaging();
                usesStaging = true;
            }

            try {
                if (usesStaging)
                {
                    //If we're not going to be writing the entire vertex structure, we need to first
                    //copy the contents of the affected vertex data into the staging buffer
                    if (vertexStep != vertexStride)
                    {
                        //If we're going to be working with all the verts, no need to copy a subresource region
                        if (offsetInBytes == 0 && startIndex == 0 && vertexCount == data.Length)
                        {
                            _graphicsDevice.CopyResource(_buffer, _staging);
                        }
                        else
                        {
                            D3D.ResourceRegion region = new D3D.ResourceRegion();
                            region.Left  = offsetInBytes;
                            region.Right = offsetInBytes + dataSize;
                            region.Front = region.Top = 0;
                            region.Back  = region.Bottom = 1;
                            _graphicsDevice.CopySubresourceRegion(_buffer, 0, region, _staging, 0, offsetInBytes, 0, 0);
                        }
                    }

                    using (SDX.DataStream ds = _staging.Map(D3D.MapMode.Read, D3D.MapFlags.None)) {
                        //If the step is zero, that means we're dealing with the entire vertex and not a subset of it
                        if (vertexStep == 0)
                        {
                            ds.Position = offsetInBytes;
                            ds.WriteRange <T>(data, startIndex, elementCount);
                        }
                        else
                        {
                            ds.Position = offsetInBytes;
                            int count = elementCount - 1;
                            int index = startIndex;
                            ds.Write <T>(data[index++]);
                            while (count > 0)
                            {
                                ds.Position += vertexStep;
                                ds.Write <T>(data[index]);
                                count--;
                                index++;
                            }
                        }
                        _staging.Unmap();

                        //If we're writing to the entire VB just copy the whole thing
                        if (offsetInBytes == 0 && startIndex == 0 && dataSize == vbSize)
                        {
                            _graphicsDevice.CopyResource(_staging, _buffer);
                        }
                        else
                        {
                            D3D.ResourceRegion region = new D3D.ResourceRegion();
                            region.Left  = offsetInBytes;
                            region.Right = offsetInBytes + dataSize;
                            region.Front = region.Top = 0;
                            region.Back  = region.Bottom = 1;
                            _graphicsDevice.CopySubresourceRegion(_staging, 0, region, _buffer, 0, offsetInBytes, 0, 0);
                        }
                    }
                    //Dynamic vertex buffers only
                }
                else
                {
                    D3D.MapMode mode = (writeOptions == DataWriteOptions.Discard) ? D3D.MapMode.WriteDiscard : D3D.MapMode.WriteNoOverwrite;
                    using (SDX.DataStream ds = _buffer.Map(mode, D3D.MapFlags.None)) {
                        //If the step is zero, that means we're dealing with the entire vertex and not a subset of it
                        if (vertexStep == 0)
                        {
                            ds.Position = offsetInBytes;
                            ds.WriteRange <T>(data, startIndex, elementCount);
                        }
                        else
                        {
                            ds.Position = offsetInBytes;
                            int count = elementCount - 1;
                            int index = startIndex;
                            ds.Write <T>(data[index++]);
                            while (count > 0)
                            {
                                ds.Position += vertexStep;
                                ds.Write <T>(data[index]);
                                count--;
                                index++;
                            }
                        }
                        _buffer.Unmap();
                    }
                }
            } catch (Exception e) {
                throw new TeslaException("Error reading from D3D10 Buffer.", e);
            }
        }
        /**
         * Render with or without texture
         **/
        protected override void _render()
        {
            if (this._bitmap == null)
            {
                // Render in solid color
                if (_brush == null)
                    _brush = new SolidColorBrush(Device.RenderTarget, Color);

                Device.RenderTarget.FillRectangle(_brush, _rectangle);

                return;
            }

            if (this._d2dBitmap == null)
            {
                // Load the texture
                var bitmapData = this._bitmap.LockBits(
                    new Rectangle(new Point(0, 0), this._bitmap.Size),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format32bppPArgb
                );
                var dataStream = new SlimDX.DataStream(
                    bitmapData.Scan0,
                    bitmapData.Stride * bitmapData.Height,
                    true,
                    false
                );
                var d2dPixelFormat = new SlimDX.Direct2D.PixelFormat(
                    SlimDX.DXGI.Format.B8G8R8A8_UNorm,
                    SlimDX.Direct2D.AlphaMode.Premultiplied
                );
                var d2dBitmapProperties = new SlimDX.Direct2D.BitmapProperties();
                d2dBitmapProperties.PixelFormat = d2dPixelFormat;

                _d2dBitmap = new SlimDX.Direct2D.Bitmap(
                    Device.RenderTarget,
                    new Size(this._bitmap.Width, this._bitmap.Height),
                    dataStream,
                    bitmapData.Stride,
                    d2dBitmapProperties
                );
                this._bitmap.UnlockBits(bitmapData);
            }

            // Render the texture
            Device.RenderTarget.DrawBitmap(_d2dBitmap, _rectangle);
        }
Exemplo n.º 27
0
        public Mesh createMesh(Device dev)
        {
            int numIndices  = 10;
            int numVertices = 5;

            Matrix4x4 Projection = new Matrix4x4(
                1, 0, 0, 0,
                0, 1, 0, 0,
                0, 0, 1, 0,
                p, p, p, 0
                );

            vertex[0] = new Vector4D(0, 0, 0, 1);
            vertex[1] = new Vector4D(-0.559, 0.559, 0.559, -0.25);
            vertex[2] = new Vector4D(0.559, -0.559, 0.559, -0.25);
            vertex[3] = new Vector4D(0.559, 0.559, -0.559, -0.25);
            vertex[4] = new Vector4D(-0.559, -0.559, -0.559, -0.25);

            for (int i = 0; i < numVertices; i++)
            {
                // scale it
                vertex[i] *= radius;

                // project it from 4d to 3d
                vertex[i] = Projection * vertex[i];

                vertex[i] = (new Vector4D(a, b, c, d)) & vertex[i] & (new Vector4D(-a, -b, -c, d));
                //FHost.Log(TLogType.Debug, "vertex " + i + " =" + vertex[i].x + ";" + vertex[i].y + ";" + vertex[i].z + ";" + vertex[i].w);
            }

            // create new Mesh
            Mesh newMesh = new Mesh(dev, numIndices, numVertices,
                                    MeshFlags.Dynamic | MeshFlags.WriteOnly,
                                    VertexFormat.Position);

            // lock buffers
            sVx = newMesh.LockVertexBuffer(LockFlags.Discard);
            sIx = newMesh.LockIndexBuffer(LockFlags.Discard);

            // write buffers
            for (int i = 0; i < numVertices; i++)
            {
                //Vector3 v = VVVV.Shared.VSlimDX.VSlimDXUtils.Vector3DToSlimDXVector3(vertex[i].xyz);
                //sVx.Write(v);

                sVx.Write((float)vertex[i].x);
                sVx.Write((float)vertex[i].y);
                sVx.Write((float)vertex[i].z);
            }

            sIx.Write <short>(0); sIx.Write <short>(1); sIx.Write <short>(2);
            sIx.Write <short>(0); sIx.Write <short>(1); sIx.Write <short>(3);
            sIx.Write <short>(0); sIx.Write <short>(1); sIx.Write <short>(4);
            sIx.Write <short>(0); sIx.Write <short>(2); sIx.Write <short>(3);
            sIx.Write <short>(0); sIx.Write <short>(2); sIx.Write <short>(4);
            sIx.Write <short>(0); sIx.Write <short>(3); sIx.Write <short>(4);
            sIx.Write <short>(1); sIx.Write <short>(2); sIx.Write <short>(3);
            sIx.Write <short>(1); sIx.Write <short>(2); sIx.Write <short>(4);
            sIx.Write <short>(1); sIx.Write <short>(3); sIx.Write <short>(4);
            sIx.Write <short>(2); sIx.Write <short>(3); sIx.Write <short>(4);

            // unlock buffers
            newMesh.UnlockIndexBuffer();
            newMesh.UnlockVertexBuffer();

            return(newMesh);
        }
Exemplo n.º 28
0
        public void UpdateResource(IPluginOut ForPin, Device OnDevice)
        {
            //Called by the PluginHost every frame for every device. Therefore a plugin should only do
            //device specific operations here and still keep node specific calculations in the Evaluate call.

            try
            {
                Mesh mrty = FDeviceMeshes[OnDevice];
                if (update)
                    RemoveResource(OnDevice);
            }
            catch
            {
                update = true;
            }

            if (update)
            {
               // Device dev = Device.FromPointer(new IntPtr(OnDevice));
                try
                {
                    Mesh nuMesh = new Mesh(OnDevice, numIndices / 3, numVertsOut, MeshFlags.Dynamic | MeshFlags.WriteOnly, VertexFormat.PositionNormal);

                    sVx = nuMesh.LockVertexBuffer(LockFlags.Discard);
                    sIx = nuMesh.LockIndexBuffer(LockFlags.Discard);

                    unsafe
                    {
                        fixed (sVxBuffer* FixTemp = &VxBuffer[0])
                        {
                            IntPtr VxPointer = new IntPtr(FixTemp);
                            sVx.WriteRange(VxPointer, sizeof(sVxBuffer) * numVertsOut);
                        }
                        fixed (short* FixTemp = &IxBuffer[0])
                        {
                            IntPtr IxPointer = new IntPtr(FixTemp);
                            sIx.WriteRange(IxPointer, sizeof(short) * numIndices);
                        }
                    }

                    nuMesh.UnlockVertexBuffer();
                    nuMesh.UnlockIndexBuffer();

                    FDeviceMeshes.Add(OnDevice, nuMesh);
                }
                finally
                {
                    //dev.Dispose();
                    update = false;
                }
            }
        }
        /// <summary>
        /// Sets the data from the array to the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array.</typeparam>
        /// <param name="data">Array of data</param>
        /// <param name="mipLevel">Mip map level to access</param>
        /// <param name="left">The left-most position in the 1D texture at which to access.</param>
        /// <param name="right">The right-most position in the 1D texture at which to acess.</param>
        /// <param name="startIndex">Starting index in the array to start reading from.</param>
        /// <param name="elementCount">Number of elements to write.</param>
        public override void SetData <T>(T[] data, int mipLevel, int left, int right, int startIndex, int elementCount)
        {
            if (_texture1D.Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (mipLevel < 0 || mipLevel >= _mipCount)
            {
                throw new ArgumentOutOfRangeException("mipLevel", String.Format("Mip level is out of range. Must be between 0 and {0}.", _mipCount.ToString()));
            }

            //Throws null or out of range exception
            D3D10Helper.CheckArrayBounds(data, startIndex, elementCount);
            SurfaceFormat format = base.Format;

            int formatSize = D3D10Helper.FormatSize(format);
            int elemSize   = MemoryHelper.SizeOf <T>();

            CheckSizes(formatSize, elemSize);

            //Calc subresource dimensions
            int width = (int)MathHelper.Max(1, base.Width >> mipLevel);

            //Check the line
            CheckLine(ref width, left, right);

            CheckTotalSize(format, ref formatSize, ref width, elemSize, elementCount);

            //Create staging
            if (_usage == D3D.ResourceUsage.Default)
            {
                CreateStaging();
            }

            try {
                if (_usage == D3D.ResourceUsage.Default)
                {
                    SDX.DataStream ds = _staging.Map(mipLevel, D3D.MapMode.Write, D3D.MapFlags.None);

                    //Compute the actual number of elements based on the format size and the element size we're copying the bytes into
                    int actWidth = (int)MathHelper.Floor(width * (formatSize / elemSize));

                    //Read data
                    ds.Position = left * formatSize;
                    ds.WriteRange <T>(data, startIndex, actWidth);
                    _staging.Unmap(mipLevel);

                    //Copy from the staging to texture
                    if (format == SurfaceFormat.DXT1 || format == SurfaceFormat.DXT3 || format == SurfaceFormat.DXT5)
                    {
                        _graphicsDevice.CopyResource(_staging, _texture1D);
                    }
                    else
                    {
                        D3D.ResourceRegion region = new D3D.ResourceRegion();
                        region.Left   = left;
                        region.Right  = right;
                        region.Top    = 0;
                        region.Bottom = 1;
                        region.Front  = 0;
                        region.Back   = 1;
                        _graphicsDevice.CopySubresourceRegion(_staging, mipLevel, region, _texture1D, mipLevel, left, 0, 0);
                    }
                }
                else
                {
                    SDX.DataStream ds = _texture1D.Map(mipLevel, D3D.MapMode.WriteDiscard, D3D.MapFlags.None);

                    //Compute the actual number of elements based on the format size and the element size we're copying the bytes into
                    int actWidth = (int)MathHelper.Floor(width * (formatSize / elemSize));

                    //Read data
                    ds.Position = left * formatSize;
                    ds.WriteRange <T>(data, startIndex, actWidth);
                    _texture1D.Unmap(mipLevel);
                }
            } catch (Exception e) {
                throw new TeslaException("Error writing to D3D10 Texture1D.", e);
            }
        }
Exemplo n.º 30
0
        public static DX11VertexGeometry Text3d(DX11RenderContext device, string text, string fontName, float fontSize, float extrude, TextAlignment textAlignment, ParagraphAlignment paragraphAlignment)
        {
            //Dictionary<DX11RenderContext, DX11VertexGeometry> deviceDict = null;
            //if (TextGeometryCache.TryGetValue(text, out deviceDict))
            //{
            //    DX11VertexGeometry geom;
            //    if(deviceDict.TryGetValue(device, out geom))
            //    {
            //        return geom;
            //    }
            //}

            if (d2dFactory == null)
            {
                d2dFactory = new D2DFactory();
                dwFactory  = new DWriteFactory(SharpDX.DirectWrite.FactoryType.Shared);
            }

            TextFormat fmt = new TextFormat(dwFactory, fontName, fontSize);

            TextLayout tl = new TextLayout(dwFactory, text, fmt, 0.0f, .0f);

            tl.WordWrapping       = WordWrapping.NoWrap;
            tl.TextAlignment      = (SharpDX.DirectWrite.TextAlignment)textAlignment;
            tl.ParagraphAlignment = (SharpDX.DirectWrite.ParagraphAlignment)paragraphAlignment;

            OutlineRenderer renderer = new OutlineRenderer(d2dFactory);
            Extruder        ex       = new Extruder(d2dFactory);

            tl.Draw(renderer, 0.0f, 0.0f);

            var geo    = renderer.GetGeometry();
            var result = ex.GetVertices(geo, extrude).ToArray();

            renderer.Dispose();
            geo.Dispose();
            fmt.Dispose();
            tl.Dispose();

            Vector3 min = new Vector3(float.MaxValue);
            Vector3 max = new Vector3(float.MinValue);

            foreach (var pn in result)
            {
                min.X = pn.Position.X < min.X ? pn.Position.X : min.X;
                min.Y = pn.Position.Y < min.Y ? pn.Position.Y : min.Y;
                min.Z = pn.Position.Z < min.Z ? pn.Position.Z : min.Z;

                max.X = pn.Position.X > max.X ? pn.Position.X : max.X;
                max.Y = pn.Position.Y > max.Y ? pn.Position.Y : max.Y;
                max.Z = pn.Position.Z > max.Z ? pn.Position.Z : max.Z;
            }

            SlimDX.DataStream ds = new SlimDX.DataStream(result.Length * Pos3Norm3VertexSDX.VertexSize, true, true);
            ds.Position = 0;

            ds.WriteRange(result);

            ds.Position = 0;

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

            ds.Dispose();

            DX11VertexGeometry vg = new DX11VertexGeometry(device);

            vg.InputLayout    = Pos3Norm3VertexSDX.Layout;
            vg.Topology       = SlimDX.Direct3D11.PrimitiveTopology.TriangleList;
            vg.VertexBuffer   = vbuffer;
            vg.VertexSize     = Pos3Norm3VertexSDX.VertexSize;
            vg.VerticesCount  = result.Length;
            vg.HasBoundingBox = true;
            vg.BoundingBox    = new SlimDX.BoundingBox(new SlimDX.Vector3(min.X, min.Y, min.Z), new SlimDX.Vector3(max.X, max.Y, max.Z));


            //if(deviceDict != null)
            //{
            //    deviceDict[device] = vg;
            //}
            //else
            //{
            //    deviceDict = new Dictionary<DX11RenderContext, DX11VertexGeometry>();
            //    deviceDict[device] = vg;
            //    TextGeometryCache[text] = deviceDict;
            //}

            return(vg);
        }
Exemplo n.º 31
0
        public Physics(VehicleDemo game)
        {
            CollisionShape groundShape = new BoxShape(50, 3, 50);

            CollisionShapes.Add(groundShape);

            CollisionConf = new DefaultCollisionConfiguration();
            Dispatcher    = new CollisionDispatcher(CollisionConf);
            Solver        = new SequentialImpulseConstraintSolver();

            Vector3 worldMin = new Vector3(-10000, -10000, -10000);
            Vector3 worldMax = new Vector3(10000, 10000, 10000);

            Broadphase = new AxisSweep3(worldMin, worldMax);
            //Broadphase = new DbvtBroadphase();

            World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, Solver, CollisionConf);

            int    i;
            Matrix tr;
            Matrix vehicleTr;

            if (UseTrimeshGround)
            {
                const float scale = 20.0f;

                //create a triangle-mesh ground
                int vertStride  = Vector3.SizeInBytes;
                int indexStride = 3 * sizeof(int);

                const int NUM_VERTS_X = 20;
                const int NUM_VERTS_Y = 20;
                const int totalVerts  = NUM_VERTS_X * NUM_VERTS_Y;

                const int totalTriangles = 2 * (NUM_VERTS_X - 1) * (NUM_VERTS_Y - 1);

                TriangleIndexVertexArray vertexArray = new TriangleIndexVertexArray();
                IndexedMesh mesh = new IndexedMesh();
                mesh.Allocate(totalVerts, vertStride, totalTriangles, indexStride, PhyScalarType.Int32, PhyScalarType.Single);

                BulletSharp.DataStream data = mesh.LockVerts();
                for (i = 0; i < NUM_VERTS_X; i++)
                {
                    for (int j = 0; j < NUM_VERTS_Y; j++)
                    {
                        float wl     = .2f;
                        float height = 20.0f * (float)(Math.Sin(i * wl) * Math.Cos(j * wl));

                        data.Write((i - NUM_VERTS_X * 0.5f) * scale);
                        data.Write(height);
                        data.Write((j - NUM_VERTS_Y * 0.5f) * scale);
                    }
                }

                int      index = 0;
                IntArray idata = mesh.TriangleIndices;
                for (i = 0; i < NUM_VERTS_X - 1; i++)
                {
                    for (int j = 0; j < NUM_VERTS_Y - 1; j++)
                    {
                        idata[index++] = j * NUM_VERTS_X + i;
                        idata[index++] = j * NUM_VERTS_X + i + 1;
                        idata[index++] = (j + 1) * NUM_VERTS_X + i + 1;

                        idata[index++] = j * NUM_VERTS_X + i;
                        idata[index++] = (j + 1) * NUM_VERTS_X + i + 1;
                        idata[index++] = (j + 1) * NUM_VERTS_X + i;
                    }
                }

                vertexArray.AddIndexedMesh(mesh);
                groundShape = new BvhTriangleMeshShape(vertexArray, true);

                tr        = Matrix.Identity;
                vehicleTr = Matrix.Translation(0, -2, 0);
            }
            else
            {
                // Use HeightfieldTerrainShape

                int width = 40, length = 40;
                //int width = 128, length = 128; // Debugging is too slow for this
                float   maxHeight   = 10.0f;
                float   heightScale = maxHeight / 256.0f;
                Vector3 scale       = new Vector3(20.0f, maxHeight, 20.0f);

                //PhyScalarType scalarType = PhyScalarType.PhyUChar;
                //FileStream file = new FileStream(heightfieldFile, FileMode.Open, FileAccess.Read);

                // Use float data
                PhyScalarType scalarType = PhyScalarType.Single;
                byte[]        terr       = new byte[width * length * 4];
                MemoryStream  file       = new MemoryStream(terr);
                BinaryWriter  writer     = new BinaryWriter(file);
                for (i = 0; i < width; i++)
                {
                    for (int j = 0; j < length; j++)
                    {
                        writer.Write((float)((maxHeight / 2) + 4 * Math.Sin(j * 0.5f) * Math.Cos(i)));
                    }
                }
                writer.Flush();
                file.Position = 0;

                HeightfieldTerrainShape heightterrainShape = new HeightfieldTerrainShape(width, length,
                                                                                         file, heightScale, 0, maxHeight, upIndex, scalarType, false);
                heightterrainShape.SetUseDiamondSubdivision(true);

                groundShape = heightterrainShape;
                groundShape.LocalScaling = new Vector3(scale.X, 1, scale.Z);

                tr        = Matrix.Translation(new Vector3(-scale.X / 2, scale.Y / 2, -scale.Z / 2));
                vehicleTr = Matrix.Translation(new Vector3(20, 3, -3));


                // Create graphics object

                file.Position = 0;
                BinaryReader reader = new BinaryReader(file);

                int totalTriangles = (width - 1) * (length - 1) * 2;
                int totalVerts     = width * length;

                game.groundMesh = new Mesh(game.Device, totalTriangles, totalVerts,
                                           MeshFlags.SystemMemory | MeshFlags.Use32Bit, VertexFormat.Position | VertexFormat.Normal);
                SlimDX.DataStream data = game.groundMesh.LockVertexBuffer(LockFlags.None);
                for (i = 0; i < width; i++)
                {
                    for (int j = 0; j < length; j++)
                    {
                        float height;
                        if (scalarType == PhyScalarType.Single)
                        {
                            // heightScale isn't applied internally for float data
                            height = reader.ReadSingle();
                        }
                        else if (scalarType == PhyScalarType.Byte)
                        {
                            height = file.ReadByte() * heightScale;
                        }
                        else
                        {
                            height = 0.0f;
                        }

                        data.Write((j - length * 0.5f) * scale.X);
                        data.Write(height);
                        data.Write((i - width * 0.5f) * scale.Z);

                        // Normals will be calculated later
                        data.Position += 12;
                    }
                }
                game.groundMesh.UnlockVertexBuffer();
                file.Close();

                data = game.groundMesh.LockIndexBuffer(LockFlags.None);
                for (i = 0; i < width - 1; i++)
                {
                    for (int j = 0; j < length - 1; j++)
                    {
                        // Using diamond subdivision
                        if ((j + i) % 2 == 0)
                        {
                            data.Write(j * width + i);
                            data.Write((j + 1) * width + i + 1);
                            data.Write(j * width + i + 1);

                            data.Write(j * width + i);
                            data.Write((j + 1) * width + i);
                            data.Write((j + 1) * width + i + 1);
                        }
                        else
                        {
                            data.Write(j * width + i);
                            data.Write((j + 1) * width + i);
                            data.Write(j * width + i + 1);

                            data.Write(j * width + i + 1);
                            data.Write((j + 1) * width + i);
                            data.Write((j + 1) * width + i + 1);
                        }

                        /*
                         * // Not using diamond subdivision
                         * data.Write(j * width + i);
                         * data.Write((j + 1) * width + i);
                         * data.Write(j * width + i + 1);
                         *
                         * data.Write(j * width + i + 1);
                         * data.Write((j + 1) * width + i);
                         * data.Write((j + 1) * width + i + 1);
                         */
                    }
                }
                game.groundMesh.UnlockIndexBuffer();

                game.groundMesh.ComputeNormals();
            }

            CollisionShapes.Add(groundShape);


            //create ground object
            RigidBody ground = LocalCreateRigidBody(0, tr, groundShape);

            ground.UserObject = "Ground";


            CollisionShape chassisShape = new BoxShape(1.0f, 0.5f, 2.0f);

            CollisionShapes.Add(chassisShape);

            CompoundShape compound = new CompoundShape();

            CollisionShapes.Add(compound);

            //localTrans effectively shifts the center of mass with respect to the chassis
            Matrix localTrans = Matrix.Translation(Vector3.UnitY);

            compound.AddChildShape(localTrans, chassisShape);
            RigidBody carChassis = LocalCreateRigidBody(800, Matrix.Identity, compound);

            carChassis.UserObject = "Chassis";
            //carChassis.SetDamping(0.2f, 0.2f);

            //CylinderShapeX wheelShape = new CylinderShapeX(wheelWidth, wheelRadius, wheelRadius);


            // clientResetScene();

            // create vehicle
            RaycastVehicle.VehicleTuning tuning           = new RaycastVehicle.VehicleTuning();
            IVehicleRaycaster            vehicleRayCaster = new DefaultVehicleRaycaster(World);

            vehicle = new RaycastVehicle(tuning, carChassis, vehicleRayCaster);

            carChassis.ActivationState = ActivationState.DisableDeactivation;
            World.AddAction(vehicle);


            float connectionHeight = 1.2f;
            bool  isFrontWheel     = true;

            // choose coordinate system
            vehicle.SetCoordinateSystem(rightIndex, upIndex, forwardIndex);

            Vector3   connectionPointCS0 = new Vector3(CUBE_HALF_EXTENTS - (0.3f * wheelWidth), connectionHeight, 2 * CUBE_HALF_EXTENTS - wheelRadius);
            WheelInfo a = vehicle.AddWheel(connectionPointCS0, wheelDirectionCS0, wheelAxleCS, suspensionRestLength, wheelRadius, tuning, isFrontWheel);

            connectionPointCS0 = new Vector3(-CUBE_HALF_EXTENTS + (0.3f * wheelWidth), connectionHeight, 2 * CUBE_HALF_EXTENTS - wheelRadius);
            vehicle.AddWheel(connectionPointCS0, wheelDirectionCS0, wheelAxleCS, suspensionRestLength, wheelRadius, tuning, isFrontWheel);

            isFrontWheel       = false;
            connectionPointCS0 = new Vector3(-CUBE_HALF_EXTENTS + (0.3f * wheelWidth), connectionHeight, -2 * CUBE_HALF_EXTENTS + wheelRadius);
            vehicle.AddWheel(connectionPointCS0, wheelDirectionCS0, wheelAxleCS, suspensionRestLength, wheelRadius, tuning, isFrontWheel);

            connectionPointCS0 = new Vector3(CUBE_HALF_EXTENTS - (0.3f * wheelWidth), connectionHeight, -2 * CUBE_HALF_EXTENTS + wheelRadius);
            vehicle.AddWheel(connectionPointCS0, wheelDirectionCS0, wheelAxleCS, suspensionRestLength, wheelRadius, tuning, isFrontWheel);


            for (i = 0; i < vehicle.NumWheels; i++)
            {
                WheelInfo wheel = vehicle.GetWheelInfo(i);
                wheel.SuspensionStiffness      = suspensionStiffness;
                wheel.WheelsDampingRelaxation  = suspensionDamping;
                wheel.WheelsDampingCompression = suspensionCompression;
                wheel.FrictionSlip             = wheelFriction;
                wheel.RollInfluence            = rollInfluence;
            }

            vehicle.RigidBody.WorldTransform = vehicleTr;
        }
Exemplo n.º 32
0
        /// <summary>
        /// Writes data from the array to the index buffer.
        /// </summary>
        /// <typeparam name="T">The type of data in the index buffer - int or short.</typeparam>
        /// <param name="data">Array to copy the data from</param>
        /// <param name="startIndex">Starting index in the array at which to start copying from</param>
        /// <param name="elementCount">Number of indices to write</param>
        /// <param name="offsetInBytes">Offset from the start of the index buffer at which to start writing at</param>
        /// <param name="writeOptions">Write options, used only if this is a dynamic buffer. None, discard, no overwrite</param>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public override void SetData <T>(T[] data, int startIndex, int elementCount, int offsetInBytes, DataWriteOptions writeOptions)
        {
            if (_buffer == null || _buffer.Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            //Throws null or out of range exception
            D3D10Helper.CheckArrayBounds(data, startIndex, elementCount);

            int numBytes = MemoryHelper.SizeOf <T>();

            int ibSize   = base.IndexCount * ((base.IndexFormat == IndexFormat.SixteenBits) ? 2 : 4);
            int dataSize = elementCount * numBytes;

            if (offsetInBytes < 0 || offsetInBytes > ibSize)
            {
                throw new ArgumentOutOfRangeException("offsetInBytes", "Byte offset is out of range.");
            }

            if ((offsetInBytes + dataSize) > ibSize)
            {
                throw new ArgumentOutOfRangeException("data", "Byte offset and the number of elements to write will cause a buffer overflow.");
            }

            bool usesStaging = false;

            if (base.BufferUsage == ResourceUsage.Static || writeOptions == DataWriteOptions.None)
            {
                CreateStaging();
                usesStaging = true;
            }

            try {
                if (usesStaging)
                {
                    using (SDX.DataStream ds = _staging.Map(D3D.MapMode.Write, D3D.MapFlags.None)) {
                        ds.Position = offsetInBytes;
                        ds.WriteRange <T>(data, startIndex, elementCount);
                        _staging.Unmap();

                        //If we're writing to the entire IB just copy the whole thing
                        if (offsetInBytes == 0 && startIndex == 0 && dataSize == ibSize)
                        {
                            _graphicsDevice.CopyResource(_staging, _buffer);
                        }
                        else
                        {
                            D3D.ResourceRegion region = new D3D.ResourceRegion();
                            region.Left  = offsetInBytes;
                            region.Right = offsetInBytes + dataSize;
                            region.Front = region.Top = 0;
                            region.Back  = region.Bottom = 1;
                            _graphicsDevice.CopySubresourceRegion(_staging, 0, region, _buffer, 0, offsetInBytes, 0, 0);
                        }
                    }
                }
                else
                {
                    D3D.MapMode mode = (writeOptions == DataWriteOptions.Discard) ? D3D.MapMode.WriteDiscard : D3D.MapMode.WriteNoOverwrite;
                    using (SDX.DataStream ds = _buffer.Map(mode, D3D.MapFlags.None)) {
                        ds.Position = offsetInBytes;
                        ds.WriteRange <T>(data, startIndex, elementCount);
                        _buffer.Unmap();
                    }
                }
            } catch (Exception e) {
                throw new TeslaException("Error writing to D3D10 Buffer.", e);
            }
        }