public unsafe bool Init(long size, VertexBufferLayout layout)
 {
     using (var layoutNative = new VertexBufferLayout_NativeInterop(ref layout))
     {
         return(Orbital_Video_D3D12_VertexBuffer_Init(handle, null, (ulong)size, sizeof(byte), &layoutNative) != 0);
     }
 }
Example #2
0
        public VertexBuffer(int numVertices, VertexBufferLayout layout)
        {
            Layout     = layout;
            _handle    = GL.GenBuffer();
            VertexSize = Marshal.SizeOf(typeof(T));

            Bind();
            GL.BufferData(BufferTarget.ArrayBuffer, numVertices * VertexSize, IntPtr.Zero, BufferUsageHint.DynamicDraw);
        }
Example #3
0
        public VertexBuffer(IEnumerable <T> vertices, VertexBufferLayout layout)
        {
            Layout     = layout;
            VertexSize = Marshal.SizeOf(typeof(T));
            _handle    = GL.GenBuffer();

            T[] data = vertices.ToArray();
            Bind();
            GL.BufferData(BufferTarget.ArrayBuffer, data.Length * VertexSize, data, BufferUsageHint.StaticDraw);
        }
Example #4
0
        public override VertexBufferBase CreateVertexBuffer <T>(T[] vertices, VertexBufferLayout layout, VertexBufferMode mode)
        {
            var abstraction = new VertexBuffer(this, mode);

            if (!abstraction.Init <T>(vertices, layout))
            {
                abstraction.Dispose();
                throw new Exception("Failed to create VertexBuffer");
            }
            return(abstraction);
        }
 public unsafe bool Init <T>(T[] vertices, VertexBufferLayout layout) where T : unmanaged
 {
     using (var layoutNative = new VertexBufferLayout_NativeInterop(ref layout))
     {
         vertexCount = vertices.Length;
         vertexSize  = Marshal.SizeOf <T>();
         fixed(T *verticesPtr = vertices)
         {
             return(Orbital_Video_D3D12_VertexBuffer_Init(handle, verticesPtr, (ulong)vertices.LongLength, (uint)vertexSize, &layoutNative) != 0);
         }
     }
 }
        public unsafe bool Init <T>(T[] vertices, VertexBufferLayout layout) where T : struct
        {
            var layoutNative = new VertexBufferLayout_NativeInterop(ref layout);

            vertexCount = vertices.Length;
            vertexSize  = Marshal.SizeOf <T>();
            byte[] verticesDataCopy = new byte[vertexSize * vertices.Length];
            var    gcHandle         = GCHandle.Alloc(vertices, GCHandleType.Pinned);

            Marshal.Copy(gcHandle.AddrOfPinnedObject(), verticesDataCopy, 0, verticesDataCopy.Length);
            gcHandle.Free();
            fixed(byte *verticesPtr = verticesDataCopy)
            {
                return(Orbital_Video_D3D12_VertexBuffer_Init(handle, verticesPtr, (ulong)vertices.LongLength, (uint)vertexSize, &layoutNative) != 0);
            }
        }
Example #7
0
    public void AddBuffer <T>(VertexBuffer <T> vb, VertexBufferLayout layout) where T : struct
    {
        Bind();
        vb.Bind();

        List <VertexBufferElement> elements = layout.GetElements();
        int offest = 0;

        for (int i = 0; i < elements.Count; i++)
        {
            var element = elements[i];
            GL.EnableVertexAttribArray(i);
            GL.VertexAttribPointer(i, element.count, element.type, element.normalized, layout.Stride, 0);

            offest += element.count * VertexBufferElement.SizeOf(element.type);
        }
    }
