Пример #1
0
        public async void GenerateCode2()
        {
            byte[] blackPixel = new byte[] { 0, 0, 0, 255 };
            byte[] whitePixel = new byte[] { 255, 255, 255, 255 };

            Random random = new Random();
            Stopwatch watch = new Stopwatch();

            var buffer = new Windows.Storage.Streams.Buffer(40000);
            using (var stream = buffer.AsStream())
            {
                watch.Start();
                await Task.Run(() =>
                {
                    for (var i = 0; i < 10000; i++)
                    {
                        if (random.NextDouble() >= 0.5)
                            stream.Write(blackPixel, 0, 4);
                        else
                            stream.Write(whitePixel, 0, 4);
                    }
                });
                watch.Stop();
                await new MessageDialog(watch.ElapsedMilliseconds.ToString()).ShowAsync();

            }
        }
Пример #2
0
        public PdfView(byte[] pdf) : this()
        {
            this.pdf = pdf;
            var capacity = pdf.Length;
            var buf      = new Windows.Storage.Streams.Buffer((uint)capacity);

            buf.AsStream().Read(pdf, 0, capacity);
            //webView.NavigateWithHttpRequestMessage(new Windows.Web.Http.HttpRequestMessage()
            //{
            //    RequestUri = new System.Uri(@"C:\sources\Sergiy_Kryvonos_SEM_Journals_NET\Source\SEM\SEM.DesktopClient\pdfjs-1.3.91-dist\build\pdf.js"),
            //    Content = new HttpBufferContent (buf),
            //});
            var ms             = new MemoryStream(pdf);
            var pdfDocLoadTask = PdfDocument.LoadFromStreamAsync(ms.AsRandomAccessStream());

            pdfDocLoadTask.AsTask().ContinueWith(task => {
                if (task.Status == System.Threading.Tasks.TaskStatus.RanToCompletion)
                {
                    PdfDocument pdfDoc = task.Result;
                    var page           = pdfDoc.GetPage(0);
                    MemoryStream msImg = new MemoryStream();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        BitmapImage img = new BitmapImage(
                            );
                        var rndImgStream = msImg.AsRandomAccessStream();
                        page.RenderToStreamAsync(rndImgStream).AsTask().ContinueWith(pageRenderTask =>
                        {
                            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                            {
                                img.SetSource(rndImgStream);
                                image.Source = img;
                            });
                        });
                    });
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                }
            });


            //webView.InvokeScriptAsync("pdfjs-1.3.91-dist/build/pdf.js", new string[] { @"C:\\sources\\oo\\evince\\browser-plugin\\tests\\test.pdf" }).AsTask().ContinueWith(str=>
            //{

            //});
        }
Пример #3
0
        public void Start(byte device, short width, short height)
        {
            Log.WriteV(this.GetType().Name, String.Format(" - d:{0};w:{1};h:{2}", (int)device, width, height));

            CoreDispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                if (!await Initialize(device, width, height))
                {
                    unchainedCamera(null); // Failed to start camera
                    return;
                }

                // Set the preview source in the UI and mirror it if necessary
                _captureElement.Source        = _mediaCapture;
                _captureElement.FlowDirection = FlowDirection.LeftToRight;

                // Start the preview
                await _mediaCapture.StartPreviewAsync();

                _running     = true;
                _previewTask = new Task(async() =>
                {
                    Windows.Storage.Streams.Buffer data = new Windows.Storage.Streams.Buffer((uint)(width * height * 4));
                    while (_running)
                    {
                        // Create the video frame to request a SoftwareBitmap preview frame
                        var videoFrame = new VideoFrame(BitmapPixelFormat.Rgba8, (int)width, (int)height);

                        using (var currentFrame = await _mediaCapture.GetPreviewFrameAsync(videoFrame))
                        {
                            // Collect the resulting frame
                            currentFrame.SoftwareBitmap.CopyToBuffer(data);
                            MemoryStream memory = new MemoryStream();
                            data.AsStream().CopyTo(memory);

                            unchainedCamera(memory.ToArray());
                        }
                    }
                }, TaskCreationOptions.None);
                _previewTask.Start();
            });
        }
