Esempio n. 1
0
 internal void Submit(SubmitInfo submitInfo, Fence fence = default)
 {
     lock (_lock)
     {
         Api.QueueSubmit(Queue.InternalHandle, 1, submitInfo, fence).ThrowOnError();
     }
 }
        private static void RechieveItsPaper(AssessActivity assessActivity)
        {
            SqlCommand cmd = new SqlCommand();

            cmd.Parameters.Add(_AssessActivityID, SqlDbType.Int).Value =
                assessActivity.AssessActivityID;
            using (
                SqlDataReader sdr =
                    SqlHelper.ExecuteReader("GetAssessActivityPaperById", cmd))
            {
                while (sdr.Read())
                {
                    SubmitInfo submitInfo = new SubmitInfo();
                    submitInfo.Choose         = sdr[_DbChoseIntention].ToString();
                    submitInfo.Comment        = sdr[_DbContent].ToString();
                    submitInfo.FillPerson     = sdr[_DbFillPerson].ToString();
                    submitInfo.StepIndex      = Convert.ToInt32(sdr[_DbStepIndex]);
                    submitInfo.SubmitTime     = Convert.ToDateTime(sdr[_DbSubmitTime]);
                    submitInfo.SalaryNow      = EmployeeWelfare.ConvertToDecimal(sdr[_DbSalaryNow]);
                    submitInfo.SalaryChange   = EmployeeWelfare.ConvertToDecimal(sdr[_DbSalaryChange]);
                    submitInfo.SubmitInfoType =
                        SubmitInfoType.RechieveSubmitInfoTypeByID(Convert.ToInt32(sdr[_DbType]));
                    assessActivity.ItsAssessActivityPaper.SubmitInfoes.Add(submitInfo);

                    int paperID = Convert.ToInt32(sdr[_DbPKID]);
                    submitInfo.SubmitInfoID = paperID;
                    RechieveItsSubmitInfo(paperID, submitInfo);
                }
            }
        }
Esempio n. 3
0
        void CopyBufferToImage(Queue queue, CommandPool cmdPool, ImageData imageData, Buffer imageBuffer)
        {
            var cmdBuffers = AllocateCommandBuffers(cmdPool, 1);
            var cmdBuffer  = cmdBuffers[0];

            var beginInfo = new CommandBufferBeginInfo();

            cmdBuffer.Begin(beginInfo);

            PipelineBarrierSetLayout(cmdBuffer, imageData.Image, ImageLayout.Preinitialized, ImageLayout.TransferDstOptimal, AccessFlags.HostWrite, AccessFlags.TransferWrite);

            var subresource = new ImageSubresourceLayers(ImageAspectFlags.Color, 0, 0, 1);
            var imageCopy   = new BufferImageCopy(0, 0, 0, subresource, new Offset3D(0, 0, 0), new Extent3D(imageData.Width, imageData.Height, 1));

            cmdBuffer.CopyBufferToImage(imageBuffer, imageData.Image, ImageLayout.TransferDstOptimal, new BufferImageCopy[] { imageCopy });

            PipelineBarrierSetLayout(cmdBuffer, imageData.Image, ImageLayout.TransferDstOptimal, ImageLayout.ColorAttachmentOptimal, AccessFlags.TransferWrite, AccessFlags.ColorAttachmentWrite);

            cmdBuffer.End();

            var submitInfo = new SubmitInfo(null, null, new[] { cmdBuffer }, null);

            queue.Submit(new[] { submitInfo });
            submitInfo.Dispose();
            queue.WaitIdle();

            device.FreeCommandBuffers(cmdPool, new[] { cmdBuffer });
        }
        public void DrawFrame()
        {
            vkPresentQueue.WaitIdle();

            uint imageIndex = vkDevice.AcquireNextImageKHR(vkSwapChain, ulong.MaxValue, vkImageAvailableSemaphore);

            var submitInfo = new SubmitInfo()
            {
                WaitSemaphores   = new Semaphore[] { vkImageAvailableSemaphore },
                WaitDstStageMask = new PipelineStageFlags[] { PipelineStageFlags.ColorAttachmentOutput },
                CommandBuffers   = new CommandBuffer[] { vkCommandBuffers[imageIndex] },
                SignalSemaphores = new Semaphore[] { vkRenderFinishedSemaphore },
            };

            vkGraphicsQueue.Submit(submitInfo);

            var presentInfo = new PresentInfoKhr()
            {
                WaitSemaphores = new Semaphore[] { vkRenderFinishedSemaphore },
                Swapchains     = new SwapchainKhr[] { vkSwapChain },
                ImageIndices   = new uint[] { imageIndex },
            };

            vkPresentQueue.PresentKHR(presentInfo);
        }
Esempio n. 5
0
        void SubmitForExecution(Queue queue, CommandBuffer cmdBuffer)
        {
            var submitInfo = new SubmitInfo(null, null, new[] { cmdBuffer }, null);

            queue.Submit(new[] { submitInfo });
            submitInfo.Dispose();
        }
Esempio n. 6
0
        public override void DrawFrame()
        {
            if (!initialized)
            {
                return;
            }

            uint nextIndex = device.AcquireNextImageKHR(swapchain, ulong.MaxValue, semaphore);

            device.ResetFence(fence);
            var submitInfo = new SubmitInfo {
                WaitSemaphores   = new Semaphore [] { semaphore },
                WaitDstStageMask = new PipelineStageFlags [] { PipelineStageFlags.AllGraphics },
                CommandBuffers   = new CommandBuffer [] { commandBuffers [nextIndex] }
            };

            queue.Submit(submitInfo, fence);
            device.WaitForFence(fence, true, 100000000);
            var presentInfo = new PresentInfoKhr {
                Swapchains   = new SwapchainKhr [] { swapchain },
                ImageIndices = new uint [] { nextIndex }
            };

            queue.PresentKHR(presentInfo);
        }
Esempio n. 7
0
        public void Flush()
        {
            if (this.setupCommanBuffer == CommandBuffer.Null)
            {
                return;
            }

            var setupCommanBuffer = this.setupCommanBuffer;

            this.setupCommanBuffer.End();

            var submitInfo = new SubmitInfo
            {
                StructureType      = StructureType.SubmitInfo,
                CommandBufferCount = 1,
                CommandBuffers     = new IntPtr(&setupCommanBuffer)
            };

            queue.Submit(1, &submitInfo, Fence.Null);

            queue.WaitIdle();

            device.FreeCommandBuffers(commandPool, 1, &setupCommanBuffer);

            this.setupCommanBuffer = CommandBuffer.Null;
        }
