Пример #1
0
        public unsafe ShaderProgram(GL gl, ShaderType shaderType, string path) : base(gl)
        {
            void CacheUniformsImpl()
            {
                GL.GetProgram(Handle, ProgramPropertyARB.ActiveUniforms, out int uniformCount);

                for (uint uniformIndex = 0; uniformIndex < uniformCount; uniformIndex++)
                {
                    string name     = GL.GetActiveUniform(Handle, uniformIndex, out _, out _);
                    int    location = GL.GetUniformLocation(Handle, name);
                    _CachedUniforms.Add(name, location);
                }
            }

            _CachedUniforms = new Dictionary <string, int>();
            Type            = shaderType;

            // this is kinda dumb, right?
            byte *shader = (byte *)SilkMarshal.StringToPtr(File.ReadAllText(path));

            Handle = GL.CreateShaderProgram(Type, 1, shader);
            CheckInfoLogAndThrow();
            CacheUniformsImpl();

            Log.Debug(string.Format(FormatHelper.DEFAULT_LOGGING, nameof(ShaderProgram), $"Loaded ({Type}): {path}"));
        }
Пример #2
0
        public ComputeShader(Vk vk, Instance instance, Device device, PhysicalDevice physicalDevice, PipelineLayout pipelineLayout, ReadOnlySpan <byte> data, string functionName, SpecializationInfo *specializationInfo)
        {
            var subgroupProperties = new PhysicalDeviceSubgroupProperties(pNext: null);
            var properties         = new PhysicalDeviceProperties2(pNext: &subgroupProperties);

            vk.GetPhysicalDeviceProperties2(physicalDevice, &properties);

            var subgroupSize = subgroupProperties.SubgroupSize;

            Console.WriteLine($"Detected subgroup size {subgroupSize}");

            var data2 = new byte[data.Length + 32];

            data.CopyTo(data2);
            _vk     = vk;
            _device = device;
            ShaderModule shaderModule;

            fixed(byte *pData = data2)
            _vk.CreateShaderModule(_device, new ShaderModuleCreateInfo(codeSize: (nuint)data.Length, pCode: (uint *)pData),
                                   null, out shaderModule).ThrowCode();

            try
            {
                var pName = SilkMarshal.StringToPtr(functionName);
                try
                {
                    PipelineCreateFlags flags = 0;

                    _vk.CreateComputePipelines(_device, default, 1, new ComputePipelineCreateInfo(flags: flags
                                                                                                  , layout: pipelineLayout,
                                                                                                  stage: new PipelineShaderStageCreateInfo(stage: ShaderStageFlags.ShaderStageComputeBit,
                                                                                                                                           module: shaderModule, pName: (byte *)pName, pSpecializationInfo: specializationInfo)), null, out _pipeline).ThrowCode();
                }
Пример #3
0
        private Device CreateLogicalDevice(out Queue GraphicsQueue, out Queue PresentQueue)
        {
            var   queueInfos    = stackalloc DeviceQueueCreateInfo[2];
            uint  infoCount     = 1;
            float queuePriority = 1f;

            queueInfos[0] = new DeviceQueueCreateInfo(queueFamilyIndex: (uint)this.QueueIndices.GraphicsFamily, queueCount: 1, pQueuePriorities: &queuePriority);

            if (this.QueueIndices.GraphicsFamily != this.QueueIndices.PresentFamily)
            {
                infoCount = 2;

                queueInfos[1] = new DeviceQueueCreateInfo(queueFamilyIndex: (uint)this.QueueIndices.PresentFamily, queueCount: 1, pQueuePriorities: &queuePriority);
            }

            PhysicalDeviceFeatures features = default;

            using var extensionNames = SilkMarshal.StringArrayToMemory(RequiredDeviceExtensions);

            PhysicalDeviceSeparateDepthStencilLayoutsFeatures depthStencilFeature = new PhysicalDeviceSeparateDepthStencilLayoutsFeatures
            {
                SType = StructureType.PhysicalDeviceSeparateDepthStencilLayoutsFeatures,
                SeparateDepthStencilLayouts = true
            };

            DeviceCreateInfo createInfo = new DeviceCreateInfo
            {
                SType = StructureType.DeviceCreateInfo,
                //PNext = &depthStencilFeature,
                QueueCreateInfoCount    = infoCount,
                PQueueCreateInfos       = queueInfos,
                EnabledExtensionCount   = (uint)RequiredDeviceExtensions.Length,
                PpEnabledExtensionNames = (byte **)extensionNames,
                PEnabledFeatures        = &features
            };

            Device device;
            var    res = VkApi.CreateDevice(this.PhysicalDevice, &createInfo, null, &device);

            if (res != Result.Success)
            {
                throw new VMASharp.VulkanResultException("Logical Device Creation Failed!", res);
            }

            Queue queue = default;

            VkApi.GetDeviceQueue(device, (uint)this.QueueIndices.GraphicsFamily, 0, &queue);

            GraphicsQueue = queue;

            if (this.QueueIndices.GraphicsFamily != this.QueueIndices.PresentFamily)
            {
                queue = default;
                VkApi.GetDeviceQueue(device, (uint)this.QueueIndices.PresentFamily, 0, &queue);
            }

            PresentQueue = queue;

            return(device);
        }
Пример #4
0
        protected override unsafe ID3D12RootSignature *CreateRootSignature()
        {
            using ComPtr <ID3D10Blob> signature = null;
            using ComPtr <ID3D10Blob> error     = null;

            var rootSignatureDesc = new RootSignatureDesc
            {
                Flags = RootSignatureFlags.RootSignatureFlagAllowInputAssemblerInputLayout
            };

            SilkMarshal.ThrowHResult
            (
                D3D12.SerializeRootSignature
                (
                    &rootSignatureDesc, D3DRootSignatureVersion.D3DRootSignatureVersion1, signature.GetAddressOf(),
                    error.GetAddressOf()
                )
            );

            ID3D12RootSignature *rootSignature;

            var iid = ID3D12RootSignature.Guid;

            SilkMarshal.ThrowHResult
            (
                D3DDevice->CreateRootSignature
                (
                    nodeMask: 0, signature.Get().GetBufferPointer(), signature.Get().GetBufferSize(), &iid,
                    (void **)&rootSignature
                )
            );

            return(rootSignature);
        }
Пример #5
0
        private void VerifyDeviceExtensionsAvailable(Vk vk, PhysicalDevice physicalDevice, List <string> extensions, ref List <string> layers)
        {
            var  copy          = extensions.ToList();
            uint propertyCount = 0;

            vk.EnumerateDeviceExtensionProperties(physicalDevice, (byte *)null, ref propertyCount, null).ThrowCode();
            var properties = (ExtensionProperties *)SilkMarshal.Allocate((int)(propertyCount * sizeof(ExtensionProperties)));

            vk.EnumerateDeviceExtensionProperties(physicalDevice, (byte *)null, ref propertyCount, properties).ThrowCode();
            for (int i = 0; i < propertyCount; i++)
            {
                var name = SilkMarshal.PtrToString((nint)properties[i].ExtensionName);
                copy.Remove(name);
            }

            foreach (var ext in copy)
            {
                if (ext == KhrSynchronization2.ExtensionName)
                {
                    layers.Add("VK_LAYER_KHRONOS_synchronization2");
                    Console.WriteLine("Attempting to enable VK_LAYER_KHRONOS_synchronization2");
                }

                Console.WriteLine($"Missing {ext}");
            }
        }
Пример #6
0
        /// <summary>
        /// To be added.
        /// </summary>
        /// <param name="shaderObj">
        /// To be added.
        /// </param>
        /// <param name="count">
        /// To be added.
        /// </param>
        /// <param name="@string">
        /// To be added.
        /// This parameter's element count is taken from count.
        /// </param>
        /// <param name="length">
        /// To be added.
        /// This parameter's element count is taken from count.
        /// </param>
        public unsafe void ShaderSource([Flow(FlowDirection.In)] uint shaderObj, [Flow(FlowDirection.In)] uint count, [Count(Parameter = "count"), Flow(FlowDirection.In)] string[] @stringSa, [Count(Parameter = "count"), Flow(FlowDirection.In)] Span <int> length)
        {
            // StringArrayOverloader
            var @string = (char **)SilkMarshal.MarshalStringArrayToPtr(@stringSa);

            ShaderSource(shaderObj, count, @string, length);
            SilkMarshal.CopyPtrToStringArray((IntPtr)@string, @stringSa);
        }
Пример #7
0
 public static unsafe void RunApp(int numArgs, byte **args, Action <string[]> callback)
 {
     BeginRun();
     CurrentMain = (inNumArgs, argsPtr) => callback(SilkMarshal.PtrToStringArray((IntPtr)argsPtr, inNumArgs));
     CoreRunApp(numArgs, args, GetCallMainPtr());
     CurrentMain = null;
     EndRun();
 }
Пример #8
0
        /// <summary>
        /// To be added.
        /// </summary>
        /// <param name="program">
        /// To be added.
        /// </param>
        /// <param name="count">
        /// To be added.
        /// </param>
        /// <param name="varyings">
        /// To be added.
        /// This parameter's element count is taken from count.
        /// </param>
        /// <param name="bufferMode">
        /// To be added.
        /// </param>
        public unsafe void TransformFeedbackVaryings([Flow(FlowDirection.In)] uint program, [Flow(FlowDirection.In)] uint count, [Count(Parameter = "count"), Flow(FlowDirection.In)] string[] varyingsSa, [Flow(FlowDirection.In)] EXT bufferMode)
        {
            // StringArrayOverloader
            var varyings = (char **)SilkMarshal.MarshalStringArrayToPtr(varyingsSa);

            TransformFeedbackVaryings(program, count, varyings, bufferMode);
            SilkMarshal.CopyPtrToStringArray((IntPtr)varyings, varyingsSa);
        }
Пример #9
0
        /// <summary>
        /// To be added.
        /// </summary>
        /// <param name="shader">
        /// To be added.
        /// </param>
        /// <param name="count">
        /// To be added.
        /// </param>
        /// <param name="path">
        /// To be added.
        /// This parameter's element count is taken from count.
        /// </param>
        /// <param name="length">
        /// To be added.
        /// This parameter's element count is taken from count.
        /// </param>
        public unsafe void CompileShaderInclude([Flow(FlowDirection.In)] uint shader, [Flow(FlowDirection.In)] uint count, [Count(Parameter = "count"), Flow(FlowDirection.In)] string[] pathSa, [Count(Parameter = "count"), Flow(FlowDirection.In)] Span <int> length)
        {
            // StringArrayOverloader
            var path = (char **)SilkMarshal.MarshalStringArrayToPtr(pathSa);

            CompileShaderInclude(shader, count, path, length);
            SilkMarshal.CopyPtrToStringArray((IntPtr)path, pathSa);
        }
        /// <summary>
        /// To be added.
        /// </summary>
        /// <param name="program">
        /// To be added.
        /// </param>
        /// <param name="uniformCount">
        /// To be added.
        /// </param>
        /// <param name="uniformNames">
        /// To be added.
        /// This parameter's element count is computed from uniformCount.
        /// </param>
        /// <param name="uniformIndices">
        /// To be added.
        /// This parameter's element count is computed from uniformCount.
        /// </param>
        public unsafe void GetUniformIndices([Flow(FlowDirection.In)] uint program, [Flow(FlowDirection.In)] uint uniformCount, [Count(Computed = "uniformCount"), Flow(FlowDirection.In)] string[] uniformNamesSa, [Count(Computed = "uniformCount"), Flow(FlowDirection.Out)] uint *uniformIndices)
        {
            // StringArrayOverloader
            var uniformNames = (char **)SilkMarshal.MarshalStringArrayToPtr(uniformNamesSa);

            GetUniformIndices(program, uniformCount, uniformNames, uniformIndices);
            SilkMarshal.CopyPtrToStringArray((IntPtr)uniformNames, uniformNamesSa);
        }
Пример #11
0
        private unsafe void CreateInstance(IVkSurface vkSurface, string[] requestedExtensions, string[]?validationLayers, out Instance instance)
        {
            nint applicationName = Info.ApplicationName.Marshal();
            nint engineName      = Info.EngineName.Marshal();

            ApplicationInfo applicationInfo = new ApplicationInfo
            {
                SType              = StructureType.ApplicationInfo,
                PApplicationName   = (byte *)applicationName,
                ApplicationVersion = Info.ApplicationVersion,
                PEngineName        = (byte *)engineName,
                EngineVersion      = Info.EngineVersion,
                ApiVersion         = Info.APIVersion
            };

            string[] requiredExtensions        = VKAPI.GetRequiredExtensions(vkSurface, requestedExtensions);
            nint     requiredExtensionsPointer = SilkMarshal.StringArrayToPtr(requiredExtensions);
            nint     enabledLayerNames         = 0x0;
            int      enabledLayerCount         = 0;

            InstanceCreateInfo createInfo = new InstanceCreateInfo
            {
                SType                   = StructureType.InstanceCreateInfo,
                PApplicationInfo        = &applicationInfo,
                PpEnabledExtensionNames = (byte **)requiredExtensionsPointer,
                EnabledExtensionCount   = (uint)requiredExtensions.Length,
                PpEnabledLayerNames     = (byte **)null !,
                EnabledLayerCount       = 0,
                PNext                   = (void *)null !
            };

            if (validationLayers is not null)
            {
                VKAPI.VerifyValidationLayerSupport(VK, validationLayers);

                enabledLayerNames = SilkMarshal.StringArrayToPtr(validationLayers);
                enabledLayerCount = validationLayers.Length;
                createInfo.PpEnabledLayerNames = (byte **)enabledLayerNames;
                createInfo.EnabledLayerCount   = (uint)enabledLayerCount;
            }

            Log.Information(string.Format(FormatHelper.DEFAULT_LOGGING, nameof(VulkanInstance), "allocating instance."));
            Result result = VK.CreateInstance(&createInfo, (AllocationCallbacks *)null !, out instance);

            if (result is not Result.Success)
            {
                throw new VulkanException(result, "Failed to create Vulkan instance.");
            }

            SilkMarshal.FreeString(applicationName);
            SilkMarshal.FreeString(engineName);
            SilkMarshal.FreeString(requiredExtensionsPointer);

            if (enabledLayerNames is not 0x0 && enabledLayerCount is not 0)
            {
                SilkMarshal.FreeString(enabledLayerNames);
            }
        }
Пример #12
0
        public static unsafe void RunApp(IReadOnlyList <string> args, IntPtr callback)
        {
            BeginRun();
            var argsPtr = SilkMarshal.StringArrayToPtr(args);

            CoreRunApp(args.Count, (byte **)argsPtr, callback);
            SilkMarshal.Free(argsPtr);
            EndRun();
        }
Пример #13
0
        /// <summary>
        /// To be added.
        /// </summary>
        /// <param name="type">
        /// To be added.
        /// </param>
        /// <param name="count">
        /// To be added.
        /// </param>
        /// <param name="strings">
        /// To be added.
        /// This parameter's element count is taken from count.
        /// </param>
        /// <returns>See summary.</returns>
        public unsafe uint CreateShaderProgram([Flow(FlowDirection.In)] ShaderType type, [Flow(FlowDirection.In)] uint count, [Count(Parameter = "count"), Flow(FlowDirection.In)] string[] stringsSa)
        {
            // StringArrayOverloader
            var strings = (char **)SilkMarshal.MarshalStringArrayToPtr(stringsSa);
            var ret     = CreateShaderProgram(type, count, strings);

            SilkMarshal.CopyPtrToStringArray((IntPtr)strings, stringsSa);
            return(ret);
        }
        private string[] GetWindowExtensions()
        {
            var ptr = (IntPtr)this.DisplayWindow.VkSurface.GetRequiredExtensions(out uint count);

            string[] arr = new string[count];

            SilkMarshal.CopyPtrToStringArray(ptr, arr);

            return(arr);
        }
Пример #15
0
        public static unsafe void RunApp(IReadOnlyList <string> args, Action <string[]> callback)
        {
            BeginRun();
            var argsPtr = SilkMarshal.StringArrayToPtr(args);

            CurrentMain = (numArgs, inArgsPtr) => callback(SilkMarshal.PtrToStringArray((IntPtr)inArgsPtr, numArgs));
            CoreRunApp(args.Count, (byte **)argsPtr, GetCallMainPtr());
            CurrentMain = null;
            SilkMarshal.Free(argsPtr);
            EndRun();
        }
Пример #16
0
        public static unsafe void RunApp(IReadOnlyList <string> args, MainFunction callback)
        {
            BeginRun();
            var argsPtr = SilkMarshal.StringArrayToPtr(args);

            CurrentMain = callback;
            CoreRunApp(args.Count, (byte **)argsPtr, GetCallMainPtr());
            CurrentMain = null;
            SilkMarshal.Free(argsPtr);
            EndRun();
        }
Пример #17
0
        public override unsafe void LoadLibraries()
        {
            base.LoadLibraries();
            if (!(Instance is null))
            {
                throw new InvalidOperationException("Only one SilkActivity may be present throughout the whole application.");
            }

            Instance = this;
            SetupMain(SilkMarshal.DelegateToPtr(CurrentMain));
        }
Пример #18
0
        private static unsafe PipelineShaderStageCreateInfo ShaderStageCreateInfo(ShaderModule module, ShaderStageFlags stage)
        {
            return(new PipelineShaderStageCreateInfo()
            {
                SType = StructureType.PipelineShaderStageCreateInfo,

                Module = module,
                PName = (byte *)SilkMarshal.StringToPtr("main"),
                PSpecializationInfo = null,
                Stage = stage
            });
        }
Пример #19
0
 private unsafe void Name(ObjectType type, ulong handle, string name)
 {
     if (_debugUtils is not null)
     {
         var ptr = SilkMarshal.StringToPtr(name);
         _debugUtils.SetDebugUtilsObjectName(_logicalDevice,
                                             new DebugUtilsObjectNameInfoEXT(objectType: type, objectHandle: handle,
                                                                             pObjectName: (byte *)ptr))
         .ThrowCode();
         SilkMarshal.Free(ptr);
     }
 }
Пример #20
0
        protected virtual ID3D12Resource *CreateDepthStencil()
        {
            ID3D12Resource *depthStencil;

            var heapProperties = new HeapProperties(HeapType.HeapTypeDefault);

            var resourceDesc = new ResourceDesc
                               (
                ResourceDimension.ResourceDimensionTexture2D,
                0ul,
                (ulong)Size.X,
                (uint)Size.Y,
                1,
                1,
                DepthBufferFormat,
                new SampleDesc()
            {
                Count = 1, Quality = 0
            },
                TextureLayout.TextureLayoutUnknown,
                ResourceFlags.ResourceFlagAllowDepthStencil
                               );

            var clearValue = new ClearValue(DepthBufferFormat, depthStencil: new DepthStencilValue(1.0f, 0));

            var iid = ID3D12Resource.Guid;

            SilkMarshal.ThrowHResult
            (
                D3DDevice->CreateCommittedResource
                (
                    &heapProperties, HeapFlags.HeapFlagNone, &resourceDesc, ResourceStates.ResourceStateDepthWrite,
                    &clearValue, &iid, (void **)&depthStencil
                )
            );

            var dsvDesc = new DepthStencilViewDesc
            {
                Format        = DepthBufferFormat,
                ViewDimension = DsvDimension.DsvDimensionTexture2D
            };

            D3DDevice->CreateDepthStencilView(depthStencil, &dsvDesc, DSVHeap->GetCPUDescriptorHandleForHeapStart());

            return(depthStencil);
        }
Пример #21
0
        public override void OnRender()
        {
            PopulateGraphicsCommandList();
            ExecuteGraphicsCommandList();

            SilkMarshal.ThrowHResult(_swapChain->Present(SyncInterval: 1, Flags: 0));
            WaitForGpu(moveToNextFrame: true);

            void PopulateGraphicsCommandList()
            {
                WaitForGpu(moveToNextFrame: false);

                SilkMarshal.ThrowHResult(CommandAllocator->Reset());
                SilkMarshal.ThrowHResult(GraphicsCommandList->Reset(CommandAllocator, PipelineState));

                SetGraphicsCommandListState();

                TransitionForRender();

                var backgroundColor = BackgroundColor;

                // in d3dx12.h:
                // new CpuDescriptorHandle(RTVHeap->GetCPUDescriptorHandleForHeapStart(), (int)FrameIndex,
                //                         RTVDescriptorSize)
                var rtvHandle = new CpuDescriptorHandle
                {
                    Ptr = (nuint)((long)@RTVHeap->GetCPUDescriptorHandleForHeapStart().Ptr +
                                  ((long)FrameIndex * (long)RTVDescriptorSize))
                };

                GraphicsCommandList->ClearRenderTargetView(rtvHandle, (float *)&backgroundColor, 0, null);

                var dsvHandle = DSVHeap->GetCPUDescriptorHandleForHeapStart();

                GraphicsCommandList->ClearDepthStencilView(dsvHandle, ClearFlags.ClearFlagDepth, 1, 0, 0, null);

                GraphicsCommandList->OMSetRenderTargets(1, &rtvHandle, 0, &dsvHandle);

                Draw();
                TransitionForPresent();

                SilkMarshal.ThrowHResult(GraphicsCommandList->Close());
            }
        }
Пример #22
0
        protected virtual void CreateDescriptorHeaps()
        {
            _rtvHeap = CreateRTVHeap(out _rtvDescriptorSize);
            _dsvHeap = CreateDSVHeap();

            ID3D12DescriptorHeap *CreateDSVHeap()
            {
                var dsvHeapDesc = new DescriptorHeapDesc
                {
                    NumDescriptors = 1,
                    Type           = DescriptorHeapType.DescriptorHeapTypeDsv,
                };

                ID3D12DescriptorHeap *dsvHeap;

                var iid = ID3D12DescriptorHeap.Guid;

                SilkMarshal.ThrowHResult(D3DDevice->CreateDescriptorHeap(&dsvHeapDesc, &iid, (void **)&dsvHeap));

                return(dsvHeap);
            }

            ID3D12DescriptorHeap *CreateRTVHeap(out uint rtvDescriptorSize)
            {
                var rtvHeapDesc = new DescriptorHeapDesc
                {
                    NumDescriptors = FrameCount,
                    Type           = DescriptorHeapType.DescriptorHeapTypeRtv,
                };

                ID3D12DescriptorHeap *rtvHeap;

                var iid = ID3D12DescriptorHeap.Guid;

                SilkMarshal.ThrowHResult(D3DDevice->CreateDescriptorHeap(&rtvHeapDesc, &iid, (void **)&rtvHeap));

                rtvDescriptorSize = D3DDevice->GetDescriptorHandleIncrementSize
                                        (DescriptorHeapType.DescriptorHeapTypeRtv);
                return(rtvHeap);
            }
        }
Пример #23
0
        public static unsafe DeviceCreateInfo DeviceCreateInfo(string[] deviceExtensions, params DeviceQueueCreateInfo[] queues)
        {
            DeviceCreateInfo deviceCreateInfo = new()
            {
                SType = StructureType.DeviceCreateInfo,

                EnabledLayerCount       = 0,
                PpEnabledLayerNames     = null,
                EnabledExtensionCount   = (uint)deviceExtensions.Length,
                PpEnabledExtensionNames = (byte **)SilkMarshal.StringArrayToPtr(deviceExtensions),

                QueueCreateInfoCount = (uint)queues.Length
            };

            fixed(DeviceQueueCreateInfo *ptr = &queues[0])
            {
                deviceCreateInfo.PQueueCreateInfos = ptr;
            }

            return(deviceCreateInfo);
        }
Пример #24
0
        internal unsafe VulkanPhysicalDevice(Vk vk, VulkanContext context, PhysicalDevice physicalDevice) : base(vk)
        {
            if (context.Instance is null)
            {
                throw new NullReferenceException(nameof(context.Instance));
            }

            _Context        = context;
            _PhysicalDevice = physicalDevice;
            VK.GetPhysicalDeviceProperties(this, out PhysicalDeviceProperties properties);

            APIVersion    = properties.ApiVersion;
            DriverVersion = properties.DriverVersion;
            VendorID      = properties.VendorID;
            DeviceID      = properties.DeviceID;
            Type          = properties.DeviceType;
            Name          = SilkMarshal.PtrToString((nint)properties.DeviceName);

            SwapChainSupportDetails = GetSwapChainSupport();
            _Extensions             = GetExtensions();
        }
Пример #25
0
        private void VerifyInstanceExtensionsAvailable(Vk vk, List <string> extensions)
        {
            var  copy          = extensions.ToList();
            uint propertyCount = 0;

            vk.EnumerateInstanceExtensionProperties((byte *)null, ref propertyCount, null).ThrowCode();
            var properties = (ExtensionProperties *)SilkMarshal.Allocate((int)(propertyCount * sizeof(ExtensionProperties)));

            vk.EnumerateInstanceExtensionProperties((byte *)null, ref propertyCount, properties).ThrowCode();
            for (int i = 0; i < propertyCount; i++)
            {
                var name = SilkMarshal.PtrToString((nint)properties[i].ExtensionName);
                copy.Remove(name);
            }

            foreach (var ext in copy)
            {
                Console.WriteLine($"Missing {ext}");
                extensions.Remove(ext);
            }
        }
        private Instance CreateInstance()
        {
            using var appName    = SilkMarshal.StringToMemory("Hello Cube");
            using var engineName = SilkMarshal.StringToMemory("Custom Engine");

            var appInfo = new ApplicationInfo
                          (
                pApplicationName: (byte *)appName,
                applicationVersion: new Version32(0, 0, 1),
                pEngineName: (byte *)engineName,
                engineVersion: new Version32(0, 0, 1),
                apiVersion: Vk.Version11
                          );

            List <string> extensions = new List <string>(GetWindowExtensions())
            {
                Debugging.DebugExtensionString
            };

            string[] layers = new string[] { "VK_LAYER_KHRONOS_validation" };

            using var extList   = SilkMarshal.StringArrayToMemory(extensions);
            using var layerList = SilkMarshal.StringArrayToMemory(layers);

            var instInfo = new InstanceCreateInfo(pApplicationInfo: &appInfo,
                                                  enabledLayerCount: (uint)layers.Length,
                                                  ppEnabledLayerNames: (byte **)layerList,
                                                  enabledExtensionCount: (uint)extensions.Count,
                                                  ppEnabledExtensionNames: (byte **)extList);

            Instance inst;
            var      res = VkApi.CreateInstance(&instInfo, null, &inst);

            if (res != Result.Success)
            {
                throw new VMASharp.VulkanResultException("Instance Creation Failed", res);
            }

            return(inst);
        }
Пример #27
0
        public unsafe GLAPI()
        {
            // validate dependency or throw
            GL = AutomataWindow.Instance.GetOpenGLContext();

            string version = SilkMarshal.PtrToString((nint)GL.GetString(StringName.Version));

            Log.Information(string.Format(_LogFormat, $"OpenGL version {version}"));

            // configure debug callback
            GL.GetInteger(GetPName.ContextFlags, out int flags);

            if (!((ContextFlags)flags).HasFlag(ContextFlags.Debug))
            {
                return;
            }

            GL.Enable(EnableCap.DebugOutput);
            GL.Enable(EnableCap.DebugOutputSynchronous);
            GL.DebugMessageCallback(DebugOutputCallback, (void *)null !);
            GL.DebugMessageControl(DebugSource.DontCare, DebugType.DontCare, DebugSeverity.DontCare, 0, (uint *)null !, true);
        }
Пример #28
0
    public unsafe void TestALContextTryGetExtension(bool isPresent)
    {
        // never do anything demonstrated in this test
        using var loader = new LamdaNativeContext(GetLoader(isPresent, out var loaderPtr, out var ctxLoaderPtr));
        using var alc    = new ALContext(loader);

        void Test <T>() where T : NativeExtension <ALContext>
        {
            _testOutputHelper.WriteLine(typeof(T).ToString());
            Assert.Equal(alc.TryGetExtension(null, out T ext), isPresent);
            Assert.Equal(ext is not null, isPresent);
        }

        Test <Capture>();
        Test <Enumeration>();
        Test <EnumerateAll>();
        Test <CaptureEnumerationEnumeration>();
        Test <EffectExtensionContext>();

        SilkMarshal.Free(loaderPtr);
        SilkMarshal.Free(ctxLoaderPtr);
    }
Пример #29
0
        private static unsafe void CheckInstanceLayersPresent(string[] enabledInstanceLayers)
        {
            uint instanceLayerCount = 0;

            AssertVulkan(Vk.EnumerateInstanceLayerProperties(ref instanceLayerCount, null));
            Span <LayerProperties> props = stackalloc LayerProperties[(int)instanceLayerCount];

            AssertVulkan(Vk.EnumerateInstanceLayerProperties(ref instanceLayerCount, ref props[0]));
            List <string> names = new();

            foreach (LayerProperties prop in props)
            {
                names.Add(SilkMarshal.PtrToString((nint)prop.LayerName));
            }
            foreach (string layer in enabledInstanceLayers)
            {
                if (!names.Contains(layer))
                {
                    Console.Error.WriteLine("WARNING: Layer not present! Name: '" + layer + "'");
                }
            }
        }
Пример #30
0
        private static unsafe void Load()
        {
            _gl ??= GL.GetApi();
            var vertShader = _gl.CreateShader(GLEnum.VertexShader);
            var fragShader = _gl.CreateShader(GLEnum.FragmentShader);
            var vertLen    = VertexShader.Length;

            _gl.ShaderSource(vertShader, 1, SilkMarshal.ToPointer(new [] { VertexShader }), &vertLen);
            var fragLen = FragmentShader.Length;

            _gl.ShaderSource(fragShader, 1, SilkMarshal.ToPointer(new [] { FragmentShader }), &fragLen);
            _gl.CompileShader(vertShader);
            _gl.CompileShader(fragShader);
            _shader = _gl.CreateProgram();
            _gl.AttachShader(_shader, vertShader);
            _gl.AttachShader(_shader, fragShader);
            _gl.LinkProgram(_shader);
            _gl.DetachShader(_shader, vertShader);
            _gl.DetachShader(_shader, fragShader);
            _gl.DeleteShader(fragShader);
            _gl.DeleteShader(vertShader);
            _gl.ClearColor(0.2f, 0.3f, 0.3f, 1.0f);
            _vertexBufferObject = _gl.GenBuffer();
            _gl.BindBuffer(GLEnum.ArrayBuffer, _vertexBufferObject);
            fixed(void *vertices = _vertices)
            {
                _gl.BufferData(GLEnum.ArrayBuffer, (uint)_vertices.Length * sizeof(float), vertices, GLEnum.StaticDraw);
            }

            _vertexArrayObject = _gl.GenVertexArray();
            _gl.BindVertexArray(_vertexArrayObject);
            var attrib = 0;

            _gl.VertexAttribPointer(0, 3, GLEnum.Float, false, 3 * sizeof(float), &attrib);
            _gl.EnableVertexAttribArray(0);
            _gl.BindBuffer(GLEnum.ArrayBuffer, _vertexBufferObject);
            Console.WriteLine("done load");
        }