Пример #4
0
        async Task Init()
        {
            var gpu = new Gpu();

#if DEBUG
            gpu.EnableD3D12DebugLayer();
#endif
            var adapter = await gpu.RequestAdapterAsync();

            Device = await adapter.RequestDeviceAsync();

            TimeBindGroupLayout = Device.CreateBindGroupLayout(new GpuBindGroupLayoutDescriptor(new GpuBindGroupLayoutEntry[]
            {
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 0,
                    Visibility = GpuShaderStageFlags.Vertex,
                    Buffer     = new GpuBufferBindingLayout()
                    {
                        Type           = GpuBufferBindingType.Uniform,
                        MinBindingSize = sizeof(float)
                    }
                }
            }));
            BindGroupLayout = Device.CreateBindGroupLayout(new GpuBindGroupLayoutDescriptor(new GpuBindGroupLayoutEntry[]
            {
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 0,
                    Visibility = GpuShaderStageFlags.Vertex,
                    Buffer     = new GpuBufferBindingLayout()
                    {
                        Type           = GpuBufferBindingType.Uniform,
                        MinBindingSize = 20
                    }
                }
            }));
            DynamicBindGroupLayout = Device.CreateBindGroupLayout(new GpuBindGroupLayoutDescriptor(new GpuBindGroupLayoutEntry[]
            {
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 0,
                    Visibility = GpuShaderStageFlags.Vertex,
                    Buffer     = new GpuBufferBindingLayout()
                    {
                        Type             = GpuBufferBindingType.Uniform,
                        HasDynamicOffset = true,
                        MinBindingSize   = 20
                    }
                }
            }));

            var pipelineLayout = Device.CreatePipelineLayout(new GpuPipelineLayoutDescriptor()
            {
                BindGroupLayouts = new GpuBindGroupLayout[] { TimeBindGroupLayout, BindGroupLayout }
            });
            var dynamicPipelineLayout = Device.CreatePipelineLayout(new GpuPipelineLayoutDescriptor()
            {
                BindGroupLayouts = new GpuBindGroupLayout[] { TimeBindGroupLayout, DynamicBindGroupLayout }
            });

            string shaderCode;
            using (var shaderFileStream = typeof(MainPage).Assembly.GetManifestResourceStream("Animometer.shader.hlsl"))
                using (var shaderStreamReader = new StreamReader(shaderFileStream))
                {
                    shaderCode = shaderStreamReader.ReadToEnd();
                }
            var shader = Device.CreateShaderModule(new GpuShaderModuleDescriptor(GpuShaderSourceType.Hlsl, shaderCode));

            var pipelineDescriptor = new GpuRenderPipelineDescriptor(new GpuVertexState(shader, "VSMain")
            {
                VertexBuffers = new GpuVertexBufferLayout[]
                {
                    new GpuVertexBufferLayout(2 * Vec4Size, new GpuVertexAttribute[]
                    {
                        new GpuVertexAttribute()
                        {
                            ShaderLocation = 0,
                            Offset         = 0,
                            Format         = GpuVertexFormat.Float4
                        },
                        new GpuVertexAttribute()
                        {
                            ShaderLocation = 1,
                            Offset         = Vec4Size,
                            Format         = GpuVertexFormat.Float4
                        }
                    })
                    {
                        StepMode = GpuInputStepMode.Vertex
                    }
                }
            })
            {
                Fragment = new GpuFragmentState(shader, "PSMain", new GpuColorTargetState[] { new GpuColorTargetState()
                                                                                              {
                                                                                                  Format = SwapChainFormat
                                                                                              } }),
                Primitive = new GpuPrimitiveState()
                {
                    Topology  = GpuPrimitiveTopology.TriangleList,
                    FrontFace = GpuFrontFace.Ccw,
                    CullMode  = GpuCullMode.None
                }
            };
            pipelineDescriptor.Layout = pipelineLayout;
            Pipeline = Device.CreateRenderPipeline(pipelineDescriptor);
            pipelineDescriptor.Layout = dynamicPipelineLayout;
            DynamicPipeline           = Device.CreateRenderPipeline(pipelineDescriptor);
            VertexBuffer = Device.CreateBuffer(new GpuBufferDescriptor(2 * 3 * Vec4Size, GpuBufferUsageFlags.Vertex)
            {
                MappedAtCreation = true
            });
            float[] vertexData = new float[]
            {
                0, 0.1f, 0, 1, 1, 0, 0, 1,
                -0.1f, -0.1f, 0, 1, 0, 1, 0, 1,
                0.1f, -0.1f, 0, 1, 0, 0, 1, 1
            };
            Windows.Storage.Streams.Buffer verticeCpuBuffer = new Windows.Storage.Streams.Buffer((uint)Buffer.ByteLength(vertexData));
            verticeCpuBuffer.Length = verticeCpuBuffer.Capacity;
            using (var verticeCpuStream = verticeCpuBuffer.AsStream())
            {
                byte[] vertexBufferBytes = new byte[Buffer.ByteLength(vertexData)];
                Buffer.BlockCopy(vertexData, 0, vertexBufferBytes, 0, Buffer.ByteLength(vertexData));
                await verticeCpuStream.WriteAsync(vertexBufferBytes, 0, Buffer.ByteLength(vertexData));
            }
            verticeCpuBuffer.CopyTo(VertexBuffer.GetMappedRange());
            VertexBuffer.Unmap();
        }