Esempio n. 8
0
        public static async Task SubscriberDataUpdaterOrchestrator(
            [OrchestrationTrigger] DurableOrchestrationContext ctx,
            ILogger log
            )
        {
            SubmitInfo submitInfo = ctx.GetInput <SubmitInfo>();
            await ctx.CallActivityAsync <string>("SendConfirmationEmail", new UpdaterOrchestratorData()
            {
                SubmitInfo = submitInfo, InstanceId = ctx.InstanceId
            });

            using (CancellationTokenSource timeoutCts = new CancellationTokenSource())
            {
                DateTime    dueTime        = ctx.CurrentUtcDateTime.AddHours(1);
                Task        durableTimeout = ctx.CreateTimer(dueTime, timeoutCts.Token);
                Task <bool> approvalEvent  = ctx.WaitForExternalEvent <bool>($"ApprovalEvent");
                if (approvalEvent == await Task.WhenAny(approvalEvent, durableTimeout)) //Terminate after 1 hour without confirmation event
                {
                    timeoutCts.Cancel();
                    bool updateResult = await ctx.CallActivityAsync <bool>("UpdateSubscriberInfo", submitInfo);

                    log.LogInformation($"Update finished for: {submitInfo.Email} with result {updateResult}");
                }
                else
                {
                    log.LogInformation($"Update timeout for: {submitInfo.Email}");
                }
            }
        }
Esempio n. 9
0
        protected void SubmitForExecution(Queue queue, Semaphore presentSemaphore, CommandBuffer cmdBuffer)
        {
            var submitInfo = new SubmitInfo(new[] { presentSemaphore }, null, new[] { cmdBuffer }, null);

            queue.Submit(new[] { submitInfo });
            submitInfo.Dispose();
        }
Esempio n. 10
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            [OrchestrationClient] DurableOrchestrationClient starter,
            ILogger log)
        {
            try
            {
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                log.LogInformation(requestBody);

                SubmitInfo submitInfo = JsonConvert.DeserializeObject <SubmitInfo>(requestBody);
                log.LogInformation($"Subscription submited by {submitInfo.Email} with treshold {submitInfo.AlertThreshold}");
                if (!string.IsNullOrWhiteSpace(submitInfo.Email) && submitInfo.AlertThreshold.HasValue && submitInfo.AlertThreshold.Value >= 0)
                {
                    string instanceId = await starter.StartNewAsync("SubscriberDataUpdaterOrchestrator", submitInfo);

                    return(new OkObjectResult($"Thank you, {submitInfo.Email}! Please wait for confirmation e-mail."));
                }
                else
                {
                    return(new BadRequestObjectResult("Activation not sucessfull. Please pass valid email and threshold level"));
                }
            }
            catch (Exception ex)
            {
                log.LogInformation(ex.StackTrace);
                return(new BadRequestObjectResult(ex.ToString()));
            }
        }
        private SubmitOutput GetTestResults(SubmitInfo info)
        {
            string date = DateTime.Now.ToString("m/dd/yyyy");

            (List <CheckResult> checks, int c, string msg) = TestManager.Test(info.SubmissionID, 0);
            StringBuilder builder = new StringBuilder($"Exercise Submitted successfully. Date Submitted: {date}");

            if (c == 4)
            {
                builder.AppendLine("This submission will be checked later.");
                builder.Replace("\n", "<br>");
                return(new SubmitOutput {
                    Text = builder.ToString(),
                    AutoGrade = -1,
                    StyleGrade = -1
                });
            }
            else if (c != 0)
            {
                throw new Exception();
            }
            else
            {
                Result result = new Result(checks);
                builder.Append(HttpUtility.HtmlEncode(result.ToString()));
                builder.Replace("\n", "<br>");
                return(new SubmitOutput {
                    Text = builder.ToString(),
                    AutoGrade = (int)Math.Round(result.GetTestsGrade()),
                    StyleGrade = 0
                });
            }
        }
Esempio n. 12
0
        private void InsertItemTable(int assessActivityPaperID, SubmitInfo submitInfo)
        {
            SqlCommand cmd = new SqlCommand();

            for (int i = 0; i < submitInfo.ItsAssessActivityItems.Count; i++)
            {
                cmd.Parameters.Add(_AssessActivityPaperID, SqlDbType.Int).Value = assessActivityPaperID;
                cmd.Parameters.Add(_ItemType, SqlDbType.Int).Value           = submitInfo.SubmitInfoType.Id;
                cmd.Parameters.Add(_Question, SqlDbType.NVarChar, 100).Value =
                    submitInfo.ItsAssessActivityItems[i].Question;
                cmd.Parameters.Add(_Grade, SqlDbType.Decimal).Value =
                    submitInfo.ItsAssessActivityItems[i].Grade;
                cmd.Parameters.Add(_Note, SqlDbType.Text).Value =
                    submitInfo.ItsAssessActivityItems[i].Note;
                cmd.Parameters.Add(_Option, SqlDbType.NVarChar, 1000).Value =
                    submitInfo.ItsAssessActivityItems[i].Option;
                cmd.Parameters.Add(_Classfication, SqlDbType.Int).Value =
                    submitInfo.ItsAssessActivityItems[i].Classfication;
                cmd.Parameters.Add(_Description, SqlDbType.Text).Value =
                    submitInfo.ItsAssessActivityItems[i].Description;
                cmd.Parameters.Add(_AssessTemplateItemType, SqlDbType.Int).Value =
                    submitInfo.ItsAssessActivityItems[i].AssessTemplateItemType;
                cmd.Parameters.Add(_Weight, SqlDbType.Decimal).Value =
                    submitInfo.ItsAssessActivityItems[i].Weight;
                ExcuteTranscation("InsertAssessActivityItem", cmd);
            }
        }
 public void SendResults(SubmitInfo info, List <User> submitters)
 {
     foreach (User submitter in submitters)
     {
         string subject = $"Course {info.CourseID} Exercise {info.ExerciseName}";
         MaleUtils.SendMail(submitter.Email, subject, info.Text);
     }
 }