Example #8
0
        private EffectTechnique GetTechniqueFromVertexBuffer <T>(Buffer <T> vertexBuffer) where T : struct
        {
            EffectTechnique    technique    = null;
            VertexInputLayout  inputLayout  = VertexInputLayout.FromBuffer(0, vertexBuffer);
            VertexBufferLayout bufferLayout = inputLayout.BufferLayouts.First();

            bool pos = false, tex = false, col = false;
            var  semantics = bufferLayout.VertexElements.Select(ve => ve.SemanticName.ToString()).ToArray();

            if (semantics.Contains("POSITION"))
            {
                pos = true;
            }

            if (semantics.Contains("TEXCOORD"))
            {
                tex = true;
            }

            if (semantics.Contains("COLOR"))
            {
                col = true;
            }

            if (pos && tex)
            {
                technique = gbufferEffect.Techniques["PositionTexture"];
            }

            if (pos && col)
            {
                technique = gbufferEffect.Techniques["PositionColor"];
            }

            if (pos)
            {
                technique = gbufferEffect.Techniques["Position"];
            }

            if (technique == null)
            {
                throw new NotSupportedException();
            }

            return(technique);
        }
        private void Init(GraphicsDevice graphicsDevice)
        {
            _screenTriangle = SharpDX.Toolkit.Graphics.Buffer.Vertex.New(graphicsDevice, new[] {
                new Vector2(-1.0f, -1.0f),
                new Vector2(3.0f, -1.0f),
                new Vector2(-1.0f, 3.0f)
            }, SharpDX.Direct3D11.ResourceUsage.Immutable);

            _vertexInputLayout = VertexInputLayout.New(
                VertexBufferLayout.New(0, new VertexElement[] { new VertexElement("POSITION", 0, SharpDX.DXGI.Format.R32G32_Float, 0) }, 0));

            var rasterizerStateDesc = SharpDX.Direct3D11.RasterizerStateDescription.Default();

            rasterizerStateDesc.CullMode = SharpDX.Direct3D11.CullMode.None;
            _noneCullingState            = RasterizerState.New(graphicsDevice, "CullModeNone", rasterizerStateDesc);

            initalised = true;
        }
Example #10
0
        public VertexBufferLayout_NativeInterop(ref VertexBufferLayout layout)
        {
            // init defaults
            elementCount = 0;
            elements     = null;

            // init elements
            if (layout.elements != null)
            {
                elementCount = layout.elements.Length;
                elements     = (VertexBufferLayoutElement_NativeInterop *)Marshal.AllocHGlobal(Marshal.SizeOf <VertexBufferLayoutElement_NativeInterop>() * elementCount);
                for (int i = 0; i != elementCount; ++i)
                {
                    elements[i].type        = layout.elements[i].type;
                    elements[i].usage       = layout.elements[i].usage;
                    elements[i].streamIndex = layout.elements[i].streamIndex;
                    elements[i].usageIndex  = layout.elements[i].usageIndex;
                    elements[i].byteOffset  = layout.elements[i].byteOffset;
                }
            }
        }
Example #11
0
        public VertexArray AddVertexBuffer <T>(VertexBuffer <T> vertexBuffer) where T : struct
        {
            Bind();
            vertexBuffer.Bind();

            VertexBufferLayout layout = vertexBuffer.Layout;

            foreach (KeyValuePair <string, IVertexBufferElement> element in layout)
            {
                GL.EnableVertexAttribArray(_attributeIndex);
                GL.VertexAttribPointer(
                    _attributeIndex,
                    element.Value.Dimensions,
                    element.Value.Type,
                    element.Value.Normalized,
                    vertexBuffer.VertexSize,
                    element.Value.Offset
                    );
                _attributeIndex++;
            }

            return(this);
        }
Example #12
0
    protected override void OnLoad(EventArgs e)
    {
        vertex = new float[8] {
            -0.5f, -0.5f,
            0.5f, -0.5f,
            0.5f, 0.5f,
            -0.5f, 0.5f
        };

        index = new uint[6]
        {
            0, 1, 2,
            2, 3, 0
        };

        vbo = new VertexBuffer <float>(vertex, vertex.Length * sizeof(float));

        vao = new VertexArray();

        VertexBufferLayout layout = new VertexBufferLayout();

        layout.Push(2, VertexAttribPointerType.Float);

        vao.AddBuffer(vbo, layout);

        ibo = new IndexBuffer(index, index.Length);

        shader = new Shader("Standard");
        shader.Bind();

        shader.Uniform4("u_Color", Color4.Teal);

        renderer = new Renderer();

        base.OnLoad(e);
    }