Пример #5
0
            public Configure(GpuDevice device, Settings settings, GpuBindGroupLayout bindGroupLayout, GpuBindGroupLayout dynamicBindGroupLayout, GpuBindGroupLayout timeBindGroupLayout, GpuRenderPipeline pipeline, GpuRenderPipeline dynamicPipeline, GpuBuffer vertexBuffer, GpuTextureFormat swapChainFormat)
            {
                Device          = device;
                Settings        = settings;
                Pipeline        = pipeline;
                DynamicPipeline = dynamicPipeline;
                VertexBuffer    = vertexBuffer;
                SwapChainFormat = swapChainFormat;

                UniformBuffer = Device.CreateBuffer(new GpuBufferDescriptor(Settings.NumTriangles * AlignedUniformBytes + sizeof(float), GpuBufferUsageFlags.Uniform | GpuBufferUsageFlags.CopyDst));
                var uniformCpuBuffer = new Windows.Storage.Streams.Buffer(Settings.NumTriangles * AlignedUniformBytes)
                {
                    Length = Settings.NumTriangles * AlignedUniformBytes
                };

                using (var uniformCpuStream = uniformCpuBuffer.AsStream())
                    using (var uniformCpuWriter = new BinaryWriter(uniformCpuStream))
                    {
                        var rand = new Random();
                        for (var i = 0; i < Settings.NumTriangles; ++i)
                        {
                            uniformCpuWriter.Seek((int)(i * AlignedUniformBytes), SeekOrigin.Begin);
                            float scale = (float)(rand.NextDouble() * 0.2 + 0.2);
                            //scale = 5;
                            float offsetX      = (float)(0.9 * 2 * (rand.NextDouble() - 0.5));
                            float offsetY      = (float)(0.9 * 2 * (rand.NextDouble() - 0.5));
                            float scalar       = (float)(rand.NextDouble() * 1.5 + 0.5);
                            float scalarOffset = (float)(rand.NextDouble() * 10);
                            uniformCpuWriter.Write(scale);        //Scale
                            uniformCpuWriter.Write(offsetX);      //offsetX
                            uniformCpuWriter.Write(offsetY);      //offsetY
                            uniformCpuWriter.Write(scalar);       //scalar
                            uniformCpuWriter.Write(scalarOffset); //scalar offset
                        }
                    }
                BindGroups = new GpuBindGroup[Settings.NumTriangles];
                for (var i = 0; i < Settings.NumTriangles; ++i)
                {
                    BindGroups[i] = Device.CreateBindGroup(new GpuBindGroupDescriptor(bindGroupLayout, new GpuBindGroupEntry[]
                    {
                        new GpuBindGroupEntry(0, new GpuBufferBinding(UniformBuffer, 6 * sizeof(float))
                        {
                            Offset = (UInt64)(i * AlignedUniformBytes)
                        })
                    }));
                }
                DynamicBindGroup = Device.CreateBindGroup(new GpuBindGroupDescriptor(dynamicBindGroupLayout, new GpuBindGroupEntry[]
                {
                    new GpuBindGroupEntry(0, new GpuBufferBinding(UniformBuffer, 6 * sizeof(float)))
                }));


                TimeBindGroup = Device.CreateBindGroup(new GpuBindGroupDescriptor(timeBindGroupLayout, new GpuBindGroupEntry[]
                {
                    new GpuBindGroupEntry(0, new GpuBufferBinding(UniformBuffer, sizeof(float))
                    {
                        Offset = TimeOffset
                    })
                }));
                Device.DefaultQueue.WriteBuffer(UniformBuffer, 0, uniformCpuBuffer);
                var renderBundleEncoder = Device.CreateRenderBundleEncoder(new GpuRenderBundleEncoderDescriptor(new GpuTextureFormat[] { SwapChainFormat }));

                RecordRenderPass(renderBundleEncoder);
                RenderBundle         = renderBundleEncoder.Finish();
                UniformTimeCpuBuffer = new Windows.Storage.Streams.Buffer(sizeof(float))
                {
                    Length = sizeof(float)
                };
            }
        async Task Init()
        {
            var adapter = await Gpu.RequestAdapterAsync();

            Device = await adapter.RequestDeviceAsync();

            GpuShaderModule computeShader;

            using (var shaderFileStream = typeof(MainWindow).Assembly.GetManifestResourceStream("ComputeBoidsWpf.compute.hlsl"))
                using (var shaderStreamReader = new StreamReader(shaderFileStream))
                {
                    var shaderCode = await shaderStreamReader.ReadToEndAsync();

                    computeShader = Device.CreateShaderModule(new GpuShaderModuleDescriptor(GpuShaderSourceType.Hlsl, shaderCode));
                }

            GpuShaderModule drawShader;

            using (var shaderFileStream = typeof(MainWindow).Assembly.GetManifestResourceStream("ComputeBoidsWpf.draw.hlsl"))
                using (var shaderStreamReader = new StreamReader(shaderFileStream))
                {
                    var shaderCode = await shaderStreamReader.ReadToEndAsync();

                    drawShader = Device.CreateShaderModule(new GpuShaderModuleDescriptor(GpuShaderSourceType.Hlsl, shaderCode));
                }
            RenderPipeline = Device.CreateRenderPipeline(new GpuRenderPipelineDescriptor(new GpuVertexState(drawShader, "VSMain")
            {
                VertexBuffers = new GpuVertexBufferLayout[]
                {
                    new GpuVertexBufferLayout(4 * 4, new GpuVertexAttribute[]
                    {
                        new GpuVertexAttribute()
                        {
                            Format         = GpuVertexFormat.Float2,
                            Offset         = 0,
                            ShaderLocation = 0
                        },
                        new GpuVertexAttribute()
                        {
                            Format         = GpuVertexFormat.Float2,
                            Offset         = 2 * 4,
                            ShaderLocation = 1
                        }
                    })
                    {
                        StepMode = GpuInputStepMode.Instance
                    },
                    new GpuVertexBufferLayout(2 * 4, new GpuVertexAttribute[]
                    {
                        new GpuVertexAttribute()
                        {
                            Format         = GpuVertexFormat.Float2,
                            Offset         = 0,
                            ShaderLocation = 2
                        }
                    })
                }
            })
            {
                Fragment = new GpuFragmentState(drawShader, "PSMain", new GpuColorTargetState[] { new GpuColorTargetState {
                                                                                                      Format = GpuTextureFormat.BGRA8UNorm, Blend = null, WriteMask = GpuColorWriteFlags.All
                                                                                                  } }),
                Primitive = new GpuPrimitiveState {
                    Topology = GpuPrimitiveTopology.TriangleList, CullMode = GpuCullMode.None, FrontFace = GpuFrontFace.Ccw
                },
                DepthStencilState = new GpuDepthStencilState(GpuTextureFormat.Depth24PlusStencil8)
                {
                    DepthWriteEnabled = true,
                    DepthCompare      = GpuCompareFunction.Less,
                }
            });
            var computeBindGroupLayout = Device.CreateBindGroupLayout(new GpuBindGroupLayoutDescriptor(new GpuBindGroupLayoutEntry[]
            {
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 0,
                    Visibility = GpuShaderStageFlags.Compute,
                    Buffer     = new GpuBufferBindingLayout()
                    {
                        Type             = GpuBufferBindingType.Uniform,
                        HasDynamicOffset = false,
                        MinBindingSize   = (ulong)(SimParamData.Length * sizeof(float))
                    }
                },
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 1,
                    Visibility = GpuShaderStageFlags.Compute,
                    Buffer     = new GpuBufferBindingLayout()
                    {
                        Type             = GpuBufferBindingType.ReadOnlyStorage,
                        HasDynamicOffset = false,
                        MinBindingSize   = NumParticles * 16
                    }
                },
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 2,
                    Visibility = GpuShaderStageFlags.Compute,
                    Buffer     = new GpuBufferBindingLayout()
                    {
                        Type             = GpuBufferBindingType.Storage,
                        HasDynamicOffset = false,
                        MinBindingSize   = NumParticles * 16
                    }
                }
            }));

            ComputePipeline = Device.CreateComputePipeline(new GpuComputePipelineDescriptor(new GpuProgrammableStage(computeShader, "main"))
            {
                Layout = Device.CreatePipelineLayout(new GpuPipelineLayoutDescriptor()
                {
                    BindGroupLayouts = new GpuBindGroupLayout[] { computeBindGroupLayout }
                }),
            });

            VerticesBuffer = Device.CreateBuffer(new GpuBufferDescriptor((ulong)(sizeof(float) * VertexBufferData.Length), GpuBufferUsageFlags.Vertex)
            {
                MappedAtCreation = true
            });
            using (var stream = VerticesBuffer.GetMappedRange().AsStream())
                using (var binaryWriter = new BinaryWriter(stream))
                {
                    for (int i = 0; i < VertexBufferData.Length; ++i)
                    {
                        binaryWriter.Write(VertexBufferData[i]);
                    }
                }
            VerticesBuffer.Unmap();

            var simParamBuffer = Device.CreateBuffer(new GpuBufferDescriptor((ulong)(sizeof(float) * SimParamData.Length), GpuBufferUsageFlags.Uniform)
            {
                MappedAtCreation = true
            });

            using (var stream = simParamBuffer.GetMappedRange().AsStream())
                using (var writer = new BinaryWriter(stream))
                {
                    for (int i = 0; i < SimParamData.Length; ++i)
                    {
                        writer.Write(SimParamData[i]);
                    }
                }
            simParamBuffer.Unmap();

            float[] initialParticleData = new float[NumParticles * 4];
            Random  random = new Random();

            for (var i = 0; i < NumParticles; ++i)
            {
                initialParticleData[4 * i + 0] = (float)(2 * (random.NextDouble() - 0.5f));
                initialParticleData[4 * i + 1] = (float)(2 * (random.NextDouble() - 0.5f));
                initialParticleData[4 * i + 2] = (float)(2 * (random.NextDouble() - 0.5f) * 0.1);
                initialParticleData[4 * i + 3] = (float)(2 * (random.NextDouble() - 0.5f) * 0.1);
            }
            Windows.Storage.Streams.Buffer initialParticleDataBuffer = new Windows.Storage.Streams.Buffer((uint)(sizeof(float) * initialParticleData.Length))
            {
                Length = (uint)(sizeof(float) * initialParticleData.Length)
            };
            using (var stream = initialParticleDataBuffer.AsStream())
                using (var writer = new BinaryWriter(stream))
                {
                    for (int i = 0; i < initialParticleData.Length; ++i)
                    {
                        writer.Write(initialParticleData[i]);
                    }
                }

            ParticleBuffers = new GpuBuffer[2];
            for (int i = 0; i < 2; ++i)
            {
                ParticleBuffers[i] = Device.CreateBuffer(new GpuBufferDescriptor(initialParticleDataBuffer.Length, GpuBufferUsageFlags.Vertex | GpuBufferUsageFlags.Storage)
                {
                    MappedAtCreation = true
                });
                initialParticleDataBuffer.CopyTo(ParticleBuffers[i].GetMappedRange());
                ParticleBuffers[i].Unmap();
            }
            ParticleBindGroups = new GpuBindGroup[2];
            for (var i = 0; i < 2; ++i)
            {
                ParticleBindGroups[i] = Device.CreateBindGroup(new GpuBindGroupDescriptor(computeBindGroupLayout, new GpuBindGroupEntry[]
                {
                    new GpuBindGroupEntry(0, new GpuBufferBinding(simParamBuffer, simParamBuffer.Size)),
                    new GpuBindGroupEntry(1, new GpuBufferBinding(ParticleBuffers[i], ParticleBuffers[i].Size)),
                    new GpuBindGroupEntry(2, new GpuBufferBinding(ParticleBuffers[(i + 1) % 2], ParticleBuffers[(i + 1) % 2].Size))
                }));
            }
            T = 0;
        }