Esempio n. 14
0
        private string LinkResult(int assessActivityID, SubmitInfo submitInfo, out string btnText)
        {
            string linkResult = "";
            string strBack    = "";

            if (_IsBack)
            {
                strBack = "Back";
            }
            switch (submitInfo.SubmitInfoType.Id)
            {
            //SubmitInfoType.HRAssess
            case 0:
                linkResult = "HRFillAssess" + strBack + "Detail.aspx?assessActivityID=" +
                             SecurityUtil.DECEncrypt(assessActivityID.ToString()) + "&submitID=" +
                             SecurityUtil.DECEncrypt(submitInfo.SubmitInfoID.ToString());
                btnText = "HR考核意见";
                break;

            //SubmitInfoType.MyselfAssess
            case 1:
                linkResult = "PersonalFillAssess" + strBack + "Detail.aspx?assessActivityID=" +
                             SecurityUtil.DECEncrypt(assessActivityID.ToString()) + "&submitID=" +
                             SecurityUtil.DECEncrypt(submitInfo.SubmitInfoID.ToString());
                btnText = "自我评定";
                break;

            //SubmitInfoType.ManagerAssess
            case 2:
                linkResult = "ManagerFillAssess" + strBack + "Detail.aspx?assessActivityID=" +
                             SecurityUtil.DECEncrypt(assessActivityID.ToString()) + "&submitID=" +
                             SecurityUtil.DECEncrypt(submitInfo.SubmitInfoID.ToString());
                btnText = "主管考核意见";
                break;

            //SubmitInfoType.Approve
            case 3:
                linkResult = "CEOFillAssess" + strBack + "Detail.aspx?assessActivityID=" +
                             SecurityUtil.DECEncrypt(assessActivityID.ToString()) + "&submitID=" +
                             SecurityUtil.DECEncrypt(submitInfo.SubmitInfoID.ToString());
                btnText = "批阅意见";
                break;

            //SubmitInfoType.SummarizeCommment
            case 4:
                linkResult = "SummaryAssess" + strBack + "Detail.aspx?assessActivityID=" +
                             SecurityUtil.DECEncrypt(assessActivityID.ToString()) + "&submitID=" +
                             SecurityUtil.DECEncrypt(submitInfo.SubmitInfoID.ToString());
                btnText = "终结评语";
                break;

            default:
                btnText = "";
                break;
            }
            return(linkResult);
        }
Esempio n. 15
0
 private void PrepareAssessActivity()
 {
     for (int i = 0; i < _AssessActivity.DiyProcess.DiySteps.Count; i++)
     {
         SubmitInfo submitInfo = new SubmitInfo();
         submitInfo.StepIndex      = i;
         submitInfo.SubmitInfoType = ChangeDiyProcessToSubmitInfoType(_AssessActivity.DiyProcess.DiySteps[i].Status);
         _AssessActivity.ItsAssessActivityPaper.SubmitInfoes.Add(submitInfo);
     }
 }
Esempio n. 16
0
        public static async Task <bool> UpdateSubscriberInfo(
            [ActivityTrigger] SubmitInfo submitInfo,
            [Table("Subscribers")] CloudTable subscribersTable,
            [Table("HourlyAlertLevels")] CloudTable alertLevelsTable,
            ILogger log)
        {
            //DI of tables to object not possible
            SubscriberService subscriberService = new SubscriberService(alertLevelsTable, subscribersTable);

            return(await subscriberService.UpdateSubscriberData(submitInfo));
        }
        public void Submit(SubmitInfo pSubmit, Fence fence = null)
        {
            Result result;

            unsafe {
                result = Interop.NativeMethods.vkQueueSubmit(this.m, (UInt32)(pSubmit != null ? 1 : 0), pSubmit != null ? pSubmit.m : (Interop.SubmitInfo *) default(IntPtr), fence != null ? fence.m : default(UInt64));
                if (result != Result.Success)
                {
                    throw new ResultException(result);
                }
            }
        }
Esempio n. 18
0
    IEnumerator Post(SubmitInfo Info)
    {
        SubmitCallBack Call_Back;

        // Set server url and data to send
        string Submit_Url = Url + "/YourWebPage";

        // Post request to server
        var Request = new UnityWebRequest(Submit_Url, "POST");

        byte[] Body_Raw = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(Info));
        Request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(Body_Raw);
        Request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        Request.SetRequestHeader("Content-Type", "application/json");
        yield return(Request.Send());

        if (Request.responseCode == 200)
        {
            string Content = Request.downloadHandler.text;
            Call_Back = JsonConvert.DeserializeObject <SubmitCallBack>(Content);

            if (Call_Back.Your_CallBack == "Insert or Update your information")
            {
                // Save informations
                File_Manager.Save_Info();

                // Deactive submit score menu and active ten highscore
                Button_OnClick.Set_SubmitScoreMenu(false);
                Button_OnClick.Set_TopTenMenu(true);

                StartCoroutine(TopTen_Records(Info));
            }
            else if (Call_Back.Your_CallBack == "Name is taken")
            {
                // Server error
                Button_OnClick.Set_InteractableSubmitScore(true);
                Button_OnClick.Set_Error(true, "this name is taken");
            }
            else
            {
                // Server error
                Button_OnClick.Set_InteractableSubmitScore(true);
                Button_OnClick.Set_Error(true, "server error");
            }
        }
        else
        {
            // Server error
            Button_OnClick.Set_InteractableSubmitScore(true);
            Button_OnClick.Set_Error(true, "server error");
        }
    }
        public async Task <bool> UpdateSubscriberData(SubmitInfo submitInfo)
        {
            string[]       emailSplited = submitInfo.Email.Split("@");
            SubscriberInfo existingInfo = await _subscribersTable.GetTableEntity <SubscriberInfo>(emailSplited[1], emailSplited[0]);

            SubscriberInfo newSubscriberInfo = new SubscriberInfo()
            {
                PartitionKey   = emailSplited[1],
                RowKey         = emailSplited[0],
                Active         = true,
                AlertThreshold = submitInfo.AlertThreshold ?? 0
            };

            if (existingInfo != null)
            {
                newSubscriberInfo.ETag = existingInfo.ETag;
            }

            TableOperation subscribersTableOperation = null;

            if (existingInfo != null)
            {
                if ((submitInfo.AlertThreshold ?? 0) == 0)
                {
                    await DeleteAlertLevelsOperation(existingInfo.AlertThreshold, submitInfo.Email);

                    subscribersTableOperation = TableOperation.Delete(existingInfo);
                }
                else if (submitInfo.AlertThreshold != existingInfo.AlertThreshold)
                {
                    await DeleteAlertLevelsOperation(existingInfo.AlertThreshold, submitInfo.Email);
                    await InsertAlertLevelsOperation(submitInfo.AlertThreshold.Value, submitInfo.Email);

                    subscribersTableOperation = TableOperation.Replace(newSubscriberInfo);
                }
            }
            else
            {
                await InsertAlertLevelsOperation(submitInfo.AlertThreshold.Value, submitInfo.Email);

                subscribersTableOperation = TableOperation.Insert(newSubscriberInfo);
            }

            if (subscribersTableOperation != null)
            {
                await _subscribersTable.ExecuteAsync(subscribersTableOperation);

                return(true);
            }
            return(false);
        }