Example #13
0
        public void Init(string platformPath, string folder64Bit, string folder32Bit)
        {
            // pre-load native libs
            string libFolderBit;

            if (IntPtr.Size == 8)
            {
                libFolderBit = folder64Bit;
            }
            else if (IntPtr.Size == 4)
            {
                libFolderBit = folder32Bit;
            }
            else
            {
                throw new NotSupportedException("Unsupported bit size: " + IntPtr.Size.ToString());
            }

                        #if RELEASE
            const string config = "Release";
                        #else
            const string config = "Debug";
                        #endif

            // load api abstraction (api-instance and hardware-device)
            var abstractionDesc = new AbstractionDesc(true);
            abstractionDesc.supportedAPIs = new AbstractionAPI[] { AbstractionAPI.D3D12 };

            abstractionDesc.deviceDescD3D12.window = window;
            abstractionDesc.nativeLibPathD3D12     = Path.Combine(platformPath, @"Shared\Orbital.Video.D3D12.Native\bin", libFolderBit, config);

            abstractionDesc.deviceDescVulkan.window = window;
            abstractionDesc.nativeLibPathVulkan     = Path.Combine(platformPath, @"Shared\Orbital.Video.Vulkan.Native\bin", libFolderBit, config);

            if (!Abstraction.InitFirstAvaliable(abstractionDesc, out instance, out device))
            {
                throw new Exception("Failed to init abstraction");
            }

            // create command list
            commandList = device.CreateCommandList();

            // create render pass
            var renderPassDesc = new RenderPassDesc()
            {
                clearColor      = true,
                clearColorValue = new Vec4(0, .2f, .4f, 1)
            };
            renderPass = device.CreateRenderPass(renderPassDesc);

            // create texture
            int textureWidth = 256, textureHeight = 256;
            var textureData = new byte[textureWidth * textureHeight * 4];
            for (int y = 0; y != textureHeight; ++y)
            {
                for (int x = 0; x != textureWidth; ++x)
                {
                    int i = (x * 4) + (y * textureWidth * 4);
                    if (x % 16 <= 7 && y % 16 <= 7)
                    {
                        textureData[i + 0] = 0;
                        textureData[i + 1] = 0;
                        textureData[i + 2] = 0;
                        textureData[i + 3] = 0;
                    }
                    else
                    {
                        textureData[i + 0] = 255;
                        textureData[i + 1] = 255;
                        textureData[i + 2] = 255;
                        textureData[i + 3] = 255;
                    }
                }
            }
            texture = device.CreateTexture2D(TextureFormat.B8G8R8A8, textureWidth, textureHeight, textureData, TextureMode.GPUOptimized);

            // create texture 2
            textureWidth  = 100;
            textureHeight = 100;
            textureData   = new byte[textureWidth * textureHeight * 4];
            for (int y = 0; y != textureHeight; ++y)
            {
                for (int x = 0; x != textureWidth; ++x)
                {
                    int i = (x * 4) + (y * textureWidth * 4);
                    if (x % 16 <= 7 && y % 16 <= 7)
                    {
                        textureData[i + 0] = 0;
                        textureData[i + 1] = 0;
                        textureData[i + 2] = 0;
                        textureData[i + 3] = 0;
                    }
                    else
                    {
                        textureData[i + 0] = 255;
                        textureData[i + 1] = 255;
                        textureData[i + 2] = 255;
                        textureData[i + 3] = 255;
                    }
                }
            }
            texture2 = device.CreateTexture2D(TextureFormat.B8G8R8A8, textureWidth, textureHeight, textureData, TextureMode.GPUOptimized);

            // create constant buffer
            constantBufferObject = new ConstantBufferObject()
            {
                offset    = .5f,
                constrast = .5f
            };
            constantBuffer = device.CreateConstantBuffer <ConstantBufferObject>(constantBufferObject, ConstantBufferMode.Write);

            // load shaders
            // TODO: load CS2X compiled ShaderEffect

            /*using (var stream = new FileStream("Shader.se", FileMode.Open, FileAccess.Read, FileShare.Read))
             * {
             *      shaderEffect = device.CreateShaderEffect(stream, ShaderEffectSamplerAnisotropy.Default);
             * }*/

            using (var vsStream = new FileStream("Shaders\\Shader_D3D12.vs", FileMode.Open, FileAccess.Read, FileShare.Read))
                using (var psStream = new FileStream("Shaders\\Shader_D3D12.ps", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var vs = new Video.D3D12.Shader((Video.D3D12.Device)device, ShaderType.VS);
                    var ps = new Video.D3D12.Shader((Video.D3D12.Device)device, ShaderType.PS);
                    if (!vs.Init(vsStream))
                    {
                        throw new Exception("Failed to init VS shader");
                    }
                    if (!ps.Init(psStream))
                    {
                        throw new Exception("Failed to init PS shader");
                    }
                    var desc = new ShaderEffectDesc();
                    desc.constantBuffers    = new ShaderEffectConstantBuffer[1];
                    desc.constantBuffers[0] = new ShaderEffectConstantBuffer()
                    {
                        registerIndex = 0,
                        usage         = ShaderEffectResourceUsage.VS
                    };
                    desc.textures    = new ShaderEffectTexture[2];
                    desc.textures[0] = new ShaderEffectTexture()
                    {
                        registerIndex = 0,
                        usage         = ShaderEffectResourceUsage.PS
                    };
                    desc.textures[1] = new ShaderEffectTexture()
                    {
                        registerIndex = 1,
                        usage         = ShaderEffectResourceUsage.PS
                    };
                    desc.samplers    = new ShaderEffectSampler[1];
                    desc.samplers[0] = new ShaderEffectSampler()
                    {
                        registerIndex = 0,
                        filter        = ShaderEffectSamplerFilter.Default,
                        anisotropy    = ShaderEffectSamplerAnisotropy.Default,
                        addressU      = ShaderEffectSamplerAddress.Wrap,
                        addressV      = ShaderEffectSamplerAddress.Wrap,
                        addressW      = ShaderEffectSamplerAddress.Wrap
                    };
                    shaderEffect = device.CreateShaderEffect(vs, ps, null, null, null, desc, true);
                }

            // create vertex buffer
            var vertexBufferLayout = new VertexBufferLayout();
            vertexBufferLayout.elements    = new VertexBufferLayoutElement[3];
            vertexBufferLayout.elements[0] = new VertexBufferLayoutElement()
            {
                type        = VertexBufferLayoutElementType.Float3,
                usage       = VertexBufferLayoutElementUsage.Position,
                streamIndex = 0, usageIndex = 0, byteOffset = 0
            };
            vertexBufferLayout.elements[1] = new VertexBufferLayoutElement()
            {
                type        = VertexBufferLayoutElementType.RGBAx8,
                usage       = VertexBufferLayoutElementUsage.Color,
                streamIndex = 0, usageIndex = 0, byteOffset = (sizeof(float) * 3)
            };
            vertexBufferLayout.elements[2] = new VertexBufferLayoutElement()
            {
                type        = VertexBufferLayoutElementType.Float2,
                usage       = VertexBufferLayoutElementUsage.UV,
                streamIndex = 0, usageIndex = 0, byteOffset = (sizeof(float) * 3) + 4
            };

            var vertices = new Vertex[]
            {
                new Vertex(new Vec3(-1, -1, 0), Color4.red, new Vec2(0, 0)),
                new Vertex(new Vec3(0, 1, 0), Color4.green, new Vec2(.5f, 1)),
                new Vertex(new Vec3(1, -1, 0), Color4.blue, new Vec2(1, 0))
            };
            vertexBuffer = device.CreateVertexBuffer <Vertex>(vertices, vertexBufferLayout, VertexBufferMode.GPUOptimized);

            // create render state
            var renderStateDesc = new RenderStateDesc()
            {
                renderPass           = renderPass,
                shaderEffect         = shaderEffect,
                constantBuffers      = new ConstantBufferBase[1],
                textures             = new TextureBase[2],
                vertexBuffer         = vertexBuffer,
                vertexBufferTopology = VertexBufferTopology.Triangle
            };
            renderStateDesc.constantBuffers[0] = constantBuffer;
            renderStateDesc.textures[0]        = texture;
            renderStateDesc.textures[1]        = texture2;
            renderState = device.CreateRenderState(renderStateDesc, 0);

            // print all GPUs this abstraction supports
            if (!instance.QuerySupportedAdapters(false, out var adapters))
            {
                throw new Exception("Failed: QuerySupportedAdapters");
            }
            foreach (var adapter in adapters)
            {
                Debug.WriteLine(adapter.name);
            }
        }
 public override VertexBufferBase CreateVertexBuffer(int size, VertexBufferLayout layout, VertexBufferMode mode)
 {
     throw new NotImplementedException();
 }
Example #15
0
        public VoxelRenderer(GraphicsDevice graphicsDevice, ContentManager contentManager)
        {
            _cubeVertexBuffer = Buffer.Vertex.New(
                graphicsDevice,
                new[]
            {
                // 3D coordinates              UV Texture coordinates
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitZ, Texcoord = new Vector2(0.0f, 1.0f)
                },                                                                                                                                     // Front
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, -1.0f), Normal = -Vector3.UnitZ, Texcoord = new Vector2(0.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, -1.0f), Normal = -Vector3.UnitZ, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitZ, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, -1.0f), Normal = -Vector3.UnitZ, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitZ, Texcoord = new Vector2(1.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, 1.0f), Normal = Vector3.UnitZ, Texcoord = new Vector2(1.0f, 0.0f)
                },                                                                                                                                    // BACK
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, 1.0f), Normal = Vector3.UnitZ, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, 1.0f), Normal = Vector3.UnitZ, Texcoord = new Vector2(1.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, 1.0f), Normal = Vector3.UnitZ, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, 1.0f), Normal = Vector3.UnitZ, Texcoord = new Vector2(0.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, 1.0f), Normal = Vector3.UnitZ, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, -1.0f), Normal = Vector3.UnitY, Texcoord = new Vector2(0.0f, 1.0f)
                },                                                                                                                                    // Top
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, 1.0f), Normal = Vector3.UnitY, Texcoord = new Vector2(0.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, 1.0f), Normal = Vector3.UnitY, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, -1.0f), Normal = Vector3.UnitY, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, 1.0f), Normal = Vector3.UnitY, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, -1.0f), Normal = Vector3.UnitY, Texcoord = new Vector2(1.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitY, Texcoord = new Vector2(1.0f, 0.0f)
                },                                                                                                                                     // Bottom
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, 1.0f), Normal = -Vector3.UnitY, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, 1.0f), Normal = -Vector3.UnitY, Texcoord = new Vector2(1.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitY, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitY, Texcoord = new Vector2(0.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, 1.0f), Normal = -Vector3.UnitY, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitX, Texcoord = new Vector2(0.0f, 1.0f)
                },                                                                                                                                     // Left
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, 1.0f), Normal = -Vector3.UnitX, Texcoord = new Vector2(0.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, 1.0f), Normal = -Vector3.UnitX, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, -1.0f, -1.0f), Normal = -Vector3.UnitX, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, 1.0f), Normal = -Vector3.UnitX, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(-1.0f, 1.0f, -1.0f), Normal = -Vector3.UnitX, Texcoord = new Vector2(1.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, -1.0f), Normal = Vector3.UnitX, Texcoord = new Vector2(1.0f, 0.0f)
                },                                                                                                                                    // Right
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, 1.0f), Normal = Vector3.UnitX, Texcoord = new Vector2(0.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, 1.0f), Normal = Vector3.UnitX, Texcoord = new Vector2(1.0f, 1.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, -1.0f, -1.0f), Normal = Vector3.UnitX, Texcoord = new Vector2(1.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, -1.0f), Normal = Vector3.UnitX, Texcoord = new Vector2(0.0f, 0.0f)
                },
                new CubeVertex()
                {
                    Position = new Vector3(1.0f, 1.0f, 1.0f), Normal = Vector3.UnitX, Texcoord = new Vector2(0.0f, 1.0f)
                }
            }, SharpDX.Direct3D11.ResourceUsage.Immutable);

            // Create an input layout from the vertices
            _vertexInputLayout = VertexInputLayout.New(
                VertexBufferLayout.New(0, new VertexElement[] { new VertexElement("POSITION_CUBE", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0),
                                                                new VertexElement("NORMAL", 0, SharpDX.DXGI.Format.R32G32B32_Float, sizeof(float) * 3),
                                                                new VertexElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, sizeof(float) * 6) }, 0),
                VertexBufferLayout.New(1, new VertexElement[] { new VertexElement("POSITION_INSTANCE", SharpDX.DXGI.Format.R32_SInt) }, 1));

            // Create instance buffer for every VoxelInfo
            _voxelTypeRenderingData = new VoxelTypeInstanceData[TypeInformation.GetNumTypes() - 1];
            for (int i = 0; i < _voxelTypeRenderingData.Length; ++i)
            {
                _voxelTypeRenderingData[i] = new VoxelTypeInstanceData(graphicsDevice, (VoxelType)(i + 1));
            }
            LoadTextures(contentManager);


            // load shader
            EffectCompilerFlags compilerFlags = EffectCompilerFlags.None;