Пример #7
0
        async Task Init()
        {
            var gpu = new Gpu();

#if DEBUG
            gpu.EnableD3D12DebugLayer();
#endif
            Device = await(await gpu.RequestAdapterAsync()).RequestDeviceAsync();

            Windows.Storage.Streams.Buffer verticeCpuBuffer = new Windows.Storage.Streams.Buffer((uint)Buffer.ByteLength(Cube.CubeVertexArray));
            verticeCpuBuffer.Length = verticeCpuBuffer.Capacity;
            using (var verticeCpuStream = verticeCpuBuffer.AsStream())
            {
                byte[] vertexBufferBytes = new byte[Buffer.ByteLength(Cube.CubeVertexArray)];
                Buffer.BlockCopy(Cube.CubeVertexArray, 0, vertexBufferBytes, 0, Buffer.ByteLength(Cube.CubeVertexArray));
                await verticeCpuStream.WriteAsync(vertexBufferBytes, 0, Buffer.ByteLength(Cube.CubeVertexArray));
            }
            VerticesBuffer = Device.CreateBuffer(new GpuBufferDescriptor((ulong)Buffer.ByteLength(Cube.CubeVertexArray), GpuBufferUsageFlags.Vertex)
            {
                MappedAtCreation = true
            });
            verticeCpuBuffer.CopyTo(VerticesBuffer.GetMappedRange());
            VerticesBuffer.Unmap();
            string shaderCode;
            using (var shaderFileStream = typeof(MainPage).Assembly.GetManifestResourceStream("RotatingCube.shader.hlsl"))
                using (var shaderStreamReader = new StreamReader(shaderFileStream))
                {
                    shaderCode = shaderStreamReader.ReadToEnd();
                }
            var shader = Device.CreateShaderModule(new GpuShaderModuleDescriptor(GpuShaderSourceType.Hlsl, shaderCode));

            //var shader = Device.CreateShaderModule(new GpuShaderModuleDescriptor(GpuShaderSourceType.Hlsl, ))

            var vertexState = new GpuVertexState(shader, "VSMain")
            {
                VertexBuffers = new GpuVertexBufferLayout[] { new GpuVertexBufferLayout(Cube.CubeVertexSize, new GpuVertexAttribute[]
                    {
                        new GpuVertexAttribute()
                        {
                            ShaderLocation = 0,
                            Format         = GpuVertexFormat.Float4,
                            Offset         = Cube.CubePositionOffset
                        },
                        new GpuVertexAttribute()
                        {
                            ShaderLocation = 1,
                            Format         = GpuVertexFormat.Float4,
                            Offset         = Cube.CubeColorOffset
                        }
                    }) }
            };
            var fragmentState = new GpuFragmentState(shader, "PSMain", new GpuColorTargetState[] { new GpuColorTargetState {
                                                                                                       Format = GpuTextureFormat.BGRA8UNorm, Blend = null, WriteMask = GpuColorWriteFlags.All
                                                                                                   } });
            var primitiveState = new GpuPrimitiveState
            {
                Topology         = GpuPrimitiveTopology.TriangleList,
                FrontFace        = GpuFrontFace.Ccw,
                CullMode         = GpuCullMode.Back,
                StripIndexFormat = null
            };
            var depthState = new GpuDepthStencilState(GpuTextureFormat.Depth24PlusStencil8)
            {
                DepthWriteEnabled = true,
                DepthCompare      = GpuCompareFunction.Less,
            };
            var uniformBindGroupLayout = Device.CreateBindGroupLayout(new GpuBindGroupLayoutDescriptor(new GpuBindGroupLayoutEntry[]
            {
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 0,
                    Visibility = GpuShaderStageFlags.Vertex,
                    Buffer     = new GpuBufferBindingLayout
                    {
                        Type             = GpuBufferBindingType.Uniform,
                        HasDynamicOffset = false,
                        MinBindingSize   = UniformBufferSize
                    }
                }
            }));
            var pipelineLayout = Device.CreatePipelineLayout(new GpuPipelineLayoutDescriptor()
            {
                BindGroupLayouts = new GpuBindGroupLayout[]
                {
                    uniformBindGroupLayout
                }
            });

            Pipeline = Device.CreateRenderPipeline(new GpuRenderPipelineDescriptor(vertexState)
            {
                Fragment          = fragmentState,
                Primitive         = primitiveState,
                DepthStencilState = depthState,
                Layout            = pipelineLayout
            });

            UniformBuffer           = Device.CreateBuffer(new GpuBufferDescriptor(UniformBufferSize, GpuBufferUsageFlags.Uniform | GpuBufferUsageFlags.CopyDst));
            UniformCpuBuffer        = new Windows.Storage.Streams.Buffer(4 * 4 * sizeof(float));
            UniformCpuBuffer.Length = UniformCpuBuffer.Capacity;
            UniformBindGroup        = Device.CreateBindGroup(new GpuBindGroupDescriptor(uniformBindGroupLayout, new GpuBindGroupEntry[]
            {
                new GpuBindGroupEntry(0, new GpuBufferBinding(UniformBuffer, UniformBufferSize))
            }));
        }