Esempio n. 20
0
        /// <summary>
        /// Executes multiple deferred command lists.
        /// </summary>
        /// <param name="count">Number of command lists to execute.</param>
        /// <param name="commandLists">The deferred command lists.</param>
        public unsafe void ExecuteCommandLists(int count, CompiledCommandList[] commandLists)
        {
            if (commandLists == null)
            {
                throw new ArgumentNullException(nameof(commandLists));
            }
            if (count > commandLists.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }

            var fenceValue = NextFenceValue++;

            // Create a fence
            var fenceCreateInfo = new FenceCreateInfo {
                StructureType = StructureType.FenceCreateInfo
            };
            var fence = nativeDevice.CreateFence(ref fenceCreateInfo);

            nativeFences.Enqueue(new KeyValuePair <long, Fence>(fenceValue, fence));

            // Collect resources
            var commandBuffers = stackalloc CommandBuffer[count];

            for (int i = 0; i < count; i++)
            {
                commandBuffers[i] = commandLists[i].NativeCommandBuffer;
                RecycleCommandListResources(commandLists[i], fenceValue);
            }

            // Submit commands
            var pipelineStageFlags   = PipelineStageFlags.BottomOfPipe;
            var presentSemaphoreCopy = presentSemaphore;
            var submitInfo           = new SubmitInfo
            {
                StructureType      = StructureType.SubmitInfo,
                CommandBufferCount = (uint)count,
                CommandBuffers     = new IntPtr(commandBuffers),
                WaitSemaphoreCount = presentSemaphore != Semaphore.Null ? 1U : 0U,
                WaitSemaphores     = new IntPtr(&presentSemaphoreCopy),
                WaitDstStageMask   = new IntPtr(&pipelineStageFlags),
            };

            lock (QueueLock) {
                NativeCommandQueue.Submit(1, &submitInfo, fence);
            }

            presentSemaphore = Semaphore.Null;
            nativeResourceCollector.Release();
            graphicsResourceLinkCollector.Release();
        }
Esempio n. 21
0
    IEnumerator TopTen_Records(SubmitInfo Info)
    {
        List <UserRecord> Records = new List <UserRecord>();

        // Set server url and data to send
        string Records_Url = Url + "/YourWebPage";

        // Post request to server
        var Request = new UnityWebRequest(Records_Url, "POST");

        byte[] Body_Raw = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(Info));
        Request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(Body_Raw);
        Request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        Request.SetRequestHeader("Content-Type", "application/json");
        yield return(Request.Send());

        if (Request.responseCode == 200)
        {
            string Content = Request.downloadHandler.text;
            Records = JsonConvert.DeserializeObject <List <UserRecord> >(Content);

            if (Records[0].Player_Information == "your server has error")
            {
                Button_OnClick.Set_RecordMessage("server error");
                Button_OnClick.Set_RecordLoading(false);
            }
            else if (Records[0].Player_Information == "There are no player yet")
            {
                Button_OnClick.Set_RecordMessage("list is empty!");
                Button_OnClick.Set_RecordLoading(false);
            }
            else
            {
                // Show records
                for (int i = 0; i < Records.Count - 1; i++)
                {
                    Button_OnClick.Set_RecordListView(i, (i + 1) + ". " + Records[i].Player_Information, Records[i].Player_HighScore);
                }

                // Set player record
                Button_OnClick.Set_RecordMessage(Records[Records.Count - 1].Player_Information + ": " + Records[Records.Count - 1].Player_HighScore);
            }
        }
        else
        {
            // Server error
            Button_OnClick.Set_RecordMessage("server error");
            Button_OnClick.Set_RecordLoading(false);
        }
    }
        internal unsafe long ExecuteCommandListInternal(CompiledCommandList commandList)
        {
            //if (nativeUploadBuffer != SharpVulkan.Buffer.Null)
            //{
            //    NativeDevice.UnmapMemory(nativeUploadBufferMemory);
            //    TemporaryResources.Enqueue(new BufferInfo(NextFenceValue, nativeUploadBuffer, nativeUploadBufferMemory));

            //    nativeUploadBuffer = SharpVulkan.Buffer.Null;
            //    nativeUploadBufferMemory = DeviceMemory.Null;
            //}

            var fenceValue = NextFenceValue++;

            // Create new fence
            var fenceCreateInfo = new FenceCreateInfo {
                StructureType = StructureType.FenceCreateInfo
            };
            var fence = nativeDevice.CreateFence(ref fenceCreateInfo);

            nativeFences.Enqueue(new KeyValuePair <long, Fence>(fenceValue, fence));

            // Collect resources
            RecycleCommandListResources(commandList, fenceValue);

            // Submit commands
            var nativeCommandBufferCopy = commandList.NativeCommandBuffer;
            var pipelineStageFlags      = PipelineStageFlags.BottomOfPipe;

            var submitInfo = new SubmitInfo
            {
                StructureType      = StructureType.SubmitInfo,
                CommandBufferCount = 1,
                CommandBuffers     = new IntPtr(&nativeCommandBufferCopy),
                WaitSemaphoreCount = 0U,
                WaitSemaphores     = IntPtr.Zero,
                WaitDstStageMask   = new IntPtr(&pipelineStageFlags),
            };

            using (QueueLock.ReadLock())
            {
                NativeCommandQueue.Submit(1, &submitInfo, fence);
            }

            nativeResourceCollector.Release();
            graphicsResourceLinkCollector.Release();

            return(fenceValue);
        }
Esempio n. 23
0
    public void Post_Score(string Name, int High_Score)
    {
        if (Name != Data_Manager.Get_PlayerName())
        {
            Data_Manager.Set_PlayerName(Name);
            Data_Manager.Set_HighScore(High_Score);

            // Generate hash
            string Hash_Data = Generate_Hash("Your info");
            Data_Manager.Set_PlayerHash(Hash_Data);
        }

        SubmitInfo Info = new SubmitInfo("Your data");

        StartCoroutine(Post(Info));
    }
Esempio n. 24
0
        public void CopyBuffer(string queue,
                               string src, string dest, int size)
        {
            if (!mBuffers.ContainsKey(src))
            {
                Misc.SafeInvoke(eErrorSpam, "No buffer named: " + src + "...");
                return;
            }
            if (!mBuffers.ContainsKey(dest))
            {
                Misc.SafeInvoke(eErrorSpam, "No buffer named: " + dest + "...");
                return;
            }
            if (!mCommandPools.ContainsKey(queue))
            {
                Misc.SafeInvoke(eErrorSpam, "No pool named: " + queue + "...");
                return;
            }

            CommandBufferAllocateInfo cbai = new CommandBufferAllocateInfo();

            cbai.Level = CommandBufferLevel.Primary;
            cbai.CommandBufferCount = 1;

            CommandBuffer   [] bufs = mCommandPools[queue].AllocateBuffers(cbai);

            CommandBufferBeginInfo cbbi = new CommandBufferBeginInfo(
                CommandBufferUsages.OneTimeSubmit);

            bufs[0].Begin(cbbi);

            BufferCopy bc = new BufferCopy(size, 0, 0);

            bufs[0].CmdCopyBuffer(mBuffers[src], mBuffers[dest], bc);

            bufs[0].End();

            SubmitInfo si = new SubmitInfo();

            si.CommandBuffers = new IntPtr[] { bufs[0].Handle };

            SubmitToQueue(si, queue, null);

            mQueueNames[queue].WaitIdle();

            bufs[0].Dispose();
        }