#if DEBUG
            compilerFlags |= EffectCompilerFlags.Debug;
#endif
            var voxelShaderCompileResult = EffectCompiler.CompileFromFile("Content/voxel.fx", compilerFlags);
            if (voxelShaderCompileResult.HasErrors)
            {
                System.Console.WriteLine(voxelShaderCompileResult.Logger.Messages);
                System.Diagnostics.Debugger.Break();
            }
            _voxelEffect = new SharpDX.Toolkit.Graphics.Effect(graphicsDevice, voxelShaderCompileResult.EffectData);

            // setup states
            var rasterizerStateDesc = SharpDX.Direct3D11.RasterizerStateDescription.Default();
            rasterizerStateDesc.CullMode = SharpDX.Direct3D11.CullMode.Back;
            _backfaceCullingState        = RasterizerState.New(graphicsDevice, "CullModeBack", rasterizerStateDesc);
            rasterizerStateDesc.CullMode = SharpDX.Direct3D11.CullMode.None;
            _noneCullingState            = RasterizerState.New(graphicsDevice, "CullModeNone", rasterizerStateDesc);

            var depthStencilStateDesc = SharpDX.Direct3D11.DepthStencilStateDescription.Default();
            depthStencilStateDesc.IsDepthEnabled = true;
            _depthStencilStateState = DepthStencilState.New(graphicsDevice, "NormalZBufferUse", depthStencilStateDesc);

            var samplerStateDesc = SharpDX.Direct3D11.SamplerStateDescription.Default();
            samplerStateDesc.AddressV = SharpDX.Direct3D11.TextureAddressMode.Mirror;
            samplerStateDesc.AddressU = SharpDX.Direct3D11.TextureAddressMode.Mirror;
            samplerStateDesc.Filter   = SharpDX.Direct3D11.Filter.MinMagMipPoint;
            _pointSamplerState        = SamplerState.New(graphicsDevice, "PointSampler", samplerStateDesc);
            _voxelEffect.Parameters["PointSampler"].SetResource(_pointSamplerState);

            var blendStateDesc = SharpDX.Direct3D11.BlendStateDescription.Default();
            _blendStateOpaque = BlendState.New(graphicsDevice, "Opaque", blendStateDesc);
            blendStateDesc.RenderTarget[0].IsBlendEnabled   = true;
            blendStateDesc.RenderTarget[0].SourceBlend      = SharpDX.Direct3D11.BlendOption.SourceAlpha;
            blendStateDesc.RenderTarget[0].DestinationBlend = SharpDX.Direct3D11.BlendOption.InverseSourceAlpha;
            blendStateDesc.RenderTarget[0].BlendOperation   = SharpDX.Direct3D11.BlendOperation.Add;
            _blendStateTransparent = BlendState.New(graphicsDevice, "AlphaBlend", blendStateDesc);

            // vertexbuffer for a single instance
            _singleInstanceBuffer = Buffer.Vertex.New <Int32>(graphicsDevice, 1, SharpDX.Direct3D11.ResourceUsage.Dynamic);
        }
 public override VertexBufferBase CreateVertexBuffer <T>(T[] vertices, VertexBufferLayout layout, VertexBufferMode mode)
 {
     throw new NotImplementedException();
 }