Пример #8
0
        async Task Init()
        {
            var gpu = new Gpu();

#if DEBUG
            gpu.EnableD3D12DebugLayer();
#endif
            Device = await(await gpu.RequestAdapterAsync()).RequestDeviceAsync();

            Windows.Storage.Streams.Buffer verticeCpuBuffer = new Windows.Storage.Streams.Buffer((uint)Buffer.ByteLength(Cube.CubeVertexArray));
            verticeCpuBuffer.Length = verticeCpuBuffer.Capacity;
            using (var verticeCpuStream = verticeCpuBuffer.AsStream())
            {
                byte[] vertexBufferBytes = new byte[Buffer.ByteLength(Cube.CubeVertexArray)];
                Buffer.BlockCopy(Cube.CubeVertexArray, 0, vertexBufferBytes, 0, Buffer.ByteLength(Cube.CubeVertexArray));
                await verticeCpuStream.WriteAsync(vertexBufferBytes, 0, Buffer.ByteLength(Cube.CubeVertexArray));
            }
            VerticesBuffer = Device.CreateBuffer(new GpuBufferDescriptor((ulong)Buffer.ByteLength(Cube.CubeVertexArray), GpuBufferUsageFlags.Vertex)
            {
                MappedAtCreation = true
            });
            verticeCpuBuffer.CopyTo(VerticesBuffer.GetMappedRange());
            VerticesBuffer.Unmap();

            string shaderCode;
            using (var shaderFileStream = typeof(MainPage).Assembly.GetManifestResourceStream("TexturedCube.shader.hlsl"))
                using (var shaderStreamReader = new StreamReader(shaderFileStream))
                {
                    shaderCode = shaderStreamReader.ReadToEnd();
                }
            var shader = Device.CreateShaderModule(new GpuShaderModuleDescriptor(GpuShaderSourceType.Hlsl, shaderCode));

            var vertexState = new GpuVertexState(shader, "VSMain")
            {
                VertexBuffers = new GpuVertexBufferLayout[] { new GpuVertexBufferLayout(Cube.CubeVertexSize, new GpuVertexAttribute[]
                    {
                        new GpuVertexAttribute()
                        {
                            ShaderLocation = 0,
                            Format         = GpuVertexFormat.Float4,
                            Offset         = Cube.CubePositionOffset
                        },
                        new GpuVertexAttribute()
                        {
                            ShaderLocation = 1,
                            Format         = GpuVertexFormat.Float2,
                            Offset         = Cube.CubeUVOffset
                        }
                    }) }
            };
            var fragmentState = new GpuFragmentState(shader, "PSMain", new GpuColorTargetState[] { new GpuColorTargetState {
                                                                                                       Format = GpuTextureFormat.BGRA8UNorm, Blend = null, WriteMask = GpuColorWriteFlags.All
                                                                                                   } });
            var primitiveState = new GpuPrimitiveState
            {
                Topology         = GpuPrimitiveTopology.TriangleList,
                FrontFace        = GpuFrontFace.Ccw,
                CullMode         = GpuCullMode.Back,
                StripIndexFormat = null
            };
            var depthState = new GpuDepthStencilState(GpuTextureFormat.Depth24PlusStencil8)
            {
                DepthWriteEnabled = true,
                DepthCompare      = GpuCompareFunction.Less,
            };
            var uniformBindGroupLayout = Device.CreateBindGroupLayout(new GpuBindGroupLayoutDescriptor(new GpuBindGroupLayoutEntry[]
            {
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 0,
                    Visibility = GpuShaderStageFlags.Vertex,
                    Buffer     = new GpuBufferBindingLayout
                    {
                        Type             = GpuBufferBindingType.Uniform,
                        HasDynamicOffset = false,
                        MinBindingSize   = UniformBufferSize
                    }
                },
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 1,
                    Visibility = GpuShaderStageFlags.Fragment,
                    Sampler    = new GpuSamplerBindingLayout()
                    {
                        Type = GpuSamplerBindingType.Filtering
                    }
                },
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 2,
                    Visibility = GpuShaderStageFlags.Fragment,
                    Texture    = new GpuTextureBindingLayout()
                    {
                        SampleType    = GpuTextureSampleType.Float,
                        ViewDimension = GpuTextureViewDimension._2D,
                        Multisampled  = false
                    }
                }
            }));
            var pipelineLayout = Device.CreatePipelineLayout(new GpuPipelineLayoutDescriptor()
            {
                BindGroupLayouts = new GpuBindGroupLayout[]
                {
                    uniformBindGroupLayout
                }
            });
            Pipeline = Device.CreateRenderPipeline(new GpuRenderPipelineDescriptor(vertexState)
            {
                Fragment          = fragmentState,
                Primitive         = primitiveState,
                DepthStencilState = depthState,
                Layout            = pipelineLayout
            });
            UniformBuffer           = Device.CreateBuffer(new GpuBufferDescriptor(UniformBufferSize, GpuBufferUsageFlags.Uniform | GpuBufferUsageFlags.CopyDst));
            UniformCpuBuffer        = new Windows.Storage.Streams.Buffer(4 * 4 * sizeof(float));
            UniformCpuBuffer.Length = UniformCpuBuffer.Capacity;

            var imgDecoder = await BitmapDecoder.CreateAsync(typeof(MainPage).Assembly.GetManifestResourceStream("TexturedCube.Di_3d.png").AsRandomAccessStream());

            var imageBitmap = await imgDecoder.GetSoftwareBitmapAsync();

            var cubeTexture = Device.CreateTexture(new GpuTextureDescriptor(new GpuExtend3DDict {
                Width = (uint)imageBitmap.PixelWidth, Height = (uint)imageBitmap.PixelHeight, Depth = 1
            }, GpuTextureFormat.BGRA8UNorm, GpuTextureUsageFlags.Sampled | GpuTextureUsageFlags.CopyDst));
            Device.DefaultQueue.CopyImageBitmapToTexture(new GpuImageCopyImageBitmap(imageBitmap), new GpuImageCopyTexture(cubeTexture), new GpuExtend3DDict {
                Width = (uint)imageBitmap.PixelWidth, Height = (uint)imageBitmap.PixelHeight, Depth = 1
            });
            var sampler = Device.CreateSampler(new GpuSamplerDescriptor()
            {
                MagFilter = GpuFilterMode.Linear,
                MinFilter = GpuFilterMode.Linear
            });
            UniformBindGroup = Device.CreateBindGroup(new GpuBindGroupDescriptor(uniformBindGroupLayout, new GpuBindGroupEntry[]
            {
                new GpuBindGroupEntry(0, new GpuBufferBinding(UniformBuffer, UniformBufferSize)),
                new GpuBindGroupEntry(1, sampler),
                new GpuBindGroupEntry(2, cubeTexture.CreateView())
            }));
        }