Esempio n. 25
0
        void DrawFrame()
        {
            uint nextIndex = device.AcquireNextImageKHR(swapchain, ulong.MaxValue, semaphore, fences [0]);

            device.ResetFences(fences);
            var submitInfo = new SubmitInfo {
                WaitSemaphores = new Semaphore [] { semaphore },
                CommandBuffers = new CommandBuffer [] { commandBuffers [nextIndex] }
            };

            queue.Submit(new SubmitInfo [] { submitInfo }, fences [0]);
            device.WaitForFences(fences, true, 100000000);
            var presentInfo = new PresentInfoKhr {
                Swapchains   = new SwapchainKhr [] { swapchain },
                ImageIndices = new uint [] { nextIndex }
            };

            queue.PresentKHR(presentInfo);
        }
Esempio n. 26
0
        internal unsafe long ExecuteCommandListInternal(CommandBuffer nativeCommandBuffer)
        {
            //if (nativeUploadBuffer != SharpVulkan.Buffer.Null)
            //{
            //    NativeDevice.UnmapMemory(nativeUploadBufferMemory);
            //    TemporaryResources.Enqueue(new BufferInfo(NextFenceValue, nativeUploadBuffer, nativeUploadBufferMemory));

            //    nativeUploadBuffer = SharpVulkan.Buffer.Null;
            //    nativeUploadBufferMemory = DeviceMemory.Null;
            //}

            // Create new fence
            var fenceCreateInfo = new FenceCreateInfo {
                StructureType = StructureType.FenceCreateInfo
            };
            var fence = nativeDevice.CreateFence(ref fenceCreateInfo);

            nativeFences.Enqueue(new KeyValuePair <long, Fence>(NextFenceValue, fence));

            // Submit commands
            var nativeCommandBufferCopy = nativeCommandBuffer;
            var pipelineStageFlags      = PipelineStageFlags.BottomOfPipe;

            var presentSemaphoreCopy = presentSemaphore;
            var submitInfo           = new SubmitInfo
            {
                StructureType      = StructureType.SubmitInfo,
                CommandBufferCount = 1,
                CommandBuffers     = new IntPtr(&nativeCommandBufferCopy),
                WaitSemaphoreCount = presentSemaphore != Semaphore.Null ? 1U : 0U,
                WaitSemaphores     = new IntPtr(&presentSemaphoreCopy),
                WaitDstStageMask   = new IntPtr(&pipelineStageFlags),
            };

            NativeCommandQueue.Submit(1, &submitInfo, fence);

            presentSemaphore = Semaphore.Null;
            NativeResourceCollector.Release();

            return(NextFenceValue++);
        }
Esempio n. 27
0
        private static void RechieveItsSubmitInfo(int paperID, SubmitInfo submitInfo)
        {
            SqlCommand cmd = new SqlCommand();

            cmd.Parameters.Add(_AssessActivityPaperID, SqlDbType.Int).Value = paperID;
            using (
                SqlDataReader sdr =
                    SqlHelper.ExecuteReader("GetAssessActivityItemByAssessActivityPaperId", cmd))
            {
                while (sdr.Read())
                {
                    AssessActivityItem assessActivityItem = new AssessActivityItem(sdr[_DbQuestion].ToString(), sdr[_DbOption].ToString(), (ItemClassficationEmnu)sdr[_DbClassfication], sdr[_DbDescription].ToString());
                    assessActivityItem.Grade = Convert.ToDecimal(sdr[_DbGrade]);
                    assessActivityItem.Note  = sdr[_DbNote].ToString();
                    assessActivityItem.AssessTemplateItemType = (AssessTemplateItemType)sdr[_DbAssessTemplateItemType];
                    assessActivityItem.Weight = Convert.ToDecimal(sdr[_DbWeight]);
                    assessActivityItem.AssessActivityItemType = (AssessActivityItemType)sdr[_DbType];
                    submitInfo.ItsAssessActivityItems.Add(assessActivityItem);
                }
            }
        }
Esempio n. 28
0
        List <ImageData> InitializeSwapchainImages(Queue queue, CommandPool cmdPool, Image[] images, Format imageFormat)
        {
            var cmdBuffers = AllocateCommandBuffers(cmdPool, 1);
            var cmdBuffer  = cmdBuffers.First();

            var inheritanceInfo = new CommandBufferInheritanceInfo();
            var beginInfo       = new CommandBufferBeginInfo {
                InheritanceInfo = inheritanceInfo
            };

            cmdBuffer.Begin(beginInfo);

            foreach (var img in images)
            {
                PipelineBarrierSetLayout(cmdBuffer, img, ImageLayout.Undefined, ImageLayout.PresentSrcKHR, AccessFlags.None, AccessFlags.None);
            }

            cmdBuffer.End();

            var submitInfo = new SubmitInfo(null, null, new[] { cmdBuffer }, null);

            queue.Submit(new[] { submitInfo });
            queue.WaitIdle();

            device.FreeCommandBuffers(cmdPool, new[] { cmdBuffer });

            var imageDatas = new List <ImageData>();

            foreach (var img in images)
            {
                var imgData = new ImageData();
                imgData.Image  = img;
                imgData.Width  = 800;
                imgData.Height = 600;
                imgData.View   = CreateImageView(img, imageFormat);
                imageDatas.Add(imgData);
            }

            return(imageDatas);
        }
Esempio n. 29
0
        ///<summary>
        ///</summary>
        ///<param name="submitInfo"></param>
        ///<param name="assessActivityID"></param>
        ///<returns></returns>
        public int UpdateAssessActivityPaper(SubmitInfo submitInfo, int assessActivityID)
        {
            InitializeTranscation();
            int affectRows;

            try
            {
                //update its main table
                SqlCommand cmd = new SqlCommand();
                cmd.Parameters.Add(_PKID, SqlDbType.Int).Value                    = submitInfo.SubmitInfoID;
                cmd.Parameters.Add(_AssessActivityID, SqlDbType.Int).Value        = assessActivityID;
                cmd.Parameters.Add(_PaperType, SqlDbType.Int).Value               = submitInfo.SubmitInfoType.Id;
                cmd.Parameters.Add(_FillPerson, SqlDbType.NVarChar, 50).Value     = submitInfo.FillPerson;
                cmd.Parameters.Add(_SubmitTime, SqlDbType.DateTime).Value         = submitInfo.SubmitTime;
                cmd.Parameters.Add(_ChoseIntention, SqlDbType.NVarChar, 50).Value = submitInfo.Choose;
                cmd.Parameters.Add(_Content, SqlDbType.Text).Value                = submitInfo.Comment;
                cmd.Parameters.Add(_StepIndex, SqlDbType.Int).Value               = submitInfo.StepIndex;
                cmd.Parameters.Add(_SalaryNow, SqlDbType.Decimal).Value           = submitInfo.SalaryNow;
                cmd.Parameters.Add(_SalaryChange, SqlDbType.Decimal).Value        = submitInfo.SalaryChange;
                affectRows = SqlHelper.TransExecuteNonQuery("UpdateAssessActivityPaper", cmd, _Conn, _Trans);

                //delete its item table
                DeleteItemTable(submitInfo.SubmitInfoID);

                //insert its item table
                InsertItemTable(submitInfo.SubmitInfoID, submitInfo);

                _Trans.Commit();
            }
            catch
            {
                _Trans.Rollback();
                throw;
            }
            finally
            {
                _Conn.Close();
            }
            return(affectRows);
        }