Example #17
0
        private void LoadFromNode(Assimp.Scene _scene, Assimp.Node _node, GraphicsDevice _device, SharpDX.Toolkit.Content.ContentManager _content, Matrix _transform)
        {
            // Sum up transformations recursively
            _transform = FromMatrix(_node.Transform) * _transform;
            Matrix transformInvTr = Helpers.CreateInverseTranspose(ref _transform);

            // Recursive load from scene
            if (_node.HasChildren)
            {
                foreach (Assimp.Node node in _node.Children)
                {
                    LoadFromNode(_scene, node, _device, _content, _transform);
                }
            }

            if (_node.HasMeshes)
            {
                foreach (int meshIndex in _node.MeshIndices)
                {
                    Assimp.Mesh mesh      = _scene.Meshes[meshIndex];
                    ModelMesh   modelMesh = new ModelMesh();

                    // if mesh has a diffuse texture extract it
                    Assimp.Material material = _scene.Materials[mesh.MaterialIndex];
                    if (material != null && material.GetTextureCount(TextureType.Diffuse) > 0)
                    {
                        TextureSlot texture = material.GetTexture(TextureType.Diffuse, 0);
                        // Create new texture for mesh
                        var dxtexture = _content.Load <Texture2D>(texture.FilePath);
                        modelMesh.DiffuseTexture = dxtexture;
                    }

                    // Position is mandarory
                    if (!mesh.HasVertices)
                    {
                        throw new Exception("Model::Model(): Model has no vertices.");
                    }

                    // Determine the elements in the vertex
                    bool hasTexCoords  = mesh.HasTextureCoords(0);
                    bool hasColors     = mesh.HasVertexColors(0);
                    bool hasNormals    = mesh.HasNormals;
                    bool hasTangents   = mesh.Tangents != null;
                    bool hasBitangents = mesh.BiTangents != null;
                    int  numElements   = 1 + (hasTexCoords ? 1 : 0) + (hasColors ? 1 : 0) + (hasNormals ? 1 : 0) + (hasTangents ? 1 : 0) + (hasBitangents ? 1 : 0);

                    // Create vertex element list: Here starts the section of creating SharpDX stuff
                    VertexElement[] vertexElements = new VertexElement[numElements];
                    uint            elementIndex   = 0;
                    vertexElements[elementIndex++] = new VertexElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0);
                    int vertexSize = Utilities.SizeOf <Vector3>();

                    if (hasColors)
                    {
                        vertexElements[elementIndex++] = new VertexElement("COLOR", 0, SharpDX.DXGI.Format.R8G8B8A8_UInt, vertexSize);
                        vertexSize += Utilities.SizeOf <Color>();
                    }
                    if (hasNormals)
                    {
                        vertexElements[elementIndex++] = new VertexElement("NORMAL", 0, SharpDX.DXGI.Format.R32G32B32_Float, vertexSize);
                        vertexSize += Utilities.SizeOf <Vector3>();
                    }
                    if (hasTangents)
                    {
                        vertexElements[elementIndex++] = new VertexElement("TANGENT", 0, SharpDX.DXGI.Format.R32G32B32_Float, vertexSize);
                        vertexSize += Utilities.SizeOf <Vector3>();
                    }
                    if (hasBitangents)
                    {
                        vertexElements[elementIndex++] = new VertexElement("BITANGENT", 0, SharpDX.DXGI.Format.R32G32B32_Float, vertexSize);
                        vertexSize += Utilities.SizeOf <Vector3>();
                    }
                    if (hasTexCoords)
                    {
                        vertexElements[elementIndex++] = new VertexElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, vertexSize);
                        vertexSize += Utilities.SizeOf <Vector2>();
                    }

                    // Set the vertex elements and size
                    modelMesh.InputLayout = VertexInputLayout.New(VertexBufferLayout.New(0, vertexElements));
                    modelMesh.VertexSize  = vertexSize;

                    // Determine primitive type
                    switch (mesh.PrimitiveType)
                    {
                    case Assimp.PrimitiveType.Point:    modelMesh.PrimitiveTopology = SharpDX.Toolkit.Graphics.PrimitiveType.PointList;    break;

                    case Assimp.PrimitiveType.Line:     modelMesh.PrimitiveTopology = SharpDX.Toolkit.Graphics.PrimitiveType.LineList;     break;

                    case Assimp.PrimitiveType.Triangle: modelMesh.PrimitiveTopology = SharpDX.Toolkit.Graphics.PrimitiveType.TriangleList; break;

                    default:                            throw new Exception("Model::Model(): Unknown primitive type");
                    }

                    // Create data stream for vertices
                    //System.IO.MemoryStream vertexStream = new System.IO.MemoryStream(mesh.VertexCount * vertexSize);
                    DataStream vertexStream = new DataStream(mesh.VertexCount * vertexSize, true, true);

                    for (int i = 0; i < mesh.VertexCount; i++)
                    {
                        vertexStream.Write <Vector3>(Helpers.Transform(FromVector(mesh.Vertices[i]), ref _transform));
                        if (hasColors)
                        {
                            vertexStream.Write <Color>(FromColor(mesh.GetVertexColors(0)[i]));
                        }
                        if (hasNormals)
                        {
                            vertexStream.Write <Vector3>(Helpers.Transform(FromVector(mesh.Normals[i]), ref transformInvTr));
                        }
                        if (hasTangents)
                        {
                            vertexStream.Write <Vector3>(Helpers.Transform(FromVector(mesh.Tangents[i]), ref transformInvTr));
                        }
                        if (hasBitangents)
                        {
                            vertexStream.Write <Vector3>(Helpers.Transform(FromVector(mesh.BiTangents[i]), ref transformInvTr));
                        }
                        if (hasTexCoords)
                        {
                            vertexStream.Write <Vector2>(new Vector2(mesh.GetTextureCoords(0)[i].X, mesh.GetTextureCoords(0)[i].Y));
                        }
                    }

                    vertexStream.Position = 0;

                    // Create new vertex buffer
                    var vertexBuffer = SharpDX.Toolkit.Graphics.Buffer.Vertex.New(_device, vertexStream);

                    // Add it to the mesh
                    modelMesh.VertexBuffer   = vertexBuffer;
                    modelMesh.VertexCount    = mesh.VertexCount;
                    modelMesh.PrimitiveCount = mesh.FaceCount;

                    // Create new index buffer
                    var indexBuffer = SharpDX.Toolkit.Graphics.Buffer.Index.New(_device, mesh.GetIndices());

                    // Add it to the mesh
                    modelMesh.IndexBuffer = indexBuffer;
                    modelMesh.IndexCount  = mesh.GetIndices().GetLength(0);

                    m_meshes.Add(modelMesh);
                }
            }
        }