Esempio n. 30
0
        private void DrawFrame()
        {
            uint nextIndex = _device.AcquireNextImageKHR
                                 (_swapchain, ulong.MaxValue, _semaphore, _fences [0]);

            _device.ResetFences(_fences);
            var submitInfo = new SubmitInfo
            {
                WaitSemaphores = new [] { _semaphore },
                CommandBuffers = new [] { _commandBuffers [nextIndex] }
            };

            _queue.Submit(new [] { submitInfo }, _fences [0]);
            _device.WaitForFences(_fences, true, 100000000);
            var presentInfo = new PresentInfoKhr
            {
                Swapchains   = new [] { _swapchain },
                ImageIndices = new [] { nextIndex }
            };

            _queue.PresentKHR(presentInfo);
        }
Esempio n. 31
0
        /// <summary>
        /// Explicitly recreate buffer with given data. Usually called after a <see cref="GraphicsDevice"/> reset.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataPointer"></param>
        public unsafe void Recreate(IntPtr dataPointer)
        {
            var createInfo = new BufferCreateInfo
            {
                StructureType = StructureType.BufferCreateInfo,
                Size = (ulong)bufferDescription.SizeInBytes,
                Flags = BufferCreateFlags.None,
            };

            createInfo.Usage |= BufferUsageFlags.TransferSource;

            // We always fill using transfer
            //if (bufferDescription.Usage != GraphicsResourceUsage.Immutable)
                createInfo.Usage |= BufferUsageFlags.TransferDestination;

            if ((ViewFlags & BufferFlags.VertexBuffer) != 0)
            {
                createInfo.Usage |= BufferUsageFlags.VertexBuffer;
                NativeAccessMask |= AccessFlags.VertexAttributeRead;
                NativePipelineStageMask |= PipelineStageFlags.VertexInput;
            }

            if ((ViewFlags & BufferFlags.IndexBuffer) != 0)
            {
                createInfo.Usage |= BufferUsageFlags.IndexBuffer;
                NativeAccessMask |= AccessFlags.IndexRead;
                NativePipelineStageMask |= PipelineStageFlags.VertexInput;
            }

            if ((ViewFlags & BufferFlags.ConstantBuffer) != 0)
            {
                createInfo.Usage |= BufferUsageFlags.UniformBuffer;
                NativeAccessMask |= AccessFlags.UniformRead;
                NativePipelineStageMask |= PipelineStageFlags.VertexShader | PipelineStageFlags.FragmentShader;
            }

            if ((ViewFlags & BufferFlags.ShaderResource) != 0)
            {
                createInfo.Usage |= BufferUsageFlags.UniformTexelBuffer;
                NativeAccessMask |= AccessFlags.ShaderRead;
                NativePipelineStageMask |= PipelineStageFlags.VertexShader | PipelineStageFlags.FragmentShader;

                if ((ViewFlags & BufferFlags.UnorderedAccess) != 0)
                {
                    createInfo.Usage |= BufferUsageFlags.StorageTexelBuffer;
                    NativeAccessMask |= AccessFlags.ShaderWrite;
                }
            }

            // Create buffer
            NativeBuffer = GraphicsDevice.NativeDevice.CreateBuffer(ref createInfo);

            // Allocate memory
            var memoryProperties = MemoryPropertyFlags.DeviceLocal;
            if (bufferDescription.Usage == GraphicsResourceUsage.Staging)
            {
                throw new NotImplementedException();
            }
            else if (Usage == GraphicsResourceUsage.Dynamic)
            {
                memoryProperties = MemoryPropertyFlags.HostVisible | MemoryPropertyFlags.HostCoherent;
            }

            MemoryRequirements memoryRequirements;
            GraphicsDevice.NativeDevice.GetBufferMemoryRequirements(NativeBuffer, out memoryRequirements);

            AllocateMemory(memoryProperties, memoryRequirements);

            if (NativeMemory != DeviceMemory.Null)
            {
                GraphicsDevice.NativeDevice.BindBufferMemory(NativeBuffer, NativeMemory, 0);
            }

            if (SizeInBytes > 0)
            {
                // Begin copy command buffer
                var commandBufferAllocateInfo = new CommandBufferAllocateInfo
                {
                    StructureType = StructureType.CommandBufferAllocateInfo,
                    CommandPool = GraphicsDevice.NativeCopyCommandPool,
                    CommandBufferCount = 1,
                    Level = CommandBufferLevel.Primary
                };
                CommandBuffer commandBuffer;
                GraphicsDevice.NativeDevice.AllocateCommandBuffers(ref commandBufferAllocateInfo, &commandBuffer);
                var beginInfo = new CommandBufferBeginInfo { StructureType = StructureType.CommandBufferBeginInfo, Flags = CommandBufferUsageFlags.OneTimeSubmit };
                commandBuffer.Begin(ref beginInfo);

                // Copy to upload buffer
                if (dataPointer != IntPtr.Zero)
                {
                    if (Usage == GraphicsResourceUsage.Dynamic)
                    {
                        var uploadMemory = GraphicsDevice.NativeDevice.MapMemory(NativeMemory, 0, (ulong)SizeInBytes, MemoryMapFlags.None);
                        Utilities.CopyMemory(uploadMemory, dataPointer, SizeInBytes);
                        GraphicsDevice.NativeDevice.UnmapMemory(NativeMemory);
                    }
                    else
                    {
                        var sizeInBytes = bufferDescription.SizeInBytes;
                        SharpVulkan.Buffer uploadResource;
                        int uploadOffset;
                        var uploadMemory = GraphicsDevice.AllocateUploadBuffer(sizeInBytes, out uploadResource, out uploadOffset);

                        Utilities.CopyMemory(uploadMemory, dataPointer, sizeInBytes);

                        // Barrier
                        var memoryBarrier = new BufferMemoryBarrier(uploadResource, AccessFlags.HostWrite, AccessFlags.TransferRead, (ulong)uploadOffset, (ulong)sizeInBytes);
                        commandBuffer.PipelineBarrier(PipelineStageFlags.Host, PipelineStageFlags.Transfer, DependencyFlags.None, 0, null, 1, &memoryBarrier, 0, null);

                        // Copy
                        var bufferCopy = new BufferCopy
                        {
                            SourceOffset = (uint)uploadOffset,
                            DestinationOffset = 0,
                            Size = (uint)sizeInBytes
                        };
                        commandBuffer.CopyBuffer(uploadResource, NativeBuffer, 1, &bufferCopy);
                    }
                }
                else
                {
                    commandBuffer.FillBuffer(NativeBuffer, 0, (uint)bufferDescription.SizeInBytes, 0);
                }

                // Barrier
                var bufferMemoryBarrier = new BufferMemoryBarrier(NativeBuffer, AccessFlags.TransferWrite, NativeAccessMask);
                commandBuffer.PipelineBarrier(PipelineStageFlags.Transfer, PipelineStageFlags.AllCommands, DependencyFlags.None, 0, null, 1, &bufferMemoryBarrier, 0, null);

                // Close and submit
                commandBuffer.End();

                var submitInfo = new SubmitInfo
                {
                    StructureType = StructureType.SubmitInfo,
                    CommandBufferCount = 1,
                    CommandBuffers = new IntPtr(&commandBuffer),
                };

                lock (GraphicsDevice.QueueLock)
                {
                    GraphicsDevice.NativeCommandQueue.Submit(1, &submitInfo, Fence.Null);
                    GraphicsDevice.NativeCommandQueue.WaitIdle();
                    //commandBuffer.Reset(CommandBufferResetFlags.None);
                    GraphicsDevice.NativeDevice.FreeCommandBuffers(GraphicsDevice.NativeCopyCommandPool, 1, &commandBuffer);
                }

                InitializeViews();
            }
        }
Esempio n. 32
0
 public unsafe void Submit(uint submitCount, SubmitInfo* submits, Fence fence)
 {
     vkQueueSubmit(this, submitCount, submits, fence).CheckError();
 }
        private unsafe void CreateBackBuffers()
        {
            // Create the texture object
            var backBufferDescription = new TextureDescription
            {
                ArraySize = 1,
                Dimension = TextureDimension.Texture2D,
                Height = Description.BackBufferHeight,
                Width = Description.BackBufferWidth,
                Depth = 1,
                Flags = TextureFlags.RenderTarget,
                Format = Description.BackBufferFormat,
                MipLevels = 1,
                MultiSampleLevel = MSAALevel.None,
                Usage = GraphicsResourceUsage.Default
            };
            backbuffer.InitializeWithoutResources(backBufferDescription);

            var createInfo = new ImageViewCreateInfo
            {
                StructureType = StructureType.ImageViewCreateInfo,
                SubresourceRange = new ImageSubresourceRange(ImageAspectFlags.Color, 0, 1, 0, 1),
                Format = backbuffer.NativeFormat,
            };

            // We initialize swapchain images to PresentSource, since we swap them out while in this layout.
            backbuffer.NativeAccessMask = AccessFlags.MemoryRead;
            backbuffer.NativeLayout = ImageLayout.PresentSource;

            var imageMemoryBarrier = new ImageMemoryBarrier
            {
                StructureType = StructureType.ImageMemoryBarrier,
                SubresourceRange = new ImageSubresourceRange(ImageAspectFlags.Color, 0, 1, 0, 1),
                OldLayout = ImageLayout.Undefined,
                NewLayout = ImageLayout.PresentSource,
                SourceAccessMask = AccessFlags.None,
                DestinationAccessMask = AccessFlags.MemoryRead
            };

            var commandBuffer = GraphicsDevice.NativeCopyCommandBuffer;
            var beginInfo = new CommandBufferBeginInfo { StructureType = StructureType.CommandBufferBeginInfo };
            commandBuffer.Begin(ref beginInfo);

            var buffers = GraphicsDevice.NativeDevice.GetSwapchainImages(swapChain);
            swapchainImages = new SwapChainImageInfo[buffers.Length];

            for (int i = 0; i < buffers.Length; i++)
            {
                // Create image views
                swapchainImages[i].NativeImage = createInfo.Image = buffers[i];
                swapchainImages[i].NativeColorAttachmentView = GraphicsDevice.NativeDevice.CreateImageView(ref createInfo);

                // Transition to default layout
                imageMemoryBarrier.Image = buffers[i];
                commandBuffer.PipelineBarrier(PipelineStageFlags.AllCommands, PipelineStageFlags.AllCommands, DependencyFlags.None, 0, null, 0, null, 1, &imageMemoryBarrier);
            }

            // Close and submit
            commandBuffer.End();

            var submitInfo = new SubmitInfo
            {
                StructureType = StructureType.SubmitInfo,
                CommandBufferCount = 1,
                CommandBuffers = new IntPtr(&commandBuffer),
            };
            GraphicsDevice.NativeCommandQueue.Submit(1, &submitInfo, Fence.Null);
            GraphicsDevice.NativeCommandQueue.WaitIdle();
            commandBuffer.Reset(CommandBufferResetFlags.None);

            // Get next image
            currentBufferIndex = GraphicsDevice.NativeDevice.AcquireNextImage(swapChain, ulong.MaxValue, GraphicsDevice.GetNextPresentSemaphore(), Fence.Null);
            
            // Apply the first swap chain image to the texture
            backbuffer.SetNativeHandles(swapchainImages[currentBufferIndex].NativeImage, swapchainImages[currentBufferIndex].NativeColorAttachmentView);
        }
Esempio n. 34
0
        protected unsafe virtual void Draw()
        {
            var semaphoreCreateInfo = new SemaphoreCreateInfo { StructureType = StructureType.SemaphoreCreateInfo };
            var presentCompleteSemaphore = device.CreateSemaphore(ref semaphoreCreateInfo);

            try
            {
                // Get the index of the next available swapchain image
                currentBackBufferIndex = device.AcquireNextImage(this.swapchain, ulong.MaxValue, presentCompleteSemaphore, Fence.Null);
            }
            catch (SharpVulkanException e) when (e.Result == Result.ErrorOutOfDate)
            {
                // TODO: Handle resize and retry draw
                throw new NotImplementedException();
            }

            // Record drawing command buffer
            var beginInfo = new CommandBufferBeginInfo { StructureType = StructureType.CommandBufferBeginInfo };
            commandBuffer.Begin(ref beginInfo);
            DrawInternal();
            commandBuffer.End();

            // Submit
            var drawCommandBuffer = commandBuffer;
            var pipelineStageFlags = PipelineStageFlags.BottomOfPipe;
            var submitInfo = new SubmitInfo
            {
                StructureType = StructureType.SubmitInfo,
                WaitSemaphoreCount = 1,
                WaitSemaphores = new IntPtr(&presentCompleteSemaphore),
                WaitDstStageMask = new IntPtr(&pipelineStageFlags),
                CommandBufferCount = 1,
                CommandBuffers = new IntPtr(&drawCommandBuffer),
            };
            queue.Submit(1, &submitInfo, Fence.Null);

            // Present
            var swapchain = this.swapchain;
            var currentBackBufferIndexCopy = currentBackBufferIndex;
            var presentInfo = new PresentInfo
            {
                StructureType = StructureType.PresentInfo,
                SwapchainCount = 1,
                Swapchains = new IntPtr(&swapchain),
                ImageIndices = new IntPtr(&currentBackBufferIndexCopy)
            };
            queue.Present(ref presentInfo);

            // Wait
            queue.WaitIdle();

            device.ResetDescriptorPool(descriptorPool, DescriptorPoolResetFlags.None);

            // Cleanup
            device.DestroySemaphore(presentCompleteSemaphore);
        }
Esempio n. 35
0
        public void Flush()
        {
            if (this.setupCommanBuffer == CommandBuffer.Null)
                return;

            var setupCommanBuffer = this.setupCommanBuffer;

            this.setupCommanBuffer.End();

            var submitInfo = new SubmitInfo
            {
                StructureType = StructureType.SubmitInfo,
                CommandBufferCount = 1,
                CommandBuffers = new IntPtr(&setupCommanBuffer)
            };

            queue.Submit(1, &submitInfo, Fence.Null);

            queue.WaitIdle();

            device.FreeCommandBuffers(commandPool, 1, &setupCommanBuffer);

            this.setupCommanBuffer = CommandBuffer.Null;
        }
Esempio n. 36
0
 internal static unsafe extern Result vkQueueSubmit(Queue queue, uint submitCount, SubmitInfo* submits, Fence fence);
Esempio n. 37
0
        private unsafe void InitializeImage(DataBox[] dataBoxes)
        {
            var commandBuffer = GraphicsDevice.NativeCopyCommandBuffer;
            var beginInfo = new CommandBufferBeginInfo { StructureType = StructureType.CommandBufferBeginInfo };
            commandBuffer.Begin(ref beginInfo);

            if (dataBoxes != null && dataBoxes.Length > 0)
            {
                // Buffer-to-image copies need to be aligned to the pixel size and 4 (always a power of 2)
                var blockSize = Format.IsCompressed() ? NativeFormat.BlockSizeInBytes() : TexturePixelSize;
                var alignmentMask = (blockSize < 4 ? 4 : blockSize) - 1;

                int totalSize = dataBoxes.Length * alignmentMask;
                for (int i = 0; i < dataBoxes.Length; i++)
                {
                    totalSize += dataBoxes[i].SlicePitch;
                }

                SharpVulkan.Buffer uploadResource;
                int uploadOffset;
                var uploadMemory = GraphicsDevice.AllocateUploadBuffer(totalSize, out uploadResource, out uploadOffset);

                // Upload buffer barrier
                var bufferMemoryBarrier = new BufferMemoryBarrier(uploadResource, AccessFlags.HostWrite, AccessFlags.TransferRead, (ulong)uploadOffset, (ulong)totalSize);

                // Image barrier
                var initialBarrier = new ImageMemoryBarrier(NativeImage, ImageLayout.Undefined, ImageLayout.TransferDestinationOptimal, AccessFlags.None, AccessFlags.TransferWrite, new ImageSubresourceRange(NativeImageAspect));
                commandBuffer.PipelineBarrier(PipelineStageFlags.TopOfPipe, PipelineStageFlags.Transfer, DependencyFlags.None, 0, null, 1, &bufferMemoryBarrier, 1, &initialBarrier);

                // Copy data boxes to upload buffer
                var copies = new BufferImageCopy[dataBoxes.Length];
                for (int i = 0; i < copies.Length; i++)
                {
                    var slicePitch = dataBoxes[i].SlicePitch;

                    int arraySlice = i / MipLevels;
                    int mipSlice = i % MipLevels;
                    var mipMapDescription = GetMipMapDescription(mipSlice);

                    SubresourceLayout layout;
                    GraphicsDevice.NativeDevice.GetImageSubresourceLayout(NativeImage, new ImageSubresource(NativeImageAspect, (uint)arraySlice, (uint)mipSlice), out layout);

                    var alignment = ((uploadOffset + alignmentMask) & ~alignmentMask) - uploadOffset;
                    uploadMemory += alignment;
                    uploadOffset += alignment;

                    Utilities.CopyMemory(uploadMemory, dataBoxes[i].DataPointer, slicePitch);

                    // TODO VULKAN: Check if pitches are valid
                    copies[i] = new BufferImageCopy
                    {
                        BufferOffset = (ulong)uploadOffset,
                        ImageSubresource = new ImageSubresourceLayers(ImageAspectFlags.Color, (uint)arraySlice, 1, (uint)mipSlice),
                        BufferRowLength = 0, //(uint)(dataBoxes[i].RowPitch / pixelSize),
                        BufferImageHeight = 0, //(uint)(dataBoxes[i].SlicePitch / dataBoxes[i].RowPitch),
                        ImageOffset = new Offset3D(0, 0, arraySlice),
                        ImageExtent = new Extent3D((uint)mipMapDescription.Width, (uint)mipMapDescription.Height, 1)
                    };

                    uploadMemory += slicePitch;
                    uploadOffset += slicePitch;
                }

                // Copy from upload buffer to image
                fixed (BufferImageCopy* copiesPointer = &copies[0])
                {
                    commandBuffer.CopyBufferToImage(uploadResource, NativeImage, ImageLayout.TransferDestinationOptimal, (uint)copies.Length, copiesPointer);
                }

                IsInitialized = true;
            }

            // Transition to default layout
            var imageMemoryBarrier = new ImageMemoryBarrier(NativeImage,
                dataBoxes == null || dataBoxes.Length == 0 ? ImageLayout.Undefined : ImageLayout.TransferDestinationOptimal, NativeLayout,
                dataBoxes == null || dataBoxes.Length == 0 ? AccessFlags.None : AccessFlags.TransferWrite, NativeAccessMask, new ImageSubresourceRange(NativeImageAspect));
            commandBuffer.PipelineBarrier(PipelineStageFlags.Transfer, PipelineStageFlags.AllCommands, DependencyFlags.None, 0, null, 0, null, 1, &imageMemoryBarrier);

            // Close and submit
            commandBuffer.End();

            var submitInfo = new SubmitInfo
            {
                StructureType = StructureType.SubmitInfo,
                CommandBufferCount = 1,
                CommandBuffers = new IntPtr(&commandBuffer),
            };

            lock (GraphicsDevice.QueueLock)
            {
                GraphicsDevice.NativeCommandQueue.Submit(1, &submitInfo, Fence.Null);
                GraphicsDevice.NativeCommandQueue.WaitIdle();
                commandBuffer.Reset(CommandBufferResetFlags.None);
            }
        }