content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Diagnostics; using System.Buffers; using System.Threading.Tasks; namespace mxProject.Devs.DataGeneration.Fields { /// <summary> /// Basic implement of a field that generates a tuple of multiple values. /// </summary> public abstract class DataGeneratorTupleFieldBase : IDataGeneratorTupleField { /// <summary> /// Creates a new instance. /// </summary> /// <param name="fieldNames">The names of the fields.</param> /// <param name="valueTypes">The value types of the fields.</param> /// <param name="mayBeNull">A value that indicates whether the fields may return a null value.</param> protected DataGeneratorTupleFieldBase(string[] fieldNames, Type[] valueTypes, bool[] mayBeNull) { m_FieldNames = fieldNames; m_ValueTypes = valueTypes; m_MayBeNull = mayBeNull; } #region fields private readonly string[] m_FieldNames; private readonly Type[] m_ValueTypes; private readonly bool[] m_MayBeNull; /// <inheritdoc/> public int FieldCount { get { return m_FieldNames.Length; } } /// <inheritdoc/> public string GetFieldName(int index) { return m_FieldNames[index]; } /// <inheritdoc/> public Type GetValueType(int index) { return m_ValueTypes[index]; } #endregion /// <inheritdoc/> public bool MayBeNull(int index) { return m_MayBeNull[index]; } /// <inheritdoc/> public abstract ValueTask<IDataGeneratorTupleFieldEnumeration> CreateEnumerationAsync(int generateCount); } }
26.768116
113
0.609637
[ "MIT" ]
mxProject/DataGenerator
mxProject.Devs.DataGenerator/mxProject.Devs.DataGenerator/mxProject.Devs.DataGenerator/Devs/DataGeneration/Fields/DataGeneratorTupleFieldBase.cs
1,849
C#
using System.Reflection; using System.Runtime.InteropServices; // La información general de un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos valores de atributo para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("capalnegocio")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("capalnegocio")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde // COM, establezca el atributo ComVisible en true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM. [assembly: Guid("0eef7b4a-34c2-4ee0-8a9d-f24fdcee4b52")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión // utilizando el carácter "*", como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
41.166667
112
0.755061
[ "MIT" ]
NeoCast/kiosco
capalnegocio/Properties/AssemblyInfo.cs
1,500
C#
using AutoMapper; namespace SchoolDiary.Mapping { public interface IHaveCustomMappings { void CreateMappings(IMapperConfigurationExpression configuration); } }
18.2
74
0.752747
[ "MIT" ]
alenSavov/WebUni
SchoolDiary.Mapping/IHaveCustomMappings.cs
184
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Tomappto.Infrastructure; namespace Tomappto.Infrastructure.Migrations { [DbContext(typeof(TomatoesContext))] partial class TomatoesContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.10") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Tomappto.Domain.Aggregates.TomatoAggregate.Tomato", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier") .HasColumnName("TomatoId"); b.Property<string>("PickedBy") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("PickedOn") .HasColumnType("datetime2"); b.HasKey("Id"); b.ToTable("Tomatoes", "Tomappto"); b.HasData( new { Id = new Guid("8503ddab-6ea8-4b21-ae9d-e7b500490be1"), PickedBy = "Person1", PickedOn = new DateTime(2021, 9, 18, 11, 8, 9, 155, DateTimeKind.Local).AddTicks(9086) }, new { Id = new Guid("99ac725b-eb7c-4bd8-8070-35be26938531"), PickedBy = "Person2", PickedOn = new DateTime(2021, 9, 18, 11, 8, 9, 160, DateTimeKind.Local).AddTicks(9737) }, new { Id = new Guid("c500614b-30df-4e42-83b7-0b605b971499"), PickedBy = "Person3", PickedOn = new DateTime(2021, 9, 18, 11, 8, 9, 160, DateTimeKind.Local).AddTicks(9816) }); }); #pragma warning restore 612, 618 } } }
40.822581
118
0.499407
[ "MIT" ]
TarcisioIsrael/TestingMyWebAPI
V1/src/Tomappto.Infrastructure/Migrations/TomatoesContextModelSnapshot.cs
2,533
C#
namespace CoatiSoftware.SourcetrailExtension.Wizard { partial class WindowMessage { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WindowMessage)); this.buttonCancel = new System.Windows.Forms.Button(); this.buttonOK = new System.Windows.Forms.Button(); this.labelContent = new System.Windows.Forms.Label(); this.SuspendLayout(); // // buttonCancel // this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonCancel.Location = new System.Drawing.Point(13, 78); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(75, 23); this.buttonCancel.TabIndex = 0; this.buttonCancel.Text = "Cancel"; this.buttonCancel.UseVisualStyleBackColor = true; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // buttonOK // this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonOK.Location = new System.Drawing.Point(257, 78); this.buttonOK.Name = "buttonOK"; this.buttonOK.Size = new System.Drawing.Size(75, 23); this.buttonOK.TabIndex = 1; this.buttonOK.Text = "OK"; this.buttonOK.UseVisualStyleBackColor = true; this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click); // // labelContent // this.labelContent.AutoSize = true; this.labelContent.Location = new System.Drawing.Point(13, 13); this.labelContent.MaximumSize = new System.Drawing.Size(300, 0); this.labelContent.Name = "labelContent"; this.labelContent.Size = new System.Drawing.Size(44, 13); this.labelContent.TabIndex = 2; this.labelContent.Text = "Content"; // // WindowMessage // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(344, 113); this.Controls.Add(this.labelContent); this.Controls.Add(this.buttonOK); this.Controls.Add(this.buttonCancel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "WindowMessage"; this.Text = "Message"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.Label labelContent; } }
44.858696
163
0.589048
[ "Apache-2.0" ]
CoatiSoftware/vs-sourcetrail
SourcetrailExtension/Wizard/WindowMessage.Designer.cs
4,038
C#
using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UnityEngine_UI_ScrollRect_ScrollRectEvent : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int constructor(IntPtr l) { try { UnityEngine.UI.ScrollRect.ScrollRectEvent o; o=new UnityEngine.UI.ScrollRect.ScrollRectEvent(); pushValue(l,true); pushValue(l,o); return 2; } catch(Exception e) { return error(l,e); } } static public void reg(IntPtr l) { LuaUnityEvent_UnityEngine_Vector2.reg(l); getTypeTable(l,"UnityEngine.UI.ScrollRect.ScrollRectEvent"); createTypeMetatable(l,constructor, typeof(UnityEngine.UI.ScrollRect.ScrollRectEvent),typeof(LuaUnityEvent_UnityEngine_Vector2)); } }
30.04
130
0.776298
[ "MIT" ]
zhangjie0072/FairyGUILearn
Assets/Slua/LuaObject/Unity/Lua_UnityEngine_UI_ScrollRect_ScrollRectEvent.cs
753
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Reflection.PortableExecutable; namespace System.Reflection.Internal { internal abstract class MemoryBlockProvider : IDisposable { /// <summary> /// Creates and hydrates a memory block representing all data. /// </summary> /// <exception cref="IOException">Error while reading from the memory source.</exception> public AbstractMemoryBlock GetMemoryBlock() { return GetMemoryBlockImpl(0, Size); } /// <summary> /// Creates and hydrates a memory block representing data in the specified range. /// </summary> /// <param name="start">Starting offset relative to the beginning of the data represented by this provider.</param> /// <param name="size">Size of the resulting block.</param> /// <exception cref="IOException">Error while reading from the memory source.</exception> public AbstractMemoryBlock GetMemoryBlock(int start, int size) { // Add cannot overflow as it is the sum of two 32-bit values done in 64 bits. // Negative start or size is handle by overflow to greater than maximum size = int.MaxValue. if ((ulong)(unchecked((uint)start)) + unchecked((uint)size) > (ulong)this.Size) { Throw.ImageTooSmallOrContainsInvalidOffsetOrCount(); } return GetMemoryBlockImpl(start, size); } /// <exception cref="IOException">IO error while reading from the underlying stream.</exception> protected abstract AbstractMemoryBlock GetMemoryBlockImpl(int start, int size); /// <summary> /// Gets a seekable and readable <see cref="Stream"/> that can be used to read all data. /// The operations on the stream has to be done under a lock of <see cref="StreamConstraints.GuardOpt"/> if non-null. /// The image starts at <see cref="StreamConstraints.ImageStart"/> and has size <see cref="StreamConstraints.ImageSize"/>. /// It is the caller's responsibility not to read outside those bounds. /// </summary> public abstract Stream GetStream(out StreamConstraints constraints); /// <summary> /// The size of the data. /// </summary> public abstract int Size { get; } protected abstract void Dispose(bool disposing); public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } }
42.253968
130
0.641998
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/MemoryBlocks/MemoryBlockProvider.cs
2,662
C#
using System; using System.Collections.Generic; using System.Linq; namespace ClosedXML.Excel { using System.Collections; internal class XLTables : IXLTables { private readonly Dictionary<String, IXLTable> _tables; internal ICollection<String> Deleted { get; private set; } public XLTables() { _tables = new Dictionary<String, IXLTable>(); Deleted = new HashSet<String>(); } #region IXLTables Members public IEnumerator<IXLTable> GetEnumerator() { return _tables.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(IXLTable table) { _tables.Add(table.Name, table); } public IXLTable Table(Int32 index) { return _tables.ElementAt(index).Value; } public IXLTable Table(String name) { return _tables[name]; } #endregion IXLTables Members public IXLTables Clear(XLClearOptions clearOptions = XLClearOptions.All) { _tables.Values.ForEach(t => t.Clear(clearOptions)); return this; } public void Remove(Int32 index) { this.Remove(_tables.ElementAt(index).Key); } public void Remove(String name) { if (!_tables.ContainsKey(name)) throw new ArgumentOutOfRangeException(nameof(name), $"Unable to delete table because the table name {name} could not be found."); var table = _tables[name] as XLTable; _tables.Remove(name); if (table.RelId != null) Deleted.Add(table.RelId); } } }
25.833333
146
0.551075
[ "MIT" ]
crypto-rsa/ClosedXML
ClosedXML/Excel/Tables/XLTables.cs
1,789
C#
using GoodToCode.Shared.Configuration; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System; namespace GoodToCode.Subjects.Infrastructure { public partial class SubjectsDbContextDeploy : SubjectsDbContext { public SubjectsDbContextDeploy() : base(new DbContextOptionsBuilder<SubjectsDbContext>().Options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer(GetConnectionFromAzureSettings("Stack:Shared:SqlConnection")); //optionsBuilder.UseCosmos(GetConnectionFromAzureSettings("Stack:Shared:CosmosConnection")); } } public string GetConnectionFromAzureSettings(string configKey) { var builder = new ConfigurationBuilder(); builder.AddAzureAppConfigurationWithSentinel(Environment.GetEnvironmentVariable("AppSettingsConnection"), "Stack:Shared:Sentinel"); var config = builder.Build(); return config[configKey]; } } }
35.411765
144
0.667774
[ "Apache-2.0" ]
goodtocode/stack
deploy/Subjects.Infrastructure.Persistence.Migrations/SubjectsDbContextDeploy.cs
1,206
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the storagegateway-2013-06-30.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.StorageGateway.Model { /// <summary> /// Container for the parameters to the DescribeSMBSettings operation. /// Gets a description of a Server Message Block (SMB) file share settings from a file /// gateway. This operation is only supported for file gateways. /// </summary> public partial class DescribeSMBSettingsRequest : AmazonStorageGatewayRequest { private string _gatewayARN; /// <summary> /// Gets and sets the property GatewayARN. /// </summary> [AWSProperty(Required=true, Min=50, Max=500)] public string GatewayARN { get { return this._gatewayARN; } set { this._gatewayARN = value; } } // Check to see if GatewayARN property is set internal bool IsSetGatewayARN() { return this._gatewayARN != null; } } }
31.767857
112
0.680157
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/StorageGateway/Generated/Model/DescribeSMBSettingsRequest.cs
1,779
C#
using GGJ2020.Common; using GGJ2020.Managers; using TMPro; using UniRx; using UniRx.Async; using UnityEngine; using UnityEngine.SceneManagement; using Zenject; namespace GGJ2020.UIs { public class ResultPresenter : MonoBehaviour { [Inject] private ResultManager _resultManager; [SerializeField] private GameObject _canvas; [SerializeField] private TextMeshProUGUI _youEarned; [SerializeField] private TextMeshProUGUI _scoreText; [Inject] private ScoreManager _scoreManager; [SerializeField] private float fade1 = 1.0f; [SerializeField] private int waitMillSeconds = 1000; [SerializeField] private float fade2 = 1.0f; void Start() { _canvas.SetActive(false); _resultManager.IsResultShowing .Where(x => x) .Take(1) .Subscribe(_ => { ShowResultAsync().Forget(); }).AddTo(this); } private async UniTaskVoid ShowResultAsync() { _canvas.SetActive(true); _scoreText.color = Color.white.SetA(0); _youEarned.color = Color.white.SetA(0); await UniTask.Delay(800); var process1 = 0.0f; while (process1 < 1.0f) { process1 += (Time.deltaTime / fade1); _youEarned.color = _youEarned.color.SetA(Mathf.Lerp(0.0f, 1.0f, process1)); await UniTask.Yield(); } await UniTask.Delay(waitMillSeconds); _scoreText.text = $"{_scoreManager.TotalScore.Value}"; var process2 = 0.0f; while (process2 < 1.0f) { process2 += (Time.deltaTime / fade2); _scoreText.color = _scoreText.color.SetA(Mathf.Lerp(0.0f, 1.0f, process2)); await UniTask.Yield(); } await UniTask.Delay(3000); _resultManager.GoToTitleAsync().Forget(); } } }
30.318182
91
0.573213
[ "Apache-2.0" ]
TORISOUP/GGJ2020_Akiba_team2
Assets/GGJ2020/Scripts/UIs/ResultPresenter.cs
2,003
C#
namespace Invictus.Testing.LogicApps.Model { /// <summary> /// Represents the status in which the <see cref="LogicAppAction"/> is currently at. /// </summary> public enum LogicAppActionStatus { /// <summary> /// Logic App action run is not specified. /// </summary> NotSpecified = 0, /// <summary> /// Logic App action run is paused. /// </summary> Paused = 1, /// <summary> /// Logic App action run is running, /// </summary> Running = 2, /// <summary> /// Logic App action run is pending. /// </summary> Waiting = 4, /// <summary> /// Logic App action run is succeeded. /// </summary> Succeeded = 8, /// <summary> /// Logic App action run is skipped. /// </summary> SKipped = 16, /// <summary> /// Logic App action run is suspended. /// </summary> Suspended = 32, /// <summary> /// Logic App action run is cancelled. /// </summary> Cancelled = 64, /// <summary> /// Logic App action run is failed. /// </summary> Failed = 128, /// <summary> /// Logic App action run is faulted. /// </summary> Faulted = 256, /// <summary> /// Logic App action run is timed out. /// </summary> TimedOut = 512, /// <summary> /// Logic App action run is aborted. /// </summary> Aborted = 1024, /// <summary> /// Logic App action run is ignored. /// </summary> Ignored = 2048 } }
23.465753
88
0.469352
[ "MIT" ]
MichielVanwelsenaere/testing-framework
src/Invictus.Testing.LogicApps/Model/LogicAppActionStatus.cs
1,715
C#
using System.Windows.Controls; namespace WPFSample.Scatter.Custom { /// <summary> /// Interaction logic for View.xaml /// </summary> public partial class View : UserControl { public View() { InitializeComponent(); } } }
17.625
43
0.567376
[ "MIT" ]
Diademics-Pty-Ltd/LiveCharts2
samples/WPFSample/Scatter/Custom/View.xaml.cs
284
C#
// <auto-generated /> using HomeAPI.Backend.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace HomeAPI.Backend.Migrations { [DbContext(typeof(DataContext))] [Migration("20201101155202_AddNewsFeedSubscriptionsTable")] partial class AddNewsFeedSubscriptionsTable { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.4"); modelBuilder.Entity("HomeAPI.Backend.Models.Lighting.LightScene", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Data") .HasColumnType("TEXT"); b.Property<string>("Name") .HasColumnType("TEXT"); b.HasKey("Id"); b.ToTable("LightScenes"); }); modelBuilder.Entity("HomeAPI.Backend.Models.News.NewsFeedSubscription", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Name") .HasColumnType("TEXT"); b.Property<string>("Url") .HasColumnType("TEXT"); b.HasKey("Id"); b.ToTable("NewsFeedSubscriptions"); }); #pragma warning restore 612, 618 } } }
31.385965
88
0.534936
[ "MIT" ]
chwun/HomeAPI.Backend
HomeAPI.Backend/Migrations/20201101155202_AddNewsFeedSubscriptionsTable.Designer.cs
1,791
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseButton : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0)) { Debug.Log("Left mouse button pressed."); Vector3 mousePos = Input.mousePosition; Debug.Log(mousePos.x); Debug.Log(mousePos.y); } if (Input.GetMouseButtonDown(1)) { Debug.Log("Right mouse button pressed."); } if (Input.GetMouseButtonDown(2)) { Debug.Log("Middle mouse button pressed."); } } }
20.486486
54
0.558047
[ "MIT" ]
uppnrise/Tutor_UnityC-
Assets/Scripts/MouseInputAndMousePosition.cs
760
C#
/* Copyright (C) 2019 Interactive Brokers LLC. All rights reserved. This code is subject to the terms * and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */ using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using IBApi; using TWSLib; using System.Linq; using System.Runtime.InteropServices; namespace OrderConditionsParsingTestProject { [TestClass] public class ControlEventsTest { [TestMethod] public void TestEWrapperToEventsConsistency() { var eWrapperMethods = typeof(EWrapper).GetMethods(); var iTwsEventsMethods = typeof(ITwsEvents).GetMethods(); var missingMethods = eWrapperMethods.Except(iTwsEventsMethods, new MethodComparer()); Assert.AreEqual(0, missingMethods.Count(), "Not all EWrapper methods are mapped to ITwsEvents: " + string.Join(", ", missingMethods.Select(m => m.Name).ToArray())); } [TestMethod] public void TestITwsEventsDispIdConsistency() { var type = typeof(ITwsEvents); var nUnique = type.GetMethods().Select(m => ((DispIdAttribute.GetCustomAttribute(m, typeof(DispIdAttribute)) as DispIdAttribute) ?? new DispIdAttribute(-1)).Value).Distinct().Count(); Assert.AreEqual(type.GetMethods().Count(), nUnique, "Check ITwsEvents interface methods [DispId] attribute"); } [TestMethod] public void TestITwsToDelegatesConsistency() { var methods = typeof(ITwsEvents).GetMethods(); var missingDelegates = methods.Where(m => AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == "TWSLib").GetType("TWSLib.Tws+" + m.Name + "Delegate", false, true) == null); Assert.AreEqual(0, missingDelegates.Count(), "Following ITWSEvents methods does not have corresponding delegates: " + string.Join(", ", missingDelegates.Select(md => md.Name).ToArray())); var delegates = methods.ToDictionary(m => AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == "TWSLib").GetType("TWSLib.Tws+" + m.Name + "Delegate", false, true)); var notMatchedDelegates = delegates.Where(d => !d.Key.GetMethod("Invoke").GetParameters().Select(p => p.ParameterType).SequenceEqual(d.Value.GetParameters().Select(p => p.ParameterType))); Assert.AreEqual(0, notMatchedDelegates.Count(), "Following ITWSEvents methods does not match signature with their delegates: " + string.Join(", ", notMatchedDelegates.Select(d => d.Value.Name).ToArray())); } } }
51.509804
218
0.679863
[ "MIT" ]
data2wealth/Interactive-Brokers-TWS-API-Python
tests/TWSLibTestProject/ControlEventsTest.cs
2,629
C#
using Files.Shared.Enums; using Files.Shared.Extensions; using System.Collections.Generic; namespace Files.Filesystem.FilesystemHistory { public class StorageHistory : IStorageHistory { #region Public Properties public FileOperationType OperationType { get; private set; } public IList<IStorageItemWithPath> Source { get; private set; } public IList<IStorageItemWithPath> Destination { get; private set; } #endregion Public Properties #region Constructor public StorageHistory(FileOperationType operationType, IList<IStorageItemWithPath> source, IList<IStorageItemWithPath> destination) { OperationType = operationType; Source = source; Destination = destination; } public StorageHistory(FileOperationType operationType, IStorageItemWithPath source, IStorageItemWithPath destination) { OperationType = operationType; Source = source.CreateList(); Destination = destination.CreateList(); } #endregion Constructor #region Modify public void Modify(IStorageHistory newHistory) { OperationType = newHistory.OperationType; Source = newHistory.Source; Destination = newHistory.Destination; } public void Modify(FileOperationType operationType, IList<IStorageItemWithPath> source, IList<IStorageItemWithPath> destination) { OperationType = operationType; Source = source; Destination = destination; } public void Modify(FileOperationType operationType, IStorageItemWithPath source, IStorageItemWithPath destination) { OperationType = operationType; Source = source.CreateList(); Destination = destination.CreateList(); } #endregion Modify #region IDisposable public void Dispose() { Source = null; Destination = null; } #endregion IDisposable } }
29.236111
139
0.64228
[ "MIT" ]
devovercome/Files
src/Files.Uwp/Filesystem/StorageHistory/StorageHistory.cs
2,107
C#
 namespace Microsoft.ApplicationInsights { using System; using System.Collections.Generic; using System.Linq; internal static class EnumerableExtensions { public static double StdDev(this IEnumerable<double> sequence) { return StdDev(sequence, (e) => e); } public static double StdDev<T>(this IEnumerable<T> sequence, Func<T, double> selector) { if (sequence.Count() <= 0) { return 0; } double avg = sequence.Average(selector); double sum = sequence.Sum(e => Math.Pow(selector(e) - avg, 2)); return Math.Sqrt(sum / sequence.Count()); } } }
24.724138
94
0.55788
[ "MIT" ]
304NotModified/ApplicationInsights-dotnet
BASE/Test/Microsoft.ApplicationInsights.Test/Microsoft.ApplicationInsights.Tests/EnumerableExtensions.cs
719
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2020-05-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CloudFront.Model { /// <summary> /// A complex type that contains a Lambda function association. /// </summary> public partial class LambdaFunctionAssociation { private EventType _eventType; private bool? _includeBody; private string _lambdaFunctionARN; /// <summary> /// Gets and sets the property EventType. /// <para> /// Specifies the event type that triggers a Lambda function invocation. You can specify /// the following values: /// </para> /// <ul> <li> /// <para> /// <code>viewer-request</code>: The function executes when CloudFront receives a request /// from a viewer and before it checks to see whether the requested object is in the edge /// cache. /// </para> /// </li> <li> /// <para> /// <code>origin-request</code>: The function executes only when CloudFront sends a request /// to your origin. When the requested object is in the edge cache, the function doesn't /// execute. /// </para> /// </li> <li> /// <para> /// <code>origin-response</code>: The function executes after CloudFront receives a response /// from the origin and before it caches the object in the response. When the requested /// object is in the edge cache, the function doesn't execute. /// </para> /// </li> <li> /// <para> /// <code>viewer-response</code>: The function executes before CloudFront returns the /// requested object to the viewer. The function executes regardless of whether the object /// was already in the edge cache. /// </para> /// /// <para> /// If the origin returns an HTTP status code other than HTTP 200 (OK), the function doesn't /// execute. /// </para> /// </li> </ul> /// </summary> [AWSProperty(Required=true)] public EventType EventType { get { return this._eventType; } set { this._eventType = value; } } // Check to see if EventType property is set internal bool IsSetEventType() { return this._eventType != null; } /// <summary> /// Gets and sets the property IncludeBody. /// <para> /// A flag that allows a Lambda function to have read access to the body content. For /// more information, see <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-include-body-access.html">Accessing /// the Request Body by Choosing the Include Body Option</a> in the Amazon CloudFront /// Developer Guide. /// </para> /// </summary> public bool IncludeBody { get { return this._includeBody.GetValueOrDefault(); } set { this._includeBody = value; } } // Check to see if IncludeBody property is set internal bool IsSetIncludeBody() { return this._includeBody.HasValue; } /// <summary> /// Gets and sets the property LambdaFunctionARN. /// <para> /// The ARN of the Lambda function. You must specify the ARN of a function version; you /// can't specify a Lambda alias or $LATEST. /// </para> /// </summary> [AWSProperty(Required=true)] public string LambdaFunctionARN { get { return this._lambdaFunctionARN; } set { this._lambdaFunctionARN = value; } } // Check to see if LambdaFunctionARN property is set internal bool IsSetLambdaFunctionARN() { return this._lambdaFunctionARN != null; } } }
35.780303
152
0.602583
[ "Apache-2.0" ]
KenHundley/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/LambdaFunctionAssociation.cs
4,723
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Boogie; using Microsoft.Boogie.GraphUtil; using System.Diagnostics; using cba.Util; using Microsoft.Boogie.Houdini; using cba; namespace StaticAnalysis { class RHS { IWeight iw; CBAProgram program; List<IntraGraph> intraGraphs; Dictionary<string, IntraGraph> id2Graph; // Call Graph Dictionary<string, HashSet<IntraGraph>> Succ; Dictionary<string, HashSet<IntraGraph>> Pred; public TimeSpan computeTime { get; private set; } public RHS(CBAProgram program, IWeight iw) { this.iw = iw; this.program = program; intraGraphs = new List<IntraGraph>(); id2Graph = new Dictionary<string, IntraGraph>(); Succ = new Dictionary<string, HashSet<IntraGraph>>(); Pred = new Dictionary<string, HashSet<IntraGraph>>(); computeTime = TimeSpan.Zero; // Make all the graphs program.TopLevelDeclarations .OfType<Implementation>() .Iter(impl => intraGraphs.Add( new IntraGraph(impl, iw, p => { if (!id2Graph.ContainsKey(p)) return null; else return id2Graph[p].summary; } ))); intraGraphs.Iter(g => id2Graph.Add(g.Id, g)); intraGraphs.Iter(g => { Succ.Add(g.Id, new HashSet<IntraGraph>()); Pred.Add(g.Id, new HashSet<IntraGraph>()); }); intraGraphs.Iter(g => g.Callees .Where(s => id2Graph.ContainsKey(s)) .Iter(s => { Succ[g.Id].Add(id2Graph[s]); Pred[s].Add(g); } )); // assign priorities var sccs = new StronglyConnectedComponents<IntraGraph>( intraGraphs, new Adjacency<IntraGraph>(g => Succ[g.Id]), new Adjacency<IntraGraph>(g => Pred[g.Id])); sccs.Compute(); var priority = intraGraphs.Count; foreach (var scc in sccs) { /* if (scc.Count > 1) { Console.WriteLine("SCC size: {0}", scc.Count); scc.Iter(g => Console.WriteLine("{0}", g.Id)); } */ scc.Iter(g => g.priority = priority); priority--; } } public void Compute() { var begin = DateTime.Now; var worklist = new SortedSet<IntraGraph>(intraGraphs.First()); intraGraphs.Iter(g => worklist.Add(g)); while (worklist.Any()) { var proc = worklist.First(); worklist.Remove(proc); proc.Compute(); if (proc.summaryChanged) { Pred[proc.Id].Iter(g => worklist.Add(g)); } } computeTime = (DateTime.Now - begin); } public void ComputePreconditions() { var NameToImpl = new Func<string, Implementation>(name => BoogieUtil.findProcedureImpl(program.TopLevelDeclarations, name)); var main = id2Graph[program.mainProcName]; main.UpdatePrecondition(main.precondition.Top(NameToImpl(main.Id))); IntraGraph.TopDown = true; var worklist = new SortedSet<IntraGraph>(main); worklist.Add(main); var SetPrecondition = new Action<string, IWeight>((name, weight) => { var g = id2Graph[name]; var changed = g.UpdatePrecondition(weight); if(changed) worklist.Add(g); }); while (worklist.Any()) { var proc = worklist.First(); worklist.Remove(proc); proc.PropagatePrecondition(NameToImpl, SetPrecondition); } IntraGraph.TopDown = false; } public IWeight GetSummary(string procName) { return id2Graph[procName].summary; } public IWeight GetPrecondition(string procName) { return id2Graph[procName].precondition; } } class IntraGraph : IComparer<IntraGraph> { public string Id; public List<Node> Nodes; public List<Edge> Edges; public int priority; // Id -> node Dictionary<string, Node> idToNode; // callee --> src node Dictionary<string, HashSet<Node>> calleeToEdgeSrc; public IEnumerable<string> Callees { get { return calleeToEdgeSrc.Keys; } } // placeholder IWeight iw; // summary public IWeight summary { get; private set; } // summary changed? public bool summaryChanged { get; private set; } // precondition public IWeight precondition { get; private set; } // precondition changed? public bool preconditionChanged { get; private set; } // List of return nodes List<Node> returnNodes; // Entry node Node entryNode; // Implementation Implementation impl; // Has Compute been run before bool computedBefore; // Summary of other procedures Func<string, IWeight> ProcSummary; public IntraGraph(Implementation impl, IWeight iw, Func<string, IWeight> ProcSummary) { this.impl = impl; this.Id = impl.Name; this.ProcSummary = ProcSummary; priority = 0; idToNode = new Dictionary<string, Node>(); Nodes = new List<Node>(); Edges = new List<Edge>(); calleeToEdgeSrc = new Dictionary<string, HashSet<Node>>(); this.iw = iw; this.summary = iw.Zero(impl); this.precondition = iw.Zero(impl); returnNodes = new List<Node>(); summaryChanged = false; preconditionChanged = false; computedBefore = false; // Create nodes foreach (var block in impl.Blocks) { var n1 = new Node(block.Label + "::in", iw.Zero(impl)); var n2 = new Node(block.Label + "::out", iw.Zero(impl)); Nodes.Add(n1); Nodes.Add(n2); var edge = new Edge(n1, n2, block.Cmds.OfType<Cmd>()); n1.AddEdge(edge); n2.AddEdge(edge); Edges.Add(edge); // return nodes if (block.TransferCmd is ReturnCmd) { returnNodes.Add(n2); } // calls foreach (var callee in edge.Callees) { if (!calleeToEdgeSrc.ContainsKey(callee)) calleeToEdgeSrc.Add(callee, new HashSet<Node>()); calleeToEdgeSrc[callee].Add(n1); } } Nodes.Iter(n => idToNode.Add(n.Id, n)); entryNode = idToNode[impl.Blocks[0].Label + "::in"]; // connecting edges foreach (var block in impl.Blocks) { var gc = block.TransferCmd as GotoCmd; if (gc == null) continue; var src = idToNode[block.Label + "::out"]; var edges = gc.labelNames .OfType<string>() .Select(s => idToNode[s + "::in"]) .Select(tgt => new Edge(src, tgt, new Cmd[] { })); edges.Iter(e => { Edges.Add(e); e.src.AddEdge(e); e.tgt.AddEdge(e); }); } // Compute priorities var sccs = new StronglyConnectedComponents<Node>(Nodes, new Adjacency<Node>(n => n.Successors.Select(e => e.tgt)), new Adjacency<Node>(n => n.Predecessors.Select(e => e.src))); sccs.Compute(); int p = 0; foreach (var scc in sccs) { scc.Iter(n => n.priority = p); p++; } } public void Compute() { Compute(calleeToEdgeSrc.Keys); } public void Compute(IEnumerable<string> updatedCallees) { var worklist = new SortedSet<Node>(entryNode); summaryChanged = false; if (!computedBefore) { entryNode.weight = iw.GetInitial(impl); worklist.Add(entryNode); } else { updatedCallees.Iter(c => calleeToEdgeSrc[c].Iter(n => worklist.Add(n))); } computedBefore = true; while (worklist.Any()) { var node = worklist.First(); worklist.Remove(node); foreach (var edge in node.Successors) { var c = edge.Propagate(ProcSummary); if (c) worklist.Add(edge.tgt); } } // Compute summary foreach (var r in returnNodes) { var c = summary.Combine(r.weight); summaryChanged = summaryChanged || c; } } public void PropagatePrecondition(Func<string, Implementation> NameToImpl, Action<string, IWeight> SetPrecondition) { foreach (var node in Nodes) { node.weight = iw.Zero(impl); } entryNode.weight = precondition; var worklist = new SortedSet<Node>(entryNode); worklist.Add(entryNode); while (worklist.Any()) { var node = worklist.First(); worklist.Remove(node); foreach (var edge in node.Successors) { var c = edge.PropagatePrecondition(ProcSummary, NameToImpl, SetPrecondition); if (c) worklist.Add(edge.tgt); } } } public bool UpdatePrecondition(IWeight weight) { return precondition.Combine(weight); } public override string ToString() { return Id; } #region IComparer<IntraGraph> Members public static bool TopDown = false; public int Compare(IntraGraph x, IntraGraph y) { if (!TopDown) { var r = x.priority.CompareTo(y.priority); if (r != 0) return r; else return x.Id.CompareTo(y.Id); } else { var r = y.priority.CompareTo(x.priority); if (r != 0) return r; else return y.Id.CompareTo(x.Id); } } #endregion } class Node :IComparer<Node> { public string Id; public IWeight weight; public List<Edge> Successors; public List<Edge> Predecessors; public int priority; public Node(string Id, IWeight weight) { this.Id = Id; this.weight = weight; this.priority = 0; Successors = new List<Edge>(); Predecessors = new List<Edge>(); } public void AddEdge(Edge edge) { if (edge.src.Equals(this)) { Successors.Add(edge); } else if (edge.tgt.Equals(this)) { Predecessors.Add(edge); } else { Debug.Assert(false); } } public override string ToString() { return Id; } public override bool Equals(object obj) { var that = obj as Node; if(that == null) return false; return Id == that.Id; } public override int GetHashCode() { return Id.GetHashCode(); } #region IComparer<Node> Members public int Compare(Node x, Node y) { var r = x.priority.CompareTo(y.priority); if (r != 0) return r; else return x.Id.CompareTo(y.Id); } #endregion } class Edge { public Node src, tgt; public List<Cmd> cmds; public Edge(Node src, Node tgt, IEnumerable<Cmd> cmds) { this.src = src; this.tgt = tgt; this.cmds = new List<Cmd>(cmds); } public bool HasCallCmd { get { return cmds.Any(c => c is CallCmd); } } public IEnumerable<string> Callees { get { return cmds.OfType<CallCmd>().Select(c => c.callee); } } public bool Propagate(Func<string, IWeight> ProcSummary) { var weight = src.weight; foreach (var cmd in cmds) { if (cmd is CallCmd) { var callee = (cmd as CallCmd).callee; var summary = ProcSummary(callee); if (summary != null) { weight = weight.Extend(cmd as CallCmd, summary); continue; } } weight = weight.Extend(cmd); } return tgt.weight.Combine(weight); } public bool PropagatePrecondition(Func<string, IWeight> ProcSummary, Func<string, Implementation> NameToImpl, Action<string, IWeight> SetPrecondition) { var weight = src.weight; foreach (var cmd in cmds) { if (cmd is CallCmd) { var callee = (cmd as CallCmd).callee; var summary = ProcSummary(callee); if (summary != null) { SetPrecondition(callee, weight.ApplyCall(cmd as CallCmd, NameToImpl(callee))); weight = weight.Extend(cmd as CallCmd, summary); continue; } } weight = weight.Extend(cmd); } return tgt.weight.Combine(weight); } public override string ToString() { return string.Format("{0} --> {1}", src, tgt); } } public interface IWeight { IWeight Zero(Implementation impl); IWeight GetInitial(Implementation impl); // Do Join and return if the current weight changed? bool Combine(IWeight weight); // Apply transformation IWeight Extend(Cmd cmd); IWeight Extend(CallCmd cmd, IWeight summary); // For precondition computation IWeight Top(Implementation impl); IWeight ApplyCall(CallCmd cmd, Implementation callee); // print on console void Print(); } }
29.322034
123
0.474117
[ "MIT" ]
PLSysSec/corral
source/CoreLib/StaticAnalysis.cs
15,572
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Shopping.API { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
26.666667
71
0.620833
[ "MIT" ]
marius721/shopping
Shopping/Shopping.API/Program.cs
720
C#
#pragma checksum "..\..\..\..\Media\Controls\GradientChooser.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "569E657658C829D6CC4F8214BE5B544CBE11FF5A" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using Imagin.Common; using Imagin.Common.Converters; using Imagin.Common.Data; using Imagin.Common.Linq; using Imagin.Common.Markup; using Imagin.Common.Media; using Imagin.Common.Media.Controls; using Imagin.Common.Numerics; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace Imagin.Common.Media.Controls { /// <summary> /// GradientPicker /// </summary> public partial class GradientPicker : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector { #line 16 "..\..\..\..\Media\Controls\GradientChooser.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal Imagin.Common.Media.Controls.GradientPicker PART_GradientPicker; #line default #line hidden #line 165 "..\..\..\..\Media\Controls\GradientChooser.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Slider PART_BandsSlider; #line default #line hidden #line 185 "..\..\..\..\Media\Controls\GradientChooser.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal Imagin.Common.Media.Controls.ColorChip PART_ColorChip; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/Imagin.Common.WPF;component/media/controls/gradientchooser.xaml", System.UriKind.Relative); #line 1 "..\..\..\..\Media\Controls\GradientChooser.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal System.Delegate _CreateDelegate(System.Type delegateType, string handler) { return System.Delegate.CreateDelegate(delegateType, this, handler); } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.PART_GradientPicker = ((Imagin.Common.Media.Controls.GradientPicker)(target)); return; case 2: this.PART_BandsSlider = ((System.Windows.Controls.Slider)(target)); return; case 3: this.PART_ColorChip = ((Imagin.Common.Media.Controls.ColorChip)(target)); return; } this._contentLoaded = true; } } }
41.309524
151
0.666859
[ "BSD-2-Clause" ]
fritzmark/Imagin.NET
Imagin.Common.WPF/obj/Debug/Media/Controls/GradientChooser.g.i.cs
5,207
C#
using Superpower.Parsers; using Superpower.Tests.Support; using Xunit; namespace Superpower.Tests.Combinators { public class AtLeastOnceCombinatorTests { [Fact] public void AtLeastOnceSucceedsWithOne() { AssertParser.SucceedsWithAll(Character.EqualTo('a').AtLeastOnce(), "a"); } [Fact] public void AtLeastOnceSucceedsWithTwo() { AssertParser.SucceedsWithAll(Character.EqualTo('a').AtLeastOnce(), "aa"); } [Fact] public void AtLeastOnceFailsWithNone() { AssertParser.Fails(Character.EqualTo('a').AtLeastOnce(), ""); } [Fact] public void TokenAtLeastOnceSucceedsWithOne() { AssertParser.SucceedsWithAll(Token.EqualTo('a').AtLeastOnce(), "a"); } [Fact] public void TokenAtLeastOnceSucceedsWithTwo() { AssertParser.SucceedsWithAll(Token.EqualTo('a').AtLeastOnce(), "aa"); } [Fact] public void TokenAtLeastOnceFailsWithNone() { AssertParser.Fails(Token.EqualTo('a').AtLeastOnce(), ""); } } }
25.434783
85
0.586325
[ "Apache-2.0" ]
BenjaminHolland/superpower
test/Superpower.Tests/Combinators/AtLeastOnceCombinatorTests.cs
1,172
C#
using System; namespace Fracture.Common.Tests.Di.TestTypes { public sealed class FooBarSuper : FooBar { public FooBarSuper() { } public void SuperFooBar() { throw new NotImplementedException(); } } }
16.647059
48
0.540636
[ "MIT" ]
Babelz/Fracture
Fracture.Common.Tests/Di/TestTypes/FooBarSuper.cs
285
C#
#nullable enable namespace System { partial class Optional { public static Optional<T> Present<T>(T value) => new(value); public static Optional<T> Absent<T>() => default; public static Optional<T> Absent<T>(Unit unit) => unit switch { _ => default }; } }
17.454545
69
0.471354
[ "MIT" ]
pfpack/pfpack-core
src/core-taggeds-optional/Optional/Optional/Optional.Factory.cs
386
C#
using Microsoft.Diagnostics.Runtime; using System; using WHQ.Core.Model.Unified; namespace WHQ.Core.Handlers.UnmanagedStackFrameWalker.AMD64 { class StackFrameParmsFetchStrategy_Win_7 : StackFrameParmsFetchStrategy { public StackFrameParmsFetchStrategy_Win_7(ClrRuntime runtime) : base(runtime) { throw new NotImplementedException(); } /* WaitForSingleObject * * 1st: RCX (handle) * 000007fe`fd24102b 488bf9 mov rdi,rcx * 2nd - RDX (Timeout) * 000007fe`fd241029 8bf2 mov esi,edx */ /* EnterCriticalSection * * 1st: RCX (CRITICAL_SECTION ptr) * 00007ffd`b57310cb 488bf9 mov rdi,rcx */ internal override Params GetWaitForMultipleObjectsParams(UnifiedStackFrame frame) { throw new NotImplementedException(); Params result = new Params(); //1st: RCX (Wait Objects count) //000007fe`fd24155a 48894c2408 mov qword ptr [rsp+8],rcx var rspPtr = frame.StackPointer + 8; result.Third = base.ReadULong(rspPtr); //2nd - RDX (Array ptr) //3rd - R8: WaitAll (BOOLEAN) //4th - R9: Timeout (DWORD) return result; } } }
26.686275
89
0.572373
[ "MIT" ]
Pavel-Durov/Clr-md-tutorials
WHQ/WHQ.Core/Handlers/StackFrameWalker/Arch_AMD64/Strategies/StackFrameParmsFetchStrategy_Win_7.cs
1,363
C#
using BlazorHero.CleanArchitecture.Application.Features.Brands.Commands.AddEdit; using BlazorHero.CleanArchitecture.Client.Extensions; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.SignalR.Client; using MudBlazor; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using BlazorHero.CleanArchitecture.Application.Constants.Application; namespace BlazorHero.CleanArchitecture.Client.Pages.Catalog { public partial class AddEditBrandModal { private bool success; private string[] errors = { }; private MudForm form; [Parameter] public int Id { get; set; } [Parameter] [Required] public string Name { get; set; } [Parameter] [Required] public decimal Tax { get; set; } [Parameter] [Required] public string Description { get; set; } [CascadingParameter] private MudDialogInstance MudDialog { get; set; } [CascadingParameter] public HubConnection hubConnection { get; set; } public void Cancel() { MudDialog.Cancel(); } private async Task SaveAsync() { form.Validate(); if (form.IsValid) { var request = new AddEditBrandCommand() { Name = Name, Description = Description, Tax = Tax, Id = Id }; var response = await _brandManager.SaveAsync(request); if (response.Succeeded) { _snackBar.Add(localizer[response.Messages[0]], Severity.Success); MudDialog.Close(); } else { foreach (var message in response.Messages) { _snackBar.Add(localizer[message], Severity.Error); } } await hubConnection.SendAsync(ApplicationConstants.SignalR.SendUpdateDashboard); } } protected override async Task OnInitializedAsync() { await LoadDataAsync(); hubConnection = hubConnection.TryInitialize(_navigationManager); if (hubConnection.State == HubConnectionState.Disconnected) { await hubConnection.StartAsync(); } } private async Task LoadDataAsync() { await Task.CompletedTask; } } }
31.189873
119
0.578328
[ "MIT" ]
unchase/CleanArchitecture-1
BlazorHero.CleanArchitecture/Client/Pages/Catalog/AddEditBrandModal.razor.cs
2,466
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using BankingApplication; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BankingApplication.Tests { [TestClass()] public class SavingsAccountTests { [TestMethod()] public void SavingsAccountWithdrawTest1() { //Test for withdrawal of the right amount. Account acc1 = new SavingsAccount("Remi martims", 5000); Assert.AreEqual(true, acc1.Withdraw(3000)); Assert.AreEqual(2000, acc1.Balance); } [TestMethod()] public void SavingsAccountWithdrawTest2() { //Test for the withdral of a larger amount greater than the balance. Account acc1 = new SavingsAccount("Remi martims", 5000); Assert.AreEqual(false, acc1.Withdraw(6000)); Assert.AreEqual(5000, acc1.Balance); } [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void SavingsAccountWithdrawTest3() { //Test for the withdrawal of a negative value. Account acc1 = new SavingsAccount("Remi martims", 5000); Assert.AreEqual(false, acc1.Withdraw(-6000)); } [TestMethod()] [ExpectedException(typeof(FormatException))] public void SavingsAccountWithdrawTest4() { //Test for the widthral of an amount that is not a multiple of 50. Account acc1 = new SavingsAccount("Remi martims", 5000); Assert.AreEqual(false, acc1.Withdraw(3030)); } [TestMethod()] public void SavingsAccountDepositTest1() { //Test for deposit of the right amount. Account acc1 = new SavingsAccount("Samson Siasia", 20000); Assert.AreEqual(true, acc1.Deposit(10000)); Assert.AreEqual(30000, acc1.Balance); } [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void SavingsAccountDepositTest2() { //Test for deposit of a negative amount. Account acc1 = new SavingsAccount("Samson Siasia", 800); Assert.AreEqual(false, acc1.Deposit(-100)); } [TestMethod()] [ExpectedException(typeof(FormatException))] public void SavingsAccountDepositTest3() { //Test for the deposit of an amount that is not a multiple of 50. Account acc1 = new SavingsAccount("Samson Siasia", 800); Assert.AreEqual(false, acc1.Deposit(501)); } [TestMethod()] public void SavingsAccountInterestRateTest() { //Test for the addition of the interest rate. Account acc1 = new SavingsAccount("Alicia keys", 1000,20); Assert.AreEqual(true, acc1.Deposit(400)); Assert.AreEqual(true, acc1.Deposit(600)); Assert.AreEqual(0,Decimal.Compare(2033.33m, acc1.Balance)); } [TestMethod()] public void SavingsAccountTransferTest1() { //Transfer from a savings account to another savings accouunt. Account acc1 = new SavingsAccount("Jon justine", 6000); Account acc2 = new SavingsAccount("Bridget kelly", 8000); Assert.AreEqual(true, acc1.TransferTo(acc2, 2000)); Assert.AreEqual(4000, acc1.Balance); Assert.AreEqual(10000, acc2.Balance); } [TestMethod()] public void SavingsAccountTransferTest2() { //Transfer from a savings account to a current account. Account acc1 = new SavingsAccount("Jon justine", 1000); Account acc2 = new CurrentAccount("Bridget kelly", 8000); Assert.AreEqual(true, acc1.TransferTo(acc2, 500)); Assert.AreEqual(500, acc1.Balance); Assert.AreEqual(8500, acc2.Balance); } } }
34.912281
81
0.609548
[ "MIT" ]
AdePhil/Csc322-BankingApplicationProject
BankingApplication/BankingApplicationTests/SavingsAccountTests.cs
3,982
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; namespace MvcStudy.Models.Menu { public class MenuViewModel : tbl_menu { public IKitchenRepository DbRepository { get; set; } public List<MealViewModel> MealCollection { get; set; } public string DateView { get { return date.ToString("dd.MM.yyyy"); } } public string MealNameView { get; private set; } public bool Selected { get; set; } public int Qty { get; set; } public MenuViewModel() { Qty = 1; } public IEnumerable<SelectListItem> MealList { get { if (MealCollection == null) InitMealCollection(); if (!MealCollection.Any()) yield break; foreach (var meal in MealCollection) yield return new SelectListItem { Text = meal.meal_name, Value = meal.id.ToString(), Selected = (meal.id == id_meal) }; } } public MenuViewModel(tbl_menu sourceMenu) { id = sourceMenu.id; id_meal = sourceMenu.id_meal; date = sourceMenu.date; MealNameView = sourceMenu.tbl_meal.meal_name; Qty = 1; } public void InitMealCollection() { if (DbRepository == null) throw new Exception("Соединение с БД потеряно"); string error; MealCollection = DbRepository.GetMeals(null, out error).Select(x => new MealViewModel(x)).ToList(); } public static tbl_menu CreateClone(MenuViewModel source) { return new tbl_menu { id = source.id, date = source.date, id_meal = source.id_meal, }; } } }
26.064103
111
0.496311
[ "Apache-2.0" ]
dimidych/Kitchen
Kitchen/Models/Menu/MenuViewModel.cs
2,056
C#
using CustomLogoNavigationPage.Views; using Xamarin.Forms; namespace CustomLogoNavigationPage { public partial class App : Application { public App() { InitializeComponent(); MainPage = new CustomNavigationPage(new MainView()); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
19.903226
64
0.552674
[ "MIT" ]
jsuarezruiz/xamarin-forms-customnavigationpage
src/CustomLogoNavigationPage/CustomLogoNavigationPage/CustomLogoNavigationPage/App.xaml.cs
619
C#
using System; using System.Collections.Generic; using NBitcoin; using NBitcoin.BouncyCastle.Math; using NBitcoin.Rules; namespace Stratis.Bitcoin.Networks { public class X42Consensus : IConsensus { /// <inheritdoc /> public long CoinbaseMaturity { get; set; } /// <inheritdoc /> public Money PremineReward { get; } /// <inheritdoc /> public long PremineHeight { get; } /// <inheritdoc /> public Money ProofOfWorkReward { get; } /// <inheritdoc /> public Money ProofOfStakeReward { get; } /// <inheritdoc /> public uint MaxReorgLength { get; private set; } /// <inheritdoc /> public long MaxMoney { get; } public ConsensusOptions Options { get; set; } public BuriedDeploymentsArray BuriedDeployments { get; } public IBIP9DeploymentsArray BIP9Deployments { get; } public int SubsidyHalvingInterval { get; } public int MajorityEnforceBlockUpgrade { get; } public int MajorityRejectBlockOutdated { get; } public int MajorityWindow { get; } public uint256 BIP34Hash { get; } public Target PowLimit { get; } public TimeSpan PowTargetTimespan { get; } public TimeSpan PowTargetSpacing { get; } public bool PowAllowMinDifficultyBlocks { get; } /// <summary> /// If <c>true</c> disables checking the next block's difficulty (work required) target on a Proof-Of-Stake network. /// <para> /// This can be used in tests to enable fast mining of blocks. /// </para> /// </summary> public bool PosNoRetargeting { get; } /// <summary> /// If <c>true</c> disables checking the next block's difficulty (work required) target on a Proof-Of-Work network. /// <para> /// This can be used in tests to enable fast mining of blocks. /// </para> /// </summary> public bool PowNoRetargeting { get; } public uint256 HashGenesisBlock { get; } /// <inheritdoc /> public uint256 MinimumChainWork { get; } public int MinerConfirmationWindow { get; set; } public int RuleChangeActivationThreshold { get; set; } /// <inheritdoc /> public int CoinType { get; } public BigInteger ProofOfStakeLimit { get; } public BigInteger ProofOfStakeLimitV2 { get; } /// <inheritdoc /> public int LastPOWBlock { get; set; } /// <inheritdoc /> public bool IsProofOfStake { get; } /// <inheritdoc /> public uint256 DefaultAssumeValid { get; } /// <inheritdoc /> public ConsensusFactory ConsensusFactory { get; } /// <inheritdoc /> public List<IIntegrityValidationConsensusRule> IntegrityValidationRules { get; set; } /// <inheritdoc /> public List<IHeaderValidationConsensusRule> HeaderValidationRules { get; set; } /// <inheritdoc /> public List<IPartialValidationConsensusRule> PartialValidationRules { get; set; } /// <inheritdoc /> public List<IFullValidationConsensusRule> FullValidationRules { get; set; } public Money ProofOfStakeRewardAfterSubsidyLimit { get; } public long SubsidyLimit { get; } /// <inheritdoc /> public Money LastProofOfStakeRewardHeight { get; } public X42Consensus( ConsensusFactory consensusFactory, ConsensusOptions consensusOptions, int coinType, uint256 hashGenesisBlock, int subsidyHalvingInterval, int majorityEnforceBlockUpgrade, int majorityRejectBlockOutdated, int majorityWindow, BuriedDeploymentsArray buriedDeployments, IBIP9DeploymentsArray bip9Deployments, uint256 bip34Hash, int ruleChangeActivationThreshold, int minerConfirmationWindow, uint maxReorgLength, uint256 defaultAssumeValid, long maxMoney, long coinbaseMaturity, long premineHeight, Money premineReward, Money proofOfWorkReward, TimeSpan powTargetTimespan, TimeSpan powTargetSpacing, bool powAllowMinDifficultyBlocks, bool posNoRetargeting, bool powNoRetargeting, Target powLimit, uint256 minimumChainWork, bool isProofOfStake, int lastPowBlock, BigInteger proofOfStakeLimitV2, Money proofOfStakeReward, Money proofOfStakeRewardAfterSubsidyLimit, long subsidyLimit, Money lastProofOfStakeRewardHeight ) { this.IntegrityValidationRules = new List<IIntegrityValidationConsensusRule>(); this.HeaderValidationRules = new List<IHeaderValidationConsensusRule>(); this.PartialValidationRules = new List<IPartialValidationConsensusRule>(); this.FullValidationRules = new List<IFullValidationConsensusRule>(); this.CoinbaseMaturity = coinbaseMaturity; this.PremineReward = premineReward; this.PremineHeight = premineHeight; this.ProofOfWorkReward = proofOfWorkReward; this.ProofOfStakeReward = proofOfStakeReward; this.MaxReorgLength = maxReorgLength; this.MaxMoney = maxMoney; this.Options = consensusOptions; this.BuriedDeployments = buriedDeployments; this.BIP9Deployments = bip9Deployments; this.SubsidyHalvingInterval = subsidyHalvingInterval; this.MajorityEnforceBlockUpgrade = majorityEnforceBlockUpgrade; this.MajorityRejectBlockOutdated = majorityRejectBlockOutdated; this.MajorityWindow = majorityWindow; this.BIP34Hash = bip34Hash; this.PowLimit = powLimit; this.PowTargetTimespan = powTargetTimespan; this.PowTargetSpacing = powTargetSpacing; this.PowAllowMinDifficultyBlocks = powAllowMinDifficultyBlocks; this.PosNoRetargeting = posNoRetargeting; this.PowNoRetargeting = powNoRetargeting; this.HashGenesisBlock = hashGenesisBlock; this.MinimumChainWork = minimumChainWork; this.MinerConfirmationWindow = minerConfirmationWindow; this.RuleChangeActivationThreshold = ruleChangeActivationThreshold; this.CoinType = coinType; this.ProofOfStakeLimitV2 = proofOfStakeLimitV2; this.LastPOWBlock = lastPowBlock; this.IsProofOfStake = isProofOfStake; this.DefaultAssumeValid = defaultAssumeValid; this.ConsensusFactory = consensusFactory; this.ProofOfStakeRewardAfterSubsidyLimit = proofOfStakeRewardAfterSubsidyLimit; this.SubsidyLimit = subsidyLimit; this.LastProofOfStakeRewardHeight = lastProofOfStakeRewardHeight; } } }
36.142857
124
0.63354
[ "MIT" ]
daniiba/X42-FullNode
src/Stratis.Bitcoin.Networks/Consensus/X42Consensus.cs
7,086
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace VirusX.Menu { class Controls : MenuPage { Menu.Page origin; public Controls(Menu menu) : base(menu) { // background Interface.Add(new InterfaceFiller(Vector2.Zero, Color.Black * 0.5f, () => { return origin == Menu.Page.INGAME || origin == Menu.Page.NEWGAME; })); string[,] data = { { null, VirusXStrings.Instance.Get("ControlKeyboard1"), VirusXStrings.Instance.Get("ControlKeyboard2"), VirusXStrings.Instance.Get("ControlKeyboard3"), VirusXStrings.Instance.Get("ControlGamepad") }, { VirusXStrings.Instance.Get("ControlMoveUp"), "W", VirusXStrings.Instance.Get("ControlArrowUp"), VirusXStrings.Instance.Get("ControlNumpad") + " 8", null }, { VirusXStrings.Instance.Get("ControlMoveLeft"), "A", VirusXStrings.Instance.Get("ControlArrowLeft"), VirusXStrings.Instance.Get("ControlNumpad") + " 4", null }, { VirusXStrings.Instance.Get("ControlMoveDown"), "S", VirusXStrings.Instance.Get("ControlArrowDown"), VirusXStrings.Instance.Get("ControlNumpad") + " 5/2", null }, { VirusXStrings.Instance.Get("ControlMoveRight"), "D", VirusXStrings.Instance.Get("ControlArrowRight"), VirusXStrings.Instance.Get("ControlNumpad") + " 6", null }, { VirusXStrings.Instance.Get("ControlActionUse"), "Tab", "Enter", VirusXStrings.Instance.Get("ControlNumpad") + " 0", null }, { VirusXStrings.Instance.Get("ControlBackHold"), "L-Shift", "R-Shift", VirusXStrings.Instance.Get("ControlNumpad") + " 7/9", null }, }; // big table int column = 190; // column width int row = 60; // row height int gap = 15; // gap between columns int top = 100; // distance from top int left = -(data.GetLength(1) * (column + gap) - gap + InterfaceButton.PADDING) / 2; for (int i = 0; i < data.GetLength(0); i++) { for (int j = 0; j < data.GetLength(1); j++) { if (data[i, j] != null) if(i == 0 || j == 0) Interface.Add(new InterfaceButton(data[i, j], new Vector2(left + j * (column + gap), top + i * row), () => { return true; }, column - gap, Alignment.TOP_CENTER)); else Interface.Add(new InterfaceButton(data[i, j], new Vector2(left + j * (column + gap), top + i * row), () => { return false; }, column - gap, Alignment.TOP_CENTER)); } } // draw icons int fontHeight = menu.GetFontHeight() + 2 * InterfaceButton.PADDING; int width = column + InterfaceImage.PADDING/2; Interface.Add(new InterfaceImage( "ButtonImages/xboxControllerLeftThumbstick", new Rectangle(left + 4 * (column + gap), top + 1 * row, width, row * 3 + fontHeight), InterfaceElement.COLOR_NORMAL, Alignment.TOP_CENTER)); Interface.Add(new InterfaceImage( "ButtonImages/xboxControllerButtonA", new Rectangle(left + 4 * (column + gap), top + 5 * row, width, fontHeight), InterfaceElement.COLOR_NORMAL, Alignment.TOP_CENTER)); Interface.Add(new InterfaceImage( "ButtonImages/xboxControllerButtonB", new Rectangle(left + 4 * (column + gap), top + 6 * row, width, fontHeight), InterfaceElement.COLOR_NORMAL, Alignment.TOP_CENTER)); // back button string label = VirusXStrings.Instance.Get("MenuBack"); Interface.Add(new InterfaceButton(label, new Vector2(-(int)(menu.Font.MeasureString(label).X / 2), 100), () => { return true; }, Alignment.BOTTOM_CENTER)); } public override void OnActivated(Menu.Page oldPage, GameTime gameTime) { origin = oldPage; base.Update(gameTime); // reduces flicker } public override void LoadContent(ContentManager content) { base.LoadContent(content); } public override void Update(GameTime gameTime) { if (InputManager.Instance.WasAnyActionPressed(InputManager.ControlActions.PAUSE) || InputManager.Instance.WasAnyActionPressed(InputManager.ControlActions.EXIT) || InputManager.Instance.WasAnyActionPressed(InputManager.ControlActions.ACTION) || InputManager.Instance.WasAnyActionPressed(InputManager.ControlActions.HOLD) || InputManager.Instance.IsButtonPressed(Keys.F1) || InputManager.Instance.AnyPressedButton(Buttons.Y)) menu.ChangePage(origin, gameTime); base.Update(gameTime); } public override void Draw(SpriteBatch spriteBatch, GameTime gameTime) { base.Draw(spriteBatch, gameTime); } } }
54.564356
253
0.554527
[ "MIT" ]
Acagamics/virusx
VirusX/Menu/Controls.cs
5,513
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace Epub { internal class AppleIbooksOptions { internal XElement ToElement() { XElement element = new XElement("display_options", new XElement("platform", new XAttribute("name", "*"), new XElement("option", new XAttribute("name", "specified-fonts"), true))); return element; } } }
27
191
0.666667
[ "MIT" ]
toxaris-/CreateEpub
CreateEpub/AppleIbooksOptions.cs
488
C#
using Unity.Entities; using Unity.Mathematics; #if ENABLE_HYBRID_RENDERER_V2 namespace Unity.Rendering { [MaterialProperty("unity_MotionVectorsParams", MaterialPropertyFormat.Float4)] public struct BuiltinMaterialPropertyUnity_MotionVectorsParams : IComponentData { public float4 Value; } [MaterialProperty("unity_MotionVectorsParams", MaterialPropertyFormat.Float4)] public struct BuiltinMaterialPropertyUnity_MotionVectorsParams_Shared : IHybridSharedComponentFloat4Override { public float4 Value; public float4 GetFloat4OverrideData() { return Value; } } } #endif
26.16
112
0.744648
[ "MIT" ]
czy123/CFrameWork
com.unity.rendering.hybrid@0.11.0-preview.42/Unity.Rendering.Hybrid/BuiltinMaterialProperties/BuiltinMaterialPropertyUnity_MotionVectorsParams.cs
654
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Avalonia.Controls; using DHT.Desktop.Common; using DHT.Desktop.Dialogs; using DHT.Desktop.Models; using DHT.Server.Data; using DHT.Server.Data.Filters; using DHT.Server.Database; namespace DHT.Desktop.Main.Controls { public class FilterPanelModel : BaseModel { private static readonly HashSet<string> FilterProperties = new () { nameof(FilterByDate), nameof(StartDate), nameof(EndDate), nameof(FilterByChannel), nameof(IncludedChannels), nameof(FilterByUser), nameof(IncludedUsers) }; public event PropertyChangedEventHandler? FilterPropertyChanged; public bool HasAnyFilters => FilterByDate || FilterByChannel || FilterByUser; private bool filterByDate = false; private DateTime? startDate = null; private DateTime? endDate = null; private bool filterByChannel = false; private HashSet<ulong>? includedChannels = null; private bool filterByUser = false; private HashSet<ulong>? includedUsers = null; public bool FilterByDate { get => filterByDate; set => Change(ref filterByDate, value); } public DateTime? StartDate { get => startDate; set => Change(ref startDate, value); } public DateTime? EndDate { get => endDate; set => Change(ref endDate, value); } public bool FilterByChannel { get => filterByChannel; set => Change(ref filterByChannel, value); } public HashSet<ulong> IncludedChannels { get => includedChannels ?? db.GetAllChannels().Select(channel => channel.Id).ToHashSet(); set => Change(ref includedChannels, value); } public bool FilterByUser { get => filterByUser; set => Change(ref filterByUser, value); } public HashSet<ulong> IncludedUsers { get => includedUsers ?? db.GetAllUsers().Select(user => user.Id).ToHashSet(); set => Change(ref includedUsers, value); } private string channelFilterLabel = ""; public string ChannelFilterLabel { get => channelFilterLabel; set => Change(ref channelFilterLabel, value); } private string userFilterLabel = ""; public string UserFilterLabel { get => userFilterLabel; set => Change(ref userFilterLabel, value); } private readonly Window window; private readonly IDatabaseFile db; [Obsolete("Designer")] public FilterPanelModel() : this(null!, DummyDatabaseFile.Instance) {} public FilterPanelModel(Window window, IDatabaseFile db) { this.window = window; this.db = db; UpdateChannelFilterLabel(); UpdateUserFilterLabel(); PropertyChanged += OnPropertyChanged; db.Statistics.PropertyChanged += OnDbStatisticsChanged; } private void OnPropertyChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName != null && FilterProperties.Contains(e.PropertyName)) { FilterPropertyChanged?.Invoke(sender, e); } if (e.PropertyName is nameof(FilterByChannel) or nameof(IncludedChannels)) { UpdateChannelFilterLabel(); } else if (e.PropertyName is nameof(FilterByUser) or nameof(IncludedUsers)) { UpdateUserFilterLabel(); } } private void OnDbStatisticsChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(DatabaseStatistics.TotalChannels)) { UpdateChannelFilterLabel(); } else if (e.PropertyName == nameof(DatabaseStatistics.TotalUsers)) { UpdateUserFilterLabel(); } } public async void OpenChannelFilterDialog() { var servers = db.GetAllServers().ToDictionary(server => server.Id); var items = new List<CheckBoxItem<ulong>>(); var included = IncludedChannels; foreach (var channel in db.GetAllChannels()) { var channelId = channel.Id; var channelName = channel.Name; string title; if (servers.TryGetValue(channel.Server, out var server)) { var titleBuilder = new StringBuilder(); var serverType = server.Type; titleBuilder.Append('[') .Append(ServerTypes.ToString(serverType)) .Append("] "); if (serverType == ServerType.DirectMessage) { titleBuilder.Append(channelName); } else { titleBuilder.Append(server.Name) .Append(" - ") .Append(channelName); } title = titleBuilder.ToString(); } else { title = channelName; } items.Add(new CheckBoxItem<ulong>(channelId) { Title = title, Checked = included.Contains(channelId) }); } var result = await OpenIdFilterDialog(window, "Included Channels", items); if (result != null) { IncludedChannels = result; } } public async void OpenUserFilterDialog() { var items = new List<CheckBoxItem<ulong>>(); var included = IncludedUsers; foreach (var user in db.GetAllUsers()) { var name = user.Name; var discriminator = user.Discriminator; items.Add(new CheckBoxItem<ulong>(user.Id) { Title = discriminator == null ? name : name + " #" + discriminator, Checked = included.Contains(user.Id) }); } var result = await OpenIdFilterDialog(window, "Included Users", items); if (result != null) { IncludedUsers = result; } } private void UpdateChannelFilterLabel() { long total = db.Statistics.TotalChannels; long included = FilterByChannel ? IncludedChannels.Count : total; ChannelFilterLabel = "Selected " + included.Format() + " / " + total.Pluralize("channel") + "."; } private void UpdateUserFilterLabel() { long total = db.Statistics.TotalUsers; long included = FilterByUser ? IncludedUsers.Count : total; UserFilterLabel = "Selected " + included.Format() + " / " + total.Pluralize("user") + "."; } public MessageFilter CreateFilter() { MessageFilter filter = new(); if (FilterByDate) { filter.StartDate = StartDate; filter.EndDate = EndDate; } if (FilterByChannel) { filter.ChannelIds = new HashSet<ulong>(IncludedChannels); } if (FilterByUser) { filter.UserIds = new HashSet<ulong>(IncludedUsers); } return filter; } private static async Task<HashSet<ulong>?> OpenIdFilterDialog(Window window, string title, List<CheckBoxItem<ulong>> items) { items.Sort((item1, item2) => item1.Title.CompareTo(item2.Title)); var model = new CheckBoxDialogModel<ulong>(items) { Title = title }; var dialog = new CheckBoxDialog { DataContext = model }; var result = await dialog.ShowDialog<DialogResult.OkCancel>(window); return result == DialogResult.OkCancel.Ok ? model.SelectedItems.Select(item => item.Item).ToHashSet() : null; } } }
27.949367
127
0.691123
[ "MIT" ]
SoftwareGuy/Discord-History-Tracker
app/Desktop/Main/Controls/FilterPanelModel.cs
6,624
C#
using UnityEngine; using UnitySteer.Events ; /// <summary> /// 插入中间 /// </summary> [AddComponentMenu("UnitySteer/Steer/... for Interpose")] public class SteerForInterpose : Steering { public Vehicle A; public Vehicle B; /// <summary> /// 计算力 /// </returns> protected override Vector3 CalculateForce() { Vector3 Midpoint = (A.Position + B.Position) / 2; //预测未来位置 /* float Timetoreach2 = (this.transform.position - Midpoint).sqrMagnitude; float Timeto = Mathf.Sqrt (Timetoreach2) * 20; Vector3 Apos = A.Position + A.Velocity * Timeto; Vector3 BPos = B.Position + B.Velocity * Timeto; Midpoint = (Apos + BPos) / 2; */ return Vehicle.GetArriveVector (Midpoint, Vehicle.Decelerate.fast); } }
23.766667
75
0.691445
[ "MIT" ]
xinghu0164/GroupAnimation
Assets/Code/Steer/SteerForInterpose.cs
739
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace LiteDB { internal static class ZipExtensions { public static IEnumerable<ZipValues> ZipValues(this IEnumerable<BsonValue> first, IEnumerable<BsonValue> second, IEnumerable<BsonValue> thrid = null) { var firstEnumerator = first.GetEnumerator(); var secondEnumerator = second.GetEnumerator(); var thridEnumerator = thrid?.GetEnumerator(); var firstCurrent = BsonValue.Null; var secondCurrent = BsonValue.Null; var thridCurrent = BsonValue.Null; // loop for read all first enumerable while (firstEnumerator.MoveNext()) { firstCurrent = firstEnumerator.Current; if (secondEnumerator.MoveNext()) { secondCurrent = secondEnumerator.Current; } if (thrid != null && thridEnumerator.MoveNext()) { thridCurrent = thridEnumerator.Current; } yield return new ZipValues(firstCurrent, secondCurrent, thridCurrent); } // loop for use all second enumerable while (secondEnumerator.MoveNext()) { secondCurrent = secondEnumerator.Current; if (thrid != null && thridEnumerator.MoveNext()) { thridCurrent = thridEnumerator.Current; } yield return new ZipValues(firstCurrent, secondCurrent, thridCurrent); } // loop for use all thrid enumerable (if exists) while (thrid != null && thridEnumerator.MoveNext()) { thridCurrent = thridEnumerator.Current; yield return new ZipValues(firstCurrent, secondCurrent, thridCurrent); } } } internal class ZipValues { public BsonValue First { get; set; } public BsonValue Second { get; set; } public BsonValue Third { get; set; } public ZipValues(BsonValue first, BsonValue second, BsonValue thrid) { this.First = first; this.Second = second; this.Third = thrid; } } }
31.565789
157
0.566069
[ "MIT" ]
3factr/LiteDB
LiteDB/Utils/Extensions/ZipExtensions.cs
2,401
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace EduFocus { static class Program { /// <summary> /// Ponto de entrada principal para o aplicativo. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmSplash()); } } }
22.391304
65
0.615534
[ "MIT" ]
LuisFernandoVL/EduFocus
EduFocus/EduFocus/Program.cs
517
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Aspose" file="AssignmentItems.cs"> // Copyright (c) 2018 Aspose.Tasks for Cloud // </copyright> // <summary> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Aspose.Tasks.Cloud.Sdk.Model { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; /// <summary> /// /// </summary> public class AssignmentItems : LinkElement { /// <summary> /// Gets or sets AssignmentItem /// </summary> public List<AssignmentItem> AssignmentItem { get; set; } /// <summary> /// Get the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class AssignmentItems {\n"); sb.Append(" AssignmentItem: ").Append(this.AssignmentItem).Append("\n"); sb.Append("}\n"); return sb.ToString(); } } }
41.864407
119
0.605263
[ "MIT" ]
aspose-tasks-cloud/aspose-tasks-cloud-dotnet
Aspose.Tasks.Cloud.Sdk/Model/AssignmentItems.cs
2,470
C#
// Copyright (c) Shane Woolcock. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Pooling; using osu.Framework.Input.Bindings; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Rush.Judgements; using osu.Game.Rulesets.Rush.Objects; using osu.Game.Rulesets.Rush.Objects.Drawables; using osu.Game.Rulesets.Rush.UI.Ground; using osu.Game.Rulesets.UI.Scrolling; using osuTK; namespace osu.Game.Rulesets.Rush.UI { [Cached] public class RushPlayfield : ScrollingPlayfield, IKeyBindingHandler<RushAction> { public const float DEFAULT_HEIGHT = 178; public const float HIT_TARGET_OFFSET = 120; public const float HIT_TARGET_SIZE = 100; public const float PLAYER_OFFSET = 130; public const float JUDGEMENT_OFFSET = 100; public const float JUDGEMENT_MOVEMENT = 300; public const double HIT_EXPLOSION_DURATION = 200f; public RushPlayerSprite PlayerSprite { get; } private readonly Container halfPaddingOverEffectContainer; private readonly Container overPlayerEffectsContainer; private readonly LanePlayfield airLane; private readonly LanePlayfield groundLane; public IEnumerable<DrawableHitObject> AllAliveHitObjects { get { if (HitObjectContainer == null) return Enumerable.Empty<DrawableHitObject>(); // Intentionally counting on the fact that we don't have nested playfields in our nested playfields IEnumerable<DrawableHitObject> enumerable = HitObjectContainer.AliveObjects.Concat(NestedPlayfields.SelectMany(p => p.HitObjectContainer.AliveObjects)).OrderBy(d => d.HitObject.StartTime); return enumerable; } } private DrawablePool<DrawableRushJudgement> judgementPool; private DrawablePool<DefaultHitExplosion> explosionPool; private DrawablePool<StarSheetHitExplosion> sheetExplosionPool; private DrawablePool<HeartHitExplosion> heartExplosionPool; private DrawablePool<HealthText> healthTextPool; [Cached] private readonly RushHitPolicy hitPolicy; public RushPlayfield() { hitPolicy = new RushHitPolicy(this); InternalChildren = new Drawable[] { new GridContainer { RelativeSizeAxes = Axes.Both, RowDimensions = new[] { new Dimension(GridSizeMode.Distributed), // Top empty area new Dimension(GridSizeMode.Absolute, DEFAULT_HEIGHT), // Playfield area new Dimension(GridSizeMode.Distributed), // Ground area, extends to overall height }, Content = new[] { new[] { Empty() }, new Drawable[] { new Container { Name = "Playfield area", RelativeSizeAxes = Axes.Both, Children = new[] { new Container { Name = "Left area", Width = HIT_TARGET_OFFSET, RelativeSizeAxes = Axes.Y, Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Depth = -1, Child = new Container { Name = "Left Play Zone", RelativeSizeAxes = Axes.Both, Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Children = new Drawable[] { PlayerSprite = new RushPlayerSprite(DEFAULT_HEIGHT, 0) { Origin = Anchor.Centre, Position = new Vector2(PLAYER_OFFSET, DEFAULT_HEIGHT), Scale = new Vector2(0.75f), }, overPlayerEffectsContainer = new Container { Origin = Anchor.Centre, Anchor = Anchor.Centre, RelativeSizeAxes = Axes.Both, } } }, }, new Container { Name = "Right area", RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Left = HIT_TARGET_OFFSET }, Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Children = new Drawable[] { airLane = new LanePlayfield(LanedHitLane.Air), groundLane = new LanePlayfield(LanedHitLane.Ground), // Contains miniboss and duals for now new Container { Name = "Hit Objects", RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Left = HIT_TARGET_OFFSET }, Child = HitObjectContainer }, halfPaddingOverEffectContainer = new Container { Name = "Over Effects (Half Padding)", RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Left = HIT_TARGET_OFFSET / 2f } } } } } }, }, new Drawable[] { new Container { Name = "Ground area", RelativeSizeAxes = Axes.Both, // Due to the size of the player sprite, we have to push the ground even more to the bottom. Padding = new MarginPadding { Top = 50f }, Depth = float.MaxValue, Child = new GroundDisplay(), } } } } }; AddNested(airLane); AddNested(groundLane); NewResult += onNewResult; } [BackgroundDependencyLoader] private void load() { RegisterPool<MiniBoss, DrawableMiniBoss>(4); RegisterPool<MiniBossTick, DrawableMiniBossTick>(10); RegisterPool<DualHit, DrawableDualHit>(8); RegisterPool<DualHitPart, DrawableDualHitPart>(16); AddRangeInternal(new Drawable[] { judgementPool = new DrawablePool<DrawableRushJudgement>(5), explosionPool = new DrawablePool<DefaultHitExplosion>(15), sheetExplosionPool = new DrawablePool<StarSheetHitExplosion>(10), heartExplosionPool = new DrawablePool<HeartHitExplosion>(2), healthTextPool = new DrawablePool<HealthText>(2), }); } protected override void OnNewDrawableHitObject(DrawableHitObject drawableHitObject) { base.OnNewDrawableHitObject(drawableHitObject); if (drawableHitObject is DrawableMiniBoss drawableMiniBoss) drawableMiniBoss.Attacked += onMiniBossAttacked; ((DrawableRushHitObject)drawableHitObject).CheckHittable = hitPolicy.IsHittable; } public override void Add(HitObject hitObject) { switch (hitObject) { case LanedHit laned: laned.LaneBindable.BindValueChanged(lane => { if (lane.OldValue != lane.NewValue) playfieldForLane(lane.OldValue).Remove(hitObject); playfieldForLane(lane.OldValue).Add(hitObject); }, true); return; } base.Add(hitObject); } private LanePlayfield playfieldForLane(LanedHitLane lane) => lane == LanedHitLane.Air ? airLane : groundLane; private void onMiniBossAttacked(DrawableMiniBoss drawableMiniBoss, double timeOffset) { halfPaddingOverEffectContainer.Add(explosionPool.Get(h => h.Apply(drawableMiniBoss))); PlayerSprite.Target = PlayerTargetLane.MiniBoss; } private void onNewResult(DrawableHitObject judgedObject, JudgementResult result) { DrawableRushHitObject rushJudgedObject = (DrawableRushHitObject)judgedObject; RushJudgementResult rushResult = (RushJudgementResult)result; PlayerSprite.HandleResult(rushJudgedObject, result); // Display hit explosions for objects that allow it. if (result.IsHit && rushJudgedObject.DisplayExplosion) { Drawable explosion = rushJudgedObject switch { DrawableStarSheetHead head => sheetExplosionPool.Get(s => s.Apply(head)), DrawableStarSheetTail tail => sheetExplosionPool.Get(s => s.Apply(tail)), DrawableHeart heart => heartExplosionPool.Get(h => h.Apply(heart)), _ => explosionPool.Get(h => h.Apply(rushJudgedObject)), }; if (rushJudgedObject is IDrawableLanedHit laned) playfieldForLane(laned.Lane).AddExplosion(explosion); } // Display health point difference if the judgement result implies it. var pointDifference = rushResult.Judgement.HealthPointIncreaseFor(rushResult); if (pointDifference != 0) overPlayerEffectsContainer.Add(healthTextPool.Get(h => h.Apply(pointDifference))); // Display judgement results in a drawable for objects that allow it. if (rushJudgedObject.DisplayResult) { DrawableRushJudgement judgementDrawable = judgementPool.Get(j => j.Apply(result, judgedObject)); LanedHitLane judgementLane = LanedHitLane.Air; // TODO: showing judgements based on the judged object suggests that // this may want to be inside the object class as well. switch (rushJudgedObject.HitObject) { case Sawblade sawblade: judgementLane = sawblade.Lane.Opposite(); break; case LanedHit lanedHit: judgementLane = lanedHit.Lane; break; case MiniBoss _: break; } playfieldForLane(judgementLane).AddJudgement(judgementDrawable); } } public bool OnPressed(RushAction action) => PlayerSprite.HandleAction(action); public void OnReleased(RushAction action) { } } }
46.416667
205
0.46529
[ "MIT" ]
swoolcock/rush-dev
osu.Game.Rulesets.Rush/UI/RushPlayfield.cs
13,081
C#
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (c) 2003-2012 by AG-Software * * All Rights Reserved. * * Contact information for AG-Software is available at http://www.ag-software.de * * * * Licence: * * The agsXMPP SDK is released under a dual licence * * agsXMPP can be used under either of two licences * * * * A commercial licence which is probably the most appropriate for commercial * * corporate use and closed source projects. * * * * The GNU Public License (GPL) is probably most appropriate for inclusion in * * other open source projects. * * * * See README.html for details. * * * * For general enquiries visit our website at: * * http://www.ag-software.de * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.Text; using System.IO; using System.Xml; namespace agsXMPP.Xml.Dom { public class Element : Node { // Member Variables private string m_TagName; private string m_Prefix; private ListDictionary m_Attributes; private Text m_Value = new Text(); public Element() { NodeType = NodeType.Element; AddChild(m_Value); m_Attributes = new ListDictionary(); m_TagName = ""; Value = ""; } public Element(string tagName) :this() { m_TagName = tagName; } public Element(string tagName, string tagText) : this(tagName) { Value = tagText; } public Element(string tagName, bool tagText) : this(tagName, tagText ? "true" : "false") { } public Element(string tagName, string tagText, string ns) : this(tagName, tagText) { Namespace = ns; } /// <summary> /// Is this Element a Rootnode? /// </summary> public bool IsRootElement { get { return (Parent != null ? false : true); } } public override string Value { get { return m_Value.Value; } set { m_Value.Value = value; } } public string Prefix { get { return m_Prefix; } set { m_Prefix = value; } } /// <summary> /// The Full Qualified Name /// </summary> public string TagName { get { return m_TagName; } set { m_TagName = value; } } public string TextBase64 { get { byte[] b = Convert.FromBase64String(Value); return Encoding.ASCII.GetString(b, 0, b.Length); } set { byte[] b = Encoding.UTF8.GetBytes(value); //byte[] b = Encoding.Default.GetBytes(value); Value = Convert.ToBase64String(b, 0, b.Length); } } public ListDictionary Attributes { get { return m_Attributes; } } public object GetAttributeEnum(string name, Type enumType) { string att = GetAttribute(name); if ((att == null)) return -1; try { #if CF return util.Enum.Parse(enumType, att, true); #else return Enum.Parse(enumType, att, true); #endif } catch (Exception) { return -1; } } public string GetAttribute(string name) { if (HasAttribute(name)) return (string) m_Attributes[name]; return null; } public int GetAttributeInt(string name) { if (HasAttribute(name)) { return int.Parse((string) m_Attributes[name]); } return 0; } public long GetAttributeLong(string name) { if (HasAttribute(name)) { return long.Parse((string) m_Attributes[name]); } return 0; } /// <summary> /// Reads a boolean Attribute, if the attrib is absent it returns also false. /// </summary> /// <param name="name"></param> /// <returns></returns> public bool GetAttributeBool(string name) { if (HasAttribute(name)) { string tmp = (string) m_Attributes[name]; if (tmp.ToLower() == "true") return true; return false; } return false; } public Jid GetAttributeJid(string name) { if (HasAttribute(name)) return new Jid(this.GetAttribute(name)); return null; } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="ifp"></param> /// <returns></returns> public double GetAttributeDouble(string name, IFormatProvider ifp) { if (HasAttribute(name)) { try { return double.Parse((string)m_Attributes[name], ifp); } catch { return double.NaN; } } return double.NaN; } /// <summary> /// Get a Attribute of type double (Decimal seperator = ".") /// </summary> /// <param name="name"></param> /// <returns></returns> public double GetAttributeDouble(string name) { // Parse the double always in english format ==> "." = Decimal seperator NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberGroupSeparator = "."; return GetAttributeDouble(name, nfi); } public bool HasAttribute(string name) { return Attributes.Contains(name); } /// <summary> /// Return the Text of the first Tag with a specified Name. /// It doesnt traverse the while tree and checks only the unerlying childnodes /// </summary> /// <param name="TagName">Name of Tag to find as string</param> /// <returns></returns> public string GetTag(string TagName) { Element tag = this._SelectElement(this, TagName); if ( tag != null) return tag.Value; return null; } public string GetTag(string TagName, bool traverseChildren) { Element tag = this._SelectElement(this, TagName, traverseChildren); if ( tag != null) return tag.Value; return null; } public string GetTag(System.Type type) { Element tag = this._SelectElement(this, type); if ( tag != null) return tag.Value; return null; } public string GetTagBase64(string TagName) { byte[] b = Convert.FromBase64String(GetTag(TagName)); return Encoding.ASCII.GetString(b, 0, b.Length); } /// <summary> /// Adds a Tag and encodes the Data to BASE64 /// </summary> /// <param name="argTagname"></param> /// <param name="argText"></param> public void SetTagBase64(string argTagname, string argText) { byte[] b = Encoding.Unicode.GetBytes(argText); SetTag(argTagname, Convert.ToBase64String(b, 0, b.Length)); } /// <summary> /// Adds a Tag end decodes the byte buffer to BASE64 /// </summary> /// <param name="argTagname"></param> /// <param name="buffer"></param> public void SetTagBase64(string argTagname, byte[] buffer) { SetTag(argTagname, Convert.ToBase64String(buffer, 0, buffer.Length)); } public void SetTag(string argTagname, string argText) { if (HasTag(argTagname) == false) AddChild(new Element(argTagname, argText)); else SelectSingleElement(argTagname).Value = argText; } public void SetTag(Type type, string argText) { if (HasTag(type) == false) { Element newel; newel = (Element) Activator.CreateInstance(type); newel.Value = argText; AddChild(newel); } else SelectSingleElement(type).Value = argText; } public void SetTag(Type type) { if (HasTag(type)) RemoveTag(type); AddChild( (Element) Activator.CreateInstance(type) ); } public void SetTag(string argTagname) { SetTag(argTagname, ""); } public void SetTag(string argTagname, string argText, string argNS) { if (HasTag(argTagname) == false) AddChild(new Element(argTagname, argText, argNS)); else { Element e = SelectSingleElement(argTagname); e.Value = argText; e.Namespace = argNS; } } public void SetTag(string argTagname, double dbl, IFormatProvider ifp) { SetTag(argTagname, dbl.ToString(ifp)); } public void SetTag(string argTagname, double dbl) { NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberGroupSeparator = "."; SetTag(argTagname, dbl, nfi); } public void SetTag(string argTagname, bool val) { SetTag(argTagname, val ? "true" : "false"); } public void SetTag(string argTagname, int val) { SetTag(argTagname, val.ToString()); } public void SetTag(string argTagname, Jid jid) { SetTag(argTagname, jid.ToString()); } public void AddTag(string argTagname, string argText) { AddChild(new Element(argTagname, argText)); } public void AddTag(string argTagname) { AddChild(new Element(argTagname)); } public object GetTagEnum(string name, System.Type enumType) { string tag = this.GetTag(name); if ( (tag == null) || (tag.Length == 0) ) return -1; try { #if CF return util.Enum.Parse(enumType, tag, true); #else return Enum.Parse(enumType, tag, true); #endif } catch (Exception) { return -1; } } /// <summary> /// Return the Text of the first Tag with a specified Name in all childnodes as boolean /// </summary> /// <param name="TagName">name of Tag to findas string</param> /// <returns></returns> public bool GetTagBool(string TagName) { Element tag = this._SelectElement(this, TagName); if ( tag != null) { if (tag.Value.ToLower() == "false" || tag.Value.ToLower() == "0") { return false; } if(tag.Value.ToLower() == "true" || tag.Value.ToLower() == "1") { return true; } return false; } return false; } public int GetTagInt(string TagName) { Element tag = _SelectElement(this, TagName); if ( tag != null) return int.Parse(tag.Value); return 0; } public Jid GetTagJid(string TagName) { string jid = GetTag(TagName); if (jid != null) return new Jid(jid); return null; } /// <summary> /// Get a Tag of type double (Decimal seperator = ".") /// </summary> /// <param name="TagName"></param> /// <returns></returns> public double GetTagDouble(string argTagName) { // Parse the double always in english format ==> "." = Decimal seperator NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberGroupSeparator = "."; return GetTagDouble(argTagName, nfi); } /// <summary> /// Get a Tag of type double with the given iFormatProvider /// </summary> /// <param name="TagName"></param> /// <param name="nfi"></param> /// <returns></returns> public double GetTagDouble(string argTagName, IFormatProvider ifp) { string val = GetTag(argTagName); if (val != null) return Double.Parse(val, ifp); return Double.NaN; } public bool HasTag(string name) { Element tag = _SelectElement(this, name); if ( tag != null) return true; return false; } public bool HasTag(string name, bool traverseChildren) { Element tag = _SelectElement(this, name, traverseChildren); if ( tag != null) return true; return false; } public bool HasTag(Type type) { Element tag = _SelectElement(this, type); if ( tag != null) return true; return false; } public bool HasTag<T>() where T : Element { return SelectSingleElement<T>() != null; } public bool HasTagt<T>(bool traverseChildren) where T : Element { return SelectSingleElement<T>(traverseChildren) != null; } public bool HasTag(Type type, bool traverseChildren) { Element tag = this._SelectElement(this, type, traverseChildren); if ( tag != null) return true; return false; } /// <summary> /// /// </summary> /// <param name="enumType"></param> /// <returns></returns> public object HasTagEnum(Type enumType) { #if CF || CF_2 string[] members = Util.Enum.GetNames(enumType); #else string[] members = Enum.GetNames(enumType); #endif foreach (string member in members) { if (HasTag(member)) #if CF return util.Enum.Parse(enumType, member, false); #else return Enum.Parse(enumType, member, false); #endif } return -1; } /// <summary> /// Remove a Tag when it exists /// </summary> /// <param name="TagName">Tagname to remove</param> /// <returns>true when existing and removed, false when not existing</returns> public bool RemoveTag(string TagName) { Element tag = _SelectElement(this, TagName); if ( tag != null) { tag.Remove(); return true; } return false; } /// <summary> /// Remove a Tag when it exists /// </summary> /// <param name="type">Type of the tag that should be removed</param> /// <returns>true when existing and removed, false when not existing</returns> public bool RemoveTag(Type type) { Element tag = _SelectElement(this, type); if (tag != null) { tag.Remove(); return true; } return false; } public bool RemoveTag<T>() where T : Element { Element tag = SelectSingleElement<T>(); if (tag != null) { tag.Remove(); return true; } return false; } /// <summary> /// Removes all Tags of the given type. Doesnt traverse the tree /// </summary> /// <param name="type">Type of the tags that should be removed</param> /// <returns>true when tags were removed, false when no tags were found and removed</returns> public bool RemoveTags(Type type) { bool ret = false; ElementList list = SelectElements(type); if (list.Count > 0) ret = true; foreach (Element e in list) e.Remove(); return ret; } /// <summary> /// Removes all Tags of the given type. Doesnt traverse the tree /// </summary> /// <typeparam name="T">Type of the tags that should be removed</typeparam> /// <returns>true when tags were removed, false when no tags were found and removed</returns> public bool RemoveTags<T>() where T : Element { return RemoveTags(typeof (T)); } /// <summary> /// Same as AddChild, but Replaces the childelement when it exists /// </summary> /// <param name="e"></param> public void ReplaceChild(Element e) { if (HasTag(e.TagName)) RemoveTag(e.TagName); AddChild(e); } public string Attribute(string name) { return (string) m_Attributes[name]; } /// <summary> /// Removes a Attribute /// </summary> /// <param name="name">Attribute as string to remove</param> public void RemoveAttribute(string name) { if (HasAttribute(name)) { Attributes.Remove(name); } } /// <summary> /// Adds a new Attribue or changes a Attriv when already exists /// </summary> /// <param name="name">name of Attribute to add/change</param> /// <param name="value">value of teh Attribute to add/change</param> public void SetAttribute(string name, string val) { // When the attrib already exists then we overweite it // So we must remove it first and add it again then if (HasAttribute(name)) { Attributes.Remove(name); } m_Attributes.Add(name, val); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="value"></param> public void SetAttribute(string name, int value) { SetAttribute(name, value.ToString()); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="value"></param> public void SetAttribute(string name, long value) { SetAttribute(name, value.ToString()); } /// <summary> /// Writes a boolean attribute, the value is either 'true' or 'false' /// </summary> /// <param name="name"></param> /// <param name="val"></param> public void SetAttribute(string name, bool val) { // When the attrib already exists then we overweite it // So we must remove it first and add it again then if (HasAttribute(name)) { Attributes.Remove(name); } m_Attributes.Add(name, val ? "true" : "false"); } /// <summary> /// Set a attribute of type Jid /// </summary> /// <param name="name"></param> /// <param name="value"></param> public void SetAttribute(string name, Jid value) { if (value != null) SetAttribute(name, value.ToString()); else RemoveAttribute(name); } /// <summary> /// Set a attribute from a double in english number format /// </summary> /// <param name="name"></param> /// <param name="value"></param> public void SetAttribute(string name, double value) { NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberGroupSeparator = "."; SetAttribute(name, value, nfi); } /// <summary> /// Set a attribute from a double with the given Format provider /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <param name="ifp"></param> public void SetAttribute(string name, double value, IFormatProvider ifp) { SetAttribute(name, value.ToString(ifp)); } public void SetNamespace(string value) { SetAttribute("xmlns", value); } private CData GetFirstCDataNode() { foreach (Node ch in ChildNodes) { if (ch.NodeType == NodeType.Cdata) return ch as CData; } return null; } /// <summary> /// Has this Element some CDATA? /// </summary> /// <returns></returns> public bool HasData() { return GetFirstCDataNode() != null; } /// <summary> /// Get the CDATA /// </summary> /// <returns></returns> public string GetData() { var data = GetFirstCDataNode(); return data == null ? null : data.Value; } /// <summary> /// Set the CDATA /// </summary> /// <param name="cdata"></param> public void SetData(string cdata) { var data = GetFirstCDataNode(); if (data == null) { data = new CData(); AddChild(data); } data.Value = cdata; } public string InnerXml { get { if (ChildNodes.Count > 0) { string xml = ""; try { for (int i = 0; i < ChildNodes.Count; i++) { if (ChildNodes.Item(i).NodeType == NodeType.Element) xml += ChildNodes.Item(i).ToString(); else if (ChildNodes.Item(i).NodeType == NodeType.Text) xml += ChildNodes.Item(i).Value; } } catch (Exception) { } return xml; } return null; } set { Document doc = new Document(); doc.LoadXml(value); Element root = doc.RootElement; if (root != null) { ChildNodes.Clear(); AddChild(root); } } } /// <summary> /// returns whether the current element has child elements or not. /// cares only about element, not text nodes etc... /// </summary> public bool HasChildElements { get { foreach (Node e in ChildNodes) { if (e.NodeType == NodeType.Element) return true; } return false; } } /// <summary> /// returns the first child element (no textNodes) /// </summary> public Element FirstChild { get { if (ChildNodes.Count > 0) { foreach (Node e in ChildNodes) { if (e.NodeType == NodeType.Element) return e as Element; } return null; } return null; } } /// <summary> /// Returns the first ChildNode, doesnt matter of which type it is /// </summary> public Node FirstNode { get { if(ChildNodes.Count > 0) return ChildNodes.Item(0) as Node; return null; } } /// <summary> /// Returns the last ChildNode, doesnt matter of which type it is /// </summary> public Node LastNode { get { if(ChildNodes.Count > 0) return ChildNodes.Item(ChildNodes.Count -1) as Node; return null; } } internal string StartTag() { using (StringWriter sw = new StringWriter()) { using (XmlTextWriter tw = new XmlTextWriter(sw)) { tw.Formatting = Formatting.None; if (Prefix == null) tw.WriteStartElement(TagName); else tw.WriteStartElement(Prefix + ":" + TagName); // Write Namespace if (Namespace != null && Namespace.Length != 0 ) { if (Prefix == null) tw.WriteAttributeString("xmlns", Namespace); else tw.WriteAttributeString("xmlns:" + Prefix, Namespace); } foreach (string attName in this.Attributes.Keys) { tw.WriteAttributeString(attName, Attribute(attName)); } tw.Flush(); tw.Close(); return sw.ToString().Replace("/>", ">"); } } } internal string EndTag() { if (Prefix == null) return "</" + TagName + ">"; return "</" + Prefix + ":" + TagName + ">"; } #region << Xml Select Functions >> /// <summary> /// Find a Element by type /// </summary> /// <param name="type"></param> /// <returns></returns> public Element SelectSingleElement(System.Type type) { return _SelectElement(this, type); } /// <summary> /// find a Element by type and loop thru all children /// </summary> /// <param name="type"></param> /// <param name="loopChildren"></param> /// <returns></returns> public Element SelectSingleElement(System.Type type, bool loopChildren) { return _SelectElement(this, type, true); } public Element SelectSingleElement(string TagName) { return _SelectElement(this, TagName); } public Element SelectSingleElement(string TagName, bool traverseChildren) { return _SelectElement(this, TagName, true); } public Element SelectSingleElement(string TagName, string AttribName, string AttribValue) { return _SelectElement(this, TagName, AttribName, AttribValue); } public Element SelectSingleElement(string TagName, string ns) { return _SelectElement(this, TagName, ns, true); } public Element SelectSingleElement(string TagName, string ns, bool traverseChildren) { return _SelectElement(this, TagName, ns, traverseChildren); } public T SelectSingleElement<T>() where T : Element { return (T)_SelectElement(this, typeof(T)); } public T SelectSingleElement<T>(bool traverseChildren) where T : Element { return (T)_SelectElement(this, typeof(T), traverseChildren); } /// <summary> /// Returns all childNodes with the given Tagname, /// this function doesn't traverse the whole tree!!! /// </summary> /// <param name="TagName"></param> /// <returns></returns> public ElementList SelectElements(string TagName) { ElementList es = new ElementList(); //return this._SelectElements(this, TagName, es); return _SelectElements(this, TagName, es, false); } public ElementList SelectElements(string TagName, bool traverseChildren) { ElementList es = new ElementList(); //return this._SelectElements(this, TagName, es); return _SelectElements(this, TagName, es, traverseChildren); } public ElementList SelectElements(System.Type type) { ElementList es = new ElementList(); return _SelectElements(this, type, es); } /// <summary> /// returns a nodelist of all found nodes of the given Type /// </summary> /// <param name="e"></param> /// <param name="type"></param> /// <param name="es"></param> /// <returns></returns> private ElementList _SelectElements(Element e, Type type, ElementList es) { return _SelectElements(e, type, es, false); } private ElementList _SelectElements(Element e, Type type, ElementList es, bool traverseChildren) { if (e.ChildNodes.Count > 0) { foreach(Node n in e.ChildNodes) { if (n.NodeType == NodeType.Element) { if (n.GetType() == type) { es.Add(n); } if (traverseChildren) _SelectElements((Element) n, type, es, true); } } } return es; } /// <summary> /// Select a single element. /// This function doesnt traverse the whole tree and checks only the underlying childnodes /// </summary> /// <param name="se"></param> /// <param name="tagname"></param> /// <returns></returns> private Element _SelectElement(Node se, string tagname) { return _SelectElement(se, tagname, false); } /// <summary> /// Select a single element /// </summary> /// <param name="se"></param> /// <param name="tagname"></param> /// <param name="traverseChildren">when set to true then the function traverses the whole tree</param> /// <returns></returns> private Element _SelectElement(Node se, string tagname, bool traverseChildren) { Element rElement = null; if (se.ChildNodes.Count > 0) { foreach(Node ch in se.ChildNodes) { if (ch.NodeType == NodeType.Element) { if ( ((Element) ch).TagName == tagname ) { rElement = (Element) ch; return rElement; } else { if( traverseChildren) { rElement = _SelectElement(ch, tagname, true); if (rElement != null) break; } } } } } return rElement; } private Element _SelectElement(Node se, System.Type type) { return _SelectElement(se, type, false); } private Element _SelectElement(Node se, System.Type type, bool traverseChildren) { Element rElement = null; if (se.ChildNodes.Count > 0) { foreach(Node ch in se.ChildNodes) { if (ch.NodeType == NodeType.Element) { if ( ch.GetType() == type ) { rElement = (Element) ch; return rElement; } else { if( traverseChildren) { rElement = _SelectElement(ch, type, true); if (rElement != null) break; } } } } } return rElement; } private Element _SelectElement(Node se, string tagname, string AttribName, string AttribValue) { Element rElement = null; if (se.NodeType == NodeType.Element) { Element e = se as Element; if (e.m_TagName == tagname) { if (e.HasAttribute(AttribName)) { if (e.GetAttribute(AttribName) == AttribValue) { rElement = e; return rElement; } } } } if (se.ChildNodes.Count > 0) { foreach(Node ch in se.ChildNodes) { rElement = _SelectElement(ch, tagname, AttribName, AttribValue); if (rElement != null) break; } } return rElement; } /// <summary> /// Find Element by Namespace /// </summary> /// <param name="se">The se.</param> /// <param name="tagname">The tagname.</param> /// <param name="nameSpace">The name space.</param> /// <param name="traverseChildren">if set to <c>true</c> [traverse children].</param> /// <returns></returns> private Element _SelectElement(Node se, string tagname, string nameSpace, bool traverseChildren) { Element rElement = null; if (se.ChildNodes.Count > 0) { foreach (Node ch in se.ChildNodes) { if (ch.NodeType == NodeType.Element) { Element e = ch as Element; if (e.TagName == tagname && e.Namespace == nameSpace) { rElement = (Element)ch; return rElement; } else { if (traverseChildren) { rElement = _SelectElement(ch, tagname, nameSpace, traverseChildren); if (rElement != null) break; } } } } } return rElement; } private ElementList _SelectElements(Element e, string tagname, ElementList es, bool traverseChildren) { if (e.ChildNodes.Count > 0) { foreach(Node n in e.ChildNodes) { if (n.NodeType == NodeType.Element) { if ( ((Element) n).m_TagName == tagname) { es.Add(n); } if (traverseChildren) _SelectElements((Element) n, tagname, es, true); } } } return es; } public List<T> SelectElements<T>() where T : Element { return SelectElements<T>(false); } public List<T> SelectElements<T>(bool traverseChildren) where T : Element { List<T> list = new List<T>(); return this._SelectElements<T>(this, list, traverseChildren); } private List<T> _SelectElements<T>(Element e, List<T> list, bool traverseChildren) where T : Element { if (e.ChildNodes.Count > 0) { foreach (Node n in e.ChildNodes) { if (n.NodeType == NodeType.Element) { if (n.GetType() == typeof(T)) { list.Add(n as T); } if (traverseChildren) _SelectElements((Element)n, list, true); } } } return list; } #endregion } }
27.233119
111
0.507586
[ "MIT" ]
gouri1shankar/JabberClient-with-roster-user
agsxmpp/Xml/Dom/Element.cs
33,878
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by Codezu. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using Mozu.Api.Contracts.Core; namespace Mozu.Api.Contracts.SiteSettings.Order.Fulfillment { public class FulfillmentSettings { public string ActionOnBOPISReject { get; set; } public AuditInfo AuditInfo { get; set; } public BPMConfiguration BpmConfiguration { get; set; } public int? DefaultBackOrderDays { get; set; } public FulfillerSettings FulfillerSettings { get; set; } public JobSettings FulfillmentJobSettings { get; set; } public ShipToStore ShipToStore { get; set; } } }
25.571429
80
0.582123
[ "MIT" ]
Mozu/mozu-dotnet
Mozu.Api/Contracts/SiteSettings/Order/Fulfillment/FulfillmentSettings.cs
895
C#
using Skoruba.IdentityServer4.Admin.BusinessLogic.Identity.Dtos.Identity.Interfaces; using System.Collections.Generic; namespace Skoruba.IdentityServer4.Admin.BusinessLogic.Identity.Dtos.Identity.Base { public class BaseUserDto<TUserId> : IBaseUserDto { public TUserId Id { get; set; } public bool IsDefaultId() => EqualityComparer<TUserId>.Default.Equals(Id, default(TUserId)); object IBaseUserDto.Id => Id; } }
32.285714
100
0.738938
[ "MIT" ]
1n5an1ty/IdentityServer4.Admin
src/Skoruba.IdentityServer4.Admin.BusinessLogic.Identity/Dtos/Identity/Base/BaseUserDto.cs
454
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.IO; using System.Threading; namespace Amazon.KinesisTap.DiagnosticTool.Core { /// <summary> /// The class for Directory watcher /// </summary> public class DirectoryWatcher : IDisposable { private readonly string _directory; private readonly string _filer; FileSystemWatcher _watcher; TextWriter _writer; Timer _timer; /// <summary> /// Directory Watcher constructor /// </summary> /// <param name="directory"></param> /// <param name="filter"></param> /// <param name="writer"></param> public DirectoryWatcher(string directory, string filter, TextWriter writer) { _directory = directory; _filer = filter; _writer = writer; _timer = new Timer(OnTimer, null, 1000, 1000); _watcher = new FileSystemWatcher(); _watcher.Path = directory; _watcher.Filter = filter; _watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size; _watcher.Changed += new FileSystemEventHandler(this.OnChanged); _watcher.Created += new FileSystemEventHandler(this.OnChanged); _watcher.Deleted += new FileSystemEventHandler(this.OnChanged); _watcher.Renamed += new RenamedEventHandler(this.OnRenamed); _watcher.EnableRaisingEvents = true; } /// <summary> /// Print out message if there is remaning in the current directory /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnRenamed(object sender, RenamedEventArgs e) { _writer.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath); } /// <summary> /// Print out message if there is any file changed in the current directory /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnChanged(object sender, FileSystemEventArgs e) { _writer.WriteLine($"File: {e.FullPath} ChangeType: {e.ChangeType}"); } protected void OnTimer(object stateInfo) { var files = Directory.GetFiles(_directory, _filer); foreach(var file in files) { var fi = new FileInfo(file); var l = fi.Length; } } protected virtual void Dispose(bool disposing) { _watcher.Dispose(); _timer.Dispose(); } public void Dispose() { Dispose(true); } } }
32.441176
106
0.596857
[ "Apache-2.0" ]
aspcompiler/kinesis-agent-windows
Amazon.KinesisTap.DiagnosticTool.Core/DirectoryWatcher.cs
3,309
C#
//***** AUTO-GENERATED - DO NOT EDIT *****// using BlueprintCore.Utils; using Kingmaker.Blueprints; using Kingmaker.Blueprints.Items; namespace BlueprintCore.Blueprints.Configurators.Items { /// <summary> /// Configurator for <see cref="BlueprintItemThiefTool"/>. /// </summary> /// <inheritdoc/> public class ItemThiefToolConfigurator : BaseItemThiefToolConfigurator<BlueprintItemThiefTool, ItemThiefToolConfigurator> { private ItemThiefToolConfigurator(Blueprint<BlueprintReference<BlueprintItemThiefTool>> blueprint) : base(blueprint) { } /// <summary> /// Returns a configurator to modify the specified blueprint. /// </summary> /// <remarks> /// <para> /// Use this to modify existing blueprints, such as blueprints from the base game. /// </para> /// <para> /// If you're using <see href="https://github.com/OwlcatOpenSource/WrathModificationTemplate">WrathModificationTemplate</see> blueprints defined in JSON already exist. /// </para> /// </remarks> public static ItemThiefToolConfigurator For(Blueprint<BlueprintReference<BlueprintItemThiefTool>> blueprint) { return new ItemThiefToolConfigurator(blueprint); } /// <summary> /// Creates a new blueprint and returns a new configurator to modify it. /// </summary> /// <remarks> /// <para> /// After creating a blueprint with this method you can use either name or GUID to reference the blueprint in BlueprintCore API calls. /// </para> /// <para> /// An implicit cast converts the string to <see cref="Utils.Blueprint{TRef}"/>, exposing the blueprint instance and its reference. /// </para> /// </remarks> public static ItemThiefToolConfigurator New(string name, string guid) { BlueprintTool.Create<BlueprintItemThiefTool>(name, guid); return For(name); } } }
36.057692
171
0.691733
[ "MIT" ]
TylerGoeringer/WW-Blueprint-Core
BlueprintCore/BlueprintCore/Blueprints/Configurators/Items/ItemThiefTool.cs
1,875
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the kms-2014-11-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.KeyManagementService.Model { /// <summary> /// Container for the parameters to the Decrypt operation. /// Decrypts ciphertext. Ciphertext is plaintext that has been previously encrypted by /// using any of the following functions: <ul> <li><a>GenerateDataKey</a></li> <li><a>GenerateDataKeyWithoutPlaintext</a></li> /// <li><a>Encrypt</a></li> </ul> /// /// /// <para> /// Note that if a caller has been granted access permissions to all keys (through, for /// example, IAM user policies that grant <code>Decrypt</code> permission on all resources), /// then ciphertext encrypted by using keys in other accounts where the key grants access /// to the caller can be decrypted. To remedy this, we recommend that you do not grant /// <code>Decrypt</code> access in an IAM user policy. Instead grant <code>Decrypt</code> /// access only in key policies. If you must grant <code>Decrypt</code> access in an IAM /// user policy, you should scope the resource to specific keys or to specific trusted /// accounts. /// </para> /// </summary> public partial class DecryptRequest : AmazonKeyManagementServiceRequest { private MemoryStream _ciphertextBlob; private Dictionary<string, string> _encryptionContext = new Dictionary<string, string>(); private List<string> _grantTokens = new List<string>(); /// <summary> /// Gets and sets the property CiphertextBlob. /// <para> /// Ciphertext to be decrypted. The blob includes metadata. /// </para> /// </summary> public MemoryStream CiphertextBlob { get { return this._ciphertextBlob; } set { this._ciphertextBlob = value; } } // Check to see if CiphertextBlob property is set internal bool IsSetCiphertextBlob() { return this._ciphertextBlob != null; } /// <summary> /// Gets and sets the property EncryptionContext. /// <para> /// The encryption context. If this was specified in the <a>Encrypt</a> function, it must /// be specified here or the decryption operation will fail. For more information, see /// <a href="http://docs.aws.amazon.com/kms/latest/developerguide/encrypt-context.html">Encryption /// Context</a>. /// </para> /// </summary> public Dictionary<string, string> EncryptionContext { get { return this._encryptionContext; } set { this._encryptionContext = value; } } // Check to see if EncryptionContext property is set internal bool IsSetEncryptionContext() { return this._encryptionContext != null && this._encryptionContext.Count > 0; } /// <summary> /// Gets and sets the property GrantTokens. /// <para> /// For more information, see <a href="http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token">Grant /// Tokens</a>. /// </para> /// </summary> public List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } // Check to see if GrantTokens property is set internal bool IsSetGrantTokens() { return this._grantTokens != null && this._grantTokens.Count > 0; } } }
38.548673
132
0.638659
[ "Apache-2.0" ]
jasoncwik/aws-sdk-net
sdk/src/Services/KeyManagementService/Generated/Model/DecryptRequest.cs
4,356
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FlowAnalysis.SymbolUsageAnalysis { internal static partial class SymbolUsageAnalysis { /// <summary> /// Dataflow analysis to compute symbol usage information (i.e. reads/writes) for locals/parameters /// in a given control flow graph, along with the information of whether or not the writes /// may be read on some control flow path. /// </summary> private sealed partial class DataFlowAnalyzer : DataFlowAnalyzer<BasicBlockAnalysisData> { private readonly FlowGraphAnalysisData _analysisData; private DataFlowAnalyzer(ControlFlowGraph cfg, ISymbol owningSymbol) => _analysisData = FlowGraphAnalysisData.Create(cfg, owningSymbol, AnalyzeLocalFunctionOrLambdaInvocation); private DataFlowAnalyzer( ControlFlowGraph cfg, IMethodSymbol lambdaOrLocalFunction, FlowGraphAnalysisData parentAnalysisData) { _analysisData = FlowGraphAnalysisData.Create(cfg, lambdaOrLocalFunction, parentAnalysisData); var entryBlockAnalysisData = GetEmptyAnalysisData(); entryBlockAnalysisData.SetAnalysisDataFrom(parentAnalysisData.CurrentBlockAnalysisData); _analysisData.SetBlockAnalysisData(cfg.EntryBlock(), entryBlockAnalysisData); } public static SymbolUsageResult RunAnalysis(ControlFlowGraph cfg, ISymbol owningSymbol, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var analyzer = new DataFlowAnalyzer(cfg, owningSymbol); _ = CustomDataFlowAnalysis<BasicBlockAnalysisData>.Run(cfg, analyzer, cancellationToken); return analyzer._analysisData.ToResult(); } public override void Dispose() => _analysisData.Dispose(); private static BasicBlockAnalysisData AnalyzeLocalFunctionOrLambdaInvocation( IMethodSymbol localFunctionOrLambda, ControlFlowGraph cfg, AnalysisData parentAnalysisData, CancellationToken cancellationToken) { Debug.Assert(localFunctionOrLambda.IsLocalFunction() || localFunctionOrLambda.IsAnonymousFunction()); cancellationToken.ThrowIfCancellationRequested(); using var analyzer = new DataFlowAnalyzer(cfg, localFunctionOrLambda, (FlowGraphAnalysisData)parentAnalysisData); var resultBlockAnalysisData = CustomDataFlowAnalysis<BasicBlockAnalysisData>.Run(cfg, analyzer, cancellationToken); if (resultBlockAnalysisData == null) { // Unreachable exit block from lambda/local. // So use our current analysis data. return parentAnalysisData.CurrentBlockAnalysisData; } // We need to return a cloned basic block analysis data as disposing the DataFlowAnalyzer // created above will dispose all basic block analysis data instances allocated by it. var clonedBasicBlockData = parentAnalysisData.CreateBlockAnalysisData(); clonedBasicBlockData.SetAnalysisDataFrom(resultBlockAnalysisData); return clonedBasicBlockData; } // Don't analyze blocks which are unreachable, as any write // in such a block which has a read outside will be marked redundant, which will just be noise for users. // For example, // int x; // if (true) // x = 0; // else // x = 1; // This will be marked redundant if "AnalyzeUnreachableBlocks = true" // return x; public override bool AnalyzeUnreachableBlocks => false; public override BasicBlockAnalysisData AnalyzeBlock(BasicBlock basicBlock, CancellationToken cancellationToken) { BeforeBlockAnalysis(); Walker.AnalyzeOperationsAndUpdateData(_analysisData.OwningSymbol, basicBlock.Operations, _analysisData, cancellationToken); AfterBlockAnalysis(); return _analysisData.CurrentBlockAnalysisData; // Local functions. void BeforeBlockAnalysis() { // Initialize current block analysis data. _analysisData.SetCurrentBlockAnalysisDataFrom(basicBlock, cancellationToken); // At start of entry block, handle parameter definitions from method declaration. if (basicBlock.Kind == BasicBlockKind.Entry) { _analysisData.SetAnalysisDataOnEntryBlockStart(); } } void AfterBlockAnalysis() { // If we are exiting the control flow graph, handle ref/out parameter definitions from method declaration. if (basicBlock.FallThroughSuccessor?.Destination == null && basicBlock.ConditionalSuccessor?.Destination == null) { _analysisData.SetAnalysisDataOnMethodExit(); } } } public override BasicBlockAnalysisData AnalyzeNonConditionalBranch( BasicBlock basicBlock, BasicBlockAnalysisData currentBlockAnalysisData, CancellationToken cancellationToken) => AnalyzeBranch(basicBlock.FallThroughSuccessor, basicBlock, currentBlockAnalysisData, cancellationToken); public override (BasicBlockAnalysisData fallThroughSuccessorData, BasicBlockAnalysisData conditionalSuccessorData) AnalyzeConditionalBranch( BasicBlock basicBlock, BasicBlockAnalysisData currentAnalysisData, CancellationToken cancellationToken) { // Ensure that we use distinct input BasicBlockAnalysisData instances with identical analysis data for both AnalyzeBranch invocations. using var savedCurrentAnalysisData = BasicBlockAnalysisData.GetInstance(); savedCurrentAnalysisData.SetAnalysisDataFrom(currentAnalysisData); var newCurrentAnalysisData = AnalyzeBranch(basicBlock.FallThroughSuccessor, basicBlock, currentAnalysisData, cancellationToken); // Ensure that we use different instances of block analysis data for fall through successor and conditional successor. _analysisData.AdditionalConditionalBranchAnalysisData.SetAnalysisDataFrom(newCurrentAnalysisData); var fallThroughSuccessorData = _analysisData.AdditionalConditionalBranchAnalysisData; var conditionalSuccessorData = AnalyzeBranch(basicBlock.ConditionalSuccessor, basicBlock, savedCurrentAnalysisData, cancellationToken); return (fallThroughSuccessorData, conditionalSuccessorData); } private BasicBlockAnalysisData AnalyzeBranch( ControlFlowBranch branch, BasicBlock basicBlock, BasicBlockAnalysisData currentBlockAnalysisData, CancellationToken cancellationToken) { // Initialize current analysis data _analysisData.SetCurrentBlockAnalysisDataFrom(currentBlockAnalysisData); // Analyze the branch value var operations = SpecializedCollections.SingletonEnumerable(basicBlock.BranchValue); Walker.AnalyzeOperationsAndUpdateData(_analysisData.OwningSymbol, operations, _analysisData, cancellationToken); ProcessOutOfScopeLocals(); return _analysisData.CurrentBlockAnalysisData; // Local functions void ProcessOutOfScopeLocals() { if (branch == null) { return; } if (basicBlock.EnclosingRegion.Kind == ControlFlowRegionKind.Catch && !branch.FinallyRegions.IsEmpty) { // Bail out for branches from the catch block // as the locals are still accessible in the finally region. return; } foreach (var region in branch.LeavingRegions) { foreach (var local in region.Locals) { _analysisData.CurrentBlockAnalysisData.Clear(local); } if (region.Kind == ControlFlowRegionKind.TryAndFinally) { // Locals defined in the outer regions of try/finally might be used in finally region. break; } } } } public override BasicBlockAnalysisData GetCurrentAnalysisData(BasicBlock basicBlock) => _analysisData.GetBlockAnalysisData(basicBlock) ?? GetEmptyAnalysisData(); public override BasicBlockAnalysisData GetEmptyAnalysisData() => _analysisData.CreateBlockAnalysisData(); public override void SetCurrentAnalysisData(BasicBlock basicBlock, BasicBlockAnalysisData data, CancellationToken cancellationToken) => _analysisData.SetBlockAnalysisDataFrom(basicBlock, data, cancellationToken); public override bool IsEqual(BasicBlockAnalysisData analysisData1, BasicBlockAnalysisData analysisData2) => analysisData1 == null ? analysisData2 == null : analysisData1.Equals(analysisData2); public override BasicBlockAnalysisData Merge( BasicBlockAnalysisData analysisData1, BasicBlockAnalysisData analysisData2, CancellationToken cancellationToken) => BasicBlockAnalysisData.Merge(analysisData1, analysisData2, _analysisData.TrackAllocatedBlockAnalysisData); } } }
50.481132
152
0.630536
[ "MIT" ]
333fred/roslyn
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.DataFlowAnalyzer.cs
10,704
C#
using System; namespace BitCoinExchangeRate.Model { // Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); public class Time { public string Updated { get; set; } public DateTime UpdatedISO { get; set; } public string Updateduk { get; set; } } public class USD { public string Code { get; set; } public string Symbol { get; set; } public string Rate { get; set; } public string Description { get; set; } public double Rate_float { get; set; } } public class GBP { public string Code { get; set; } public string Symbol { get; set; } public string Rate { get; set; } public string Description { get; set; } public double Rate_float { get; set; } } public class EUR { public string Code { get; set; } public string Symbol { get; set; } public string Rate { get; set; } public string Description { get; set; } public double Rate_float { get; set; } } public class Bpi { public USD USD { get; set; } public GBP GBP { get; set; } public EUR EUR { get; set; } } public class Root { public Time Time { get; set; } public string Disclaimer { get; set; } public string ChartName { get; set; } public Bpi Bpi { get; set; } } }
21.583333
85
0.620077
[ "MIT" ]
fredatgithub/BitCoinPrice
BitCoinExchangeRate/Model/USD.cs
1,297
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Configurations; using Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Helpers; using Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Models; using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Infrastructure.Models; using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Infrastructure.Repository; using Microsoft.WindowsAzure.Storage.Table; using Moq; using Newtonsoft.Json; using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoMoq; using Xunit; namespace Microsoft.Azure.Devices.Applications.RemoteMonitoring.UnitTests.Infrastructure { public class DeviceRulesRepositoryTests { private readonly Mock<IBlobStorageClient> _blobClientMock; private readonly Mock<IAzureTableStorageClient> _tableStorageClientMock; private readonly DeviceRulesRepository deviceRulesRepository; private readonly IFixture fixture; public DeviceRulesRepositoryTests() { fixture = new Fixture(); var configProviderMock = new Mock<IConfigurationProvider>(); _tableStorageClientMock = new Mock<IAzureTableStorageClient>(); _blobClientMock = new Mock<IBlobStorageClient>(); configProviderMock.Setup(x => x.GetConfigurationSettingValue(It.IsNotNull<string>())) .ReturnsUsingFixture(fixture); var tableStorageClientFactory = new AzureTableStorageClientFactory(_tableStorageClientMock.Object); var blobClientFactory = new BlobStorageClientFactory(_blobClientMock.Object); deviceRulesRepository = new DeviceRulesRepository(configProviderMock.Object, tableStorageClientFactory, blobClientFactory); } [Fact] public async void GetAllRulesAsyncTest() { var ruleEntities = fixture.Create<List<DeviceRuleTableEntity>>(); _tableStorageClientMock.Setup(x => x.ExecuteQueryAsync(It.IsNotNull<TableQuery<DeviceRuleTableEntity>>())) .ReturnsAsync(ruleEntities); var deviceRules = await deviceRulesRepository.GetAllRulesAsync(); Assert.NotNull(deviceRules); Assert.Equal(ruleEntities.Count, deviceRules.Count); Assert.Equal(ruleEntities[0].DataField, deviceRules[0].DataField); Assert.Equal(ruleEntities[0].DeviceId, deviceRules[0].DeviceID); Assert.Equal(ruleEntities[0].Threshold, deviceRules[0].Threshold); Assert.Equal(">", deviceRules[0].Operator); Assert.Equal(ruleEntities[0].RuleOutput, deviceRules[0].RuleOutput); Assert.Equal(ruleEntities[0].ETag, deviceRules[0].Etag); } [Fact] public async void GetDeviceRuleAsyncTest() { var ruleEntity = fixture.Create<DeviceRuleTableEntity>(); _tableStorageClientMock.Setup(x => x.Execute(It.IsNotNull<TableOperation>())) .Returns(new TableResult {Result = ruleEntity}); var ret = await deviceRulesRepository.GetDeviceRuleAsync(ruleEntity.DeviceId, ruleEntity.RuleId); Assert.NotNull(ret); Assert.Equal(ruleEntity.DeviceId, ret.DeviceID); Assert.Equal(ruleEntity.DataField, ret.DataField); Assert.Equal(ruleEntity.Threshold, ret.Threshold); Assert.Equal(">", ret.Operator); Assert.Equal(ruleEntity.RuleOutput, ret.RuleOutput); Assert.Equal(ruleEntity.ETag, ret.Etag); } [Fact] public async void GetAllRulesForDeviceAsyncTest() { var ruleEntities = fixture.Create<List<DeviceRuleTableEntity>>(); ruleEntities.ForEach(x => x.DeviceId = "DeviceXXXId"); _tableStorageClientMock.Setup(x => x.ExecuteQueryAsync(It.IsNotNull<TableQuery<DeviceRuleTableEntity>>())) .ReturnsAsync(ruleEntities); var deviceRules = await deviceRulesRepository.GetAllRulesForDeviceAsync("DeviceXXXId"); Assert.NotNull(deviceRules); Assert.Equal(ruleEntities.Count, deviceRules.Count); Assert.Equal(ruleEntities[0].DataField, deviceRules[0].DataField); Assert.Equal(ruleEntities[0].DeviceId, deviceRules[0].DeviceID); Assert.Equal(ruleEntities[0].Threshold, deviceRules[0].Threshold); Assert.Equal(">", deviceRules[0].Operator); Assert.Equal(ruleEntities[0].RuleOutput, deviceRules[0].RuleOutput); Assert.Equal(ruleEntities[0].ETag, deviceRules[0].Etag); } [Fact] public async void SaveDeviceRuleAsyncTest() { var newRule = fixture.Create<DeviceRule>(); DeviceRuleTableEntity tableEntity = null; var resp = new TableStorageResponse<DeviceRule> { Entity = newRule, Status = TableStorageResponseStatus.Successful }; _tableStorageClientMock.Setup( x => x.DoTableInsertOrReplaceAsync(It.IsNotNull<DeviceRuleTableEntity>(), It.IsNotNull<Func<DeviceRuleTableEntity, DeviceRule>>())) .Callback<DeviceRuleTableEntity, Func<DeviceRuleTableEntity, DeviceRule>>( (entity, func) => tableEntity = entity) .ReturnsAsync(resp); var tableEntities = fixture.Create<List<DeviceRuleTableEntity>>(); _tableStorageClientMock.Setup(x => x.ExecuteQueryAsync(It.IsNotNull<TableQuery<DeviceRuleTableEntity>>())) .ReturnsAsync(tableEntities); string blobEntititesStr = null; _blobClientMock.Setup(x => x.UploadTextAsync(It.IsNotNull<string>(), It.IsNotNull<string>())) .Callback<string, string>((name, blob) => blobEntititesStr = blob) .Returns(Task.FromResult(true)); var ret = await deviceRulesRepository.SaveDeviceRuleAsync(newRule); Assert.NotNull(ret); Assert.Equal(resp, ret); Assert.NotNull(tableEntity); Assert.Equal(newRule.DeviceID, tableEntity.DeviceId); Assert.NotNull(blobEntititesStr); } [Fact] public async void DeleteDeviceRuleAsyncTest() { var newRule = fixture.Create<DeviceRule>(); DeviceRuleTableEntity tableEntity = null; var resp = new TableStorageResponse<DeviceRule> { Entity = newRule, Status = TableStorageResponseStatus.Successful }; _tableStorageClientMock.Setup( x => x.DoDeleteAsync(It.IsNotNull<DeviceRuleTableEntity>(), It.IsNotNull<Func<DeviceRuleTableEntity, DeviceRule>>())) .Callback<DeviceRuleTableEntity, Func<DeviceRuleTableEntity, DeviceRule>>( (entity, func) => tableEntity = entity) .ReturnsAsync(resp); var tableEntities = fixture.Create<List<DeviceRuleTableEntity>>(); _tableStorageClientMock.Setup(x => x.ExecuteQueryAsync(It.IsNotNull<TableQuery<DeviceRuleTableEntity>>())) .ReturnsAsync(tableEntities); string blobEntititesStr = null; _blobClientMock.Setup(x => x.UploadTextAsync(It.IsNotNull<string>(), It.IsNotNull<string>())) .Callback<string, string>((name, blob) => blobEntititesStr = blob) .Returns(Task.FromResult(true)); var ret = await deviceRulesRepository.DeleteDeviceRuleAsync(newRule); Assert.NotNull(ret); Assert.Equal(resp, ret); Assert.NotNull(tableEntity); Assert.Equal(newRule.DeviceID, tableEntity.DeviceId); Assert.NotNull(blobEntititesStr); } } }
51.603896
118
0.655719
[ "MIT" ]
Anchinga/TechnicalCommunityContent
IoT/Azure IoT Suite/Session 3 - Building Practical IoT Solutions/Solutions/Demo 3.2/UnitTests/Infrastructure/DeviceRulesRepositoryTests.cs
7,949
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MaterialSurfaceExample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MaterialSurfaceExample")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("13e44d7e-220e-4adb-8c16-0684a4e04b3a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.162162
84
0.751416
[ "MIT" ]
princ3od/MaterialSurface
MaterialSurfaceExample/Properties/AssemblyInfo.cs
1,415
C#
//----------------------------------------------------------------------- // <copyright file="ConditionBase.cs" company="Company"> // Copyright (C) Company. All Rights Reserved. // </copyright> // <author>nainaigu</author> // <summary></summary> //----------------------------------------------------------------------- using System.ComponentModel; namespace ViewModels.Condition { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// 分页查询 /// </summary> public class ConditionBase { private int pageSize; /// <summary> /// 条数,默认10 /// </summary> [Description("条数,默认10")] public int PageSize { get { return pageSize <= 0 ? 10 : pageSize; } set { pageSize = value; } } private int pageIndex ; /// <summary> /// 页数,默认1 /// </summary> [Description("页数,默认1")] public int PageIndex { get { return pageIndex <= 0 ?1 : pageIndex; } set { pageIndex = value; } } private string orderBy; /// <summary> /// 排序字段 /// </summary> [Description("排序字段")] public string OrderBy { get { return orderBy; } set { orderBy = value; } } private string orderSequence; /// <summary> /// asc | desc /// </summary> [Description("asc | desc")] public string OrderSequence { get { return string.IsNullOrEmpty(orderSequence)?"asc": orderSequence; } set { orderSequence = value; } } /// <summary> /// 相应查询的sql /// </summary> public string Sql { get { return sql; } set { sql = value; } } private string sql; } }
23.214286
84
0.45641
[ "Apache-2.0" ]
sigeshitou/shenyu-mgr
ViewModels/ViewModels/Condition/ConditionBase.cs
2,018
C#
using ESI.NET; using ESI.NET.Enumerations; using ESI.NET.Models.Assets; using ESI.NET.Models.Character; using ESI.NET.Models.Corporation; using ESI.NET.Models.Industry; using ESI.NET.Models.Location; using ESI.NET.Models.Market; using ESI.NET.Models.SSO; using ESI.NET.Models.Wallet; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using System.Linq; using ESI.NET.Models.Skills; using ESI.NET.Models.Clones; using ESI.NET.Models.Fittings; using ESI.NET.Models; using System.Reflection; using ESI.NET.Models.Alliance; namespace EvEESITool { public class AllianceData : DataClassesBase { public Alliance Information { get; private set; } = new Alliance(); public Alliance GetAlliance(int allianceID) { return DownloadData("Alliance Information", Settings.EsiClient.Alliance.Information(allianceID)); } public List<int> Corporations { get; private set; } = new List<int>(); public List<int> GetCorporations(int allianceID) { return DownloadData("Alliance Corporations", Settings.EsiClient.Alliance.Corporations(AllianceID)); } public Images Icons { get; private set; } = new Images(); public Images GetIcons(int allianceID) { return DownloadData("Images", Settings.EsiClient.Alliance.Icons(AllianceID)); } public List<ESI.NET.Models.Contacts.Contact> Contacts { get; private set; } = new List<ESI.NET.Models.Contacts.Contact>(); public int AllianceID { get; set; } = 0; /// <summary> /// Do not remove this constructor. Even though it might say 0 references, it does get called by the deserialization in ReadInData() /// </summary> [JsonConstructor] internal AllianceData() { } internal AllianceData(ref ProfileSettings settings) : base(ref settings) { AllianceID = Settings.AuthorisationData.AllianceID; if (AllianceID > 0) { GetData(); } } protected override void Download() { Information = DownloadData("Information", Settings.EsiClient.Alliance.Information(AllianceID)); Corporations = DownloadData("Corporations", Settings.EsiClient.Alliance.Corporations(AllianceID)); Icons = DownloadData("Images", Settings.EsiClient.Alliance.Icons(AllianceID)); Contacts = DownloadData("Contacts", Settings.EsiClient.Contacts.ListForAlliance(1)); Console.WriteLine(); SaveToFile(); } protected override bool ReadInData() { using (StreamReader myReader = new StreamReader(SaveFile)) { AllianceData temp = Settings.MainSettings.serializer.Deserialize<AllianceData>(new JsonTextReader(myReader)); Console.Write($"Loading data from {Path.GetFileName(SaveFile)}"); Console.Write(" - successful"); Console.WriteLine(); return true; } } } }
33.427083
141
0.648489
[ "MIT" ]
DanFraserUK/EvEESITool
EvEESIDownloadTool/DataClasses/AllianceData.cs
3,211
C#
using System; using System.Text; using UnityEngine; using FairyGUI.Utils; namespace FairyGUI { /// <summary> /// /// </summary> public class DisplayObject : EventDispatcher { /// <summary> /// /// </summary> public string name; /// <summary> /// /// </summary> public Container parent { get; private set; } /// <summary> /// /// </summary> public GameObject gameObject { get; protected set; } /// <summary> /// /// </summary> public Transform cachedTransform { get; protected set; } /// <summary> /// /// </summary> public NGraphics graphics { get; protected set; } /// <summary> /// /// </summary> public NGraphics paintingGraphics { get; protected set; } /// <summary> /// /// </summary> public event Action onPaint; /// <summary> /// /// </summary> public GObject gOwner; /// <summary> /// /// </summary> public uint id; bool _visible; bool _touchable; Vector2 _pivot; Vector3 _pivotOffset; Vector3 _rotation; //由于万向锁,单独旋转一个轴是会影响到其他轴的,所以这里需要单独保存 Vector2 _skew; int _renderingOrder; float _alpha; bool _grayed; BlendMode _blendMode; IFilter _filter; Transform _home; string _cursor; bool _perspective; int _focalLength; Vector3 _pixelPerfectAdjustment; int _checkPixelPerfect; EventListener _onClick; EventListener _onRightClick; EventListener _onTouchBegin; EventListener _onTouchMove; EventListener _onTouchEnd; EventListener _onRollOver; EventListener _onRollOut; EventListener _onMouseWheel; EventListener _onAddedToStage; EventListener _onRemovedFromStage; EventListener _onKeyDown; EventListener _onClickLink; EventListener _onFocusIn; EventListener _onFocusOut; protected internal int _paintingMode; //1-滤镜,2-blendMode,4-transformMatrix, 8-cacheAsBitmap protected internal PaintingInfo _paintingInfo; protected Rect _contentRect; protected NGraphics.VertexMatrix _vertexMatrix; protected internal Flags _flags; protected internal float[] _batchingBounds; internal static uint _gInstanceCounter; internal static HideFlags hideFlags = HideFlags.None; public DisplayObject() { id = _gInstanceCounter++; _alpha = 1; _visible = true; _touchable = true; _blendMode = BlendMode.Normal; _focalLength = 2000; _flags |= Flags.OutlineChanged; if (UIConfig.makePixelPerfect) _flags |= Flags.PixelPerfect; } /// <summary> /// /// </summary> public EventListener onClick { get { return _onClick ?? (_onClick = new EventListener(this, "onClick")); } } /// <summary> /// /// </summary> public EventListener onRightClick { get { return _onRightClick ?? (_onRightClick = new EventListener(this, "onRightClick")); } } /// <summary> /// /// </summary> public EventListener onTouchBegin { get { return _onTouchBegin ?? (_onTouchBegin = new EventListener(this, "onTouchBegin")); } } /// <summary> /// /// </summary> public EventListener onTouchMove { get { return _onTouchMove ?? (_onTouchMove = new EventListener(this, "onTouchMove")); } } /// <summary> /// /// </summary> public EventListener onTouchEnd { get { return _onTouchEnd ?? (_onTouchEnd = new EventListener(this, "onTouchEnd")); } } /// <summary> /// /// </summary> public EventListener onRollOver { get { return _onRollOver ?? (_onRollOver = new EventListener(this, "onRollOver")); } } /// <summary> /// /// </summary> public EventListener onRollOut { get { return _onRollOut ?? (_onRollOut = new EventListener(this, "onRollOut")); } } /// <summary> /// /// </summary> public EventListener onMouseWheel { get { return _onMouseWheel ?? (_onMouseWheel = new EventListener(this, "onMouseWheel")); } } /// <summary> /// /// </summary> public EventListener onAddedToStage { get { return _onAddedToStage ?? (_onAddedToStage = new EventListener(this, "onAddedToStage")); } } /// <summary> /// /// </summary> public EventListener onRemovedFromStage { get { return _onRemovedFromStage ?? (_onRemovedFromStage = new EventListener(this, "onRemovedFromStage")); } } /// <summary> /// /// </summary> public EventListener onKeyDown { get { return _onKeyDown ?? (_onKeyDown = new EventListener(this, "onKeyDown")); } } /// <summary> /// /// </summary> public EventListener onClickLink { get { return _onClickLink ?? (_onClickLink = new EventListener(this, "onClickLink")); } } /// <summary> /// /// </summary> public EventListener onFocusIn { get { return _onFocusIn ?? (_onFocusIn = new EventListener(this, "onFocusIn")); } } /// <summary> /// /// </summary> public EventListener onFocusOut { get { return _onFocusOut ?? (_onFocusOut = new EventListener(this, "onFocusOut")); } } protected void CreateGameObject(string gameObjectName) { gameObject = new GameObject(gameObjectName); cachedTransform = gameObject.transform; if (Application.isPlaying) { UnityEngine.Object.DontDestroyOnLoad(gameObject); DisplayObjectInfo info = gameObject.AddComponent<DisplayObjectInfo>(); info.displayObject = this; } gameObject.hideFlags = DisplayObject.hideFlags; gameObject.SetActive(false); } protected void SetGameObject(GameObject gameObject) { this.gameObject = gameObject; this.cachedTransform = gameObject.transform; _rotation = cachedTransform.localEulerAngles; _flags |= Flags.UserGameObject; } protected void DestroyGameObject() { if ((_flags & Flags.UserGameObject) == 0 && gameObject != null) { if (Application.isPlaying) GameObject.Destroy(gameObject); else GameObject.DestroyImmediate(gameObject); gameObject = null; cachedTransform = null; } } /// <summary> /// /// </summary> public float alpha { get { return _alpha; } set { _alpha = value; } } /// <summary> /// /// </summary> public bool grayed { get { return _grayed; } set { _grayed = value; } } /// <summary> /// /// </summary> public bool visible { get { return _visible; } set { if (_visible != value) { _visible = value; _flags |= Flags.OutlineChanged; if (parent != null && _visible) { gameObject.SetActive(true); InvalidateBatchingState(); if (this is Container) ((Container)this).InvalidateBatchingState(true); } else gameObject.SetActive(false); } } } /// <summary> /// /// </summary> public float x { get { return cachedTransform.localPosition.x; } set { SetPosition(value, -cachedTransform.localPosition.y, cachedTransform.localPosition.z); } } /// <summary> /// /// </summary> public float y { get { return -cachedTransform.localPosition.y; } set { SetPosition(cachedTransform.localPosition.x, value, cachedTransform.localPosition.z); } } /// <summary> /// /// </summary> public float z { get { return cachedTransform.localPosition.z; } set { SetPosition(cachedTransform.localPosition.x, -cachedTransform.localPosition.y, value); } } /// <summary> /// /// </summary> public Vector2 xy { get { return new Vector2(this.x, this.y); } set { SetPosition(value.x, value.y, cachedTransform.localPosition.z); } } /// <summary> /// /// </summary> public Vector3 position { get { return new Vector3(this.x, this.y, this.z); } set { SetPosition(value.x, value.y, value.z); } } /// <summary> /// /// </summary> /// <param name="xv"></param> /// <param name="yv"></param> public void SetXY(float xv, float yv) { SetPosition(xv, yv, cachedTransform.localPosition.z); } /// <summary> /// /// </summary> /// <param name="xv"></param> /// <param name="yv"></param> /// <param name="zv"></param> public void SetPosition(float xv, float yv, float zv) { Vector3 v = new Vector3(); v.x = xv; v.y = -yv; v.z = zv; if (v != cachedTransform.localPosition) { cachedTransform.localPosition = v; _flags |= Flags.OutlineChanged; if ((_flags & Flags.PixelPerfect) != 0) { //总在下一帧再完成PixelPerfect,这样当物体在连续运动时,不会因为PixelPerfect而发生抖动。 _checkPixelPerfect = Time.frameCount; _pixelPerfectAdjustment = Vector3.zero; } } } /// <summary> /// If the object position is align by pixel /// </summary> public bool pixelPerfect { get { return (_flags & Flags.PixelPerfect) != 0; } set { if (value) _flags |= Flags.PixelPerfect; else _flags &= ~Flags.PixelPerfect; } } /// <summary> /// /// </summary> public float width { get { EnsureSizeCorrect(); return _contentRect.width; } set { if (!Mathf.Approximately(value, _contentRect.width)) { _contentRect.width = value; _flags |= Flags.WidthChanged; _flags &= ~Flags.HeightChanged; OnSizeChanged(); } } } /// <summary> /// /// </summary> public float height { get { EnsureSizeCorrect(); return _contentRect.height; } set { if (!Mathf.Approximately(value, _contentRect.height)) { _contentRect.height = value; _flags &= ~Flags.WidthChanged; _flags |= Flags.HeightChanged; OnSizeChanged(); } } } /// <summary> /// /// </summary> public Vector2 size { get { EnsureSizeCorrect(); return _contentRect.size; } set { SetSize(value.x, value.y); } } /// <summary> /// /// </summary> /// <param name="wv"></param> /// <param name="hv"></param> public void SetSize(float wv, float hv) { if (!Mathf.Approximately(wv, _contentRect.width)) _flags |= Flags.WidthChanged; else _flags &= ~Flags.WidthChanged; if (!Mathf.Approximately(hv, _contentRect.height)) _flags |= Flags.HeightChanged; else _flags &= ~Flags.HeightChanged; if ((_flags & Flags.WidthChanged) != 0 || (_flags & Flags.HeightChanged) != 0) { _contentRect.width = wv; _contentRect.height = hv; OnSizeChanged(); } } virtual public void EnsureSizeCorrect() { } virtual protected void OnSizeChanged() { ApplyPivot(); if (_paintingInfo != null) _paintingInfo.flag = 1; if (graphics != null) graphics.contentRect = _contentRect; _flags |= Flags.OutlineChanged; } /// <summary> /// /// </summary> public float scaleX { get { return cachedTransform.localScale.x; } set { Vector3 v = cachedTransform.localScale; v.x = v.z = ValidateScale(value); cachedTransform.localScale = v; _flags |= Flags.OutlineChanged; ApplyPivot(); } } /// <summary> /// /// </summary> public float scaleY { get { return cachedTransform.localScale.y; } set { Vector3 v = cachedTransform.localScale; v.y = ValidateScale(value); cachedTransform.localScale = v; _flags |= Flags.OutlineChanged; ApplyPivot(); } } /// <summary> /// /// </summary> /// <param name="xv"></param> /// <param name="yv"></param> public void SetScale(float xv, float yv) { Vector3 v = new Vector3(); v.x = v.z = ValidateScale(xv); v.y = ValidateScale(yv); cachedTransform.localScale = v; _flags |= Flags.OutlineChanged; ApplyPivot(); } /// <summary> /// 在scale过小情况(极端情况=0),当使用Transform的坐标变换时,变换到世界,再从世界变换到本地,会由于精度问题造成结果错误。 /// 这种错误会导致Batching错误,因为Batching会使用缓存的outline。 /// 这里限制一下scale的最小值作为当前解决方案。 /// 这个方案并不完美,因为限制了本地scale值并不能保证对世界scale不会过小。 /// </summary> /// <param name="value"></param> /// <returns></returns> private float ValidateScale(float value) { if (value >= 0 && value < 0.001f) value = 0.001f; else if (value < 0 && value > -0.001f) value = -0.001f; return value; } /// <summary> /// /// </summary> public Vector2 scale { get { return cachedTransform.localScale; } set { SetScale(value.x, value.y); } } /// <summary> /// /// </summary> public float rotation { get { //和Unity默认的旋转方向相反 return -_rotation.z; } set { _rotation.z = -value; _flags |= Flags.OutlineChanged; if (_perspective) UpdateTransformMatrix(); else { cachedTransform.localEulerAngles = _rotation; ApplyPivot(); } } } /// <summary> /// /// </summary> public float rotationX { get { return _rotation.x; } set { _rotation.x = value; _flags |= Flags.OutlineChanged; if (_perspective) UpdateTransformMatrix(); else { cachedTransform.localEulerAngles = _rotation; ApplyPivot(); } } } /// <summary> /// /// </summary> public float rotationY { get { return _rotation.y; } set { _rotation.y = value; _flags |= Flags.OutlineChanged; if (_perspective) UpdateTransformMatrix(); else { cachedTransform.localEulerAngles = _rotation; ApplyPivot(); } } } /// <summary> /// /// </summary> public Vector2 skew { get { return _skew; } set { _skew = value; _flags |= Flags.OutlineChanged; if (!Application.isPlaying) //编辑期间不支持!! return; UpdateTransformMatrix(); } } /// <summary> /// 当对象处于ScreenSpace,也就是使用正交相机渲染时,对象虽然可以绕X轴或者Y轴旋转,但没有透视效果。设置perspective,可以模拟出透视效果。 /// </summary> public bool perspective { get { return _perspective; } set { if (_perspective != value) { _perspective = value; if (_perspective)//屏蔽Unity自身的旋转变换 cachedTransform.localEulerAngles = Vector3.zero; else cachedTransform.localEulerAngles = _rotation; ApplyPivot(); UpdateTransformMatrix(); } } } /// <summary> /// /// </summary> public int focalLength { get { return _focalLength; } set { if (value <= 0) value = 1; _focalLength = value; if (_vertexMatrix != null) UpdateTransformMatrix(); } } void UpdateTransformMatrix() { Matrix4x4 matrix = Matrix4x4.identity; if (_skew.x != 0 || _skew.y != 0) ToolSet.SkewMatrix(ref matrix, _skew.x, _skew.y); if (_perspective) matrix *= Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(_rotation), Vector3.one); if (matrix.isIdentity) _vertexMatrix = null; else if (_vertexMatrix == null) _vertexMatrix = new NGraphics.VertexMatrix(); //组件的transformMatrix是通过paintingMode实现的,因为全部通过矩阵变换的话,和unity自身的变换混杂在一起,无力理清。 if (_vertexMatrix != null) { _vertexMatrix.matrix = matrix; _vertexMatrix.cameraPos = new Vector3(_pivot.x * _contentRect.width, -_pivot.y * _contentRect.height, _focalLength); if (graphics == null) EnterPaintingMode(4, null); } else { if (graphics == null) LeavePaintingMode(4); } if (_paintingMode > 0) { paintingGraphics.vertexMatrix = _vertexMatrix; _paintingInfo.flag = 1; } else if (graphics != null) graphics.vertexMatrix = _vertexMatrix; _flags |= Flags.OutlineChanged; } /// <summary> /// /// </summary> public Vector2 pivot { get { return _pivot; } set { Vector3 deltaPivot = new Vector2((value.x - _pivot.x) * _contentRect.width, (_pivot.y - value.y) * _contentRect.height); Vector3 oldOffset = _pivotOffset; _pivot = value; UpdatePivotOffset(); Vector3 v = cachedTransform.localPosition; v += oldOffset - _pivotOffset + deltaPivot; cachedTransform.localPosition = v; _flags |= Flags.OutlineChanged; } } void UpdatePivotOffset() { float px = _pivot.x * _contentRect.width; float py = _pivot.y * _contentRect.height; //注意这里不用处理skew,因为在顶点变换里有对pivot的处理 Matrix4x4 matrix = Matrix4x4.TRS(Vector3.zero, cachedTransform.localRotation, cachedTransform.localScale); _pivotOffset = matrix.MultiplyPoint(new Vector3(px, -py, 0)); if (_vertexMatrix != null) _vertexMatrix.cameraPos = new Vector3(_pivot.x * _contentRect.width, -_pivot.y * _contentRect.height, _focalLength); } void ApplyPivot() { if (_pivot.x != 0 || _pivot.y != 0) { Vector3 oldOffset = _pivotOffset; UpdatePivotOffset(); Vector3 v = cachedTransform.localPosition; if ((_flags & Flags.PixelPerfect) != 0) { v -= _pixelPerfectAdjustment; _checkPixelPerfect = Time.frameCount; _pixelPerfectAdjustment = Vector3.zero; } v += oldOffset - _pivotOffset; cachedTransform.localPosition = v; _flags |= Flags.OutlineChanged; } } /// <summary> /// This is the pivot position /// </summary> public Vector3 location { get { Vector3 pos = this.position; pos.x += _pivotOffset.x; pos.y -= _pivotOffset.y; pos.z += _pivotOffset.z; return pos; } set { this.SetPosition(value.x - _pivotOffset.x, value.y + _pivotOffset.y, value.z - _pivotOffset.z); } } /// <summary> /// /// </summary> virtual public Material material { get { if (graphics != null) return graphics.material; else return null; } set { if (graphics != null) graphics.material = value; } } /// <summary> /// /// </summary> virtual public string shader { get { if (graphics != null) return graphics.shader; else return null; } set { if (graphics != null) graphics.shader = value; } } /// <summary> /// /// </summary> virtual public int renderingOrder { get { return _renderingOrder; } set { if ((_flags & Flags.GameObjectDisposed) != 0) { DisplayDisposedWarning(); return; } _renderingOrder = value; if (graphics != null) graphics.sortingOrder = value; if (_paintingMode > 0) paintingGraphics.sortingOrder = value; } } /// <summary> /// /// </summary> public int layer { get { if (_paintingMode > 0) return paintingGraphics.gameObject.layer; else return gameObject.layer; } set { SetLayer(value, false); } } /// <summary> /// If the object can be focused? /// </summary> public bool focusable { get { return (_flags & Flags.NotFocusable) == 0; } set { if (value) _flags &= ~Flags.NotFocusable; else _flags |= Flags.NotFocusable; } } /// <summary> /// If the object can be navigated by TAB? /// </summary> public bool tabStop { get { return (_flags & Flags.TabStop) != 0; } set { if (value) _flags |= Flags.TabStop; else _flags &= ~Flags.TabStop; } } /// <summary> /// If the object focused? /// </summary> public bool focused { get { return Stage.inst.focus == this || (this is Container) && ((Container)this).IsAncestorOf(Stage.inst.focus); } } internal bool _AcceptTab() { if (_touchable && _visible && ((_flags & Flags.TabStop) != 0 || (_flags & Flags.TabStopChildren) != 0) && (_flags & Flags.NotFocusable) == 0) { Stage.inst.SetFocus(this, true); return true; } else return false; } /// <summary> /// /// </summary> /// <value></value> public string cursor { get { return _cursor; } set { _cursor = value; if (Application.isPlaying && (this == Stage.inst.touchTarget || (this is Container) && ((Container)this).IsAncestorOf(Stage.inst.touchTarget))) { Stage.inst._ChangeCursor(_cursor); } } } /// <summary> /// /// </summary> public bool isDisposed { get { return (_flags & Flags.Disposed) != 0 || gameObject == null; } } internal void InternalSetParent(Container value) { if (parent != value) { if (value == null && (parent._flags & Flags.Disposed) != 0) parent = value; else { parent = value; UpdateHierarchy(); } _flags |= Flags.OutlineChanged; } } /// <summary> /// /// </summary> public Container topmost { get { DisplayObject currentObject = this; while (currentObject.parent != null) currentObject = currentObject.parent; return currentObject as Container; } } /// <summary> /// /// </summary> public Stage stage { get { return topmost as Stage; } } /// <summary> /// /// </summary> public Container worldSpaceContainer { get { Container wsc = null; DisplayObject currentObject = this; while (currentObject.parent != null) { if ((currentObject is Container) && ((Container)currentObject).renderMode == RenderMode.WorldSpace) { wsc = (Container)currentObject; break; } currentObject = currentObject.parent; } return wsc; } } /// <summary> /// /// </summary> public bool touchable { get { return _touchable; } set { if (_touchable != value) { _touchable = value; if (this is Container) { ColliderHitTest hitArea = ((Container)this).hitArea as ColliderHitTest; if (hitArea != null) hitArea.collider.enabled = value; } } } } /// <summary> /// /// </summary> /// <value></value> public bool touchDisabled { get { return (_flags & Flags.TouchDisabled) != 0; } } /// <summary> /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。 /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。 /// </summary> public void EnterPaintingMode() { EnterPaintingMode(16384, null, 1); } /// <summary> /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。 /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。 /// 可能有多个地方要求进入绘画模式,这里用requestorId加以区别,取值是1、2、4、8、16以此类推。1024内内部保留。用户自定义的id从1024开始。 /// </summary> /// <param name="requestId">请求者id</param> /// <param name="extend">纹理四周的留空。如果特殊处理后的内容大于原内容,那么这里的设置可以使纹理扩大。</param> public void EnterPaintingMode(int requestorId, Margin? extend) { EnterPaintingMode(requestorId, extend, 1); } /// <summary> /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。 /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。 /// 可能有多个地方要求进入绘画模式,这里用requestorId加以区别,取值是1、2、4、8、16以此类推。1024内内部保留。用户自定义的id从1024开始。 /// </summary> /// <param name="requestorId">请求者id</param> /// <param name="extend">扩展纹理。如果特殊处理后的内容大于原内容,那么这里的设置可以使纹理扩大。</param> /// <param name="scale">附加一个缩放系数</param> public void EnterPaintingMode(int requestorId, Margin? extend, float scale) { bool first = _paintingMode == 0; _paintingMode |= requestorId; if (first) { if (_paintingInfo == null) { _paintingInfo = new PaintingInfo() { captureDelegate = Capture, scale = 1 }; } if (paintingGraphics == null) { if (graphics == null) paintingGraphics = new NGraphics(this.gameObject); else { GameObject go = new GameObject(this.gameObject.name + " (Painter)"); go.layer = this.gameObject.layer; go.transform.SetParent(cachedTransform, false); go.hideFlags = DisplayObject.hideFlags; paintingGraphics = new NGraphics(go); } } else paintingGraphics.enabled = true; paintingGraphics.vertexMatrix = null; if (this is Container) { ((Container)this).SetChildrenLayer(CaptureCamera.hiddenLayer); ((Container)this).UpdateBatchingFlags(); } else this.InvalidateBatchingState(); if (graphics != null) this.gameObject.layer = CaptureCamera.hiddenLayer; } if (extend != null) _paintingInfo.extend = (Margin)extend; _paintingInfo.scale = scale; _paintingInfo.flag = 1; } /// <summary> /// 离开绘画模式 /// </summary> /// <param name="requestId"></param> public void LeavePaintingMode(int requestorId) { if (_paintingMode == 0 || (_flags & Flags.Disposed) != 0) return; _paintingMode ^= requestorId; if (_paintingMode == 0) { paintingGraphics.enabled = false; if (this is Container) { ((Container)this).SetChildrenLayer(this.layer); ((Container)this).UpdateBatchingFlags(); } else this.InvalidateBatchingState(); if (graphics != null) this.gameObject.layer = paintingGraphics.gameObject.layer; } } /// <summary> /// /// </summary> public bool paintingMode { get { return _paintingMode > 0; } } /// <summary> /// 将整个显示对象(如果是容器,则容器包含的整个显示列表)静态化,所有内容被缓冲到一张纹理上。 /// DC将保持为1。CPU消耗将降到最低。但对象的任何变化不会更新。 /// 当cacheAsBitmap已经为true时,再次调用cacheAsBitmap=true将会刷新对象一次。 /// </summary> public bool cacheAsBitmap { get { return (_flags & Flags.CacheAsBitmap) != 0; } set { if (value) { _flags |= Flags.CacheAsBitmap; EnterPaintingMode(8, null, UIContentScaler.scaleFactor); } else { _flags &= ~Flags.CacheAsBitmap; LeavePaintingMode(8); } } } /// <summary> /// /// </summary> /// <param name="extend"></param> /// <param name="scale"></param> /// <returns></returns> public Texture2D GetScreenShot(Margin? extend, float scale) { EnterPaintingMode(8, null, scale); UpdatePainting(); Capture(); Texture2D output; if (paintingGraphics.texture == null) output = new Texture2D(1, 1, TextureFormat.RGBA32, false, true); else { RenderTexture rt = (RenderTexture)paintingGraphics.texture.nativeTexture; output = new Texture2D(rt.width, rt.height, TextureFormat.RGBA32, false, true); RenderTexture old = RenderTexture.active; RenderTexture.active = rt; output.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); output.Apply(); RenderTexture.active = old; } LeavePaintingMode(8); return output; } /// <summary> /// /// </summary> public IFilter filter { get { return _filter; } set { if (!Application.isPlaying) //编辑期间不支持!! return; if (value == _filter) return; if (_filter != null) _filter.Dispose(); if (value != null && value.target != null) value.target.filter = null; _filter = value; if (_filter != null) _filter.target = this; } } /// <summary> /// /// </summary> public BlendMode blendMode { get { return _blendMode; } set { _blendMode = value; InvalidateBatchingState(); if (graphics == null) { if (_blendMode != BlendMode.Normal) { if (!Application.isPlaying) //Not supported in edit mode! return; EnterPaintingMode(2, null); paintingGraphics.blendMode = _blendMode; } else LeavePaintingMode(2); } else graphics.blendMode = _blendMode; } } /// <summary> /// /// </summary> /// <param name="targetSpace"></param> /// <returns></returns> virtual public Rect GetBounds(DisplayObject targetSpace) { EnsureSizeCorrect(); if (targetSpace == this) // optimization { return _contentRect; } else if (targetSpace == parent && _rotation.z == 0) { return new Rect(cachedTransform.localPosition.x, -cachedTransform.localPosition.y, _contentRect.width * cachedTransform.localScale.x, _contentRect.height * cachedTransform.localScale.y); } else return TransformRect(_contentRect, targetSpace); } internal DisplayObject InternalHitTest() { if (_visible && (!HitTestContext.forTouch || _touchable)) return HitTest(); else return null; } internal DisplayObject InternalHitTestMask() { if (_visible) return HitTest(); else return null; } virtual protected DisplayObject HitTest() { Rect rect = GetBounds(this); if (rect.width == 0 || rect.height == 0) return null; Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction); if (rect.Contains(localPoint)) return this; else return null; } /// <summary> /// 将舞台坐标转换为本地坐标 /// </summary> /// <param name="point"></param> /// <returns></returns> public Vector2 GlobalToLocal(Vector2 point) { Container wsc = this.worldSpaceContainer; if (wsc != null)//I am in a world space { Camera cam = wsc.GetRenderCamera(); Vector3 worldPoint; Vector3 direction; Vector3 screenPoint = new Vector3(); screenPoint.x = point.x; screenPoint.y = Screen.height - point.y; if (wsc.hitArea is MeshColliderHitTest) { Ray ray = cam.ScreenPointToRay(screenPoint); RaycastHit hit; if (((MeshColliderHitTest)wsc.hitArea).collider.Raycast(ray, out hit, 100)) { point = new Vector2(hit.textureCoord.x * wsc._contentRect.width, (1 - hit.textureCoord.y) * wsc._contentRect.height); worldPoint = Stage.inst.cachedTransform.TransformPoint(point.x, -point.y, 0); direction = Vector3.back; } else //当射线没有击中模型时,无法确定本地坐标 return new Vector2(float.NaN, float.NaN); } else { screenPoint.z = cam.WorldToScreenPoint(this.cachedTransform.position).z; worldPoint = cam.ScreenToWorldPoint(screenPoint); Ray ray = cam.ScreenPointToRay(screenPoint); direction = Vector3.zero - ray.direction; } return this.WorldToLocal(worldPoint, direction); } else //I am in stage space { Vector3 worldPoint = Stage.inst.cachedTransform.TransformPoint(point.x, -point.y, 0); return this.WorldToLocal(worldPoint, Vector3.back); } } /// <summary> /// 将本地坐标转换为舞台坐标 /// </summary> /// <param name="point"></param> /// <returns></returns> public Vector2 LocalToGlobal(Vector2 point) { Container wsc = this.worldSpaceContainer; Vector3 worldPoint = this.cachedTransform.TransformPoint(point.x, -point.y, 0); if (wsc != null) { if (wsc.hitArea is MeshColliderHitTest) //Not supported for UIPainter, use TransfromPoint instead. return new Vector2(float.NaN, float.NaN); Vector3 screePoint = wsc.GetRenderCamera().WorldToScreenPoint(worldPoint); return new Vector2(screePoint.x, Stage.inst.size.y - screePoint.y); } else { point = Stage.inst.cachedTransform.InverseTransformPoint(worldPoint); point.y = -point.y; return point; } } /// <summary> /// 转换世界坐标点到等效的本地xy平面的点。等效的意思是他们在屏幕方向看到的位置一样。 /// 返回的点是在对象的本地坐标空间,且z=0 /// </summary> /// <param name="worldPoint"></param> /// <param name="direction"></param> /// <returns></returns> public Vector3 WorldToLocal(Vector3 worldPoint, Vector3 direction) { Vector3 localPoint = this.cachedTransform.InverseTransformPoint(worldPoint); if (localPoint.z != 0) //如果对象绕x轴或y轴旋转过,或者对象是在透视相机,那么z值可能不为0, { //将世界坐标的摄影机方向在本地空间上投射,求出与xy平面的交点 direction = this.cachedTransform.InverseTransformDirection(direction); float distOnLine = Vector3.Dot(Vector3.zero - localPoint, Vector3.forward) / Vector3.Dot(direction, Vector3.forward); if (float.IsInfinity(distOnLine)) return Vector2.zero; localPoint = localPoint + direction * distOnLine; } else if (_vertexMatrix != null) { Vector3 center = _vertexMatrix.cameraPos; center.z = 0; center -= _vertexMatrix.matrix.MultiplyPoint(center); Matrix4x4 mm = _vertexMatrix.matrix.inverse; localPoint -= center; localPoint = mm.MultiplyPoint(localPoint); Vector3 camPos = mm.MultiplyPoint(_vertexMatrix.cameraPos); Vector3 vec = localPoint - camPos; float lambda = -camPos.z / vec.z; localPoint = camPos + lambda * vec; localPoint.z = 0; } localPoint.y = -localPoint.y; return localPoint; } /// <summary> /// /// </summary> /// <param name="localPoint"></param> /// <returns></returns> public Vector3 LocalToWorld(Vector3 localPoint) { localPoint.y = -localPoint.y; if (_vertexMatrix != null) { Vector3 center = _vertexMatrix.cameraPos; center.z = 0; center -= _vertexMatrix.matrix.MultiplyPoint(center); localPoint = _vertexMatrix.matrix.MultiplyPoint(localPoint); localPoint += center; Vector3 camPos = _vertexMatrix.cameraPos; Vector3 vec = localPoint - camPos; float lambda = -camPos.z / vec.z; localPoint = camPos + lambda * vec; localPoint.z = 0; } return this.cachedTransform.TransformPoint(localPoint); } /// <summary> /// /// </summary> /// <param name="point"></param> /// <param name="targetSpace">null if to world space</param> /// <returns></returns> public Vector2 TransformPoint(Vector2 point, DisplayObject targetSpace) { if (targetSpace == this) return point; point = LocalToWorld(point); if (targetSpace != null) point = targetSpace.WorldToLocal(point, Vector3.back); return point; } /// <summary> /// /// </summary> /// <param name="rect"></param> /// <param name="targetSpace">null if to world space</param> /// <returns></returns> public Rect TransformRect(Rect rect, DisplayObject targetSpace) { if (targetSpace == this) return rect; if (targetSpace == parent && _rotation.z == 0) // optimization { Vector3 vec = cachedTransform.localScale; return new Rect((this.x + rect.x) * vec.x, (this.y + rect.y) * vec.y, rect.width * vec.x, rect.height * vec.y); } else { Vector4 vec4 = new Vector4(float.MaxValue, float.MaxValue, float.MinValue, float.MinValue); TransformRectPoint(rect.xMin, rect.yMin, targetSpace, ref vec4); TransformRectPoint(rect.xMax, rect.yMin, targetSpace, ref vec4); TransformRectPoint(rect.xMin, rect.yMax, targetSpace, ref vec4); TransformRectPoint(rect.xMax, rect.yMax, targetSpace, ref vec4); return Rect.MinMaxRect(vec4.x, vec4.y, vec4.z, vec4.w); } } protected void TransformRectPoint(float px, float py, DisplayObject targetSpace, ref Vector4 vec4) { Vector2 v = TransformPoint(new Vector2(px, py), targetSpace); if (vec4.x > v.x) vec4.x = v.x; if (vec4.z < v.x) vec4.z = v.x; if (vec4.y > v.y) vec4.y = v.y; if (vec4.w < v.y) vec4.w = v.y; } /// <summary> /// /// </summary> public void RemoveFromParent() { if (parent != null) parent.RemoveChild(this); } /// <summary> /// /// </summary> public void InvalidateBatchingState() { if (parent != null) parent.InvalidateBatchingState(true); } virtual public void Update(UpdateContext context) { if (_checkPixelPerfect != 0) { if (_rotation == Vector3.zero) { Vector3 v = cachedTransform.localPosition; v.x = Mathf.Round(v.x); v.y = Mathf.Round(v.y); _pixelPerfectAdjustment = v - cachedTransform.localPosition; if (_pixelPerfectAdjustment != Vector3.zero) cachedTransform.localPosition = v; } _checkPixelPerfect = 0; } if (graphics != null) graphics.Update(context, context.alpha * _alpha, context.grayed | _grayed); if (_paintingMode != 0) { UpdatePainting(); //如果是容器,Capture要等到Container.Update的最后执行,因为容器中可能也有需要Capture的内容,要等他们完成后再进行容器的Capture。 if (!(this is Container)) { if ((_flags & Flags.CacheAsBitmap) == 0 || _paintingInfo.flag != 2) UpdateContext.OnEnd += _paintingInfo.captureDelegate; } paintingGraphics.Update(context, 1, false); } if (_filter != null) _filter.Update(); Stats.ObjectCount++; } void UpdatePainting() { NTexture paintingTexture = paintingGraphics.texture; if (paintingTexture != null && paintingTexture.disposed) //Texture可能已被Stage.MonitorTexture销毁 { paintingTexture = null; _paintingInfo.flag = 1; } if (_paintingInfo.flag == 1) { _paintingInfo.flag = 0; //从优化考虑,决定使用绘画模式的容器都需要明确指定大小,而不是自动计算包围。这在UI使用上并没有问题,因为组件总是有固定大小的 Margin extend = _paintingInfo.extend; paintingGraphics.contentRect = new Rect(-extend.left, -extend.top, _contentRect.width + extend.left + extend.right, _contentRect.height + extend.top + extend.bottom); int textureWidth = Mathf.RoundToInt(paintingGraphics.contentRect.width * _paintingInfo.scale); int textureHeight = Mathf.RoundToInt(paintingGraphics.contentRect.height * _paintingInfo.scale); if (paintingTexture == null || paintingTexture.width != textureWidth || paintingTexture.height != textureHeight) { if (paintingTexture != null) paintingTexture.Dispose(); if (textureWidth > 0 && textureHeight > 0) { paintingTexture = new NTexture(CaptureCamera.CreateRenderTexture(textureWidth, textureHeight, UIConfig.depthSupportForPaintingMode)); Stage.inst.MonitorTexture(paintingTexture); } else paintingTexture = null; paintingGraphics.texture = paintingTexture; } } if (paintingTexture != null) paintingTexture.lastActive = Time.time; } void Capture() { if (paintingGraphics.texture == null) return; Vector2 offset = new Vector2(_paintingInfo.extend.left, _paintingInfo.extend.top); CaptureCamera.Capture(this, (RenderTexture)paintingGraphics.texture.nativeTexture, paintingGraphics.contentRect.height, offset); _paintingInfo.flag = 2; //2表示已完成一次Capture if (onPaint != null) onPaint(); } /// <summary> /// 为对象设置一个默认的父Transform。当对象不在显示列表里时,它的GameObject挂到哪里。 /// </summary> public Transform home { get { return _home; } set { _home = value; if (value != null && cachedTransform.parent == null) cachedTransform.SetParent(value, false); } } void UpdateHierarchy() { if ((_flags & Flags.GameObjectDisposed) != 0) return; if ((_flags & Flags.UserGameObject) != 0) { //we dont change transform parent of this object if (gameObject != null) { if (parent != null && visible) gameObject.SetActive(true); else gameObject.SetActive(false); } } else if (parent != null) { cachedTransform.SetParent(parent.cachedTransform, false); if (_visible) gameObject.SetActive(true); int layerValue = parent.gameObject.layer; if (parent._paintingMode != 0) layerValue = CaptureCamera.hiddenLayer; SetLayer(layerValue, true); } else if ((_flags & Flags.Disposed) == 0 && this.gameObject != null && !StageEngine.beingQuit) { if (Application.isPlaying) { if (gOwner == null || gOwner.parent == null)//如果gOwner还有parent的话,说明只是暂时的隐藏 { cachedTransform.SetParent(_home, false); if (_home == null) UnityEngine.Object.DontDestroyOnLoad(this.gameObject); } } gameObject.SetActive(false); } } virtual protected bool SetLayer(int value, bool fromParent) { if ((_flags & Flags.LayerSet) != 0) //setted { if (fromParent) return false; } else if ((_flags & Flags.LayerFromParent) != 0) //inherit from parent { if (!fromParent) _flags |= Flags.LayerSet; } else { if (fromParent) _flags |= Flags.LayerFromParent; else _flags |= Flags.LayerSet; } if (_paintingMode > 0) paintingGraphics.gameObject.layer = value; else if (gameObject.layer != value) { gameObject.layer = value; if ((this is Container)) { int cnt = ((Container)this).numChildren; for (int i = 0; i < cnt; i++) { DisplayObject child = ((Container)this).GetChildAt(i); child.SetLayer(value, true); } } } return true; } internal void _SetLayerDirect(int value) { if (_paintingMode > 0) paintingGraphics.gameObject.layer = value; else gameObject.layer = value; } virtual public void Dispose() { if ((_flags & Flags.Disposed) != 0) return; _flags |= Flags.Disposed; RemoveFromParent(); RemoveEventListeners(); if (graphics != null) graphics.Dispose(); if (_filter != null) _filter.Dispose(); if (paintingGraphics != null) { if (paintingGraphics.texture != null) paintingGraphics.texture.Dispose(); paintingGraphics.Dispose(); if (paintingGraphics.gameObject != this.gameObject) { if (Application.isPlaying) UnityEngine.Object.Destroy(paintingGraphics.gameObject); else UnityEngine.Object.DestroyImmediate(paintingGraphics.gameObject); } } DestroyGameObject(); } internal void DisplayDisposedWarning() { if ((_flags & Flags.DisposedWarning) == 0) { _flags |= Flags.DisposedWarning; StringBuilder sb = new StringBuilder(); sb.Append("DisplayObject is still in use but GameObject was disposed. ("); if (gOwner != null) { sb.Append("type=").Append(gOwner.GetType().Name).Append(", x=").Append(gOwner.x).Append(", y=").Append(gOwner.y).Append(", name=").Append(gOwner.name); if (gOwner.packageItem != null) sb.Append(", res=" + gOwner.packageItem.name); } else { sb.Append("id=").Append(id).Append(", type=").Append(this.GetType().Name).Append(", name=").Append(name); } sb.Append(")"); Debug.LogError(sb.ToString()); } } protected internal class PaintingInfo { public Action captureDelegate; //缓存这个delegate,可以防止Capture状态下每帧104B的GC public Margin extend; public float scale; public int flag; } [Flags] protected internal enum Flags { Disposed = 1, UserGameObject = 2, TouchDisabled = 4, OutlineChanged = 8, UpdatingSize = 0x10, WidthChanged = 0x20, HeightChanged = 0x40, PixelPerfect = 0x80, LayerSet = 0x100, LayerFromParent = 0x200, NotFocusable = 0x400, TabStop = 0x800, TabStopChildren = 0x1000, FairyBatching = 0x2000, BatchingRequested = 0x4000, BatchingRoot = 0x8000, SkipBatching = 0x10000, CacheAsBitmap = 0x20000, GameObjectDisposed = 0x40000, DisposedWarning = 0x80000 } } /// <summary> /// /// </summary> public class DisplayObjectInfo : MonoBehaviour { /// <summary> /// /// /// </summary> [System.NonSerialized] public DisplayObject displayObject; private void OnDestroy() { if (displayObject != null) displayObject._flags |= DisplayObject.Flags.GameObjectDisposed; } } }
31.453965
183
0.447684
[ "MIT" ]
tanghuipang/FairyGUI-unity
Assets/Scripts/Core/DisplayObject.cs
61,406
C#
using Pomelo.EntityFrameworkCore.MySql.FunctionalTests.TestUtilities; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.TestUtilities; namespace Pomelo.EntityFrameworkCore.MySql.FunctionalTests.Query { public class ComplexNavigationsWeakQueryMySqlFixture : ComplexNavigationsWeakQueryRelationalFixtureBase { protected override ITestStoreFactory TestStoreFactory => MySqlTestStoreFactory.Instance; } }
38.583333
108
0.827214
[ "MIT" ]
DeeJayTC/Pomelo.EntityFrameworkCore.MySql
test/EFCore.MySql.FunctionalTests/Query/ComplexNavigationsWeakQueryMySqlFixture.cs
465
C#
using ShapeTemplateLib.Templates.User0; namespace Edit2DLib { public partial class Edit2DGraphLayer { public void SelectEdgeByHoleGroupID(string HoleGroupID) { for (int i=0; i < EdgeList.Count; i++) { Edge oEdge = EdgeList.GetFrom(i); if (oEdge.HoleGroupID == HoleGroupID) { MostRecentlySelectedEdge = oEdge; return; } } } } }
24.227273
64
0.467167
[ "MIT" ]
johnmott59/FloorLayout
Edit2DLib/Edit2DGraphLayer/SelectEdgeByHoleGroupID.cs
535
C#
namespace EnvironmentAssessment.Common.VimApi { public class OvfAttribute : OvfInvalidPackage { protected string _elementName; protected string _attributeName; public string ElementName { get { return this._elementName; } set { this._elementName = value; } } public string AttributeName { get { return this._attributeName; } set { this._attributeName = value; } } } }
14.16129
46
0.656036
[ "MIT" ]
octansIt/environmentassessment
EnvironmentAssessment.Wizard/Common/VimApi/O/OvfAttribute.cs
439
C#
using Application.Features.AppUsers.Queries.GetAppUserById; using Application.Features.Categories.Queries.GetCategoryById; using Application.Features.Places.Queries.GetPlaces; using System; using System.Collections.Generic; using System.Text; namespace Application.Features.PaymentTypes.Queries.GetPaymentTypeById { public class GetPaymentTypeViewModel { public virtual Guid Id { get; set; } public string CreatedBy { get; set; } public DateTime CreatedAt { get; set; } public DateTime? UpdatedAt { get; set; } public string UpdatedBy { get; set; } public string ImgLink { get; set; } public string Name { get; set; } public string Description { get; set; } public DateTime Date { get; set; } public float Price { get; set; } public string StatusPaymentType { get; set; } public int NoPriority { get; set; } public Guid CategoryId { get; set; } public GetCategoryViewModel Category { get; set; } public string AppUserId { get; set; } public GetAppUserViewModel AppUser { get; set; } public virtual ICollection<GetPlacesViewModel> Places { get; set; } } }
34.542857
75
0.672457
[ "Apache-2.0" ]
Stephane-AmStrong/MaxiEvent
src/Core/Application/Features/PaymentTypes/Queries/GetPaymentTypeById/GetPaymentTypeViewModel.cs
1,211
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Yunjing.V20180228.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeAccountStatisticsRequest : AbstractModel { /// <summary> /// 返回数量,默认为10,最大值为100。 /// </summary> [JsonProperty("Limit")] public ulong? Limit{ get; set; } /// <summary> /// 偏移量,默认为0。 /// </summary> [JsonProperty("Offset")] public ulong? Offset{ get; set; } /// <summary> /// 过滤条件。 /// <li>Username - String - 是否必填:否 - 帐号用户名</li> /// </summary> [JsonProperty("Filters")] public Filter[] Filters{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Limit", this.Limit); this.SetParamSimple(map, prefix + "Offset", this.Offset); this.SetParamArrayObj(map, prefix + "Filters.", this.Filters); } } }
30.372881
81
0.614397
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Yunjing/V20180228/Models/DescribeAccountStatisticsRequest.cs
1,868
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.AI; using Polyperfect.Common; #if UNITY_EDITOR using UnityEditor; #endif namespace Polyperfect.Animals { public class Animal_WanderScript : Common_WanderScript { } }
19.214286
62
0.810409
[ "MIT" ]
JohnMurwin/NaturalSelectionSimulation
Assets/Plugins/polyperfect/Low Poly Animated Animals/- Scripts/Wander Script/Animal_WanderScript.cs
271
C#
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell; using ShaderTools.VisualStudio.LanguageServices; [assembly: AssemblyTitle("HLSL Tools for Visual Studio")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tim Jones")] [assembly: AssemblyProduct("HLSL Tools for Visual Studio")] [assembly: AssemblyCopyright("Copyright © 2015-2017 Tim Jones")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion(ShaderToolsPackage.Version)] [assembly: AssemblyFileVersion(ShaderToolsPackage.Version)] [assembly: InternalsVisibleTo("ShaderTools.Editor.VisualStudio.Tests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
39.16
72
0.78141
[ "Apache-2.0" ]
BigHeadGift/HLSL
src/ShaderTools.Editor.VisualStudio/Properties/AssemblyInfo.cs
958
C#
/** TestScript */ namespace TestScript { /** 自動生成。 */ public class SceneList { /** CreateStatusList */ public static TestStatus[] CreateStatusList() { return new TestStatus[]{ test01.CreateStatus(), test02.CreateStatus(), test03.CreateStatus(), test04.CreateStatus(), test05.CreateStatus(), test06.CreateStatus(), test07.CreateStatus(), test08.CreateStatus(), test09.CreateStatus(), test10.CreateStatus(), test11.CreateStatus(), test12.CreateStatus(), test13.CreateStatus(), test14.CreateStatus(), test15.CreateStatus(), test16.CreateStatus(), test17.CreateStatus(), test18.CreateStatus(), test19.CreateStatus(), test20.CreateStatus(), test21.CreateStatus(), test22.CreateStatus(), test23.CreateStatus(), test24.CreateStatus(), test25.CreateStatus(), test26.CreateStatus(), test27.CreateStatus(), test28.CreateStatus(), test29.CreateStatus(), test30.CreateStatus(), test31.CreateStatus(), test32.CreateStatus(), test33.CreateStatus(), test34.CreateStatus(), test35.CreateStatus(), test36.CreateStatus(), test37.CreateStatus(), test38.CreateStatus(), test39.CreateStatus(), test40.CreateStatus(), }; } } }
21.131148
47
0.656323
[ "MIT" ]
bluebackblue/fee_project
unity_2020_1/Assets/TestScript/System/SceneList.cs
1,299
C#
using System.IO; using Rosalia.Core.Logging; namespace CrystalQuartz.Build.Tasks { using System.Linq; using CrystalQuartz.Build.Common; using Rosalia.Core.Api; using Rosalia.Core.Tasks; using Rosalia.Core.Tasks.Results; using Rosalia.FileSystem; using Rosalia.TaskLib.Standard.Tasks; public class MergeBinariesTask : Subflow { private readonly string[] _webAssemblies400 = { /* * Please note that because of bacward campatibility * the CrystalQuartz.Core.dll could not be merged here * and should be included to the NuGet package as * a separate assembly. */ "CrystalQuartz.Core.Quartz2.dll", "CrystalQuartz.WebFramework.dll", "CrystalQuartz.Application.dll", "CrystalQuartz.Web.dll", "CrystalQuartz.WebFramework.SystemWeb.dll" }; private readonly string[] _webAssemblies452 = { "CrystalQuartz.Core.Quartz2.dll", "CrystalQuartz.Core.Quartz3.dll", "CrystalQuartz.WebFramework.dll", "CrystalQuartz.Application.dll", "CrystalQuartz.Web.dll", "CrystalQuartz.WebFramework.SystemWeb.dll" }; private readonly string[] _owinAssemblies450 = { "CrystalQuartz.Owin.dll", "CrystalQuartz.Core.dll", "CrystalQuartz.Core.Quartz2.dll", "CrystalQuartz.Application.dll", "CrystalQuartz.WebFramework.dll", "CrystalQuartz.WebFramework.Owin.dll" }; private readonly string[] _owinAssemblies452 = { "CrystalQuartz.Owin.dll", "CrystalQuartz.Core.dll", "CrystalQuartz.Core.Quartz2.dll", "CrystalQuartz.Core.Quartz3.dll", "CrystalQuartz.WebFramework.dll", "CrystalQuartz.Application.dll", "CrystalQuartz.WebFramework.Owin.dll" }; private readonly string[] _netStandardAssemblies20 = { "CrystalQuartz.AspNetCore.dll", "CrystalQuartz.Core.dll", "CrystalQuartz.Core.Quartz2.dll", "CrystalQuartz.Core.Quartz3.dll", "CrystalQuartz.WebFramework.dll", "CrystalQuartz.Application.dll" }; private readonly string[] _dotNetCoreLibsCandidates = { "/usr/local/share/dotnet/sdk/NuGetFallbackFolder/microsoft.netcore.app/2.0.0/ref/netcoreapp2.0", "/usr/local/share/dotnet/sdk/NuGetFallbackFolder/microsoft.netcore.app/2.0.7/ref/netcoreapp2.0", "/usr/local/share/dotnet/shared/Microsoft.NETCore.App/2.0.0", "/usr/local/share/dotnet/shared/Microsoft.NETCore.App/2.0.7", "/usr/local/share/dotnet/sdk/NuGetFallbackFolder/netstandard.library/2.0.0/build/netstandard2.0/ref", "/usr/local/share/dotnet/sdk/NuGetFallbackFolder/netstandard.library/2.0.7/build/netstandard2.0/ref", "/usr/share/dotnet/sdk/NuGetFallbackFolder/microsoft.netcore.app/2.0.0/ref/netcoreapp2.0", "/usr/share/dotnet/sdk/NuGetFallbackFolder/microsoft.netcore.app/2.0.7/ref/netcoreapp2.0", "/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0", "/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.7", "/usr/share/dotnet/sdk/NuGetFallbackFolder/netstandard.library/2.0.0/build/netstandard2.0/ref", "/usr/share/dotnet/sdk/NuGetFallbackFolder/netstandard.library/2.0.7/build/netstandard2.0/ref", }; private readonly SolutionStructure _solution; private readonly string _configuration; private readonly bool _skipCore; public MergeBinariesTask(SolutionStructure solution, string configuration, bool skipCore) { _solution = solution; _configuration = configuration; _skipCore = skipCore; } protected override bool IsSequence { get { return true; } } protected override void RegisterTasks() { Task( "MergeSystemWeb400", CreateMergeTask("CrystalQuartz.Web.dll", _webAssemblies400, "400")); Task( "MergeSystemWeb452", CreateMergeTask("CrystalQuartz.Web.dll", _webAssemblies452, "452")); Task( "MergeOwin450", CreateMergeTask("CrystalQuartz.Owin.dll", _owinAssemblies450, "450")); Task( "MergeOwin452", CreateMergeTask("CrystalQuartz.Owin.dll", _owinAssemblies452, "452")); var resolveCoreLibs = Task( "resolve Core Libs", context => { context.Log.Info("Discovering core libs directories"); return _dotNetCoreLibsCandidates .Select(path => { bool exists = new DefaultDirectory(path).Exists; context.Log.AddMessage(exists ? MessageLevel.Success : MessageLevel.Warn, "Checking [" + path + "]: " + (exists ? "found" : "not found")); return new { Found = exists, Path = path }; }) .Where(x => x.Found) .Select(x => x.Path) .ToArray() .AsTaskResult(); }); Task( "MergeNetStandard20", from libs in resolveCoreLibs select CreateMergeTask( "CrystalQuartz.AspNetCore.dll", _netStandardAssemblies20.Select(x => Path.Combine("netstandard2.0", x)).ToArray(), "netstandard2.0", libs) .WithPrecondition(() => !_skipCore)); } private ITask<Nothing> CreateMergeTask(string outputDllName, string[] inputAssembliesNames, string dotNetVersionAlias, string[] libs = null) { IDirectory ilMergePackage = (_solution.Src/"packages").AsDirectory().Directories.Last(d => d.Name.StartsWith("ILRepack")); IDirectory bin = _solution.Artifacts / ("bin_" + dotNetVersionAlias); return new ExecTask { ToolPath = ilMergePackage/"tools"/"ILRepack.exe", Arguments = string.Format( "{0}/out:{1} {2}", libs == null || libs.Length == 0 ? string.Empty : (string.Join(" ", libs.Select(x => "/lib:" + x)) + " "), bin/(_configuration + "_Merged")/outputDllName, string.Join(" ", inputAssembliesNames.Select(dll => (bin/_configuration/dll).AsFile().AbsolutePath))) }; } } }
39.711864
167
0.556409
[ "MIT" ]
MyTkme/CrystalQuartz
src/CrystalQuartz.Build/Tasks/MergeBinariesTask.cs
7,031
C#
using System; using System.Runtime.InteropServices; using System.Threading; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Mono.Debugging.Client; using Task = System.Threading.Tasks.Task; namespace HazelToolsVS { /// <summary> /// This is the class that implements the package exposed by this assembly. /// </summary> /// <remarks> /// <para> /// The minimum requirement for a class to be considered a valid package for Visual Studio /// is to implement the IVsPackage interface and register itself with the shell. /// This package uses the helper classes defined inside the Managed Package Framework (MPF) /// to do it: it derives from the Package class that provides the implementation of the /// IVsPackage interface and uses the registration attributes defined in the framework to /// register itself and its components with the shell. These attributes tell the pkgdef creation /// utility what data to put into .pkgdef file. /// </para> /// <para> /// To get loaded into VS, the package must be referred by &lt;Asset Type="Microsoft.VisualStudio.VsPackage" ...&gt; in .vsixmanifest file. /// </para> /// </remarks> [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] [Guid(PackageGuidString)] [ProvideMenuResource("Menus.ctmenu", 1)] [ProvideOptionPage(typeof(HazelToolsGeneralOptions), "Hazel Tools", "General", 0, 0, true)] [ProvideUIContextRule(UIContextHasCSProjectGuid, name: "Has CSharp Project", expression: "HasCSProject", termNames: new[] { "HasCSProject" }, termValues: new[] { "SolutionHasProjectCapability:CSharp" })] public sealed class HazelToolsPackage : AsyncPackage { /// <summary> /// GodotPackage GUID string. /// </summary> public const string PackageGuidString = "c7a2ebd8-63d8-4332-b696-67ca11f7f971"; private const string UIContextHasCSProjectGuid = "df4efbdd-f234-4d5c-a753-4b50e0837327"; #region Package Members public static HazelToolsPackage Instance { get; private set; } public HazelToolsPackage() { Instance = this; } internal HazelSolutionEventsListener SolutionEventsListener { get; private set; } internal HazelToolsGeneralOptions GeneralOptions => GetDialogPage(typeof(HazelToolsGeneralOptions)) as HazelToolsGeneralOptions; /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> /// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param> /// <param name="progress">A provider for progress updates.</param> /// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns> protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { // When initialized asynchronously, the current thread may be a background thread at this point. // Do any initialization that requires the UI thread after switching to the UI thread. await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); await AttachHazelnutCommand.InitializeAsync(this); SolutionEventsListener = new HazelSolutionEventsListener(this); } public async Task ShowErrorMessageBoxAsync(string title, string message) { await JoinableTaskFactory.SwitchToMainThreadAsync(); var uiShell = (IVsUIShell)await GetServiceAsync(typeof(SVsUIShell)); if (uiShell == null) throw new ServiceUnavailableException(typeof(SVsUIShell)); var clsID = Guid.Empty; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(uiShell.ShowMessageBox( 0, ref clsID, title, message, string.Empty, 0, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, OLEMSGICON.OLEMSGICON_CRITICAL, 0, pnResult: out _ )); } #endregion } }
40.683168
170
0.758335
[ "MIT" ]
StudioCherno/HazelToolsVS
HazelToolsVS/HazelToolsPackage.cs
4,109
C#
using Codoxide.Outcomes; using System; namespace Codoxide { using static Codoxide.OutcomeInternals.Utility; public static class OutcomeThenThenExtensions { [Obsolete("Use 'Map' instead")] public static Outcome<ResultType> Then<T, ResultType>(this Outcome<T> @this, Func<ResultType> fn) { if (!@this.IsSuccessful) return Outcome<ResultType>.Reject(@this.FailureOrNull()); return Outcome.Of(fn); } [Obsolete("Use 'Map' instead")] public static Outcome<ResultType> Then<T, ResultType>(this Outcome<T> @this, Func<Outcome<ResultType>> fn) { if (!@this.IsSuccessful) return Outcome<ResultType>.Reject(@this.FailureOrNull()); return Try(fn); } [Obsolete("Use 'Map' instead")] public static Outcome<ResultType> Then<T, ResultType>(this Outcome<T> @this, Func<T, ResultType> fn) { if (!@this.IsSuccessful) return Outcome<ResultType>.Reject(@this.FailureOrNull()); return Outcome.Of(() => fn(@this.ResultOrDefault())); } [Obsolete("Use 'Map' instead")] public static Outcome<ResultType> Then<T, ResultType>(this Outcome<T> @this, Func<T, Outcome<ResultType>> fn) { if (!@this.IsSuccessful) return Outcome<ResultType>.Reject(@this.FailureOrNull()); return Try(() => fn(@this.ResultOrDefault())); } [Obsolete("Use 'Map' instead")] public static Outcome<ResultType> Then<T, ResultType>(this Outcome<T> @this, Func<ValueTuple<ResultType, Failure>> fn) { if (!@this.IsSuccessful) return Outcome<ResultType>.Reject(@this.FailureOrNull()); return Try<ResultType>(() => fn()); } [Obsolete("Use 'Map' instead")] public static Outcome<ResultType> Then<T, ResultType>(this Outcome<T> @this, Func<T, ValueTuple<ResultType, Failure>> fn) { if (!@this.IsSuccessful) return Outcome<ResultType>.Reject(@this.FailureOrNull()); return Try<ResultType>(() => fn(@this.ResultOrDefault())); } } }
35.533333
129
0.612101
[ "Apache-2.0" ]
sameera/Codoxide.Outcome
Codoxide.Outcome.Extensions.Map/src/Then.extensions.cs
2,132
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public float MoveSpeed = 5f; private Vector3 Direction; private Vector3 Rotation; public KeyCode moveUp = KeyCode.W; public KeyCode moveRight = KeyCode.D; public KeyCode moveDown = KeyCode.S; public KeyCode moveLeft = KeyCode.A; public void Update() { Direction = Vector3.zero; Rotation = Vector3.zero; if (Input.GetKey(moveUp)) { Rotation.z -= 1; Direction = Vector3.forward; } if (Input.GetKey(moveDown)) { Rotation.z += 1; Direction = Vector3.forward; } if (Input.GetKey(moveRight)) { Rotation.x -= 1; Direction = Vector3.forward; } if (Input.GetKey(moveLeft)) { Rotation.x += 1; Direction = Vector3.forward; } if (Rotation != Vector3.zero) { Quaternion rotate = Quaternion.LookRotation(Vector3.up, Rotation); // This is to prevent the rotation along these two axis. The game // has 3d objects within a 2d scene. rotate.x = 0; rotate.z = 0; transform.rotation = rotate; } transform.Translate(Direction * MoveSpeed * Time.deltaTime); } }
23.080645
78
0.556953
[ "MIT" ]
TriNerdia/game-jam-2019
Game/Assets/Source/PlayerMovement.cs
1,433
C#
using System.Collections.Generic; using System.Linq; using Omnium.Core.ast; using Omnium.Core.ast.declarations; using Omnium.Core.ast.expressions; using Omnium.Core.ast.expressions.literals; using Omnium.Core.ast.statements; using Omnium.Core.ast.types; namespace Omnium.Core.compiler { public abstract class TreeVoidWalker { protected bool skipChildren = false; public readonly List<CompilationError> Errors = new List<CompilationError>(); public readonly List<CompilationError> Warnings = new List<CompilationError>(); public virtual void Visit(INode node) { if (node == null) return; if (node is INode) EnterINode((INode) node); if (node is Node) EnterNode((Node) node); if (node is ITypeNode) EnterITypeNode((ITypeNode) node); if (node is IStatement) EnterIStatement((IStatement) node); if (node is IExpression) EnterIExpression((IExpression) node); if (node is IHasVariables) EnterIHasVariables((IHasVariables) node); if (node is INamedDeclaration) EnterINamedDeclaration((INamedDeclaration) node); if (node is Token) EnterToken((Token) node); if (node is ArrayType) EnterArrayType((ArrayType) node); if (node is FunctionType) EnterFunctionType((FunctionType) node); if (node is FunctionParameter) EnterFunctionParameter((FunctionParameter) node); if (node is GenericType) EnterGenericType((GenericType) node); if (node is ReferenceType) EnterReferenceType((ReferenceType) node); if (node is TypeList) EnterTypeList((TypeList) node); if (node is TypeNodeWrapper) EnterTypeNodeWrapper((TypeNodeWrapper) node); if (node is Assertion) EnterAssertion((Assertion) node); if (node is BlockStatement) EnterBlockStatement((BlockStatement) node); if (node is BreakStatement) EnterBreakStatement((BreakStatement) node); if (node is ContinueStatement) EnterContinueStatement((ContinueStatement) node); if (node is ExpressionStatement) EnterExpressionStatement((ExpressionStatement) node); if (node is ForeachStatement) EnterForeachStatement((ForeachStatement) node); if (node is ForStatement) EnterForStatement((ForStatement) node); if (node is GotoStatement) EnterGotoStatement((GotoStatement) node); if (node is GotoTargetStatement) EnterGotoTargetStatement((GotoTargetStatement) node); if (node is IfStatement) EnterIfStatement((IfStatement) node); if (node is ReturnStatement) EnterReturnStatement((ReturnStatement) node); if (node is SwitchStatement) EnterSwitchStatement((SwitchStatement) node); if (node is SwitchGroup) EnterSwitchGroup((SwitchGroup) node); if (node is SwitchLabel) EnterSwitchLabel((SwitchLabel) node); if (node is VariableDeclarationStatement) EnterVariableDeclarationStatement((VariableDeclarationStatement) node); if (node is WhileStatement) EnterWhileStatement((WhileStatement) node); if (node is Expression) EnterExpression((Expression) node); if (node is INameExpression) EnterINameExpression((INameExpression) node); if (node is NativeMethodInvocationExpression) EnterNativeMethodInvocationExpression((NativeMethodInvocationExpression) node); if (node is ILiteral) EnterILiteral((ILiteral) node); if (node is AbstractTopLevelNode) EnterAbstractTopLevelNode((AbstractTopLevelNode) node); if (node is ClassDeclaration) EnterClassDeclaration((ClassDeclaration) node); if (node is ConstructorDeclaration) EnterConstructorDeclaration((ConstructorDeclaration) node); if (node is EnumDeclaration) EnterEnumDeclaration((EnumDeclaration) node); if (node is EnumValue) EnterEnumValue((EnumValue) node); if (node is GenericTypeDeclaration) EnterGenericTypeDeclaration((GenericTypeDeclaration) node); if (node is GetterDeclaration) EnterGetterDeclaration((GetterDeclaration) node); if (node is GetterSetterDeclaration) EnterGetterSetterDeclaration((GetterSetterDeclaration) node); if (node is ImportDeclaration) EnterImportDeclaration((ImportDeclaration) node); if (node is MethodDeclaration) EnterMethodDeclaration((MethodDeclaration) node); if (node is Root) EnterRoot((Root) node); if (node is RuleDeclaration) EnterRuleDeclaration((RuleDeclaration) node); if (node is SetterDeclaration) EnterSetterDeclaration((SetterDeclaration) node); if (node is VariableDeclaration) EnterVariableDeclaration((VariableDeclaration) node); if (node is BoolType) EnterBoolType((BoolType) node); if (node is NumberType) EnterNumberType((NumberType) node); if (node is StringType) EnterStringType((StringType) node); if (node is VoidType) EnterVoidType((VoidType) node); if (node is ArrayCreationExpression) EnterArrayCreationExpression((ArrayCreationExpression) node); if (node is ArrayIndexExpression) EnterArrayIndexExpression((ArrayIndexExpression) node); if (node is AssignmentExpression) EnterAssignmentExpression((AssignmentExpression) node); if (node is AssignmentOperator) EnterAssignmentOperator((AssignmentOperator) node); if (node is BinaryExpression) EnterBinaryExpression((BinaryExpression) node); if (node is CastExpression) EnterCastExpression((CastExpression) node); if (node is ChaseExpression) EnterChaseExpression((ChaseExpression) node); if (node is StopChaseExpression) EnterStopChaseExpression((StopChaseExpression) node); if (node is LambdaExpression) EnterLambdaExpression((LambdaExpression) node); if (node is ListLambdaExpression) EnterListLambdaExpression((ListLambdaExpression) node); if (node is MemberExpression) EnterMemberExpression((MemberExpression) node); if (node is MethodInvocationExpression) EnterMethodInvocationExpression((MethodInvocationExpression) node); if (node is NativeTrigger) EnterNativeTrigger((NativeTrigger) node); if (node is ObjectCreationExpression) EnterObjectCreationExpression((ObjectCreationExpression) node); if (node is PlayerVarsExpression) EnterPlayerVarsExpression((PlayerVarsExpression) node); if (node is PlayerVarsPlayerExpression) EnterPlayerVarsPlayerExpression((PlayerVarsPlayerExpression) node); if (node is PosfixOperationExpression) EnterPosfixOperationExpression((PosfixOperationExpression) node); if (node is SimpleNameExpression) EnterSimpleNameExpression((SimpleNameExpression) node); if (node is ThisExpression) EnterThisExpression((ThisExpression) node); if (node is UnaryExpression) EnterUnaryExpression((UnaryExpression) node); if (node is BooleanLiteral) EnterBooleanLiteral((BooleanLiteral) node); if (node is NullLiteral) EnterNullLiteral((NullLiteral) node); if (node is NumberLiteral) EnterNumberLiteral((NumberLiteral) node); if (node is StringLiteral) EnterStringLiteral((StringLiteral) node); if (node is ModuleDeclaration) EnterModuleDeclaration((ModuleDeclaration) node); if (node is SourceFile) EnterSourceFile((SourceFile) node); if (skipChildren) skipChildren = false; else foreach (var child in node.Children.ToList()) Visit(child); if (node is INode) ExitINode((INode) node); if (node is Node) ExitNode((Node) node); if (node is ITypeNode) ExitITypeNode((ITypeNode) node); if (node is IStatement) ExitIStatement((IStatement) node); if (node is IExpression) ExitIExpression((IExpression) node); if (node is IHasVariables) ExitIHasVariables((IHasVariables) node); if (node is INamedDeclaration) ExitINamedDeclaration((INamedDeclaration) node); if (node is Token) ExitToken((Token) node); if (node is ArrayType) ExitArrayType((ArrayType) node); if (node is FunctionType) ExitFunctionType((FunctionType) node); if (node is FunctionParameter) ExitFunctionParameter((FunctionParameter) node); if (node is GenericType) ExitGenericType((GenericType) node); if (node is ReferenceType) ExitReferenceType((ReferenceType) node); if (node is TypeList) ExitTypeList((TypeList) node); if (node is TypeNodeWrapper) ExitTypeNodeWrapper((TypeNodeWrapper) node); if (node is Assertion) ExitAssertion((Assertion) node); if (node is BlockStatement) ExitBlockStatement((BlockStatement) node); if (node is BreakStatement) ExitBreakStatement((BreakStatement) node); if (node is ContinueStatement) ExitContinueStatement((ContinueStatement) node); if (node is ExpressionStatement) ExitExpressionStatement((ExpressionStatement) node); if (node is ForeachStatement) ExitForeachStatement((ForeachStatement) node); if (node is ForStatement) ExitForStatement((ForStatement) node); if (node is GotoStatement) ExitGotoStatement((GotoStatement) node); if (node is GotoTargetStatement) ExitGotoTargetStatement((GotoTargetStatement) node); if (node is IfStatement) ExitIfStatement((IfStatement) node); if (node is ReturnStatement) ExitReturnStatement((ReturnStatement) node); if (node is SwitchStatement) ExitSwitchStatement((SwitchStatement) node); if (node is SwitchGroup) ExitSwitchGroup((SwitchGroup) node); if (node is SwitchLabel) ExitSwitchLabel((SwitchLabel) node); if (node is VariableDeclarationStatement) ExitVariableDeclarationStatement((VariableDeclarationStatement) node); if (node is WhileStatement) ExitWhileStatement((WhileStatement) node); if (node is Expression) ExitExpression((Expression) node); if (node is INameExpression) ExitINameExpression((INameExpression) node); if (node is NativeMethodInvocationExpression) ExitNativeMethodInvocationExpression((NativeMethodInvocationExpression) node); if (node is ILiteral) ExitILiteral((ILiteral) node); if (node is AbstractTopLevelNode) ExitAbstractTopLevelNode((AbstractTopLevelNode) node); if (node is ClassDeclaration) ExitClassDeclaration((ClassDeclaration) node); if (node is ConstructorDeclaration) ExitConstructorDeclaration((ConstructorDeclaration) node); if (node is EnumDeclaration) ExitEnumDeclaration((EnumDeclaration) node); if (node is EnumValue) ExitEnumValue((EnumValue) node); if (node is GenericTypeDeclaration) ExitGenericTypeDeclaration((GenericTypeDeclaration) node); if (node is GetterDeclaration) ExitGetterDeclaration((GetterDeclaration) node); if (node is GetterSetterDeclaration) ExitGetterSetterDeclaration((GetterSetterDeclaration) node); if (node is ImportDeclaration) ExitImportDeclaration((ImportDeclaration) node); if (node is MethodDeclaration) ExitMethodDeclaration((MethodDeclaration) node); if (node is Root) ExitRoot((Root) node); if (node is RuleDeclaration) ExitRuleDeclaration((RuleDeclaration) node); if (node is SetterDeclaration) ExitSetterDeclaration((SetterDeclaration) node); if (node is VariableDeclaration) ExitVariableDeclaration((VariableDeclaration) node); if (node is BoolType) ExitBoolType((BoolType) node); if (node is NumberType) ExitNumberType((NumberType) node); if (node is StringType) ExitStringType((StringType) node); if (node is VoidType) ExitVoidType((VoidType) node); if (node is ArrayCreationExpression) ExitArrayCreationExpression((ArrayCreationExpression) node); if (node is ArrayIndexExpression) ExitArrayIndexExpression((ArrayIndexExpression) node); if (node is AssignmentExpression) ExitAssignmentExpression((AssignmentExpression) node); if (node is AssignmentOperator) ExitAssignmentOperator((AssignmentOperator) node); if (node is BinaryExpression) ExitBinaryExpression((BinaryExpression) node); if (node is CastExpression) ExitCastExpression((CastExpression) node); if (node is ChaseExpression) ExitChaseExpression((ChaseExpression) node); if (node is StopChaseExpression) ExitStopChaseExpression((StopChaseExpression) node); if (node is LambdaExpression) ExitLambdaExpression((LambdaExpression) node); if (node is ListLambdaExpression) ExitListLambdaExpression((ListLambdaExpression) node); if (node is MemberExpression) ExitMemberExpression((MemberExpression) node); if (node is MethodInvocationExpression) ExitMethodInvocationExpression((MethodInvocationExpression) node); if (node is NativeTrigger) ExitNativeTrigger((NativeTrigger) node); if (node is ObjectCreationExpression) ExitObjectCreationExpression((ObjectCreationExpression) node); if (node is PlayerVarsExpression) ExitPlayerVarsExpression((PlayerVarsExpression) node); if (node is PlayerVarsPlayerExpression) ExitPlayerVarsPlayerExpression((PlayerVarsPlayerExpression) node); if (node is PosfixOperationExpression) ExitPosfixOperationExpression((PosfixOperationExpression) node); if (node is SimpleNameExpression) ExitSimpleNameExpression((SimpleNameExpression) node); if (node is ThisExpression) ExitThisExpression((ThisExpression) node); if (node is UnaryExpression) ExitUnaryExpression((UnaryExpression) node); if (node is BooleanLiteral) ExitBooleanLiteral((BooleanLiteral) node); if (node is NullLiteral) ExitNullLiteral((NullLiteral) node); if (node is NumberLiteral) ExitNumberLiteral((NumberLiteral) node); if (node is StringLiteral) ExitStringLiteral((StringLiteral) node); if (node is ModuleDeclaration) ExitModuleDeclaration((ModuleDeclaration) node); if (node is SourceFile) ExitSourceFile((SourceFile) node); } public virtual void EnterINode(INode iNode) { } public virtual void ExitINode(INode iNode) { } public virtual void EnterNode(Node node) { } public virtual void ExitNode(Node node) { } public virtual void EnterITypeNode(ITypeNode iTypeNode) { } public virtual void ExitITypeNode(ITypeNode iTypeNode) { } public virtual void EnterIStatement(IStatement iStatement) { } public virtual void ExitIStatement(IStatement iStatement) { } public virtual void EnterIExpression(IExpression iExpression) { } public virtual void ExitIExpression(IExpression iExpression) { } public virtual void EnterIHasVariables(IHasVariables iHasVariables) { } public virtual void ExitIHasVariables(IHasVariables iHasVariables) { } public virtual void EnterINamedDeclaration(INamedDeclaration iNamedDeclaration) { } public virtual void ExitINamedDeclaration(INamedDeclaration iNamedDeclaration) { } public virtual void EnterToken(Token token) { } public virtual void ExitToken(Token token) { } public virtual void EnterArrayType(ArrayType arrayType) { } public virtual void ExitArrayType(ArrayType arrayType) { } public virtual void EnterFunctionType(FunctionType functionType) { } public virtual void ExitFunctionType(FunctionType functionType) { } public virtual void EnterFunctionParameter(FunctionParameter functionParameter) { } public virtual void ExitFunctionParameter(FunctionParameter functionParameter) { } public virtual void EnterGenericType(GenericType genericType) { } public virtual void ExitGenericType(GenericType genericType) { } public virtual void EnterReferenceType(ReferenceType referenceType) { } public virtual void ExitReferenceType(ReferenceType referenceType) { } public virtual void EnterTypeList(TypeList typeList) { } public virtual void ExitTypeList(TypeList typeList) { } public virtual void EnterTypeNodeWrapper(TypeNodeWrapper typeNodeWrapper) { } public virtual void ExitTypeNodeWrapper(TypeNodeWrapper typeNodeWrapper) { } public virtual void EnterAssertion(Assertion assertion) { } public virtual void ExitAssertion(Assertion assertion) { } public virtual void EnterBlockStatement(BlockStatement blockStatement) { } public virtual void ExitBlockStatement(BlockStatement blockStatement) { } public virtual void EnterBreakStatement(BreakStatement breakStatement) { } public virtual void ExitBreakStatement(BreakStatement breakStatement) { } public virtual void EnterContinueStatement(ContinueStatement continueStatement) { } public virtual void ExitContinueStatement(ContinueStatement continueStatement) { } public virtual void EnterExpressionStatement(ExpressionStatement expressionStatement) { } public virtual void ExitExpressionStatement(ExpressionStatement expressionStatement) { } public virtual void EnterForeachStatement(ForeachStatement foreachStatement) { } public virtual void ExitForeachStatement(ForeachStatement foreachStatement) { } public virtual void EnterForStatement(ForStatement forStatement) { } public virtual void ExitForStatement(ForStatement forStatement) { } public virtual void EnterGotoStatement(GotoStatement gotoStatement) { } public virtual void ExitGotoStatement(GotoStatement gotoStatement) { } public virtual void EnterGotoTargetStatement(GotoTargetStatement gotoTargetStatement) { } public virtual void ExitGotoTargetStatement(GotoTargetStatement gotoTargetStatement) { } public virtual void EnterIfStatement(IfStatement ifStatement) { } public virtual void ExitIfStatement(IfStatement ifStatement) { } public virtual void EnterReturnStatement(ReturnStatement returnStatement) { } public virtual void ExitReturnStatement(ReturnStatement returnStatement) { } public virtual void EnterSwitchStatement(SwitchStatement switchStatement) { } public virtual void ExitSwitchStatement(SwitchStatement switchStatement) { } public virtual void EnterSwitchGroup(SwitchGroup switchGroup) { } public virtual void ExitSwitchGroup(SwitchGroup switchGroup) { } public virtual void EnterSwitchLabel(SwitchLabel switchLabel) { } public virtual void ExitSwitchLabel(SwitchLabel switchLabel) { } public virtual void EnterVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement) { } public virtual void ExitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement) { } public virtual void EnterWhileStatement(WhileStatement whileStatement) { } public virtual void ExitWhileStatement(WhileStatement whileStatement) { } public virtual void EnterExpression(Expression expression) { } public virtual void ExitExpression(Expression expression) { } public virtual void EnterINameExpression(INameExpression iNameExpression) { } public virtual void ExitINameExpression(INameExpression iNameExpression) { } public virtual void EnterNativeMethodInvocationExpression(NativeMethodInvocationExpression nativeMethodInvocationExpression) { } public virtual void ExitNativeMethodInvocationExpression(NativeMethodInvocationExpression nativeMethodInvocationExpression) { } public virtual void EnterILiteral(ILiteral iLiteral) { } public virtual void ExitILiteral(ILiteral iLiteral) { } public virtual void EnterAbstractTopLevelNode(AbstractTopLevelNode abstractTopLevelNode) { } public virtual void ExitAbstractTopLevelNode(AbstractTopLevelNode abstractTopLevelNode) { } public virtual void EnterClassDeclaration(ClassDeclaration classDeclaration) { } public virtual void ExitClassDeclaration(ClassDeclaration classDeclaration) { } public virtual void EnterConstructorDeclaration(ConstructorDeclaration constructorDeclaration) { } public virtual void ExitConstructorDeclaration(ConstructorDeclaration constructorDeclaration) { } public virtual void EnterEnumDeclaration(EnumDeclaration enumDeclaration) { } public virtual void ExitEnumDeclaration(EnumDeclaration enumDeclaration) { } public virtual void EnterEnumValue(EnumValue enumValue) { } public virtual void ExitEnumValue(EnumValue enumValue) { } public virtual void EnterGenericTypeDeclaration(GenericTypeDeclaration genericTypeDeclaration) { } public virtual void ExitGenericTypeDeclaration(GenericTypeDeclaration genericTypeDeclaration) { } public virtual void EnterGetterDeclaration(GetterDeclaration getterDeclaration) { } public virtual void ExitGetterDeclaration(GetterDeclaration getterDeclaration) { } public virtual void EnterGetterSetterDeclaration(GetterSetterDeclaration getterSetterDeclaration) { } public virtual void ExitGetterSetterDeclaration(GetterSetterDeclaration getterSetterDeclaration) { } public virtual void EnterImportDeclaration(ImportDeclaration importDeclaration) { } public virtual void ExitImportDeclaration(ImportDeclaration importDeclaration) { } public virtual void EnterMethodDeclaration(MethodDeclaration methodDeclaration) { } public virtual void ExitMethodDeclaration(MethodDeclaration methodDeclaration) { } public virtual void EnterRoot(Root root) { } public virtual void ExitRoot(Root root) { } public virtual void EnterRuleDeclaration(RuleDeclaration ruleDeclaration) { } public virtual void ExitRuleDeclaration(RuleDeclaration ruleDeclaration) { } public virtual void EnterSetterDeclaration(SetterDeclaration setterDeclaration) { } public virtual void ExitSetterDeclaration(SetterDeclaration setterDeclaration) { } public virtual void EnterVariableDeclaration(VariableDeclaration variableDeclaration) { } public virtual void ExitVariableDeclaration(VariableDeclaration variableDeclaration) { } public virtual void EnterBoolType(BoolType boolType) { } public virtual void ExitBoolType(BoolType boolType) { } public virtual void EnterNumberType(NumberType numberType) { } public virtual void ExitNumberType(NumberType numberType) { } public virtual void EnterStringType(StringType stringType) { } public virtual void ExitStringType(StringType stringType) { } public virtual void EnterVoidType(VoidType voidType) { } public virtual void ExitVoidType(VoidType voidType) { } public virtual void EnterArrayCreationExpression(ArrayCreationExpression arrayCreationExpression) { } public virtual void ExitArrayCreationExpression(ArrayCreationExpression arrayCreationExpression) { } public virtual void EnterArrayIndexExpression(ArrayIndexExpression arrayIndexExpression) { } public virtual void ExitArrayIndexExpression(ArrayIndexExpression arrayIndexExpression) { } public virtual void EnterAssignmentExpression(AssignmentExpression assignmentExpression) { } public virtual void ExitAssignmentExpression(AssignmentExpression assignmentExpression) { } public virtual void EnterAssignmentOperator(AssignmentOperator assignmentOperator) { } public virtual void ExitAssignmentOperator(AssignmentOperator assignmentOperator) { } public virtual void EnterBinaryExpression(BinaryExpression binaryExpression) { } public virtual void ExitBinaryExpression(BinaryExpression binaryExpression) { } public virtual void EnterCastExpression(CastExpression castExpression) { } public virtual void ExitCastExpression(CastExpression castExpression) { } public virtual void EnterChaseExpression(ChaseExpression chaseExpression) { } public virtual void ExitChaseExpression(ChaseExpression chaseExpression) { } public virtual void EnterStopChaseExpression(StopChaseExpression stopChaseExpression) { } public virtual void ExitStopChaseExpression(StopChaseExpression stopChaseExpression) { } public virtual void EnterLambdaExpression(LambdaExpression lambdaExpression) { } public virtual void ExitLambdaExpression(LambdaExpression lambdaExpression) { } public virtual void EnterListLambdaExpression(ListLambdaExpression listLambdaExpression) { } public virtual void ExitListLambdaExpression(ListLambdaExpression listLambdaExpression) { } public virtual void EnterMemberExpression(MemberExpression memberExpression) { } public virtual void ExitMemberExpression(MemberExpression memberExpression) { } public virtual void EnterMethodInvocationExpression(MethodInvocationExpression methodInvocationExpression) { } public virtual void ExitMethodInvocationExpression(MethodInvocationExpression methodInvocationExpression) { } public virtual void EnterNativeTrigger(NativeTrigger nativeTrigger) { } public virtual void ExitNativeTrigger(NativeTrigger nativeTrigger) { } public virtual void EnterObjectCreationExpression(ObjectCreationExpression objectCreationExpression) { } public virtual void ExitObjectCreationExpression(ObjectCreationExpression objectCreationExpression) { } public virtual void EnterPlayerVarsExpression(PlayerVarsExpression playerVarsExpression) { } public virtual void ExitPlayerVarsExpression(PlayerVarsExpression playerVarsExpression) { } public virtual void EnterPlayerVarsPlayerExpression(PlayerVarsPlayerExpression playerVarsPlayerExpression) { } public virtual void ExitPlayerVarsPlayerExpression(PlayerVarsPlayerExpression playerVarsPlayerExpression) { } public virtual void EnterPosfixOperationExpression(PosfixOperationExpression posfixOperationExpression) { } public virtual void ExitPosfixOperationExpression(PosfixOperationExpression posfixOperationExpression) { } public virtual void EnterSimpleNameExpression(SimpleNameExpression simpleNameExpression) { } public virtual void ExitSimpleNameExpression(SimpleNameExpression simpleNameExpression) { } public virtual void EnterThisExpression(ThisExpression thisExpression) { } public virtual void ExitThisExpression(ThisExpression thisExpression) { } public virtual void EnterUnaryExpression(UnaryExpression unaryExpression) { } public virtual void ExitUnaryExpression(UnaryExpression unaryExpression) { } public virtual void EnterBooleanLiteral(BooleanLiteral booleanLiteral) { } public virtual void ExitBooleanLiteral(BooleanLiteral booleanLiteral) { } public virtual void EnterNullLiteral(NullLiteral nullLiteral) { } public virtual void ExitNullLiteral(NullLiteral nullLiteral) { } public virtual void EnterNumberLiteral(NumberLiteral numberLiteral) { } public virtual void ExitNumberLiteral(NumberLiteral numberLiteral) { } public virtual void EnterStringLiteral(StringLiteral stringLiteral) { } public virtual void ExitStringLiteral(StringLiteral stringLiteral) { } public virtual void EnterModuleDeclaration(ModuleDeclaration moduleDeclaration) { } public virtual void ExitModuleDeclaration(ModuleDeclaration moduleDeclaration) { } public virtual void EnterSourceFile(SourceFile sourceFile) { } public virtual void ExitSourceFile(SourceFile sourceFile) { } } }
60.525692
136
0.68001
[ "MIT" ]
Beier/Omnium
Omnium.Core/compiler/TreeVoidWalker.cs
30,626
C#
/* * Intersight REST API * * This is Intersight REST API * * OpenAPI spec version: 0.1.0-559 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = intersight.Client.SwaggerDateConverter; namespace intersight.Model { /// <summary> /// CondHclStatusJobRef /// </summary> [DataContract] public partial class CondHclStatusJobRef : IEquatable<CondHclStatusJobRef>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="CondHclStatusJobRef" /> class. /// </summary> [JsonConstructorAttribute] public CondHclStatusJobRef() { } /// <summary> /// Gets or Sets Moid /// </summary> [DataMember(Name="Moid", EmitDefaultValue=false)] public string Moid { get; private set; } /// <summary> /// Gets or Sets ObjectType /// </summary> [DataMember(Name="ObjectType", EmitDefaultValue=false)] public string ObjectType { get; private set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CondHclStatusJobRef {\n"); sb.Append(" Moid: ").Append(Moid).Append("\n"); sb.Append(" ObjectType: ").Append(ObjectType).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as CondHclStatusJobRef); } /// <summary> /// Returns true if CondHclStatusJobRef instances are equal /// </summary> /// <param name="other">Instance of CondHclStatusJobRef to be compared</param> /// <returns>Boolean</returns> public bool Equals(CondHclStatusJobRef other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Moid == other.Moid || this.Moid != null && this.Moid.Equals(other.Moid) ) && ( this.ObjectType == other.ObjectType || this.ObjectType != null && this.ObjectType.Equals(other.ObjectType) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Moid != null) hash = hash * 59 + this.Moid.GetHashCode(); if (this.ObjectType != null) hash = hash * 59 + this.ObjectType.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
32.169014
140
0.559982
[ "Apache-2.0" ]
CiscoUcs/intersight-powershell
csharp/swaggerClient/src/intersight/Model/CondHclStatusJobRef.cs
4,568
C#
namespace FirstSimpleMappingSample; public class ClassB { public int Item1 { get; set; } public BasicList<int> FirstList { get; set; } = new(); public BasicList<BasicList<int>> SecondList { get; set; } = new(); public DateOnly DateUsed { get; set; } public string Item2 { get; set; } = ""; }
34.666667
70
0.650641
[ "MIT" ]
musictopia2/UseSourceGeneratorSamples
MappingSamples/FirstSimpleMappingSample/ClassB.cs
314
C#
using Microsoft.Online.SharePoint.TenantAdministration; using Microsoft.SharePoint.Client; using PnP.Framework.Diagnostics; using PnP.Framework.Provisioning.Model; using PnP.Framework.Provisioning.Model.Configuration; using PnP.Framework.Provisioning.ObjectHandlers.TokenDefinitions; using PnP.Framework.Sites; using PnP.Framework.Utilities; using System; using System.Collections.Generic; using System.Linq; namespace PnP.Framework.Provisioning.ObjectHandlers { internal class ObjectHierarchySequenceSites : ObjectHierarchyHandlerBase { private readonly List<TokenDefinition> _additionalTokens = new List<TokenDefinition>(); public override string Name => "Sequences"; public override ProvisioningHierarchy ExtractObjects(Tenant tenant, ProvisioningHierarchy hierarchy, ExtractConfiguration configuration) { ProvisioningHierarchy tenantTemplate = new ProvisioningHierarchy(); List<string> siteCollectionUrls = configuration.Tenant.Sequence.SiteUrls; List<string> connectedSiteUrls = new List<string>(); foreach (var siteCollectionUrl in siteCollectionUrls) { using (var siteContext = tenant.Context.Clone(siteCollectionUrl)) { if (configuration.Tenant.Sequence.IncludeJoinedSites && siteContext.Site.EnsureProperty(s => s.IsHubSite)) { foreach (var hubsiteChildUrl in tenant.GetHubSiteChildUrls(siteContext.Site.EnsureProperty(s => s.Id))) { if (!connectedSiteUrls.Contains(hubsiteChildUrl) && !siteCollectionUrl.Contains(hubsiteChildUrl)) { connectedSiteUrls.Add(hubsiteChildUrl); } } } } } siteCollectionUrls.AddRange(connectedSiteUrls); ProvisioningSequence provisioningSequence = new ProvisioningSequence { ID = "TENANTSEQUENCE" }; foreach (var siteCollectionUrl in siteCollectionUrls) { var siteProperties = tenant.GetSitePropertiesByUrl(siteCollectionUrl, true); tenant.Context.Load(siteProperties); tenant.Context.ExecuteQueryRetry(); Model.SiteCollection siteCollection = null; using (var siteContext = tenant.Context.Clone(siteCollectionUrl)) { siteContext.Site.EnsureProperties(s => s.Id, s => s.ShareByEmailEnabled, s => s.Classification, s => s.GroupId); var templateGuid = siteContext.Site.Id.ToString("N"); switch (siteProperties.Template) { case "SITEPAGEPUBLISHING#0": { siteCollection = new CommunicationSiteCollection { IsHubSite = siteProperties.IsHubSite }; if (siteProperties.IsHubSite) { var hubsiteProperties = tenant.GetHubSitePropertiesByUrl(siteCollectionUrl); tenant.Context.Load(hubsiteProperties); tenant.Context.ExecuteQueryRetry(); siteCollection.HubSiteLogoUrl = hubsiteProperties.LogoUrl; siteCollection.HubSiteTitle = hubsiteProperties.Title; } siteCollection.Description = siteProperties.Description; ((CommunicationSiteCollection)siteCollection).Language = (int)siteProperties.Lcid; ((CommunicationSiteCollection)siteCollection).Owner = siteProperties.OwnerEmail; ((CommunicationSiteCollection)siteCollection).AllowFileSharingForGuestUsers = siteContext.Site.ShareByEmailEnabled; if (!string.IsNullOrEmpty(siteContext.Site.Classification)) { ((CommunicationSiteCollection)siteCollection).Classification = siteContext.Site.Classification; } tenantTemplate.Parameters.Add($"SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_URL", siteProperties.Url); ((CommunicationSiteCollection)siteCollection).Url = $"{{parameter:SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_URL}}"; tenantTemplate.Parameters.Add($"SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_TITLE", siteProperties.Title); siteCollection.Title = $"{{parameter:SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_TITLE}}"; break; } case "GROUP#0": { siteCollection = new TeamSiteCollection { IsHubSite = siteProperties.IsHubSite }; if (siteProperties.IsHubSite) { var hubsiteProperties = tenant.GetHubSitePropertiesByUrl(siteCollectionUrl); tenant.Context.Load(hubsiteProperties); tenant.Context.ExecuteQueryRetry(); siteCollection.HubSiteLogoUrl = hubsiteProperties.LogoUrl; siteCollection.HubSiteTitle = hubsiteProperties.Title; } siteCollection.Description = siteProperties.Description; var groupInfo = Sites.SiteCollection.GetGroupInfoByGroupIdAsync(siteContext, siteContext.Site.GroupId.ToString()).GetAwaiter().GetResult(); if (groupInfo != null) { tenantTemplate.Parameters.Add($"SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_ALIAS", Convert.ToString(groupInfo["alias"])); ((TeamSiteCollection)siteCollection).Alias = $"{{parameter:SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_ALIAS}}"; if (groupInfo["classification"] != null) { ((TeamSiteCollection)siteCollection).Classification = Convert.ToString(groupInfo["classification"]); } ((TeamSiteCollection)siteCollection).IsPublic = Convert.ToBoolean(groupInfo["isPublic"]); } ((TeamSiteCollection)siteCollection).DisplayName = siteProperties.Title; ((TeamSiteCollection)siteCollection).Language = (int)siteProperties.Lcid; ((TeamSiteCollection)siteCollection).HideTeamify = Sites.SiteCollection.IsTeamifyPromptHiddenAsync(siteContext).GetAwaiter().GetResult(); tenantTemplate.Parameters.Add($"SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_TITLE", siteProperties.Title); siteCollection.Title = $"{{parameter:SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_TITLE}}"; break; } case "STS#3": { if (siteContext.Site.GroupId == Guid.Empty) { siteCollection = new TeamNoGroupSiteCollection { IsHubSite = siteProperties.IsHubSite }; if (siteProperties.IsHubSite) { var hubsiteProperties = tenant.GetHubSitePropertiesByUrl(siteCollectionUrl); tenant.Context.Load(hubsiteProperties); tenant.Context.ExecuteQueryRetry(); siteCollection.HubSiteLogoUrl = hubsiteProperties.LogoUrl; siteCollection.HubSiteTitle = hubsiteProperties.Title; } siteCollection.Description = siteProperties.Description; ((TeamNoGroupSiteCollection)siteCollection).Language = (int)siteProperties.Lcid; ((TeamNoGroupSiteCollection)siteCollection).Owner = siteProperties.OwnerEmail; ((TeamNoGroupSiteCollection)siteCollection).TimeZoneId = siteProperties.TimeZoneId; tenantTemplate.Parameters.Add($"SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_URL", siteProperties.Url); ((TeamNoGroupSiteCollection)siteCollection).Url = $"{{parameter:SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_URL}}"; tenantTemplate.Parameters.Add($"SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_TITLE", siteProperties.Title); siteCollection.Title = $"{{parameter:SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_TITLE}}"; break; } else { goto case "GROUP#0"; } } } var siteTemplateCreationInfo = new ProvisioningTemplateCreationInformation(siteContext.Web); // Retrieve the template for the site if (configuration != null) { siteTemplateCreationInfo = configuration.ToCreationInformation(siteContext.Web); } var siteTemplate = siteContext.Web.GetProvisioningTemplate(siteTemplateCreationInfo); siteTemplate.Id = $"TEMPLATE-{templateGuid}"; if (siteProperties.HubSiteId != Guid.Empty && siteProperties.HubSiteId != siteContext.Site.Id && siteTemplate.WebSettings != null) { siteTemplate.WebSettings.HubSiteUrl = $"{{parameter:SITECOLLECTION_{siteProperties.HubSiteId.ToString("N")}_URL}}"; } tenantTemplate.Templates.Add(siteTemplate); siteCollection.Templates.Add(siteTemplate.Id); if (siteProperties.WebsCount > 1 && configuration.Tenant.Sequence.IncludeSubsites) { var webs = siteContext.Web.EnsureProperty(w => w.Webs); int currentDepth = 1; foreach (var subweb in webs) { siteCollection.Sites.Add(ParseSubsiteSequences(subweb, ref tenantTemplate, configuration, currentDepth, configuration.Tenant.Sequence.MaxSubsiteDepth)); } } provisioningSequence.SiteCollections.Add(siteCollection); } } tenantTemplate.Sequences.Add(provisioningSequence); PnPProvisioningContext.Current?.ParsedSiteUrls.Clear(); PnPProvisioningContext.Current?.ParsedSiteUrls.AddRange(siteCollectionUrls); return tenantTemplate; } private SubSite ParseSubsiteSequences(Web subweb, ref ProvisioningHierarchy tenantTemplate, ExtractConfiguration configuration, int currentDepth, int maxDepth) { subweb.EnsureProperties(sw => sw.Url, sw => sw.Title, sw => sw.QuickLaunchEnabled, sw => sw.Description, sw => sw.Language, sw => sw.RegionalSettings.TimeZone, sw => sw.Webs, sw => sw.HasUniqueRoleAssignments); var subwebTemplate = subweb.GetProvisioningTemplate(configuration.ToCreationInformation(subweb)); var uniqueid = subweb.Id.ToString("N"); subwebTemplate.Id = $"TEMPLATE-{uniqueid}"; tenantTemplate.Templates.Add(subwebTemplate); tenantTemplate.Parameters.Add($"SUBSITE_{uniqueid}_URL", subweb.Url.Substring(subweb.Url.LastIndexOf("/"))); tenantTemplate.Parameters.Add($"SUBSITE_{uniqueid}_TITLE", subweb.Title); var subSiteCollection = new TeamNoGroupSubSite() { Url = $"{{parameter:SUBSITE_{uniqueid}_URL}}", Title = $"{{parameter:SUBSITE_{uniqueid}_TITLE}}", QuickLaunchEnabled = subweb.QuickLaunchEnabled, Description = subweb.Description, Language = (int)subweb.Language, TimeZoneId = subweb.RegionalSettings.TimeZone.Id, UseSamePermissionsAsParentSite = !subweb.HasUniqueRoleAssignments, Templates = { subwebTemplate.Id } }; bool traverse = true; if (maxDepth != 0) { currentDepth++; traverse = currentDepth <= maxDepth; } if (traverse && subweb.Webs.AreItemsAvailable) { currentDepth++; foreach (var subsubweb in subweb.Webs) { subSiteCollection.Sites.Add(ParseSubsiteSequences(subsubweb, ref tenantTemplate, configuration, currentDepth, maxDepth)); } } return subSiteCollection; } public override TokenParser ProvisionObjects(Tenant tenant, Model.ProvisioningHierarchy hierarchy, string sequenceId, TokenParser tokenParser, ApplyConfiguration configuration) { using (var scope = new PnPMonitoredScope(CoreResources.Provisioning_ObjectHandlers_Provisioning)) { bool nowait = false; if (configuration != null) { nowait = configuration.Tenant.DoNotWaitForSitesToBeFullyCreated; } var sequence = hierarchy.Sequences.FirstOrDefault(s => s.ID == sequenceId); if (sequence != null) { var siteUrls = new Dictionary<Guid, string>(); TokenParser siteTokenParser = null; // CHANGED: To avoid issues with low privilege users ClientObjectList<Microsoft.Online.SharePoint.TenantManagement.ThemeProperties> tenantThemes = null; if (TenantExtensions.IsCurrentUserTenantAdmin((ClientContext)tenant.Context)) { tenantThemes = tenant.GetAllTenantThemes(); tenant.Context.Load(tenantThemes); tenant.Context.ExecuteQueryRetry(); } foreach (var sitecollection in sequence.SiteCollections) { var rootSiteUrl = tenant.Context.Url.Replace("-admin", ""); ClientContext rootSiteContext = tenant.Context.Clone(rootSiteUrl, configuration.AccessTokens); ClientContext siteContext = null; switch (sitecollection) { case TeamSiteCollection t: { TeamSiteCollectionCreationInformation siteInfo = new TeamSiteCollectionCreationInformation() { Alias = tokenParser.ParseString(t.Alias), DisplayName = tokenParser.ParseString(t.Title), Description = tokenParser.ParseString(t.Description), Classification = tokenParser.ParseString(t.Classification), IsPublic = t.IsPublic, Lcid = (uint)t.Language }; if (Guid.TryParse(t.SiteDesign, out Guid siteDesignId)) { siteInfo.SiteDesignId = siteDesignId; } var groupSiteInfo = Sites.SiteCollection.GetGroupInfoAsync(rootSiteContext, siteInfo.Alias).GetAwaiter().GetResult(); if (groupSiteInfo == null) { string graphAccessToken = null; if (PnPProvisioningContext.Current != null) { try { graphAccessToken = PnPProvisioningContext.Current.AcquireCookie(PnP.Framework.Utilities.Graph.GraphHelper.MicrosoftGraphBaseURI); } catch { graphAccessToken = PnPProvisioningContext.Current.AcquireToken(new Uri(PnP.Framework.Utilities.Graph.GraphHelper.MicrosoftGraphBaseURI).Authority, null); } } WriteMessage($"Creating Team Site {siteInfo.Alias}", ProvisioningMessageType.Progress); #pragma warning disable CS0618 siteContext = Sites.SiteCollection.Create(rootSiteContext, siteInfo, configuration.Tenant.DelayAfterModernSiteCreation, noWait: nowait, graphAccessToken: graphAccessToken); #pragma warning restore CS0618 } else { if (groupSiteInfo.ContainsKey("siteUrl")) { WriteMessage($"Using existing Team Site {siteInfo.Alias}", ProvisioningMessageType.Progress); siteContext = (tenant.Context as ClientContext).Clone(groupSiteInfo["siteUrl"], configuration.AccessTokens); } } if (t.IsHubSite) { siteContext.Load(siteContext.Site, s => s.Id); siteContext.ExecuteQueryRetry(); RegisterAsHubSite(tenant, siteContext.Url, siteContext.Site.Id, t.HubSiteLogoUrl, t.HubSiteTitle, tokenParser); } if (!string.IsNullOrEmpty(t.Theme) && tenantThemes != null) { var parsedTheme = tokenParser.ParseString(t.Theme); if (tenantThemes.FirstOrDefault(th => th.Name == parsedTheme) != null) { tenant.SetWebTheme(parsedTheme, siteContext.Url); tenant.Context.ExecuteQueryRetry(); } else { WriteMessage($"Theme {parsedTheme} doesn't exist in the tenant, will not be applied", ProvisioningMessageType.Warning); } } if (t.Teamify) { try { WriteMessage($"Teamifying the O365 group connected site at URL - {siteContext.Url}", ProvisioningMessageType.Progress); siteContext.TeamifyAsync().GetAwaiter().GetResult(); } catch (Exception ex) { WriteMessage($"Teamifying site at URL - {siteContext.Url} failed due to an exception:- {ex.Message}", ProvisioningMessageType.Warning); } } if (t.HideTeamify) { try { WriteMessage($"Teamify prompt is now hidden for site at URL - {siteContext.Url}", ProvisioningMessageType.Progress); siteContext.HideTeamifyPromptAsync().GetAwaiter().GetResult(); } catch (Exception ex) { WriteMessage($"Teamify prompt couldn't be hidden for site at URL - {siteContext.Url} due to an exception:- {ex.Message}", ProvisioningMessageType.Warning); } } siteUrls.Add(t.Id, siteContext.Url); if (!string.IsNullOrEmpty(t.ProvisioningId)) { _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, t.ProvisioningId, siteContext.Url)); siteContext.Web.EnsureProperty(w => w.Id); _additionalTokens.Add(new SequenceSiteIdToken(null, t.ProvisioningId, siteContext.Web.Id)); siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId); _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, t.ProvisioningId, siteContext.Site.Id)); _additionalTokens.Add(new SequenceSiteGroupIdToken(null, t.ProvisioningId, siteContext.Site.GroupId)); } break; } case CommunicationSiteCollection c: { var siteUrl = tokenParser.ParseString(c.Url); if (!siteUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)) { // CHANGED: Modified to support low privilege users siteUrl = UrlUtility.Combine(rootSiteUrl, siteUrl); } CommunicationSiteCollectionCreationInformation siteInfo = new CommunicationSiteCollectionCreationInformation() { ShareByEmailEnabled = c.AllowFileSharingForGuestUsers, Classification = tokenParser.ParseString(c.Classification), Description = tokenParser.ParseString(c.Description), Lcid = (uint)c.Language, Owner = tokenParser.ParseString(c.Owner), Title = tokenParser.ParseString(c.Title), Url = siteUrl }; Guid siteDesignId; if (Guid.TryParse(c.SiteDesign, out siteDesignId)) { siteInfo.SiteDesignId = siteDesignId; } else if (Guid.TryParse(tokenParser.ParseString(c.SiteDesign), out siteDesignId)) { siteInfo.SiteDesignId = siteDesignId; } else { if (!string.IsNullOrEmpty(c.SiteDesign)) { siteInfo.SiteDesign = (CommunicationSiteDesign)Enum.Parse(typeof(CommunicationSiteDesign), c.SiteDesign); } else { siteInfo.SiteDesign = CommunicationSiteDesign.Showcase; } } // check if site exists var siteExistence = tenant.SiteExistsAnywhere(siteInfo.Url); if (siteExistence == SiteExistence.Yes) { WriteMessage($"Using existing Communications Site at {siteInfo.Url}", ProvisioningMessageType.Progress); siteContext = (tenant.Context as ClientContext).Clone(siteInfo.Url, configuration.AccessTokens); } else if (siteExistence == SiteExistence.Recycled) { var errorMessage = $"The requested Communications Site at {siteInfo.Url} is in the Recycle Bin and cannot be created"; WriteMessage(errorMessage, ProvisioningMessageType.Error); throw new RecycledSiteException(errorMessage); } else { WriteMessage($"Creating Communications Site at {siteInfo.Url}", ProvisioningMessageType.Progress); #pragma warning disable CS0618 siteContext = Sites.SiteCollection.Create(rootSiteContext, siteInfo, configuration.Tenant.DelayAfterModernSiteCreation, noWait: nowait); #pragma warning restore CS0618 } if (c.IsHubSite) { siteContext.Load(siteContext.Site, s => s.Id); siteContext.ExecuteQueryRetry(); RegisterAsHubSite(tenant, siteInfo.Url, siteContext.Site.Id, c.HubSiteLogoUrl, c.HubSiteTitle, tokenParser); } if (!string.IsNullOrEmpty(c.Theme) && tenantThemes != null) { var parsedTheme = tokenParser.ParseString(c.Theme); if (tenantThemes.FirstOrDefault(th => th.Name == parsedTheme) != null) { tenant.SetWebTheme(parsedTheme, siteInfo.Url); tenant.Context.ExecuteQueryRetry(); } else { WriteMessage($"Theme {parsedTheme} doesn't exist in the tenant, will not be applied", ProvisioningMessageType.Warning); } } siteUrls.Add(c.Id, siteInfo.Url); if (!string.IsNullOrEmpty(c.ProvisioningId)) { _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, c.ProvisioningId, siteInfo.Url)); siteContext.Web.EnsureProperty(w => w.Id); _additionalTokens.Add(new SequenceSiteIdToken(null, c.ProvisioningId, siteContext.Web.Id)); siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId); _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, c.ProvisioningId, siteContext.Site.Id)); _additionalTokens.Add(new SequenceSiteGroupIdToken(null, c.ProvisioningId, siteContext.Site.GroupId)); } break; } case TeamNoGroupSiteCollection t: { var siteUrl = tokenParser.ParseString(t.Url); TeamNoGroupSiteCollectionCreationInformation siteInfo = new TeamNoGroupSiteCollectionCreationInformation() { Lcid = (uint)t.Language, Url = siteUrl, Title = tokenParser.ParseString(t.Title), Description = tokenParser.ParseString(t.Description), Owner = tokenParser.ParseString(t.Owner) }; // check if site exists var siteExistence = tenant.SiteExistsAnywhere(siteUrl); if (siteExistence == SiteExistence.Yes) { WriteMessage($"Using existing Team Site at {siteUrl}", ProvisioningMessageType.Progress); siteContext = (tenant.Context as ClientContext).Clone(siteUrl, configuration.AccessTokens); } else if (siteExistence == SiteExistence.Recycled) { var errorMessage = $"The requested Team Site at {siteUrl} is in the Recycle Bin and cannot be created"; WriteMessage(errorMessage, ProvisioningMessageType.Error); throw new RecycledSiteException(errorMessage); } else { WriteMessage($"Creating Team Site with no Office 365 group at {siteUrl}", ProvisioningMessageType.Progress); #pragma warning disable CS0618 siteContext = Sites.SiteCollection.Create(rootSiteContext, siteInfo, configuration.Tenant.DelayAfterModernSiteCreation, noWait: nowait); #pragma warning restore CS0618 } if (t.Groupify) { if (string.IsNullOrEmpty(t.Alias)) { // We generate the alias, if it is missing t.Alias = t.Title.Replace(" ", string.Empty).ToLower(); } // In case we need to groupify the just created site var groupifyInformation = new TeamSiteCollectionGroupifyInformation { Alias = t.Alias, // Mandatory Classification = t.Classification, // Optional Description = t.Description, DisplayName = t.Title, HubSiteId = Guid.Empty, // Optional, so far we skip it IsPublic = t.IsPublic, // Mandatory KeepOldHomePage = t.KeepOldHomePage, // Optional, but we provide it Lcid = (uint)t.Language, Owners = new string[] { t.Owner }, }; tenant.GroupifySite(siteUrl, groupifyInformation); } if (t.IsHubSite) { siteContext.Load(siteContext.Site, s => s.Id); siteContext.ExecuteQueryRetry(); RegisterAsHubSite(tenant, siteContext.Url, siteContext.Site.Id, t.HubSiteLogoUrl, t.HubSiteTitle, tokenParser); } if (!string.IsNullOrEmpty(t.Theme) && tenantThemes != null) { var parsedTheme = tokenParser.ParseString(t.Theme); if (tenantThemes.FirstOrDefault(th => th.Name == parsedTheme) != null) { tenant.SetWebTheme(parsedTheme, siteContext.Url); tenant.Context.ExecuteQueryRetry(); } else { WriteMessage($"Theme {parsedTheme} doesn't exist in the tenant, will not be applied", ProvisioningMessageType.Warning); } } siteUrls.Add(t.Id, siteContext.Url); if (!string.IsNullOrEmpty(t.ProvisioningId)) { _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, t.ProvisioningId, siteContext.Url)); siteContext.Web.EnsureProperty(w => w.Id); _additionalTokens.Add(new SequenceSiteIdToken(null, t.ProvisioningId, siteContext.Web.Id)); siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId); _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, t.ProvisioningId, siteContext.Site.Id)); _additionalTokens.Add(new SequenceSiteGroupIdToken(null, t.ProvisioningId, siteContext.Site.GroupId)); } break; } } var web = siteContext.Web; if (siteTokenParser == null) { siteTokenParser = new TokenParser(tenant, hierarchy, configuration.ToApplyingInformation()); foreach (var token in _additionalTokens) { siteTokenParser.AddToken(token); // Add the token to the global token parser, too tokenParser.AddToken(token); } } foreach (var subsite in sitecollection.Sites) { var subSiteObject = (TeamNoGroupSubSite)subsite; web.EnsureProperties(w => w.Webs.IncludeWithDefaultProperties(), w => w.ServerRelativeUrl); siteTokenParser = CreateSubSites(hierarchy, siteTokenParser, sitecollection, siteContext, web, subSiteObject); } siteTokenParser = null; } // System.Threading.Thread.Sleep(TimeSpan.FromMinutes(10)); WriteMessage("Applying templates", ProvisioningMessageType.Progress); var currentSite = ""; var provisioningTemplateApplyingInformation = configuration.ToApplyingInformation(); provisioningTemplateApplyingInformation.ProgressDelegate = (string message, int step, int total) => { configuration.ProgressDelegate?.Invoke($"{currentSite} : {message}", step, total); }; foreach (var sitecollection in sequence.SiteCollections) { currentSite = sitecollection.ProvisioningId != null ? sitecollection.ProvisioningId : sitecollection.Title; siteUrls.TryGetValue(sitecollection.Id, out string siteUrl); if (siteUrl != null) { using (var clonedContext = tenant.Context.Clone(siteUrl, configuration.AccessTokens)) { var web = clonedContext.Web; foreach (var templateRef in sitecollection.Templates) { var provisioningTemplate = hierarchy.Templates.FirstOrDefault(t => t.Id == templateRef); if (provisioningTemplate != null) { provisioningTemplate.Connector = hierarchy.Connector; //if (siteTokenParser == null) //{ siteTokenParser = new TokenParser(web, provisioningTemplate, configuration.ToApplyingInformation()); foreach (var token in _additionalTokens) { siteTokenParser.AddToken(token); } //} //else //{ // siteTokenParser.Rebase(web, provisioningTemplate); //} WriteMessage($"Applying Template", ProvisioningMessageType.Progress); new SiteToTemplateConversion().ApplyRemoteTemplate(web, provisioningTemplate, provisioningTemplateApplyingInformation, true, siteTokenParser); } else { WriteMessage($"Referenced template ID {templateRef} not found", ProvisioningMessageType.Error); } } if (siteTokenParser == null) { siteTokenParser = new TokenParser(tenant, hierarchy, configuration.ToApplyingInformation()); foreach (var token in _additionalTokens) { siteTokenParser.AddToken(token); } } foreach (var subsite in sitecollection.Sites) { var subSiteObject = (TeamNoGroupSubSite)subsite; web.EnsureProperties(w => w.Webs.IncludeWithDefaultProperties(), w => w.ServerRelativeUrl); siteTokenParser = ApplySubSiteTemplates(hierarchy, siteTokenParser, sitecollection, clonedContext, web, subSiteObject, provisioningTemplateApplyingInformation); } if (sitecollection.IsHubSite) { RESTUtilities.ExecuteGetAsync(web, "/_api/web/hubsitedata(true)").GetAwaiter().GetResult(); } } } } } return tokenParser; } } private static void RegisterAsHubSite(Tenant tenant, string siteUrl, Guid siteId, string logoUrl, string hubsiteTitle, TokenParser parser) { siteUrl = parser.ParseString(siteUrl); var hubSiteProperties = tenant.GetHubSitePropertiesByUrl(siteUrl); tenant.Context.Load<HubSiteProperties>(hubSiteProperties); tenant.Context.ExecuteQueryRetry(); if (hubSiteProperties.ServerObjectIsNull == true) { var ci = new HubSiteCreationInformation { SiteId = siteId }; if (!string.IsNullOrEmpty(logoUrl)) { ci.LogoUrl = parser.ParseString(logoUrl); } if (!string.IsNullOrEmpty(hubsiteTitle)) { ci.Title = parser.ParseString(hubsiteTitle); } tenant.RegisterHubSiteWithCreationInformation(siteUrl, ci); //tenant.Context.Load(hubSiteProperties); tenant.Context.ExecuteQueryRetry(); } else { bool isDirty = false; if (!string.IsNullOrEmpty(logoUrl)) { logoUrl = parser.ParseString(logoUrl); hubSiteProperties.LogoUrl = logoUrl; isDirty = true; } if (!string.IsNullOrEmpty(hubsiteTitle)) { hubsiteTitle = parser.ParseString(hubsiteTitle); hubSiteProperties.Title = hubsiteTitle; isDirty = true; } if (isDirty) { hubSiteProperties.Update(); tenant.Context.ExecuteQueryRetry(); } } } private TokenParser CreateSubSites(ProvisioningHierarchy hierarchy, TokenParser tokenParser, Model.SiteCollection sitecollection, ClientContext siteContext, Web web, TeamNoGroupSubSite subSiteObject) { var url = tokenParser.ParseString(subSiteObject.Url); var subweb = web.Webs.FirstOrDefault(t => t.ServerRelativeUrl.Equals(UrlUtility.Combine(web.ServerRelativeUrl, "/", url.Trim(new char[] { '/' })))); if (subweb == null) { subweb = web.Webs.Add(new WebCreationInformation() { Language = subSiteObject.Language, Url = url, Description = tokenParser.ParseString(subSiteObject.Description), Title = tokenParser.ParseString(subSiteObject.Title), UseSamePermissionsAsParentSite = subSiteObject.UseSamePermissionsAsParentSite, WebTemplate = "STS#3" }); WriteMessage($"Creating Sub Site with no Office 365 group at {url}", ProvisioningMessageType.Progress); siteContext.Load(subweb); siteContext.ExecuteQueryRetry(); } else { WriteMessage($"Using existing Sub Site with no Office 365 group at {url}", ProvisioningMessageType.Progress); } if (subSiteObject.Sites.Any()) { foreach (var subsubSite in subSiteObject.Sites) { var subsubSiteObject = (TeamNoGroupSubSite)subsubSite; tokenParser = CreateSubSites(hierarchy, tokenParser, sitecollection, siteContext, subweb, subsubSiteObject); } } return tokenParser; } private TokenParser ApplySubSiteTemplates(ProvisioningHierarchy hierarchy, TokenParser tokenParser, Model.SiteCollection sitecollection, ClientContext siteContext, Web web, TeamNoGroupSubSite subSiteObject, ProvisioningTemplateApplyingInformation provisioningTemplateApplyingInformation) { var url = tokenParser.ParseString(subSiteObject.Url); var subweb = web.Webs.FirstOrDefault(t => t.ServerRelativeUrl.Equals(UrlUtility.Combine(web.ServerRelativeUrl, "/", url.Trim(new char[] { '/' })))); foreach (var templateRef in subSiteObject.Templates) { var provisioningTemplate = hierarchy.Templates.FirstOrDefault(t => t.Id == templateRef); if (provisioningTemplate != null) { provisioningTemplate.Connector = hierarchy.Connector; if (tokenParser == null) { tokenParser = new TokenParser(subweb, provisioningTemplate); } else { tokenParser.Rebase(subweb, provisioningTemplate, provisioningTemplateApplyingInformation); } new SiteToTemplateConversion().ApplyRemoteTemplate(subweb, provisioningTemplate, provisioningTemplateApplyingInformation, true, tokenParser); } else { WriteMessage($"Referenced template ID {templateRef} not found", ProvisioningMessageType.Error); } } if (subSiteObject.Sites.Any()) { foreach (var subsubSite in subSiteObject.Sites) { var subsubSiteObject = (TeamNoGroupSubSite)subsubSite; tokenParser = ApplySubSiteTemplates(hierarchy, tokenParser, sitecollection, siteContext, subweb, subsubSiteObject, provisioningTemplateApplyingInformation); } } return tokenParser; } public override bool WillExtract(Tenant tenant, Model.ProvisioningHierarchy hierarchy, string sequenceId, ExtractConfiguration creationInfo) { return true; } public override bool WillProvision(Tenant tenant, Model.ProvisioningHierarchy hierarchy, string sequenceId, ApplyConfiguration configuration) { return hierarchy.Sequences.Count > 0; } } }
60.986023
295
0.465643
[ "MIT" ]
mbakhoff/pnpframework
src/lib/PnP.Framework/Provisioning/ObjectHandlers/ObjectHierarchySequenceSites.cs
47,998
C#
using System; using System.IO; using System.Text; using System.Threading.Tasks; using FileSystemAbstraction.Adapters.Local; using Microsoft.Extensions.DependencyInjection; namespace FileSystemAbstraction.Sample { class Program { static async Task Main(string[] args) { var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); await RunAsync(serviceProvider); } private static void ConfigureServices(IServiceCollection services) { services .AddFileSystem(defaultScheme: "Local1") .AddLocal( scheme: "Local1", directory: Path.Combine(Directory.GetCurrentDirectory(), "Files/Local1"), create:true) .AddLocal( scheme: "Local2", directory: Path.Combine(Directory.GetCurrentDirectory(), "Files/Local2"), create: true) ; } static async Task RunAsync(IServiceProvider services) { var fileSystem = services.GetService<IFileSystem>(); // ====== FileSystem API Read/Write file with default scheme (Local1) await ReadWriteDefaultSchemeAsync(fileSystem); // ====== File API with another schemes ========= var barFile = await FileApiReadWriteAsync(fileSystem); // ====== File API across schemes ========= var movedFile = await FileApiMoveFileAcrossSchemesAsync(fileSystem, barFile); // ====== File API delete movedFile ======== await FileApiDeleteAsync(fileSystem, movedFile); // ====== FileSystem API delete test.txt ======== await FileSystemApiDeleteWithScheme(fileSystem); } private static async Task ReadWriteDefaultSchemeAsync(IFileSystem fileSystem) { const string fileName = "test.txt"; // Write 'Hello world!' to 'test.txt' (using default scheme : Local1) // --> Files/Local1/test.txt await fileSystem.WriteAsync(fileName, Encoding.UTF8.GetBytes("Hello world!"), overwrite: true); // Read the content of 'test.txt' (using default scheme : Local1) // --> Files/Local1/test.txt var content = await fileSystem.ReadAllBytesAsync(fileName); Console.WriteLine("Content of 'Files/Local1/test.txt' : " + Encoding.UTF8.GetString(content)); } private static async Task<IFile> FileApiReadWriteAsync(IFileSystem fileSystem) { const string fileName = "bar.txt"; // Get not yet existing file 'bar.txt (using scheme : Local2) // --> Files/Local2/bar.txt var barFile = await fileSystem.GetAsync("Local2", fileName, create: true); // Write 'Foo' to 'bar.txt' (using the second scheme : Local2) // --> Files/Local2/bar.txt await barFile.WriteAsync(Encoding.UTF8.GetBytes("Foo"), overwrite: true); // Read the content of 'test.text' (using default scheme : Local2) // --> Files/Local2/bar.txt var content = await barFile.ReadAllBytesAsync(); Console.WriteLine("Content of 'Files/Local2/bar.txt' : " + Encoding.UTF8.GetString(content)); return barFile; } private static async Task<IFile> FileApiMoveFileAcrossSchemesAsync(IFileSystem fileSystem, IFile fileToMove) { const string fileName = "bar1.txt"; // Get not yet existing file 'bar1.txt (using scheme : Local1) // --> Files/Local1/bar1.txt var newFile = await fileSystem.GetAsync("Local1", fileName, create: true); await fileToMove.MoveToAsync(newFile); // Read the content of 'bar1.txt' (using scheme : Local1) // --> Files/Local1/bar1.txt var content = await fileSystem.ReadAllBytesAsync(fileName); Console.WriteLine("Content of 'Files/Local1/bar1.txt' : " + Encoding.UTF8.GetString(content)); // Check existence of originalFile (should be deleted because of the move operation) var exists = await fileToMove.ExistsAsync(); Console.WriteLine("'Files/Local2/bar.txt' existence : " + exists); return newFile; } private static async Task FileApiDeleteAsync(IFileSystem fileSystem, IFile fileToDelete) { await fileToDelete.DeleteAsync(); } private static async Task FileSystemApiDeleteWithScheme(IFileSystem fileSystem) { await fileSystem.DeleteAsync("Local1", "test.txt"); } } }
37.90625
116
0.598722
[ "MIT" ]
srigaux/FileSystemAbstraction
samples/FileSystemAbstraction.Sample/Program.cs
4,854
C#
//--------------------------------------------------------- // <auto-generated> // This code was generated by a tool. Changes to this // file may cause incorrect behavior and will be lost // if the code is regenerated. // // Generated on 2020 October 09 06:03:58 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using static go.builtin; using ast = go.go.ast_package; using types = go.go.types_package; using log = go.log_package; using reflect = go.reflect_package; using analysis = go.golang.org.x.tools.go.analysis_package; using inspect = go.golang.org.x.tools.go.analysis.passes.inspect_package; using inspector = go.golang.org.x.tools.go.ast.inspector_package; using cfg = go.golang.org.x.tools.go.cfg_package; using typeutil = go.golang.org.x.tools.go.types.typeutil_package; using go; #nullable enable namespace go { namespace golang.org { namespace x { namespace tools { namespace go { namespace analysis { namespace passes { public static partial class ctrlflow_package { [GeneratedCode("go2cs", "0.1.0.0")] private partial struct noReturn { // Constructors public noReturn(NilType _) { } // Enable comparisons between nil and noReturn struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(noReturn value, NilType nil) => value.Equals(default(noReturn)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(noReturn value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, noReturn value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, noReturn value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator noReturn(NilType nil) => default(noReturn); } [GeneratedCode("go2cs", "0.1.0.0")] private static noReturn noReturn_cast(dynamic value) { return new noReturn(); } } }}}}}}}
34.826087
107
0.642114
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/ctrlflow_noReturnStruct.cs
2,403
C#
namespace TransitCity.Models.Transit { using System.Collections.Generic; using TransitCity.MVVM; public class Line : PropertyChangedBase { private uint _ridership; public Line(uint number, string name = null) { Name = name ?? number.ToString(); } public List<StationConnection> StationConnections { get; } = new List<StationConnection>(); public string Name { get; } public uint Number { get; } public int NumStations => GetStations().Count; public uint Ridership { get { return _ridership; } set { if (value != _ridership) { _ridership = value; OnPropertyChanged(); } } } public List<Station> GetStations() { if (StationConnections == null) { return null; } var list = new List<Station>(StationConnections.Count + 1) { StationConnections[0].StationA }; foreach (var stationConnection in StationConnections) { list.Add(stationConnection.StationB); } return list; } } }
23.87037
106
0.505818
[ "MIT" ]
gartenriese2/TransitCity
TransitCity/TransitCity/Models/Transit/Line.cs
1,291
C#
/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IFakeClassnameTags123ApiSync : IApiAccessor { #region Synchronous Operations /// <summary> /// To test class name in snake case /// </summary> /// <remarks> /// To test class name in snake case /// </remarks> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">client model</param> /// <returns>ModelClient</returns> ModelClient TestClassname (ModelClient body); /// <summary> /// To test class name in snake case /// </summary> /// <remarks> /// To test class name in snake case /// </remarks> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">client model</param> /// <returns>ApiResponse of ModelClient</returns> ApiResponse<ModelClient> TestClassnameWithHttpInfo (ModelClient body); #endregion Synchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IFakeClassnameTags123ApiAsync : IApiAccessor { #region Asynchronous Operations /// <summary> /// To test class name in snake case /// </summary> /// <remarks> /// To test class name in snake case /// </remarks> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">client model</param> /// <returns>Task of ModelClient</returns> System.Threading.Tasks.Task<ModelClient> TestClassnameAsync (ModelClient body); /// <summary> /// To test class name in snake case /// </summary> /// <remarks> /// To test class name in snake case /// </remarks> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">client model</param> /// <returns>Task of ApiResponse (ModelClient)</returns> System.Threading.Tasks.Task<ApiResponse<ModelClient>> TestClassnameAsyncWithHttpInfo (ModelClient body); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IFakeClassnameTags123Api : IFakeClassnameTags123ApiSync, IFakeClassnameTags123ApiAsync { } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class FakeClassnameTags123Api : IFakeClassnameTags123Api { private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="FakeClassnameTags123Api"/> class. /// </summary> /// <returns></returns> public FakeClassnameTags123Api() : this((string) null) { } /// <summary> /// Initializes a new instance of the <see cref="FakeClassnameTags123Api"/> class. /// </summary> /// <returns></returns> public FakeClassnameTags123Api(String basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, new Org.OpenAPITools.Client.Configuration { BasePath = basePath } ); this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="FakeClassnameTags123Api"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public FakeClassnameTags123Api(Org.OpenAPITools.Client.Configuration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, configuration ); this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="FakeClassnameTags123Api"/> class /// using a Configuration object and client instance. /// </summary> /// <param name="client">The client interface for synchronous API access.</param> /// <param name="asyncClient">The client interface for asynchronous API access.</param> /// <param name="configuration">The configuration object.</param> public FakeClassnameTags123Api(Org.OpenAPITools.Client.ISynchronousClient client,Org.OpenAPITools.Client.IAsynchronousClient asyncClient, Org.OpenAPITools.Client.IReadableConfiguration configuration) { if(client == null) throw new ArgumentNullException("client"); if(asyncClient == null) throw new ArgumentNullException("asyncClient"); if(configuration == null) throw new ArgumentNullException("configuration"); this.Client = client; this.AsynchronousClient = asyncClient; this.Configuration = configuration; this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// The client for accessing this underlying API asynchronously. /// </summary> public Org.OpenAPITools.Client.IAsynchronousClient AsynchronousClient { get; set; } /// <summary> /// The client for accessing this underlying API synchronously. /// </summary> public Org.OpenAPITools.Client.ISynchronousClient Client { get; set; } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.BasePath; } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Org.OpenAPITools.Client.IReadableConfiguration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// To test class name in snake case To test class name in snake case /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">client model</param> /// <returns>ModelClient</returns> public ModelClient TestClassname (ModelClient body) { Org.OpenAPITools.Client.ApiResponse<ModelClient> localVarResponse = TestClassnameWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// To test class name in snake case To test class name in snake case /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">client model</param> /// <returns>ApiResponse of ModelClient</returns> public Org.OpenAPITools.Client.ApiResponse< ModelClient > TestClassnameWithHttpInfo (ModelClient body) { // verify the required parameter 'body' is set if (body == null) throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'body' when calling FakeClassnameTags123Api->TestClassname"); Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); String[] _contentTypes = new String[] { "application/json" }; // to determine the Accept header String[] _accepts = new String[] { "application/json" }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); localVarRequestOptions.Data = body; // authentication (api_key_query) required if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) { localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); } // make the HTTP request var localVarResponse = this.Client.Patch< ModelClient >("/fake_classname_test", localVarRequestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); if (_exception != null) throw _exception; } return localVarResponse; } /// <summary> /// To test class name in snake case To test class name in snake case /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">client model</param> /// <returns>Task of ModelClient</returns> public async System.Threading.Tasks.Task<ModelClient> TestClassnameAsync (ModelClient body) { Org.OpenAPITools.Client.ApiResponse<ModelClient> localVarResponse = await TestClassnameAsyncWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// To test class name in snake case To test class name in snake case /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">client model</param> /// <returns>Task of ApiResponse (ModelClient)</returns> public async System.Threading.Tasks.Task<Org.OpenAPITools.Client.ApiResponse<ModelClient>> TestClassnameAsyncWithHttpInfo (ModelClient body) { // verify the required parameter 'body' is set if (body == null) throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'body' when calling FakeClassnameTags123Api->TestClassname"); Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); String[] _contentTypes = new String[] { "application/json" }; // to determine the Accept header String[] _accepts = new String[] { "application/json" }; foreach (var _contentType in _contentTypes) localVarRequestOptions.HeaderParameters.Add("Content-Type", _contentType); foreach (var _accept in _accepts) localVarRequestOptions.HeaderParameters.Add("Accept", _accept); localVarRequestOptions.Data = body; // authentication (api_key_query) required if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) { localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); } // make the HTTP request var localVarResponse = await this.AsynchronousClient.PatchAsync<ModelClient>("/fake_classname_test", localVarRequestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); if (_exception != null) throw _exception; } return localVarResponse; } } }
43.472561
207
0.640578
[ "Apache-2.0" ]
0x4a616e/openapi-generator
samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs
14,259
C#
using System; using System.Collections.Generic; namespace Claytondus.EasyPost.Models { public class Event { public string id { get; set; } public DateTime? created_at { get; set; } public DateTime? updated_at { get; set; } public Dictionary<string, object> result { get; set; } public string description { get; set; } public string mode { get; set; } public Dictionary<string, object> previous_attributes { get; set; } public List<string> pending_urls { get; set; } public List<string> completed_urls { get; set; } public string status { get; set; } } }
34.421053
75
0.622324
[ "MIT" ]
ragnarek81997/Claytondus.EasyPost
src/Claytondus.EasyPost/Models/Event.cs
656
C#
using System; namespace ViswaVSHW { class Program { static void Main(string[] args) { //I am viswaanand before change // The changes after the change sync the github //This line denoted after changed the changes and new branch name "Student" } } }
19.117647
87
0.575385
[ "MIT" ]
URviswaanand/ViswaVSprojects
ViswaVSHW/ViswaVSHW/Program.cs
327
C#
using System.Collections.Generic; namespace SimasoftCorp.DesafioStone.Dominio.Financeiro.Contratos.Repositorio { public interface IFinanceiroRepositorio { void CadastraCliente(Cliente clienteDominio); void CadastraCobrancaParaCliente(string cpf, Cobranca cobrancaDominio); Cliente ObterPorCpf(string cpf); List<Cliente> ListarCobrancasRegistradasPorCpfOuMesDeReferencia(string cpf, byte mesDeReferencia); List<Cliente> ListarTodos(); bool Integracao(); } }
34.6
106
0.751445
[ "MIT" ]
gabrielsimas/desafio-stone-01
src/SimasoftCorp.DesafioStone.Dominio/Financeiro/Contratos/Repositorio/IFinanceiroRepositorio.cs
521
C#
// Decompiled with JetBrains decompiler // Type: CodeEditor.OnOffButton // Assembly: CodeEditor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: 9A3DD43E-5EEA-4321-8BB2-B177FCA0FAE4 // Assembly location: C:\Program Files (x86)\CodeEditor\CodeEditor.exe using System.Drawing; using System.Windows.Forms; namespace CodeEditor { internal class OnOffButton { public Rectangle m_Position; public bool m_Pushed; public bool m_BeingPushed; private Ref<bool> m_Value; public void Initialize(Ref<bool> Value, int X, int Y) { this.m_Value = Value; this.m_Position = new Rectangle(X, Y, 44, 34); } public void print(PaintEventArgs e, Bitmap ButtonOff, Bitmap ButtonOn) { bool flag = this.m_Value.Value; Rectangle position = this.m_Position; position.Inflate(-1, -1); if (this.m_Pushed) { e.Graphics.DrawImage((Image) BitmapList.Grayer, this.m_Position); e.Graphics.DrawImage(flag ? (Image) ButtonOn : (Image) ButtonOff, position); } else e.Graphics.DrawImage(flag ? (Image) ButtonOn : (Image) ButtonOff, this.m_Position); } public bool OnMouseDown(MouseEventArgs e) { if (!this.m_Position.Contains(e.Location)) return false; this.m_Value.Value = !this.m_Value.Value; this.m_Pushed = true; this.m_BeingPushed = true; return true; } public bool OnMouseMove(MouseEventArgs e) { return this.m_Position.Contains(e.Location); } } }
27.8
91
0.669065
[ "Unlicense" ]
natefun/Marshall-Code-Editor
OnOffButton.cs
1,531
C#
using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Position Modification Sample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Position Modification Sample")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("35f19c43-c7cc-4f53-b8e0-61caaf9cd8e8")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] #if DEBUG [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations)] #endif
33.3
128
0.786787
[ "MIT" ]
spotware/ctrader-automate-samples
Robots/Position Modification Sample/Position Modification Sample/Properties/AssemblyInfo.cs
668
C#
using System; namespace Org.BouncyCastle.Crypto { /// <summary> /// Base interface for operators that serve as stream-based signature calculators. /// </summary> public interface ISignatureFactory { /// <summary>The algorithm details object for this calculator.</summary> Object AlgorithmDetails { get ; } /// <summary> /// Create a stream calculator for this signature calculator. The stream /// calculator is used for the actual operation of entering the data to be signed /// and producing the signature block. /// </summary> /// <returns>A calculator producing an IBlockResult with a signature in it.</returns> IStreamCalculator CreateCalculator(); } }
32.375
94
0.642214
[ "Apache-2.0", "MIT" ]
flobecker/trudi-koala
src/IVU.BouncyCastle.Crypto/src/crypto/ISignatureFactory.cs
777
C#
/* * Swagger Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; namespace IO.Swagger.Model { /// <summary> /// FormatTest /// </summary> [DataContract] public partial class FormatTest : IEquatable<FormatTest> { /// <summary> /// Initializes a new instance of the <see cref="FormatTest" /> class. /// </summary> [JsonConstructorAttribute] protected FormatTest() { } /// <summary> /// Initializes a new instance of the <see cref="FormatTest" /> class. /// </summary> /// <param name="integer">integer.</param> /// <param name="int32">int32.</param> /// <param name="int64">int64.</param> /// <param name="number">number (required).</param> /// <param name="_float">_float.</param> /// <param name="_double">_double.</param> /// <param name="_string">_string.</param> /// <param name="_byte">_byte (required).</param> /// <param name="binary">binary.</param> /// <param name="date">date (required).</param> /// <param name="dateTime">dateTime.</param> /// <param name="uuid">uuid.</param> /// <param name="password">password (required).</param> public FormatTest(int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), decimal? number = default(decimal?), float? _float = default(float?), double? _double = default(double?), string _string = default(string), byte[] _byte = default(byte[]), byte[] binary = default(byte[]), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), Guid? uuid = default(Guid?), string password = default(string)) { // to ensure "number" is required (not null) if (number == null) { throw new InvalidDataException("number is a required property for FormatTest and cannot be null"); } else { this.Number = number; } // to ensure "_byte" is required (not null) if (_byte == null) { throw new InvalidDataException("_byte is a required property for FormatTest and cannot be null"); } else { this.Byte = _byte; } // to ensure "date" is required (not null) if (date == null) { throw new InvalidDataException("date is a required property for FormatTest and cannot be null"); } else { this.Date = date; } // to ensure "password" is required (not null) if (password == null) { throw new InvalidDataException("password is a required property for FormatTest and cannot be null"); } else { this.Password = password; } this.Integer = integer; this.Int32 = int32; this.Int64 = int64; this.Float = _float; this.Double = _double; this.String = _string; this.Binary = binary; this.DateTime = dateTime; this.Uuid = uuid; } /// <summary> /// Gets or Sets Integer /// </summary> [DataMember(Name="integer", EmitDefaultValue=false)] public int? Integer { get; set; } /// <summary> /// Gets or Sets Int32 /// </summary> [DataMember(Name="int32", EmitDefaultValue=false)] public int? Int32 { get; set; } /// <summary> /// Gets or Sets Int64 /// </summary> [DataMember(Name="int64", EmitDefaultValue=false)] public long? Int64 { get; set; } /// <summary> /// Gets or Sets Number /// </summary> [DataMember(Name="number", EmitDefaultValue=false)] public decimal? Number { get; set; } /// <summary> /// Gets or Sets Float /// </summary> [DataMember(Name="float", EmitDefaultValue=false)] public float? Float { get; set; } /// <summary> /// Gets or Sets Double /// </summary> [DataMember(Name="double", EmitDefaultValue=false)] public double? Double { get; set; } /// <summary> /// Gets or Sets String /// </summary> [DataMember(Name="string", EmitDefaultValue=false)] public string String { get; set; } /// <summary> /// Gets or Sets Byte /// </summary> [DataMember(Name="byte", EmitDefaultValue=false)] public byte[] Byte { get; set; } /// <summary> /// Gets or Sets Binary /// </summary> [DataMember(Name="binary", EmitDefaultValue=false)] public byte[] Binary { get; set; } /// <summary> /// Gets or Sets Date /// </summary> [DataMember(Name="date", EmitDefaultValue=false)] [JsonConverter(typeof(SwaggerDateConverter))] public DateTime? Date { get; set; } /// <summary> /// Gets or Sets DateTime /// </summary> [DataMember(Name="dateTime", EmitDefaultValue=false)] public DateTime? DateTime { get; set; } /// <summary> /// Gets or Sets Uuid /// </summary> [DataMember(Name="uuid", EmitDefaultValue=false)] public Guid? Uuid { get; set; } /// <summary> /// Gets or Sets Password /// </summary> [DataMember(Name="password", EmitDefaultValue=false)] public string Password { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class FormatTest {\n"); sb.Append(" Integer: ").Append(Integer).Append("\n"); sb.Append(" Int32: ").Append(Int32).Append("\n"); sb.Append(" Int64: ").Append(Int64).Append("\n"); sb.Append(" Number: ").Append(Number).Append("\n"); sb.Append(" Float: ").Append(Float).Append("\n"); sb.Append(" Double: ").Append(Double).Append("\n"); sb.Append(" String: ").Append(String).Append("\n"); sb.Append(" Byte: ").Append(Byte).Append("\n"); sb.Append(" Binary: ").Append(Binary).Append("\n"); sb.Append(" Date: ").Append(Date).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" Password: ").Append(Password).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as FormatTest); } /// <summary> /// Returns true if FormatTest instances are equal /// </summary> /// <param name="input">Instance of FormatTest to be compared</param> /// <returns>Boolean</returns> public bool Equals(FormatTest input) { if (input == null) return false; return ( this.Integer == input.Integer || (this.Integer != null && this.Integer.Equals(input.Integer)) ) && ( this.Int32 == input.Int32 || (this.Int32 != null && this.Int32.Equals(input.Int32)) ) && ( this.Int64 == input.Int64 || (this.Int64 != null && this.Int64.Equals(input.Int64)) ) && ( this.Number == input.Number || (this.Number != null && this.Number.Equals(input.Number)) ) && ( this.Float == input.Float || (this.Float != null && this.Float.Equals(input.Float)) ) && ( this.Double == input.Double || (this.Double != null && this.Double.Equals(input.Double)) ) && ( this.String == input.String || (this.String != null && this.String.Equals(input.String)) ) && ( this.Byte == input.Byte || (this.Byte != null && this.Byte.Equals(input.Byte)) ) && ( this.Binary == input.Binary || (this.Binary != null && this.Binary.Equals(input.Binary)) ) && ( this.Date == input.Date || (this.Date != null && this.Date.Equals(input.Date)) ) && ( this.DateTime == input.DateTime || (this.DateTime != null && this.DateTime.Equals(input.DateTime)) ) && ( this.Uuid == input.Uuid || (this.Uuid != null && this.Uuid.Equals(input.Uuid)) ) && ( this.Password == input.Password || (this.Password != null && this.Password.Equals(input.Password)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Integer != null) hashCode = hashCode * 59 + this.Integer.GetHashCode(); if (this.Int32 != null) hashCode = hashCode * 59 + this.Int32.GetHashCode(); if (this.Int64 != null) hashCode = hashCode * 59 + this.Int64.GetHashCode(); if (this.Number != null) hashCode = hashCode * 59 + this.Number.GetHashCode(); if (this.Float != null) hashCode = hashCode * 59 + this.Float.GetHashCode(); if (this.Double != null) hashCode = hashCode * 59 + this.Double.GetHashCode(); if (this.String != null) hashCode = hashCode * 59 + this.String.GetHashCode(); if (this.Byte != null) hashCode = hashCode * 59 + this.Byte.GetHashCode(); if (this.Binary != null) hashCode = hashCode * 59 + this.Binary.GetHashCode(); if (this.Date != null) hashCode = hashCode * 59 + this.Date.GetHashCode(); if (this.DateTime != null) hashCode = hashCode * 59 + this.DateTime.GetHashCode(); if (this.Uuid != null) hashCode = hashCode * 59 + this.Uuid.GetHashCode(); if (this.Password != null) hashCode = hashCode * 59 + this.Password.GetHashCode(); return hashCode; } } } }
38.014451
461
0.478902
[ "Apache-2.0" ]
severin83/swagger-codegen
samples/client/petstore/csharp/SwaggerClientNet35/src/IO.Swagger/Model/FormatTest.cs
13,153
C#
//----------------------------------------------------------------------------- // FILE: PasswordListCommand.cs // CONTRIBUTOR: Jeff Lill // COPYRIGHT: Copyright (c) 2005-2021 by neonFORGE LLC. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft; using Newtonsoft.Json; using Neon.Common; using Neon.Cryptography; using Neon.Kube; namespace NeonCli { /// <summary> /// Implements the <b>password list</b> command. /// </summary> [Command] public class PasswordListCommand : CommandBase { private const string usage = @" Lists passwords. USAGE: neon password list|ls "; /// <inheritdoc/> public override string[] Words => new string[] { "password", "list" }; /// <inheritdoc/> public override string[] AltWords => new string[] { "password", "ls" }; /// <inheritdoc/> public override void Help() { Console.WriteLine(usage); } /// <inheritdoc/> public override async Task RunAsync(CommandLine commandLine) { if (commandLine.HasHelpOption) { Console.WriteLine(usage); Program.Exit(0); } foreach (var path in Directory.GetFiles(KubeHelper.PasswordsFolder).OrderBy(path => path.ToLowerInvariant())) { Console.WriteLine(Path.GetFileName(path)); } Program.Exit(0); await Task.CompletedTask; } } }
27.390244
121
0.615761
[ "Apache-2.0" ]
nforgeio/neonKUBE
Tools/neon-cli/Commands/Password/PasswordListCommand.cs
2,248
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Web; using Nop.Core; using Nop.Core.Domain.Blogs; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Customers; using Nop.Core.Domain.Forums; using Nop.Core.Domain.Messages; using Nop.Core.Domain.News; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Shipping; using Nop.Core.Domain.Stores; using Nop.Core.Domain.Tax; using Nop.Core.Html; using Nop.Core.Infrastructure; using Nop.Services.Catalog; using Nop.Services.Common; using Nop.Services.Customers; using Nop.Services.Directory; using Nop.Services.Events; using Nop.Services.Forums; using Nop.Services.Helpers; using Nop.Services.Localization; using Nop.Services.Media; using Nop.Services.Orders; using Nop.Services.Payments; using Nop.Services.Seo; using Nop.Services.Stores; namespace Nop.Services.Messages { public partial class MessageTokenProvider : IMessageTokenProvider { #region Fields private readonly ILanguageService _languageService; private readonly ILocalizationService _localizationService; private readonly IDateTimeHelper _dateTimeHelper; private readonly IPriceFormatter _priceFormatter; private readonly ICurrencyService _currencyService; private readonly IWorkContext _workContext; private readonly IDownloadService _downloadService; private readonly IOrderService _orderService; private readonly IPaymentService _paymentService; private readonly IProductAttributeParser _productAttributeParser; private readonly IAddressAttributeFormatter _addressAttributeFormatter; private readonly IStoreService _storeService; private readonly IStoreContext _storeContext; private readonly MessageTemplatesSettings _templatesSettings; private readonly CatalogSettings _catalogSettings; private readonly TaxSettings _taxSettings; private readonly IEventPublisher _eventPublisher; #endregion #region Ctor public MessageTokenProvider(ILanguageService languageService, ILocalizationService localizationService, IDateTimeHelper dateTimeHelper, IPriceFormatter priceFormatter, ICurrencyService currencyService, IWorkContext workContext, IDownloadService downloadService, IOrderService orderService, IPaymentService paymentService, IStoreService storeService, IStoreContext storeContext, IProductAttributeParser productAttributeParser, IAddressAttributeFormatter addressAttributeFormatter, MessageTemplatesSettings templatesSettings, CatalogSettings catalogSettings, TaxSettings taxSettings, IEventPublisher eventPublisher) { this._languageService = languageService; this._localizationService = localizationService; this._dateTimeHelper = dateTimeHelper; this._priceFormatter = priceFormatter; this._currencyService = currencyService; this._workContext = workContext; this._downloadService = downloadService; this._orderService = orderService; this._paymentService = paymentService; this._productAttributeParser = productAttributeParser; this._addressAttributeFormatter = addressAttributeFormatter; this._storeService = storeService; this._storeContext = storeContext; this._templatesSettings = templatesSettings; this._catalogSettings = catalogSettings; this._taxSettings = taxSettings; this._eventPublisher = eventPublisher; } #endregion #region Utilities /// <summary> /// Convert a collection to a HTML table /// </summary> /// <param name="order">Order</param> /// <param name="languageId">Language identifier</param> /// <param name="vendorId">Vendor identifier (used to limit products by vendor</param> /// <returns>HTML table of products</returns> protected virtual string ProductListToHtmlTable(Order order, int languageId, int vendorId) { var result = ""; var language = _languageService.GetLanguageById(languageId); var sb = new StringBuilder(); sb.AppendLine("<table border=\"0\" style=\"width:100%;\">"); #region Products sb.AppendLine(string.Format("<tr style=\"background-color:{0};text-align:center;\">", _templatesSettings.Color1)); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).Name", languageId))); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).Price", languageId))); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).Quantity", languageId))); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).Total", languageId))); sb.AppendLine("</tr>"); var table = order.OrderItems.ToList(); for (int i = 0; i <= table.Count - 1; i++) { var orderItem = table[i]; var product = orderItem.Product; if (product == null) continue; if (vendorId > 0 && product.VendorId != vendorId) continue; sb.AppendLine(string.Format("<tr style=\"background-color: {0};text-align: center;\">", _templatesSettings.Color2)); //product name string productName = product.GetLocalized(x => x.Name, languageId); sb.AppendLine("<td style=\"padding: 0.6em 0.4em;text-align: left;\">" + HttpUtility.HtmlEncode(productName)); //add download link if (_downloadService.IsDownloadAllowed(orderItem)) { //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs) string downloadUrl = string.Format("{0}download/getdownload/{1}", GetStoreUrl(order.StoreId), orderItem.OrderItemGuid); string downloadLink = string.Format("<a class=\"link\" href=\"{0}\">{1}</a>", downloadUrl, _localizationService.GetResource("Messages.Order.Product(s).Download", languageId)); sb.AppendLine("&nbsp;&nbsp;("); sb.AppendLine(downloadLink); sb.AppendLine(")"); } //attributes if (!String.IsNullOrEmpty(orderItem.AttributeDescription)) { sb.AppendLine("<br />"); sb.AppendLine(orderItem.AttributeDescription); } //rental info if (orderItem.Product.IsRental) { var rentalStartDate = orderItem.RentalStartDateUtc.HasValue ? orderItem.Product.FormatRentalDate(orderItem.RentalStartDateUtc.Value) : ""; var rentalEndDate = orderItem.RentalEndDateUtc.HasValue ? orderItem.Product.FormatRentalDate(orderItem.RentalEndDateUtc.Value) : ""; var rentalInfo = string.Format(_localizationService.GetResource("Order.Rental.FormattedDate"), rentalStartDate, rentalEndDate); sb.AppendLine("<br />"); sb.AppendLine(rentalInfo); } //sku if (_catalogSettings.ShowProductSku) { var sku = product.FormatSku(orderItem.AttributesXml, _productAttributeParser); if (!String.IsNullOrEmpty(sku)) { sb.AppendLine("<br />"); sb.AppendLine(string.Format(_localizationService.GetResource("Messages.Order.Product(s).SKU", languageId), HttpUtility.HtmlEncode(sku))); } } sb.AppendLine("</td>"); string unitPriceStr = string.Empty; if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { //including tax var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, order.CurrencyRate); unitPriceStr = _priceFormatter.FormatPrice(unitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true); } else { //excluding tax var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate); unitPriceStr = _priceFormatter.FormatPrice(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false); } sb.AppendLine(string.Format("<td style=\"padding: 0.6em 0.4em;text-align: right;\">{0}</td>", unitPriceStr)); sb.AppendLine(string.Format("<td style=\"padding: 0.6em 0.4em;text-align: center;\">{0}</td>", orderItem.Quantity)); string priceStr = string.Empty; if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { //including tax var priceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceInclTax, order.CurrencyRate); priceStr = _priceFormatter.FormatPrice(priceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true); } else { //excluding tax var priceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceExclTax, order.CurrencyRate); priceStr = _priceFormatter.FormatPrice(priceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false); } sb.AppendLine(string.Format("<td style=\"padding: 0.6em 0.4em;text-align: right;\">{0}</td>", priceStr)); sb.AppendLine("</tr>"); } #endregion if (vendorId == 0) { //we render checkout attributes and totals only for store owners (hide for vendors) #region Checkout Attributes if (!String.IsNullOrEmpty(order.CheckoutAttributeDescription)) { sb.AppendLine("<tr><td style=\"text-align:right;\" colspan=\"1\">&nbsp;</td><td colspan=\"3\" style=\"text-align:right\">"); sb.AppendLine(order.CheckoutAttributeDescription); sb.AppendLine("</td></tr>"); } #endregion #region Totals //subtotal string cusSubTotal = string.Empty; bool displaySubTotalDiscount = false; string cusSubTotalDiscount = string.Empty; if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal) { //including tax //subtotal var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate); cusSubTotal = _priceFormatter.FormatPrice(orderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true); //discount (applied to order subtotal) var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate); if (orderSubTotalDiscountInclTaxInCustomerCurrency > decimal.Zero) { cusSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true); displaySubTotalDiscount = true; } } else { //exсluding tax //subtotal var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate); cusSubTotal = _priceFormatter.FormatPrice(orderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false); //discount (applied to order subtotal) var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate); if (orderSubTotalDiscountExclTaxInCustomerCurrency > decimal.Zero) { cusSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false); displaySubTotalDiscount = true; } } //shipping, payment method fee string cusShipTotal = string.Empty; string cusPaymentMethodAdditionalFee = string.Empty; var taxRates = new SortedDictionary<decimal, decimal>(); string cusTaxTotal = string.Empty; string cusDiscount = string.Empty; string cusTotal = string.Empty; if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { //including tax //shipping var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate); cusShipTotal = _priceFormatter.FormatShippingPrice(orderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true); //payment method additional fee var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate); cusPaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true); } else { //excluding tax //shipping var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate); cusShipTotal = _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false); //payment method additional fee var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate); cusPaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false); } //shipping bool displayShipping = order.ShippingStatus != ShippingStatus.ShippingNotRequired; //payment method fee bool displayPaymentMethodFee = order.PaymentMethodAdditionalFeeExclTax > decimal.Zero; //tax bool displayTax = true; bool displayTaxRates = true; if (_taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { displayTax = false; displayTaxRates = false; } else { if (order.OrderTax == 0 && _taxSettings.HideZeroTax) { displayTax = false; displayTaxRates = false; } else { taxRates = new SortedDictionary<decimal, decimal>(); foreach (var tr in order.TaxRatesDictionary) taxRates.Add(tr.Key, _currencyService.ConvertCurrency(tr.Value, order.CurrencyRate)); displayTaxRates = _taxSettings.DisplayTaxRates && taxRates.Count > 0; displayTax = !displayTaxRates; var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate); string taxStr = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false, language); cusTaxTotal = taxStr; } } //discount bool displayDiscount = false; if (order.OrderDiscount > decimal.Zero) { var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate); cusDiscount = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false, language); displayDiscount = true; } //total var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate); cusTotal = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, language); //subtotal sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td>&nbsp;</td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, _localizationService.GetResource("Messages.Order.SubTotal", languageId), cusSubTotal)); //discount (applied to order subtotal) if (displaySubTotalDiscount) { sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td>&nbsp;</td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, _localizationService.GetResource("Messages.Order.SubTotalDiscount", languageId), cusSubTotalDiscount)); } //shipping if (displayShipping) { sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td>&nbsp;</td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, _localizationService.GetResource("Messages.Order.Shipping", languageId), cusShipTotal)); } //payment method fee if (displayPaymentMethodFee) { string paymentMethodFeeTitle = _localizationService.GetResource("Messages.Order.PaymentMethodAdditionalFee", languageId); sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td>&nbsp;</td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, paymentMethodFeeTitle, cusPaymentMethodAdditionalFee)); } //tax if (displayTax) { sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td>&nbsp;</td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, _localizationService.GetResource("Messages.Order.Tax", languageId), cusTaxTotal)); } if (displayTaxRates) { foreach (var item in taxRates) { string taxRate = String.Format(_localizationService.GetResource("Messages.Order.TaxRateLine"), _priceFormatter.FormatTaxRate(item.Key)); string taxValue = _priceFormatter.FormatPrice(item.Value, true, order.CustomerCurrencyCode, false, language); sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td>&nbsp;</td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, taxRate, taxValue)); } } //discount if (displayDiscount) { sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td>&nbsp;</td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, _localizationService.GetResource("Messages.Order.TotalDiscount", languageId), cusDiscount)); } //gift cards var gcuhC = order.GiftCardUsageHistory; foreach (var gcuh in gcuhC) { string giftCardText = String.Format(_localizationService.GetResource("Messages.Order.GiftCardInfo", languageId), HttpUtility.HtmlEncode(gcuh.GiftCard.GiftCardCouponCode)); string giftCardAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, language); sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td>&nbsp;</td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, giftCardText, giftCardAmount)); } //reward points if (order.RedeemedRewardPointsEntry != null) { string rpTitle = string.Format(_localizationService.GetResource("Messages.Order.RewardPoints", languageId), -order.RedeemedRewardPointsEntry.Points); string rpAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, language); sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td>&nbsp;</td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, rpTitle, rpAmount)); } //total sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td>&nbsp;</td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, _localizationService.GetResource("Messages.Order.OrderTotal", languageId), cusTotal)); #endregion } sb.AppendLine("</table>"); result = sb.ToString(); return result; } /// <summary> /// Convert a collection to a HTML table /// </summary> /// <param name="shipment">Shipment</param> /// <param name="languageId">Language identifier</param> /// <returns>HTML table of products</returns> protected virtual string ProductListToHtmlTable(Shipment shipment, int languageId) { var result = ""; var sb = new StringBuilder(); sb.AppendLine("<table border=\"0\" style=\"width:100%;\">"); #region Products sb.AppendLine(string.Format("<tr style=\"background-color:{0};text-align:center;\">", _templatesSettings.Color1)); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).Name", languageId))); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).Quantity", languageId))); sb.AppendLine("</tr>"); var table = shipment.ShipmentItems.ToList(); for (int i = 0; i <= table.Count - 1; i++) { var si = table[i]; var orderItem = _orderService.GetOrderItemById(si.OrderItemId); if (orderItem == null) continue; var product = orderItem.Product; if (product == null) continue; sb.AppendLine(string.Format("<tr style=\"background-color: {0};text-align: center;\">", _templatesSettings.Color2)); //product name string productName = product.GetLocalized(x => x.Name, languageId); sb.AppendLine("<td style=\"padding: 0.6em 0.4em;text-align: left;\">" + HttpUtility.HtmlEncode(productName)); //attributes if (!String.IsNullOrEmpty(orderItem.AttributeDescription)) { sb.AppendLine("<br />"); sb.AppendLine(orderItem.AttributeDescription); } //rental info if (orderItem.Product.IsRental) { var rentalStartDate = orderItem.RentalStartDateUtc.HasValue ? orderItem.Product.FormatRentalDate(orderItem.RentalStartDateUtc.Value) : ""; var rentalEndDate = orderItem.RentalEndDateUtc.HasValue ? orderItem.Product.FormatRentalDate(orderItem.RentalEndDateUtc.Value) : ""; var rentalInfo = string.Format(_localizationService.GetResource("Order.Rental.FormattedDate"), rentalStartDate, rentalEndDate); sb.AppendLine("<br />"); sb.AppendLine(rentalInfo); } //sku if (_catalogSettings.ShowProductSku) { var sku = product.FormatSku(orderItem.AttributesXml, _productAttributeParser); if (!String.IsNullOrEmpty(sku)) { sb.AppendLine("<br />"); sb.AppendLine(string.Format(_localizationService.GetResource("Messages.Order.Product(s).SKU", languageId), HttpUtility.HtmlEncode(sku))); } } sb.AppendLine("</td>"); sb.AppendLine(string.Format("<td style=\"padding: 0.6em 0.4em;text-align: center;\">{0}</td>", si.Quantity)); sb.AppendLine("</tr>"); } #endregion sb.AppendLine("</table>"); result = sb.ToString(); return result; } /// <summary> /// Get store URL /// </summary> /// <param name="storeId">Store identifier; Pass 0 to load URL of the current store</param> /// <param name="useSsl">Use SSL</param> /// <returns></returns> protected virtual string GetStoreUrl(int storeId = 0, bool useSsl = false) { var store = _storeService.GetStoreById(storeId) ?? _storeContext.CurrentStore; if (store == null) throw new Exception("No store could be loaded"); return useSsl ? store.SecureUrl : store.Url; } #endregion #region Methods public virtual void AddStoreTokens(IList<Token> tokens, Store store, EmailAccount emailAccount) { if (emailAccount == null) throw new ArgumentNullException("emailAccount"); tokens.Add(new Token("Store.Name", store.GetLocalized(x => x.Name))); tokens.Add(new Token("Store.URL", store.Url, true)); tokens.Add(new Token("Store.Email", emailAccount.Email)); tokens.Add(new Token("Store.CompanyName", store.CompanyName)); tokens.Add(new Token("Store.CompanyAddress", store.CompanyAddress)); tokens.Add(new Token("Store.CompanyPhoneNumber", store.CompanyPhoneNumber)); tokens.Add(new Token("Store.CompanyVat", store.CompanyVat)); //event notification _eventPublisher.EntityTokensAdded(store, tokens); } public virtual void AddOrderTokens(IList<Token> tokens, Order order, int languageId, int vendorId = 0) { tokens.Add(new Token("Order.OrderNumber", order.Id.ToString())); tokens.Add(new Token("Order.CustomerFullName", string.Format("{0} {1}", order.BillingAddress.FirstName, order.BillingAddress.LastName))); tokens.Add(new Token("Order.CustomerEmail", order.BillingAddress.Email)); tokens.Add(new Token("Order.BillingFirstName", order.BillingAddress.FirstName)); tokens.Add(new Token("Order.BillingLastName", order.BillingAddress.LastName)); tokens.Add(new Token("Order.BillingPhoneNumber", order.BillingAddress.PhoneNumber)); tokens.Add(new Token("Order.BillingEmail", order.BillingAddress.Email)); tokens.Add(new Token("Order.BillingFaxNumber", order.BillingAddress.FaxNumber)); tokens.Add(new Token("Order.BillingCompany", order.BillingAddress.Company)); tokens.Add(new Token("Order.BillingAddress1", order.BillingAddress.Address1)); tokens.Add(new Token("Order.BillingAddress2", order.BillingAddress.Address2)); tokens.Add(new Token("Order.BillingCity", order.BillingAddress.City)); tokens.Add(new Token("Order.BillingStateProvince", order.BillingAddress.StateProvince != null ? order.BillingAddress.StateProvince.GetLocalized(x => x.Name) : "")); tokens.Add(new Token("Order.BillingZipPostalCode", order.BillingAddress.ZipPostalCode)); tokens.Add(new Token("Order.BillingCountry", order.BillingAddress.Country != null ? order.BillingAddress.Country.GetLocalized(x => x.Name) : "")); tokens.Add(new Token("Order.BillingCustomAttributes", _addressAttributeFormatter.FormatAttributes(order.BillingAddress.CustomAttributes), true)); tokens.Add(new Token("Order.ShippingMethod", order.ShippingMethod)); tokens.Add(new Token("Order.ShippingFirstName", order.ShippingAddress != null ? order.ShippingAddress.FirstName : "")); tokens.Add(new Token("Order.ShippingLastName", order.ShippingAddress != null ? order.ShippingAddress.LastName : "")); tokens.Add(new Token("Order.ShippingPhoneNumber", order.ShippingAddress != null ? order.ShippingAddress.PhoneNumber : "")); tokens.Add(new Token("Order.ShippingEmail", order.ShippingAddress != null ? order.ShippingAddress.Email : "")); tokens.Add(new Token("Order.ShippingFaxNumber", order.ShippingAddress != null ? order.ShippingAddress.FaxNumber : "")); tokens.Add(new Token("Order.ShippingCompany", order.ShippingAddress != null ? order.ShippingAddress.Company : "")); tokens.Add(new Token("Order.ShippingAddress1", order.ShippingAddress != null ? order.ShippingAddress.Address1 : "")); tokens.Add(new Token("Order.ShippingAddress2", order.ShippingAddress != null ? order.ShippingAddress.Address2 : "")); tokens.Add(new Token("Order.ShippingCity", order.ShippingAddress != null ? order.ShippingAddress.City : "")); tokens.Add(new Token("Order.ShippingStateProvince", order.ShippingAddress != null && order.ShippingAddress.StateProvince != null ? order.ShippingAddress.StateProvince.GetLocalized(x => x.Name) : "")); tokens.Add(new Token("Order.ShippingZipPostalCode", order.ShippingAddress != null ? order.ShippingAddress.ZipPostalCode : "")); tokens.Add(new Token("Order.ShippingCountry", order.ShippingAddress != null && order.ShippingAddress.Country != null ? order.ShippingAddress.Country.GetLocalized(x => x.Name) : "")); tokens.Add(new Token("Order.ShippingCustomAttributes", _addressAttributeFormatter.FormatAttributes(order.ShippingAddress != null ? order.ShippingAddress.CustomAttributes : ""), true)); var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName); var paymentMethodName = paymentMethod != null ? paymentMethod.GetLocalizedFriendlyName(_localizationService, _workContext.WorkingLanguage.Id) : order.PaymentMethodSystemName; tokens.Add(new Token("Order.PaymentMethod", paymentMethodName)); tokens.Add(new Token("Order.VatNumber", order.VatNumber)); var sbCustomValues = new StringBuilder(); var customValues = order.DeserializeCustomValues(); if (customValues != null) { foreach (var item in customValues) { sbCustomValues.AppendFormat("{0}: {1}", HttpUtility.HtmlEncode(item.Key), HttpUtility.HtmlEncode(item.Value != null ? item.Value.ToString() : "")); sbCustomValues.Append("<br />"); } } tokens.Add(new Token("Order.CustomValues", sbCustomValues.ToString(), true)); tokens.Add(new Token("Order.Product(s)", ProductListToHtmlTable(order, languageId, vendorId), true)); var language = _languageService.GetLanguageById(languageId); if (language != null && !String.IsNullOrEmpty(language.LanguageCulture)) { DateTime createdOn = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, TimeZoneInfo.Utc, _dateTimeHelper.GetCustomerTimeZone(order.Customer)); tokens.Add(new Token("Order.CreatedOn", createdOn.ToString("D", new CultureInfo(language.LanguageCulture)))); } else { tokens.Add(new Token("Order.CreatedOn", order.CreatedOnUtc.ToString("D"))); } //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs) tokens.Add(new Token("Order.OrderURLForCustomer", string.Format("{0}orderdetails/{1}", GetStoreUrl(order.StoreId), order.Id), true)); //event notification _eventPublisher.EntityTokensAdded(order, tokens); } public virtual void AddShipmentTokens(IList<Token> tokens, Shipment shipment, int languageId) { tokens.Add(new Token("Shipment.ShipmentNumber", shipment.Id.ToString())); tokens.Add(new Token("Shipment.TrackingNumber", shipment.TrackingNumber)); tokens.Add(new Token("Shipment.Product(s)", ProductListToHtmlTable(shipment, languageId), true)); tokens.Add(new Token("Shipment.URLForCustomer", string.Format("{0}orderdetails/shipment/{1}", GetStoreUrl(shipment.Order.StoreId), shipment.Id), true)); //event notification _eventPublisher.EntityTokensAdded(shipment, tokens); } public virtual void AddOrderNoteTokens(IList<Token> tokens, OrderNote orderNote) { tokens.Add(new Token("Order.NewNoteText", orderNote.FormatOrderNoteText(), true)); //event notification _eventPublisher.EntityTokensAdded(orderNote, tokens); } public virtual void AddRecurringPaymentTokens(IList<Token> tokens, RecurringPayment recurringPayment) { tokens.Add(new Token("RecurringPayment.ID", recurringPayment.Id.ToString())); //event notification _eventPublisher.EntityTokensAdded(recurringPayment, tokens); } public virtual void AddReturnRequestTokens(IList<Token> tokens, ReturnRequest returnRequest, OrderItem orderItem) { tokens.Add(new Token("ReturnRequest.ID", returnRequest.Id.ToString())); tokens.Add(new Token("ReturnRequest.OrderId", orderItem.OrderId.ToString())); tokens.Add(new Token("ReturnRequest.Product.Quantity", returnRequest.Quantity.ToString())); tokens.Add(new Token("ReturnRequest.Product.Name", orderItem.Product.Name)); tokens.Add(new Token("ReturnRequest.Reason", returnRequest.ReasonForReturn)); tokens.Add(new Token("ReturnRequest.RequestedAction", returnRequest.RequestedAction)); tokens.Add(new Token("ReturnRequest.CustomerComment", HtmlHelper.FormatText(returnRequest.CustomerComments, false, true, false, false, false, false), true)); tokens.Add(new Token("ReturnRequest.StaffNotes", HtmlHelper.FormatText(returnRequest.StaffNotes, false, true, false, false, false, false), true)); tokens.Add(new Token("ReturnRequest.Status", returnRequest.ReturnRequestStatus.GetLocalizedEnum(_localizationService, _workContext))); //event notification _eventPublisher.EntityTokensAdded(returnRequest, tokens); } public virtual void AddGiftCardTokens(IList<Token> tokens, GiftCard giftCard) { tokens.Add(new Token("GiftCard.SenderName", giftCard.SenderName)); tokens.Add(new Token("GiftCard.SenderEmail",giftCard.SenderEmail)); tokens.Add(new Token("GiftCard.RecipientName", giftCard.RecipientName)); tokens.Add(new Token("GiftCard.RecipientEmail", giftCard.RecipientEmail)); tokens.Add(new Token("GiftCard.Amount", _priceFormatter.FormatPrice(giftCard.Amount, true, false))); tokens.Add(new Token("GiftCard.CouponCode", giftCard.GiftCardCouponCode)); var giftCardMesage = !String.IsNullOrWhiteSpace(giftCard.Message) ? HtmlHelper.FormatText(giftCard.Message, false, true, false, false, false, false) : ""; tokens.Add(new Token("GiftCard.Message", giftCardMesage, true)); //event notification _eventPublisher.EntityTokensAdded(giftCard, tokens); } public virtual void AddCustomerTokens(IList<Token> tokens, Customer customer) { tokens.Add(new Token("Customer.Email", customer.Email)); tokens.Add(new Token("Customer.Username", customer.Username)); tokens.Add(new Token("Customer.FullName", customer.GetFullName())); tokens.Add(new Token("Customer.FirstName", customer.GetAttribute<string>(SystemCustomerAttributeNames.FirstName))); tokens.Add(new Token("Customer.LastName", customer.GetAttribute<string>(SystemCustomerAttributeNames.LastName))); tokens.Add(new Token("Customer.VatNumber", customer.GetAttribute<string>(SystemCustomerAttributeNames.VatNumber))); tokens.Add(new Token("Customer.VatNumberStatus", ((VatNumberStatus)customer.GetAttribute<int>(SystemCustomerAttributeNames.VatNumberStatusId)).ToString())); //note: we do not use SEO friendly URLS because we can get errors caused by having .(dot) in the URL (from the email address) //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs) string passwordRecoveryUrl = string.Format("{0}passwordrecovery/confirm?token={1}&email={2}", GetStoreUrl(), customer.GetAttribute<string>(SystemCustomerAttributeNames.PasswordRecoveryToken), HttpUtility.UrlEncode(customer.Email)); string accountActivationUrl = string.Format("{0}customer/activation?token={1}&email={2}", GetStoreUrl(), customer.GetAttribute<string>(SystemCustomerAttributeNames.AccountActivationToken), HttpUtility.UrlEncode(customer.Email)); var wishlistUrl = string.Format("{0}wishlist/{1}", GetStoreUrl(), customer.CustomerGuid); tokens.Add(new Token("Customer.PasswordRecoveryURL", passwordRecoveryUrl, true)); tokens.Add(new Token("Customer.AccountActivationURL", accountActivationUrl, true)); tokens.Add(new Token("Wishlist.URLForCustomer", wishlistUrl, true)); //event notification _eventPublisher.EntityTokensAdded(customer, tokens); } public virtual void AddNewsLetterSubscriptionTokens(IList<Token> tokens, NewsLetterSubscription subscription) { tokens.Add(new Token("NewsLetterSubscription.Email", subscription.Email)); const string urlFormat = "{0}newsletter/subscriptionactivation/{1}/{2}"; var activationUrl = String.Format(urlFormat, GetStoreUrl(), subscription.NewsLetterSubscriptionGuid, "true"); tokens.Add(new Token("NewsLetterSubscription.ActivationUrl", activationUrl, true)); var deActivationUrl = String.Format(urlFormat, GetStoreUrl(), subscription.NewsLetterSubscriptionGuid, "false"); tokens.Add(new Token("NewsLetterSubscription.DeactivationUrl", deActivationUrl, true)); //event notification _eventPublisher.EntityTokensAdded(subscription, tokens); } public virtual void AddProductReviewTokens(IList<Token> tokens, ProductReview productReview) { tokens.Add(new Token("ProductReview.ProductName", productReview.Product.Name)); //event notification _eventPublisher.EntityTokensAdded(productReview, tokens); } public virtual void AddBlogCommentTokens(IList<Token> tokens, BlogComment blogComment) { tokens.Add(new Token("BlogComment.BlogPostTitle", blogComment.BlogPost.Title)); //event notification _eventPublisher.EntityTokensAdded(blogComment, tokens); } public virtual void AddNewsCommentTokens(IList<Token> tokens, NewsComment newsComment) { tokens.Add(new Token("NewsComment.NewsTitle", newsComment.NewsItem.Title)); //event notification _eventPublisher.EntityTokensAdded(newsComment, tokens); } public virtual void AddProductTokens(IList<Token> tokens, Product product, int languageId) { tokens.Add(new Token("Product.ID", product.Id.ToString())); tokens.Add(new Token("Product.Name", product.GetLocalized(x => x.Name, languageId))); tokens.Add(new Token("Product.ShortDescription", product.GetLocalized(x => x.ShortDescription, languageId), true)); tokens.Add(new Token("Product.SKU", product.Sku)); tokens.Add(new Token("Product.StockQuantity", product.GetTotalStockQuantity().ToString())); //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs) var productUrl = string.Format("{0}{1}", GetStoreUrl(), product.GetSeName()); tokens.Add(new Token("Product.ProductURLForCustomer", productUrl, true)); //event notification _eventPublisher.EntityTokensAdded(product, tokens); } public virtual void AddAttributeCombinationTokens(IList<Token> tokens, ProductAttributeCombination combination, int languageId) { //attributes //we cannot inject IProductAttributeFormatter into constructor because it'll cause circular references. //that's why we resolve it here this way var productAttributeFormatter = EngineContext.Current.Resolve<IProductAttributeFormatter>(); string attributes = productAttributeFormatter.FormatAttributes(combination.Product, combination.AttributesXml, _workContext.CurrentCustomer, renderPrices: false); tokens.Add(new Token("AttributeCombination.Formatted", attributes, true)); tokens.Add(new Token("AttributeCombination.SKU", combination.Product.FormatSku(combination.AttributesXml, _productAttributeParser))); tokens.Add(new Token("AttributeCombination.StockQuantity", combination.StockQuantity.ToString())); //event notification _eventPublisher.EntityTokensAdded(combination, tokens); } public virtual void AddForumTopicTokens(IList<Token> tokens, ForumTopic forumTopic, int? friendlyForumTopicPageIndex = null, int? appendedPostIdentifierAnchor = null) { //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs) string topicUrl; if (friendlyForumTopicPageIndex.HasValue && friendlyForumTopicPageIndex.Value > 1) topicUrl = string.Format("{0}boards/topic/{1}/{2}/page/{3}", GetStoreUrl(), forumTopic.Id, forumTopic.GetSeName(), friendlyForumTopicPageIndex.Value); else topicUrl = string.Format("{0}boards/topic/{1}/{2}", GetStoreUrl(), forumTopic.Id, forumTopic.GetSeName()); if (appendedPostIdentifierAnchor.HasValue && appendedPostIdentifierAnchor.Value > 0) topicUrl = string.Format("{0}#{1}", topicUrl, appendedPostIdentifierAnchor.Value); tokens.Add(new Token("Forums.TopicURL", topicUrl, true)); tokens.Add(new Token("Forums.TopicName", forumTopic.Subject)); //event notification _eventPublisher.EntityTokensAdded(forumTopic, tokens); } public virtual void AddForumPostTokens(IList<Token> tokens, ForumPost forumPost) { tokens.Add(new Token("Forums.PostAuthor", forumPost.Customer.FormatUserName())); tokens.Add(new Token("Forums.PostBody", forumPost.FormatPostText(), true)); //event notification _eventPublisher.EntityTokensAdded(forumPost, tokens); } public virtual void AddForumTokens(IList<Token> tokens, Forum forum) { //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs) var forumUrl = string.Format("{0}boards/forum/{1}/{2}", GetStoreUrl(), forum.Id, forum.GetSeName()); tokens.Add(new Token("Forums.ForumURL", forumUrl, true)); tokens.Add(new Token("Forums.ForumName", forum.Name)); //event notification _eventPublisher.EntityTokensAdded(forum, tokens); } public virtual void AddPrivateMessageTokens(IList<Token> tokens, PrivateMessage privateMessage) { tokens.Add(new Token("PrivateMessage.Subject", privateMessage.Subject)); tokens.Add(new Token("PrivateMessage.Text", privateMessage.FormatPrivateMessageText(), true)); //event notification _eventPublisher.EntityTokensAdded(privateMessage, tokens); } public virtual void AddBackInStockTokens(IList<Token> tokens, BackInStockSubscription subscription) { tokens.Add(new Token("BackInStockSubscription.ProductName", subscription.Product.Name)); //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs) var productUrl = string.Format("{0}{1}", GetStoreUrl(subscription.StoreId), subscription.Product.GetSeName()); tokens.Add(new Token("BackInStockSubscription.ProductUrl", productUrl, true)); //event notification _eventPublisher.EntityTokensAdded(subscription, tokens); } /// <summary> /// Gets list of allowed (supported) message tokens for campaigns /// </summary> /// <returns>List of allowed (supported) message tokens for campaigns</returns> public virtual string[] GetListOfCampaignAllowedTokens() { var allowedTokens = new List<string> { "%Store.Name%", "%Store.URL%", "%Store.Email%", "%Store.CompanyName%", "%Store.CompanyAddress%", "%Store.CompanyPhoneNumber%", "%Store.CompanyVat%", "%NewsLetterSubscription.Email%", "%NewsLetterSubscription.ActivationUrl%", "%NewsLetterSubscription.DeactivationUrl%" }; return allowedTokens.ToArray(); } public virtual string[] GetListOfAllowedTokens() { var allowedTokens = new List<string> { "%Store.Name%", "%Store.URL%", "%Store.Email%", "%Store.CompanyName%", "%Store.CompanyAddress%", "%Store.CompanyPhoneNumber%", "%Store.CompanyVat%", "%Order.OrderNumber%", "%Order.CustomerFullName%", "%Order.CustomerEmail%", "%Order.BillingFirstName%", "%Order.BillingLastName%", "%Order.BillingPhoneNumber%", "%Order.BillingEmail%", "%Order.BillingFaxNumber%", "%Order.BillingCompany%", "%Order.BillingAddress1%", "%Order.BillingAddress2%", "%Order.BillingCity%", "%Order.BillingStateProvince%", "%Order.BillingZipPostalCode%", "%Order.BillingCountry%", "%Order.BillingCustomAttributes%", "%Order.ShippingMethod%", "%Order.ShippingFirstName%", "%Order.ShippingLastName%", "%Order.ShippingPhoneNumber%", "%Order.ShippingEmail%", "%Order.ShippingFaxNumber%", "%Order.ShippingCompany%", "%Order.ShippingAddress1%", "%Order.ShippingAddress2%", "%Order.ShippingCity%", "%Order.ShippingStateProvince%", "%Order.ShippingZipPostalCode%", "%Order.ShippingCountry%", "%Order.ShippingCustomAttributes%", "%Order.PaymentMethod%", "%Order.VatNumber%", "%Order.CustomValues%", "%Order.Product(s)%", "%Order.CreatedOn%", "%Order.OrderURLForCustomer%", "%Order.NewNoteText%", "%RecurringPayment.ID%", "%Shipment.ShipmentNumber%", "%Shipment.TrackingNumber%", "%Shipment.Product(s)%", "%Shipment.URLForCustomer%", "%ReturnRequest.ID%", "%ReturnRequest.OrderId%", "%ReturnRequest.Product.Quantity%", "%ReturnRequest.Product.Name%", "%ReturnRequest.Reason%", "%ReturnRequest.RequestedAction%", "%ReturnRequest.CustomerComment%", "%ReturnRequest.StaffNotes%", "%ReturnRequest.Status%", "%GiftCard.SenderName%", "%GiftCard.SenderEmail%", "%GiftCard.RecipientName%", "%GiftCard.RecipientEmail%", "%GiftCard.Amount%", "%GiftCard.CouponCode%", "%GiftCard.Message%", "%Customer.Email%", "%Customer.Username%", "%Customer.FullName%", "%Customer.FirstName%", "%Customer.LastName%", "%Customer.VatNumber%", "%Customer.VatNumberStatus%", "%Customer.PasswordRecoveryURL%", "%Customer.AccountActivationURL%", "%Wishlist.URLForCustomer%", "%NewsLetterSubscription.Email%", "%NewsLetterSubscription.ActivationUrl%", "%NewsLetterSubscription.DeactivationUrl%", "%ProductReview.ProductName%", "%BlogComment.BlogPostTitle%", "%NewsComment.NewsTitle%", "%Product.ID%", "%Product.Name%", "%Product.ShortDescription%", "%Product.ProductURLForCustomer%", "%Product.SKU%", "%Product.StockQuantity%", "%Forums.TopicURL%", "%Forums.TopicName%", "%Forums.PostAuthor%", "%Forums.PostBody%", "%Forums.ForumURL%", "%Forums.ForumName%", "%AttributeCombination.Formatted%", "%AttributeCombination.SKU%", "%AttributeCombination.StockQuantity%", "%PrivateMessage.Subject%", "%PrivateMessage.Text%", "%BackInStockSubscription.ProductName%", "%BackInStockSubscription.ProductUrl%", }; return allowedTokens.ToArray(); } #endregion } }
55.41219
415
0.618785
[ "Apache-2.0" ]
atiq-shumon/DotNetProjects
Vialinker Source/BaseVialinkerCommerceApps/Libraries/Nop.Services/Messages/MessageTokenProvider.cs
53,642
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNet.Mvc; namespace FiltersWebSite { public class GlobalResultFilter : IResultFilter { public void OnResultExecuted(ResultExecutedContext context) { if (context.ActionDescriptor.DisplayName == "FiltersWebSite.ProductsController.GetPrice") { context.HttpContext.Response.Headers.Append("filters", "Global Result Filter - OnResultExecuted"); } } public void OnResultExecuting(ResultExecutingContext context) { if (context.ActionDescriptor.DisplayName == "FiltersWebSite.ResultFilterController.GetHelloWorld") { context.Result = Helpers.GetContentResult(context.Result, "GlobalResultFilter.OnResultExecuting"); } if (context.ActionDescriptor.DisplayName == "FiltersWebSite.ProductsController.GetPrice") { context.HttpContext.Response.Headers.Append("filters", "Global Result Filter - OnResultExecuted"); } } } }
38.515152
114
0.646735
[ "Apache-2.0" ]
ardalis/Mvc
test/WebSites/FiltersWebSite/Filters/GlobalResultFilter.cs
1,273
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics.Alt; using Microsoft.Extensions.Logging; namespace Microsoft.Azure.WebJobs.Script.Tests { [DebuggerDisplay("{DebuggerDisplay,nq}")] public class TestLogger : ILogger { private readonly object _syncLock = new object(); private IList<LogMessage> _logMessages = new List<LogMessage>(); public TestLogger(string category) { Category = category; } public string Category { get; private set; } private string DebuggerDisplay => $"Category: {Category}, Count: {_logMessages.Count}"; public IDisposable BeginScope<TState>(TState state) { return DictionaryLoggerScope.Push(state); } public bool IsEnabled(LogLevel logLevel) { return true; } public IList<LogMessage> GetLogMessages() { lock (_syncLock) { return _logMessages.ToList(); } } public void ClearLogMessages() { lock (_syncLock) { _logMessages.Clear(); } } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { LogMessage logMessage = new LogMessage { Level = logLevel, EventId = eventId, State = state as IEnumerable<KeyValuePair<string, object>>, Scope = DictionaryLoggerScope.GetMergedStateDictionary(), Exception = exception, FormattedMessage = formatter(state, exception), Category = Category, Timestamp = DateTime.UtcNow }; lock (_syncLock) { _logMessages.Add(logMessage); } } } public class LogMessage { public LogLevel Level { get; set; } public EventId EventId { get; set; } public IEnumerable<KeyValuePair<string, object>> State { get; set; } public IDictionary<string, object> Scope { get; set; } public Exception Exception { get; set; } public string FormattedMessage { get; set; } public string Category { get; set; } public DateTime Timestamp { get; set; } public override string ToString() { return $"[{Timestamp.ToString("HH:mm:ss.fff")}] [{Category}] {FormattedMessage}"; } } }
28.693878
145
0.581792
[ "MIT" ]
t-l-k/functions-test-helper
WebJobs.Script.Tests.Shared/TestLogger.cs
2,814
C#
namespace Edi.Core.Interfaces.DocumentTypes { public interface IFileFilterEntry { string FileFilter { get; } FileOpenDelegate FileOpenMethod { get; } } }
18
44
0.753086
[ "MIT" ]
Dirkster99/Edi
Edi/Edi.Core/Interfaces/DocumentTypes/IFileFilterEntry.cs
164
C#
using System; namespace Toy_Shop { class Program { static void Main(string[] args) { double tripPrice = double.Parse(Console.ReadLine()); int puzzles = int.Parse(Console.ReadLine()); int puppets = int.Parse(Console.ReadLine()); int tedybears = int.Parse(Console.ReadLine()); int minions = int.Parse(Console.ReadLine()); int trucks = int.Parse(Console.ReadLine()); double puzzlePice = (2.60* puzzles); double puppetPrice = (3.00* puppets); double tedyPrice = (4.10* tedybears); double minionPrice = (8.20* minions); double truckPrice = (2.00 * trucks); double totalToysPrice = (puzzlePice + puppetPrice + tedyPrice + minionPrice + truckPrice); // double profit = 0; double discount = 0.25 * totalToysPrice; int toys = (puzzles + puppets + tedybears + minions + trucks); if (toys >= 50) { double rent = (totalToysPrice - discount) * 0.10; double profit = totalToysPrice - rent - discount; double diff = profit - tripPrice; if (profit >= tripPrice) { Console.WriteLine($"Yes! {diff:f2} lv left."); } else { double diff1 = tripPrice - profit; Console.WriteLine($"Not enough money! {diff1:f2} lv needed."); } } else { { double rent = totalToysPrice * 0.10; double profit = totalToysPrice - rent; double diff = profit - tripPrice; if (profit >= tripPrice) { Console.WriteLine($"Yes! {diff:f2} lv left."); } else { double diff1 = tripPrice - profit; Console.WriteLine($"Not enough money! {diff1:f2} lv needed."); } } } } } } /* Петя има магазин за детски играчки. Тя получава голяма поръчка, която трябва да изпълни. С парите, които ще спечели иска да отиде на екскурзия. Да се напише програма, която пресмята печалбата от поръчката. Цени на играчките: • Пъзел - 2.60 лв. • Говореща кукла - 3 лв. • Плюшено мече - 4.10 лв. • Миньон - 8.20 лв. • Камионче - 2 лв. Ако поръчаните играчки са 50 или повече магазинът прави отстъпка 25% от общата цена. От спечелените пари Петя трябва да даде 10% за наема на магазина. Да се пресметне дали парите ще ѝ стигнат да отиде на екскурзия. От конзолата се четат 6 реда: 1. Цена на екскурзията - реално число в интервала [1.00 … 10000.00] 2. Брой пъзели - цяло число в интервала [0… 1000] 3. Брой говорещи кукли - цяло число в интервала [0 … 1000] 4. Брой плюшени мечета - цяло число в интервала [0 … 1000] 5. Брой миньони - цяло число в интервала [0 … 1000] 6. Брой камиончета - цяло число в интервала [0 … 1000] На конзолата се отпечатва: • Ако парите са достатъчни се отпечатва: o "Yes! {оставащите пари} lv left." • Ако парите НЕ са достатъчни се отпечатва: o "Not enough money! {недостигащите пари} lv needed." */
35.892473
102
0.549431
[ "MIT" ]
desata/csharp
Numbers1To10/Toy_Shop/Program.cs
4,109
C#
using Saar.FFmpeg.Delegates; using Saar.FFmpeg.Internal; using Saar.FFmpeg.Structs; using Saar.FFmpeg.Support; using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Saar.FFmpeg.CSharp { public enum AVActiveFormatDescription : int { Same = 8, _4_3 = 9, _16_9 = 10, _14_9 = 11, _4_3Sp_14_9 = 13, _16_9Sp_14_9 = 14, Sp_4_3 = 15, } /// <summary> /// Message types used by avdevice_app_to_dev_control_message(). /// </summary> public enum AVAppToDevMessageType : int { /// <summary> /// Dummy message. /// </summary> None = 1313820229, /// <summary> /// Window size change message. /// </summary> WindowSize = 1195724621, /// <summary> /// Repaint request message. /// </summary> WindowRepaint = 1380274241, /// <summary> /// Request pause/play. /// </summary> Pause = 1346458912, /// <summary> /// Request pause/play. /// </summary> Play = 1347174745, /// <summary> /// Request pause/play. /// </summary> TogglePause = 1346458964, /// <summary> /// Volume control message. /// </summary> SetVolume = 1398165324, /// <summary> /// Mute control messages. /// </summary> Mute = 541939028, /// <summary> /// Mute control messages. /// </summary> Unmute = 1431131476, /// <summary> /// Mute control messages. /// </summary> ToggleMute = 1414354260, /// <summary> /// Get volume/mute messages. /// </summary> GetVolume = 1196838732, /// <summary> /// Get volume/mute messages. /// </summary> GetMute = 1196250452, } public enum AVAudioServiceType : int { Main = 0, Effects = 1, VisuallyImpaired = 2, HearingImpaired = 3, Dialogue = 4, Commentary = 5, Emergency = 6, VoiceOver = 7, Karaoke = 8, /// <summary> /// Not part of ABI /// </summary> Nb = 9, } public enum AVBuffersinkFlag : int { NoRequest = 0x2, Peek = 0x1, } [Flags] public enum AVChannelLayout : ulong { FrontLeft = 0x00000001, FrontRight = 0x00000002, FrontCenter = 0x00000004, LowFrequency = 0x00000008, BackLeft = 0x00000010, BackRight = 0x00000020, FrontLeftOfCenter = 0x00000040, FrontRightOfCenter = 0x00000080, BackCenter = 0x00000100, SideLeft = 0x00000200, SideRight = 0x00000400, TopCenter = 0x00000800, TopFrontLeft = 0x00001000, TopFrontCenter = 0x00002000, TopFrontRight = 0x00004000, TopBackLeft = 0x00008000, TopBackCenter = 0x00010000, TopBackRight = 0x00020000, StereoLeft = 0x20000000, StereoRight = 0x40000000, WideLeft = 0x0000000080000000UL, WideRight = 0x0000000100000000UL, SurroundDirectLeft = 0x0000000200000000UL, SurroundDirectRight = 0x0000000400000000UL, LowFrequency2 = 0x0000000800000000UL, LayoutNative = 0x8000000000000000UL, LayoutMono = (FrontCenter), LayoutStereo = (FrontLeft | FrontRight), Layout2point1 = (LayoutStereo | LowFrequency), Layout2_1 = (LayoutStereo | BackCenter), LayoutSurround = (LayoutStereo | FrontCenter), Layout3point1 = (LayoutSurround | LowFrequency), Layout4point0 = (LayoutSurround | BackCenter), Layout4point1 = (Layout4point0 | LowFrequency), Layout2_2 = (LayoutStereo | SideLeft | SideRight), LayoutQuad = (LayoutStereo | BackLeft | BackRight), Layout5point0 = (LayoutSurround | SideLeft | SideRight), Layout5point1 = (Layout5point0 | LowFrequency), Layout5point0Back = (LayoutSurround | BackLeft | BackRight), Layout5point1Back = (Layout5point0Back | LowFrequency), Layout6point0 = (Layout5point0 | BackCenter), Layout6point0Front = (Layout2_2 | FrontLeftOfCenter | FrontRightOfCenter), LayoutHexagonal = (Layout5point0Back | BackCenter), Layout6point1 = (Layout5point1 | BackCenter), Layout6point1Back = (Layout5point1Back | BackCenter), Layout6point1Front = (Layout6point0Front | LowFrequency), Layout7point0 = (Layout5point0 | BackLeft | BackRight), Layout7point0Front = (Layout5point0 | FrontLeftOfCenter | FrontRightOfCenter), Layout7point1 = (Layout5point1 | BackLeft | BackRight), Layout7point1Wide = (Layout5point1 | FrontLeftOfCenter | FrontRightOfCenter), Layout7point1WideBack = (Layout5point1Back | FrontLeftOfCenter | FrontRightOfCenter), LayoutOctagonal = (Layout5point0 | BackLeft | BackCenter | BackRight), LayoutHexadecagonal = (LayoutOctagonal | WideLeft | WideRight | TopBackLeft | TopBackRight | TopBackCenter | TopFrontCenter | TopFrontLeft | TopFrontRight), LayoutStereoDownmix = (StereoLeft | StereoRight), } /// <summary> /// Location of chroma samples. /// </summary> public enum AVChromaLocation : int { Unspecified = 0, /// <summary> /// MPEG-2/4 4:2:0, H.264 default for 4:2:0 /// </summary> Left = 1, /// <summary> /// MPEG-1 4:2:0, JPEG 4:2:0, H.263 4:2:0 /// </summary> Center = 2, /// <summary> /// ITU-R 601, SMPTE 274M 296M S314M(DV 4:1:1), mpeg2 4:2:2 /// </summary> Topleft = 3, Top = 4, Bottomleft = 5, Bottom = 6, /// <summary> /// Not part of ABI /// </summary> Nb = 7, } public enum AVClassCategory : int { Na = 0, Input = 1, Output = 2, Muxer = 3, Demuxer = 4, Encoder = 5, Decoder = 6, Filter = 7, BitstreamFilter = 8, Swscaler = 9, Swresampler = 10, DeviceVideoOutput = 40, DeviceVideoInput = 41, DeviceAudioOutput = 42, DeviceAudioInput = 43, DeviceOutput = 44, DeviceInput = 45, /// <summary> /// not part of ABI/API /// </summary> Nb = 46, } public enum AVCodecCap : uint { VariableFrameSize = 0x1 << 0x10, Truncated = 0x1 << 0x3, Subframes = 0x1 << 0x8, SmallLastFrame = 0x1 << 0x6, SliceThreads = 0x1 << 0xd, ParamChange = 0x1 << 0xe, Lossless = 0x80000000U, IntraOnly = 0x40000000, Hybrid = 0x1 << 0x13, Hardware = 0x1 << 0x12, FrameThreads = 0x1 << 0xc, Experimental = 0x1 << 0x9, DrawHorizBand = 0x1 << 0x0, Dr1 = 0x1 << 0x1, Delay = 0x1 << 0x5, ChannelConf = 0x1 << 0xa, AVOidProbing = 0x1 << 0x11, AutoThreads = 0x1 << 0xf, } public enum AVCodecFlag : uint { Pass1 = 0x1 << 0x9, OutputCorrupt = 0x1 << 0x3, LowDelay = 0x1 << 0x13, LoopFilter = 0x1 << 0xb, InterlacedMe = 0x1 << 0x1d, InterlacedDct = 0x1 << 0x12, Gray = 0x1 << 0xd, GlobalHeader = 0x1 << 0x16, ClosedGop = 0x1U << 0x1f, Bitexact = 0x1 << 0x17, AcPred = 0x1 << 0x18, _4mv = 0x1 << 0x2, } public enum AVCodecFlag2 : uint { Chunks = 0x1 << 0xf, DropFrameTimecode = 0x1 << 0xd, ExportMvs = 0x1 << 0x1c, Fast = 0x1 << 0x0, IgnoreCrop = 0x1 << 0x10, LocalHeader = 0x1 << 0x3, NoOutput = 0x1 << 0x2, RoFlushNoop = 0x1 << 0x1e, ShowAll = 0x1 << 0x16, SkipManual = 0x1 << 0x1d, } /// <summary> /// Identify the syntax and semantics of the bitstream. The principle is roughly: Two decoders with the same ID can decode the same streams. Two encoders with the same ID can encode compatible streams. There may be slight deviations from the principle due to implementation details. /// </summary> public enum AVCodecID : int { None = 0, Mpeg1video = 1, /// <summary> /// preferred ID for MPEG-1/2 video decoding /// </summary> Mpeg2video = 2, H261 = 3, H263 = 4, Rv10 = 5, Rv20 = 6, Mjpeg = 7, Mjpegb = 8, Ljpeg = 9, Sp5x = 10, Jpegls = 11, Mpeg4 = 12, Rawvideo = 13, Msmpeg4v1 = 14, Msmpeg4v2 = 15, Msmpeg4v3 = 16, Wmv1 = 17, Wmv2 = 18, H263p = 19, H263i = 20, Flv1 = 21, Svq1 = 22, Svq3 = 23, Dvvideo = 24, Huffyuv = 25, Cyuv = 26, H264 = 27, Indeo3 = 28, Vp3 = 29, Theora = 30, Asv1 = 31, Asv2 = 32, Ffv1 = 33, _4XM = 34, Vcr1 = 35, Cljr = 36, Mdec = 37, Roq = 38, InterplayVideo = 39, XanWc3 = 40, XanWc4 = 41, Rpza = 42, Cinepak = 43, WsVqa = 44, Msrle = 45, Msvideo1 = 46, Idcin = 47, _8BPS = 48, Smc = 49, Flic = 50, Truemotion1 = 51, Vmdvideo = 52, Mszh = 53, Zlib = 54, Qtrle = 55, Tscc = 56, Ulti = 57, Qdraw = 58, Vixl = 59, Qpeg = 60, Png = 61, Ppm = 62, Pbm = 63, Pgm = 64, Pgmyuv = 65, Pam = 66, Ffvhuff = 67, Rv30 = 68, Rv40 = 69, Vc1 = 70, Wmv3 = 71, Loco = 72, Wnv1 = 73, Aasc = 74, Indeo2 = 75, Fraps = 76, Truemotion2 = 77, Bmp = 78, Cscd = 79, Mmvideo = 80, Zmbv = 81, Avs = 82, Smackvideo = 83, Nuv = 84, Kmvc = 85, Flashsv = 86, Cavs = 87, Jpeg2000 = 88, Vmnc = 89, Vp5 = 90, Vp6 = 91, Vp6f = 92, Targa = 93, Dsicinvideo = 94, Tiertexseqvideo = 95, Tiff = 96, Gif = 97, Dxa = 98, Dnxhd = 99, Thp = 100, Sgi = 101, C93 = 102, Bethsoftvid = 103, Ptx = 104, Txd = 105, Vp6a = 106, Amv = 107, Vb = 108, Pcx = 109, Sunrast = 110, Indeo4 = 111, Indeo5 = 112, Mimic = 113, Rl2 = 114, Escape124 = 115, Dirac = 116, Bfi = 117, Cmv = 118, Motionpixels = 119, Tgv = 120, Tgq = 121, Tqi = 122, Aura = 123, Aura2 = 124, V210x = 125, Tmv = 126, V210 = 127, Dpx = 128, Mad = 129, Frwu = 130, Flashsv2 = 131, Cdgraphics = 132, R210 = 133, Anm = 134, Binkvideo = 135, IffIlbm = 136, Kgv1 = 137, Yop = 138, Vp8 = 139, Pictor = 140, Ansi = 141, A64Multi = 142, A64Multi5 = 143, R10k = 144, Mxpeg = 145, Lagarith = 146, Prores = 147, Jv = 148, Dfa = 149, Wmv3image = 150, Vc1image = 151, Utvideo = 152, BmvVideo = 153, Vble = 154, Dxtory = 155, V410 = 156, Xwd = 157, Cdxl = 158, Xbm = 159, Zerocodec = 160, Mss1 = 161, Msa1 = 162, Tscc2 = 163, Mts2 = 164, Cllc = 165, Mss2 = 166, Vp9 = 167, Aic = 168, Escape130 = 169, G2m = 170, Webp = 171, Hnm4Video = 172, Hevc = 173, Fic = 174, AliasPix = 175, BrenderPix = 176, PafVideo = 177, Exr = 178, Vp7 = 179, Sanm = 180, Sgirle = 181, Mvc1 = 182, Mvc2 = 183, Hqx = 184, Tdsc = 185, HqHqa = 186, Hap = 187, Dds = 188, Dxv = 189, Screenpresso = 190, Rscc = 191, Avs2 = 192, Y41p = 32768, Avrp = 32769, _012V = 32770, Avui = 32771, Ayuv = 32772, TargaY216 = 32773, V308 = 32774, V408 = 32775, Yuv4 = 32776, Avrn = 32777, Cpia = 32778, Xface = 32779, Snow = 32780, Smvjpeg = 32781, Apng = 32782, Daala = 32783, Cfhd = 32784, Truemotion2rt = 32785, M101 = 32786, Magicyuv = 32787, Sheervideo = 32788, Ylc = 32789, Psd = 32790, Pixlet = 32791, Speedhq = 32792, Fmvc = 32793, Scpr = 32794, Clearvideo = 32795, Xpm = 32796, Av1 = 32797, Bitpacked = 32798, Mscc = 32799, Srgc = 32800, Svg = 32801, Gdv = 32802, Fits = 32803, Imm4 = 32804, Prosumer = 32805, Mwsc = 32806, Wcmv = 32807, Rasc = 32808, /// <summary> /// A dummy id pointing at the start of audio codecs /// </summary> FirstAudio = 65536, PcmS16le = 65536, PcmS16be = 65537, PcmU16le = 65538, PcmU16be = 65539, PcmS8 = 65540, PcmU8 = 65541, PcmMulaw = 65542, PcmAlaw = 65543, PcmS32le = 65544, PcmS32be = 65545, PcmU32le = 65546, PcmU32be = 65547, PcmS24le = 65548, PcmS24be = 65549, PcmU24le = 65550, PcmU24be = 65551, PcmS24daud = 65552, PcmZork = 65553, PcmS16lePlanar = 65554, PcmDvd = 65555, PcmF32be = 65556, PcmF32le = 65557, PcmF64be = 65558, PcmF64le = 65559, PcmBluray = 65560, PcmLxf = 65561, S302m = 65562, PcmS8Planar = 65563, PcmS24lePlanar = 65564, PcmS32lePlanar = 65565, PcmS16bePlanar = 65566, PcmS64le = 67584, PcmS64be = 67585, PcmF16le = 67586, PcmF24le = 67587, PcmVidc = 67588, AdpcmImaQt = 69632, AdpcmImaWav = 69633, AdpcmImaDk3 = 69634, AdpcmImaDk4 = 69635, AdpcmImaWs = 69636, AdpcmImaSmjpeg = 69637, AdpcmMs = 69638, Adpcm_4XM = 69639, AdpcmXa = 69640, AdpcmAdx = 69641, AdpcmEa = 69642, AdpcmG726 = 69643, AdpcmCt = 69644, AdpcmSwf = 69645, AdpcmYamaha = 69646, AdpcmSbpro_4 = 69647, AdpcmSbpro_3 = 69648, AdpcmSbpro_2 = 69649, AdpcmThp = 69650, AdpcmImaAmv = 69651, AdpcmEaR1 = 69652, AdpcmEaR3 = 69653, AdpcmEaR2 = 69654, AdpcmImaEaSead = 69655, AdpcmImaEaEacs = 69656, AdpcmEaXas = 69657, AdpcmEaMaxisXa = 69658, AdpcmImaIss = 69659, AdpcmG722 = 69660, AdpcmImaApc = 69661, AdpcmVima = 69662, AdpcmAfc = 71680, AdpcmImaOki = 71681, AdpcmDtk = 71682, AdpcmImaRad = 71683, AdpcmG726le = 71684, AdpcmThpLe = 71685, AdpcmPsx = 71686, AdpcmAica = 71687, AdpcmImaDat4 = 71688, AdpcmMtaf = 71689, AmrNb = 73728, AmrWb = 73729, Ra_144 = 77824, Ra_288 = 77825, RoqDpcm = 81920, InterplayDpcm = 81921, XanDpcm = 81922, SolDpcm = 81923, Sdx2Dpcm = 83968, GremlinDpcm = 83969, Mp2 = 86016, /// <summary> /// preferred ID for decoding MPEG audio layer 1, 2 or 3 /// </summary> Mp3 = 86017, Aac = 86018, Ac3 = 86019, Dts = 86020, Vorbis = 86021, Dvaudio = 86022, Wmav1 = 86023, Wmav2 = 86024, Mace3 = 86025, Mace6 = 86026, Vmdaudio = 86027, Flac = 86028, Mp3adu = 86029, Mp3on4 = 86030, Shorten = 86031, Alac = 86032, WestwoodSnd1 = 86033, /// <summary> /// as in Berlin toast format /// </summary> Gsm = 86034, Qdm2 = 86035, Cook = 86036, Truespeech = 86037, Tta = 86038, Smackaudio = 86039, Qcelp = 86040, Wavpack = 86041, Dsicinaudio = 86042, Imc = 86043, Musepack7 = 86044, Mlp = 86045, GsmMs = 86046, Atrac3 = 86047, Ape = 86048, Nellymoser = 86049, Musepack8 = 86050, Speex = 86051, Wmavoice = 86052, Wmapro = 86053, Wmalossless = 86054, Atrac3p = 86055, Eac3 = 86056, Sipr = 86057, Mp1 = 86058, Twinvq = 86059, Truehd = 86060, Mp4als = 86061, Atrac1 = 86062, BinkaudioRdft = 86063, BinkaudioDct = 86064, AacLatm = 86065, Qdmc = 86066, Celt = 86067, G723_1 = 86068, G729 = 86069, _8SVXExp = 86070, _8SVXFib = 86071, BmvAudio = 86072, Ralf = 86073, Iac = 86074, Ilbc = 86075, Opus = 86076, ComfortNoise = 86077, Tak = 86078, Metasound = 86079, PafAudio = 86080, On2avc = 86081, DssSp = 86082, Codec2 = 86083, Ffwavesynth = 88064, Sonic = 88065, SonicLs = 88066, Evrc = 88067, Smv = 88068, DsdLsbf = 88069, DsdMsbf = 88070, DsdLsbfPlanar = 88071, DsdMsbfPlanar = 88072, _4GV = 88073, InterplayAcm = 88074, Xma1 = 88075, Xma2 = 88076, Dst = 88077, Atrac3al = 88078, Atrac3pal = 88079, DolbyE = 88080, Aptx = 88081, AptxHd = 88082, Sbc = 88083, Atrac9 = 88084, /// <summary> /// A dummy ID pointing at the start of subtitle codecs. /// </summary> FirstSubtitle = 94208, DvdSubtitle = 94208, DvbSubtitle = 94209, /// <summary> /// raw UTF-8 text /// </summary> Text = 94210, Xsub = 94211, Ssa = 94212, MovText = 94213, HdmvPgsSubtitle = 94214, DvbTeletext = 94215, Srt = 94216, Microdvd = 96256, Eia_608 = 96257, Jacosub = 96258, Sami = 96259, Realtext = 96260, Stl = 96261, Subviewer1 = 96262, Subviewer = 96263, Subrip = 96264, Webvtt = 96265, Mpl2 = 96266, Vplayer = 96267, Pjs = 96268, Ass = 96269, HdmvTextSubtitle = 96270, Ttml = 96271, /// <summary> /// A dummy ID pointing at the start of various fake codecs. /// </summary> FirstUnknown = 98304, Ttf = 98304, /// <summary> /// Contain timestamp estimated through PCR of program stream. /// </summary> Scte_35 = 98305, Bintext = 100352, Xbin = 100353, Idf = 100354, Otf = 100355, SmpteKlv = 100356, DvdNav = 100357, TimedId3 = 100358, BinData = 100359, /// <summary> /// codec_id is not known (like AV_CODEC_ID_NONE) but lavf should attempt to identify it /// </summary> Probe = 102400, /// <summary> /// _FAKE_ codec to indicate a raw MPEG-2 TS stream (only used by libavformat) /// </summary> Mpeg2ts = 131072, /// <summary> /// _FAKE_ codec to indicate a MPEG-4 Systems stream (only used by libavformat) /// </summary> Mpeg4systems = 131073, /// <summary> /// Dummy codec for streams containing only metadata information. /// </summary> Ffmetadata = 135168, /// <summary> /// Passthrough codec, AVFrames wrapped in AVPacket /// </summary> WrappedAvframe = 135169, H265 = Hevc, IffByterun1 = IffIlbm, } public enum AVCodecProp : int { BitmapSub = 0x1 << 0x10, IntraOnly = 0x1 << 0x0, Lossless = 0x1 << 0x2, Lossy = 0x1 << 0x1, Reorder = 0x1 << 0x3, TextSub = 0x1 << 0x11, } /// <summary> /// Chromaticity coordinates of the source primaries. These values match the ones defined by ISO/IEC 23001-8_2013 § 7.1. /// </summary> public enum AVColorPrimaries : int { Reserved0 = 0, /// <summary> /// also ITU-R BT1361 / IEC 61966-2-4 / SMPTE RP177 Annex B /// </summary> Bt709 = 1, Unspecified = 2, Reserved = 3, /// <summary> /// also FCC Title 47 Code of Federal Regulations 73.682 (a)(20) /// </summary> Bt470m = 4, /// <summary> /// also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL &amp; SECAM /// </summary> Bt470bg = 5, /// <summary> /// also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC /// </summary> Smpte170m = 6, /// <summary> /// functionally identical to above /// </summary> Smpte240m = 7, /// <summary> /// colour filters using Illuminant C /// </summary> Film = 8, /// <summary> /// ITU-R BT2020 /// </summary> Bt2020 = 9, /// <summary> /// SMPTE ST 428-1 (CIE 1931 XYZ) /// </summary> Smpte428 = 10, Smptest428_1 = 10, /// <summary> /// SMPTE ST 431-2 (2011) / DCI P3 /// </summary> Smpte431 = 11, /// <summary> /// SMPTE ST 432-1 (2010) / P3 D65 / Display P3 /// </summary> Smpte432 = 12, /// <summary> /// JEDEC P22 phosphors /// </summary> JedecP22 = 22, /// <summary> /// Not part of ABI /// </summary> Nb = 23, } /// <summary> /// MPEG vs JPEG YUV range. /// </summary> public enum AVColorRange : int { Unspecified = 0, /// <summary> /// the normal 219*2^(n-8) &quot;MPEG&quot; YUV ranges /// </summary> Mpeg = 1, /// <summary> /// the normal 2^n-1 &quot;JPEG&quot; YUV ranges /// </summary> Jpeg = 2, /// <summary> /// Not part of ABI /// </summary> Nb = 3, } /// <summary> /// YUV colorspace type. These values match the ones defined by ISO/IEC 23001-8_2013 § 7.3. /// </summary> public enum AVColorSpace : int { /// <summary> /// order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB) /// </summary> Rgb = 0, /// <summary> /// also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / SMPTE RP177 Annex B /// </summary> Bt709 = 1, Unspecified = 2, Reserved = 3, /// <summary> /// FCC Title 47 Code of Federal Regulations 73.682 (a)(20) /// </summary> Fcc = 4, /// <summary> /// also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL &amp; SECAM / IEC 61966-2-4 xvYCC601 /// </summary> Bt470bg = 5, /// <summary> /// also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC /// </summary> Smpte170m = 6, /// <summary> /// functionally identical to above /// </summary> Smpte240m = 7, /// <summary> /// Used by Dirac / VC-2 and H.264 FRext, see ITU-T SG16 /// </summary> Ycgco = 8, Ycocg = 8, /// <summary> /// ITU-R BT2020 non-constant luminance system /// </summary> Bt2020Ncl = 9, /// <summary> /// ITU-R BT2020 constant luminance system /// </summary> Bt2020Cl = 10, /// <summary> /// SMPTE 2085, Y&apos;D&apos;zD&apos;x /// </summary> Smpte2085 = 11, /// <summary> /// Chromaticity-derived non-constant luminance system /// </summary> ChromaDerivedNcl = 12, /// <summary> /// Chromaticity-derived constant luminance system /// </summary> ChromaDerivedCl = 13, /// <summary> /// ITU-R BT.2100-0, ICtCp /// </summary> Ictcp = 14, /// <summary> /// Not part of ABI /// </summary> Nb = 15, } /// <summary> /// Color Transfer Characteristic. These values match the ones defined by ISO/IEC 23001-8_2013 § 7.2. /// </summary> public enum AVColorTransferCharacteristic : int { Reserved0 = 0, /// <summary> /// also ITU-R BT1361 /// </summary> Bt709 = 1, Unspecified = 2, Reserved = 3, /// <summary> /// also ITU-R BT470M / ITU-R BT1700 625 PAL &amp; SECAM /// </summary> Gamma22 = 4, /// <summary> /// also ITU-R BT470BG /// </summary> Gamma28 = 5, /// <summary> /// also ITU-R BT601-6 525 or 625 / ITU-R BT1358 525 or 625 / ITU-R BT1700 NTSC /// </summary> Smpte170m = 6, Smpte240m = 7, /// <summary> /// &quot;Linear transfer characteristics&quot; /// </summary> Linear = 8, /// <summary> /// &quot;Logarithmic transfer characteristic (100:1 range)&quot; /// </summary> Log = 9, /// <summary> /// &quot;Logarithmic transfer characteristic (100 * Sqrt(10) : 1 range)&quot; /// </summary> LogSqrt = 10, /// <summary> /// IEC 61966-2-4 /// </summary> Iec61966_2_4 = 11, /// <summary> /// ITU-R BT1361 Extended Colour Gamut /// </summary> Bt1361Ecg = 12, /// <summary> /// IEC 61966-2-1 (sRGB or sYCC) /// </summary> Iec61966_2_1 = 13, /// <summary> /// ITU-R BT2020 for 10-bit system /// </summary> Bt2020_10 = 14, /// <summary> /// ITU-R BT2020 for 12-bit system /// </summary> Bt2020_12 = 15, /// <summary> /// SMPTE ST 2084 for 10-, 12-, 14- and 16-bit systems /// </summary> Smpte2084 = 16, Smptest2084 = 16, /// <summary> /// SMPTE ST 428-1 /// </summary> Smpte428 = 17, Smptest428_1 = 17, /// <summary> /// ARIB STD-B67, known as &quot;Hybrid log-gamma&quot; /// </summary> AribStdB67 = 18, /// <summary> /// Not part of ABI /// </summary> Nb = 19, } public enum AVCpuFlag : uint { Xop = 0x400, Vsx = 0x2, Vfpv3 = 0x1 << 0x4, VfpVm = 0x1 << 0x7, Vfp = 0x1 << 0x3, Ssse3slow = 0x4000000, Ssse3 = 0x80, Sse42 = 0x200, Sse4 = 0x100, Sse3slow = 0x20000000, Sse3 = 0x40, Sse2slow = 0x40000000, Sse2 = 0x10, Sse = 0x8, Setend = 0x1 << 0x10, Power8 = 0x4, Neon = 0x1 << 0x5, Mmxext = 0x2, Mmx2 = 0x2, Mmx = 0x1, Force = 0x80000000U, Fma4 = 0x800, Fma3 = 0x10000, Cmov = 0x1000, Bmi2 = 0x40000, Bmi1 = 0x20000, AVXslow = 0x8000000, Avx512 = 0x100000, Avx2 = 0x8000, Avx = 0x4000, Atom = 0x10000000, Armv8 = 0x1 << 0x6, Armv6t2 = 0x1 << 0x2, Armv6 = 0x1 << 0x1, Armv5te = 0x1 << 0x0, Altivec = 0x1, Aesni = 0x80000, _3dnowext = 0x20, _3dnow = 0x4, } /// <summary> /// Message types used by avdevice_dev_to_app_control_message(). /// </summary> public enum AVDevToAppMessageType : int { /// <summary> /// Dummy message. /// </summary> None = 1313820229, /// <summary> /// Create window buffer message. /// </summary> CreateWindowBuffer = 1111708229, /// <summary> /// Prepare window buffer message. /// </summary> PrepareWindowBuffer = 1112560197, /// <summary> /// Display window buffer message. /// </summary> DisplayWindowBuffer = 1111771475, /// <summary> /// Destroy window buffer message. /// </summary> DestroyWindowBuffer = 1111770451, /// <summary> /// Buffer fullness status messages. /// </summary> BufferOverflow = 1112491596, /// <summary> /// Buffer fullness status messages. /// </summary> BufferUnderflow = 1112884812, /// <summary> /// Buffer readable/writable. /// </summary> BufferReadable = 1112687648, /// <summary> /// Buffer readable/writable. /// </summary> BufferWritable = 1113018912, /// <summary> /// Mute state change message. /// </summary> MuteStateChanged = 1129141588, /// <summary> /// Volume level change message. /// </summary> VolumeLevelChanged = 1129729868, } public enum AVDict : int { Append = 0x20, DontOverwrite = 0x10, DontStrdupKey = 0x4, DontStrdupVal = 0x8, IgnoreSuffix = 0x2, MatchCase = 0x1, Multikey = 0x40, } public enum AVDiscard : int { /// <summary> /// discard nothing /// </summary> None = -16, /// <summary> /// discard useless packets like 0 size packets in avi /// </summary> Default = 0, /// <summary> /// discard all non reference /// </summary> Nonref = 8, /// <summary> /// discard all bidirectional frames /// </summary> Bidir = 16, /// <summary> /// discard all non intra frames /// </summary> Nonintra = 24, /// <summary> /// discard all frames except keyframes /// </summary> Nonkey = 32, /// <summary> /// discard all /// </summary> All = 48, } public enum AVDisposition : int { VisualImpaired = 0x100, TimedThumbnails = 0x800, StillImage = 0x100000, Original = 0x4, Metadata = 0x40000, Lyrics = 0x10, Karaoke = 0x20, HearingImpaired = 0x80, Forced = 0x40, Dub = 0x2, Descriptions = 0x20000, Dependent = 0x80000, Default = 0x1, Comment = 0x8, CleanEffects = 0x200, Captions = 0x10000, AttachedPic = 0x400, } /// <summary> /// The duration of a video can be estimated through various ways, and this enum can be used to know how the duration was estimated. /// </summary> public enum AVDurationEstimationMethod : int { /// <summary> /// Duration accurately estimated from PTSes /// </summary> Pts = 0, /// <summary> /// Duration estimated from a stream with a known duration /// </summary> Stream = 1, /// <summary> /// Duration estimated from bitrate (less accurate) /// </summary> Bitrate = 2, } public enum AVEf : int { Aggressive = 0x1 << 0x12, Bitstream = 0x1 << 0x1, Buffer = 0x1 << 0x2, Careful = 0x1 << 0x10, Compliant = 0x1 << 0x11, Crccheck = 0x1 << 0x0, Explode = 0x1 << 0x3, IgnoreErr = 0x1 << 0xf, } public enum AVError : int { BsfNotFound = -(0xf8 | ('B' << 8) | ('S' << 16) | ('F' << 24)), BufferTooSmall = -('B' | ('U' << 8) | ('F' << 16) | ('S' << 24)), Bug = -('B' | ('U' << 8) | ('G' << 16) | ('!' << 24)), Bug2 = -('B' | ('U' << 8) | ('G' << 16) | (' ' << 24)), DecoderNotFound = -(0xf8 | ('D' << 8) | ('E' << 16) | ('C' << 24)), DemuxerNotFound = -(0xf8 | ('D' << 8) | ('E' << 16) | ('M' << 24)), EncoderNotFound = -(0xf8 | ('E' << 8) | ('N' << 16) | ('C' << 24)), Eof = -('E' | ('O' << 8) | ('F' << 16) | (' ' << 24)), Exit = -('E' | ('X' << 8) | ('I' << 16) | ('T' << 24)), Experimental = -0x2bb2afa8, External = -('E' | ('X' << 8) | ('T' << 16) | (' ' << 24)), FilterNotFound = -(0xf8 | ('F' << 8) | ('I' << 16) | ('L' << 24)), HttpBadRequest = -(0xf8 | ('4' << 8) | ('0' << 16) | ('0' << 24)), HttpForbidden = -(0xf8 | ('4' << 8) | ('0' << 16) | ('3' << 24)), HttpNotFound = -(0xf8 | ('4' << 8) | ('0' << 16) | ('4' << 24)), HttpOther_4xx = -(0xf8 | ('4' << 8) | ('X' << 16) | ('X' << 24)), HttpServerError = -(0xf8 | ('5' << 8) | ('X' << 16) | ('X' << 24)), HttpUnauthorized = -(0xf8 | ('4' << 8) | ('0' << 16) | ('1' << 24)), InputChanged = -0x636e6701, Invaliddata = -('I' | ('N' << 8) | ('D' << 16) | ('A' << 24)), MuxerNotFound = -(0xf8 | ('M' << 8) | ('U' << 16) | ('X' << 24)), OptionNotFound = -(0xf8 | ('O' << 8) | ('P' << 16) | ('T' << 24)), OutputChanged = -0x636e6702, Patchwelcome = -('P' | ('A' << 8) | ('W' << 16) | ('E' << 24)), ProtocolNotFound = -(0xf8 | ('P' << 8) | ('R' << 16) | ('O' << 24)), StreamNotFound = -(0xf8 | ('S' << 8) | ('T' << 16) | ('R' << 24)), Unknown = -('U' | ('N' << 8) | ('K' << 16) | ('N' << 24)), } public enum AVFieldOrder : int { Unknown = 0, Progressive = 1, Tt = 2, Bb = 3, Tb = 4, Bt = 5, } /// <summary> /// stage of the initialization of the link properties (dimensions, etc) /// </summary> public enum AVFilterLink_InitState : int { /// <summary> /// not started /// </summary> Uninit = 0, /// <summary> /// started, but incomplete /// </summary> Startinit = 1, /// <summary> /// complete /// </summary> Init = 2, } public enum AVFmt : int { VariableFps = 0x400, TsNonstrict = 0x20000, TsNegative = 0x40000, TsDiscont = 0x200, ShowIds = 0x8, SeekToPts = 0x4000000, Notimestamps = 0x80, Nostreams = 0x1000, Nogensearch = 0x4000, Nofile = 0x1, Nodimensions = 0x800, Nobinsearch = 0x2000, NoByteSeek = 0x8000, Neednumber = 0x2, Globalheader = 0x40, GenericIndex = 0x100, EventFlagMetadataUpdated = 0x1, AVOidNegTsMakeZero = 0x2, AVOidNegTsMakeNonNegative = 0x1, AVOidNegTsAuto = -0x1, AllowFlush = 0x10000, } [Flags] public enum AVFmtFlag : int { SortDts = 0x10000, Shortest = 0x100000, PrivOpt = 0x20000, Noparse = 0x20, Nonblock = 0x4, Nofillin = 0x10, Nobuffer = 0x40, Mp4aLatm = 0x8000, KeepSideData = 0x40000, Ignidx = 0x2, Igndts = 0x8, Genpts = 0x1, FlushPackets = 0x200, FastSeek = 0x80000, DiscardCorrupt = 0x100, CustomIO = 0x80, Bitexact = 0x400, AutoBsf = 0x200000, } public enum AVFmtctx : int { Unseekable = 0x2, Noheader = 0x1, } public enum AVFrameFlag : int { Discard = 0x1 << 0x2, Corrupt = 0x1 << 0x0, } /// <summary> /// @{ AVFrame is an abstraction for reference-counted raw multimedia data. /// </summary> public enum AVFrameSideDataType : int { /// <summary> /// The data is the AVPanScan struct defined in libavcodec. /// </summary> Panscan = 0, /// <summary> /// ATSC A53 Part 4 Closed Captions. A53 CC bitstream is stored as uint8_t in AVFrameSideData.data. The number of bytes of CC data is AVFrameSideData.size. /// </summary> A53Cc = 1, /// <summary> /// Stereoscopic 3d metadata. The data is the AVStereo3D struct defined in libavutil/stereo3d.h. /// </summary> Stereo3d = 2, /// <summary> /// The data is the AVMatrixEncoding enum defined in libavutil/channel_layout.h. /// </summary> Matrixencoding = 3, /// <summary> /// Metadata relevant to a downmix procedure. The data is the AVDownmixInfo struct defined in libavutil/downmix_info.h. /// </summary> DownmixInfo = 4, /// <summary> /// ReplayGain information in the form of the AVReplayGain struct. /// </summary> Replaygain = 5, /// <summary> /// This side data contains a 3x3 transformation matrix describing an affine transformation that needs to be applied to the frame for correct presentation. /// </summary> Displaymatrix = 6, /// <summary> /// Active Format Description data consisting of a single byte as specified in ETSI TS 101 154 using AVActiveFormatDescription enum. /// </summary> Afd = 7, /// <summary> /// Motion vectors exported by some codecs (on demand through the export_mvs flag set in the libavcodec AVCodecContext flags2 option). The data is the AVMotionVector struct defined in libavutil/motion_vector.h. /// </summary> MotionVectors = 8, /// <summary> /// Recommmends skipping the specified number of samples. This is exported only if the &quot;skip_manual&quot; AVOption is set in libavcodec. This has the same format as AV_PKT_DATA_SKIP_SAMPLES. /// </summary> SkipSamples = 9, /// <summary> /// This side data must be associated with an audio frame and corresponds to enum AVAudioServiceType defined in avcodec.h. /// </summary> AudioServiceType = 10, /// <summary> /// Mastering display metadata associated with a video frame. The payload is an AVMasteringDisplayMetadata type and contains information about the mastering display color volume. /// </summary> MasteringDisplayMetadata = 11, /// <summary> /// The GOP timecode in 25 bit timecode format. Data format is 64-bit integer. This is set on the first frame of a GOP that has a temporal reference of 0. /// </summary> GopTimecode = 12, /// <summary> /// The data represents the AVSphericalMapping structure defined in libavutil/spherical.h. /// </summary> Spherical = 13, /// <summary> /// Content light level (based on CTA-861.3). This payload contains data in the form of the AVContentLightMetadata struct. /// </summary> ContentLightLevel = 14, /// <summary> /// The data contains an ICC profile as an opaque octet buffer following the format described by ISO 15076-1 with an optional name defined in the metadata key entry &quot;name&quot;. /// </summary> IccProfile = 15, /// <summary> /// Implementation-specific description of the format of AV_FRAME_QP_TABLE_DATA. The contents of this side data are undocumented and internal; use av_frame_set_qp_table() and av_frame_get_qp_table() to access this in a meaningful way instead. /// </summary> QpTableProperties = 16, /// <summary> /// Raw QP table data. Its format is described by AV_FRAME_DATA_QP_TABLE_PROPERTIES. Use av_frame_set_qp_table() and av_frame_get_qp_table() to access this instead. /// </summary> QpTableData = 17, /// <summary> /// Timecode which conforms to SMPTE ST 12-1. The data is an array of 4 uint32_t where the first uint32_t describes how many (1-3) of the other timecodes are used. The timecode format is described in the av_timecode_get_smpte_from_framenum() function in libavutil/timecode.c. /// </summary> S12mTimecode = 18, } public enum AVHave : long { Bigendian = 0x0, FastUnaligned = 0x1, } public enum AVHwaccel : int { CodecCapExperimental = 0x200, FlagAllowHighDepth = 0x1 << 0x1, FlagAllowProfileMismatch = 0x1 << 0x2, FlagIgnoreLevel = 0x1 << 0x0, } public enum AVHWDeviceType : int { None = 0, Vdpau = 1, Cuda = 2, Vaapi = 3, Dxva2 = 4, Qsv = 5, Videotoolbox = 6, D3d11va = 7, Drm = 8, Opencl = 9, Mediacodec = 10, } public enum AVHWFrameTransferDirection : int { /// <summary> /// Transfer the data from the queried hw frame. /// </summary> From = 0, /// <summary> /// Transfer the data to the queried hw frame. /// </summary> To = 1, } public enum AVIndex : int { Keyframe = 0x1, DiscardFrame = 0x2, } public enum AVInputBuffer : int { MinSize = 0x4000, PaddingSize = 0x40, } public enum AVIo : int { FlagDirect = 0x8000, FlagNonblock = 0x8, FlagRead = 0x1, FlagReadWrite = FlagRead | FlagWrite, FlagWrite = 0x2, SeekableNormal = 0x1 << 0x0, SeekableTime = 0x1 << 0x1, } /// <summary> /// Different data types that can be returned via the AVIO write_data_type callback. /// </summary> public enum AVIODataMarkerType : int { /// <summary> /// Header data; this needs to be present for the stream to be decodeable. /// </summary> Header = 0, /// <summary> /// A point in the output bytestream where a decoder can start decoding (i.e. a keyframe). A demuxer/decoder given the data flagged with AVIO_DATA_MARKER_HEADER, followed by any AVIO_DATA_MARKER_SYNC_POINT, should give decodeable results. /// </summary> SyncPoint = 1, /// <summary> /// A point in the output bytestream where a demuxer can start parsing (for non self synchronizing bytestream formats). That is, any non-keyframe packet start point. /// </summary> BoundaryPoint = 2, /// <summary> /// This is any, unlabelled data. It can either be a muxer not marking any positions at all, it can be an actual boundary/sync point that the muxer chooses not to mark, or a later part of a packet/fragment that is cut into multiple write callbacks due to limited IO buffer size. /// </summary> Unknown = 3, /// <summary> /// Trailer data, which doesn&apos;t contain actual content, but only for finalizing the output file. /// </summary> Trailer = 4, /// <summary> /// A point in the output bytestream where the underlying AVIOContext might flush the buffer depending on latency or buffering requirements. Typically means the end of a packet. /// </summary> FlushPoint = 5, } /// <summary> /// Directory entry types. /// </summary> public enum AVIODirEntryType : int { Unknown = 0, BlockDevice = 1, CharacterDevice = 2, Directory = 3, NamedPipe = 4, SymbolicLink = 5, Socket = 6, File = 7, Server = 8, Share = 9, Workgroup = 10, } /// <summary> /// Lock operation used by lockmgr /// </summary> public enum AVLockOp : int { /// <summary> /// Create a mutex /// </summary> Create = 0, /// <summary> /// Lock the mutex /// </summary> Obtain = 1, /// <summary> /// Unlock the mutex /// </summary> Release = 2, /// <summary> /// Free mutex resources /// </summary> Destroy = 3, } public enum AVLog : long { Debug = 0x30, Error = 0x10, Fatal = 0x8, Info = 0x20, MaxOffset = Trace - Quiet, Panic = 0x0, PrintLevel = 0x2, Quiet = -0x8, SkipRepeated = 0x1, Trace = 0x38, Verbose = 0x28, Warning = 0x18, } public enum AVMatrixEncoding : int { None = 0, Dolby = 1, Dplii = 2, Dpliix = 3, Dpliiz = 4, Dolbyex = 5, Dolbyheadphone = 6, Nb = 7, } /// <summary> /// Media Type /// </summary> public enum AVMediaType : int { /// <summary> /// Usually treated as AVMEDIA_TYPE_DATA /// </summary> Unknown = -1, Video = 0, Audio = 1, /// <summary> /// Opaque data information usually continuous /// </summary> Data = 2, Subtitle = 3, /// <summary> /// Opaque data information usually sparse /// </summary> Attachment = 4, Nb = 5, } public enum AVOpt : int { FlagReadonly = 0x80, FlagFilteringParam = 0x1 << 0x10, FlagExport = 0x40, FlagEncodingParam = 0x1, FlagDeprecated = 0x1 << 0x11, FlagDecodingParam = 0x2, FlagBsfParam = 0x1 << 0x8, FlagAudioParam = 0x8, AllowNull = 0x1 << 0x2, FlagSubtitleParam = 0x20, FlagVideoParam = 0x10, MultiComponentRange = 0x1 << 0xc, SearchChildren = 0x1 << 0x0, SearchFakeObj = 0x1 << 0x1, SerializeOptFlagsExact = 0x2, SerializeSkipDefaults = 0x1, } /// <summary> /// @{ AVOptions provide a generic system to declare options on arbitrary structs (&quot;objects&quot;). An option can have a help text, a type and a range of possible values. Options may then be enumerated, read and written to. /// </summary> public enum AVOptionType : int { Flags = 0, Int = 1, Int64 = 2, Double = 3, Float = 4, String = 5, Rational = 6, /// <summary> /// offset must point to a pointer immediately followed by an int for the length /// </summary> Binary = 7, Dict = 8, Uint64 = 9, Const = 10, /// <summary> /// offset must point to two consecutive integers /// </summary> ImageSize = 11, PixelFmt = 12, SampleFmt = 13, /// <summary> /// offset must point to AVRational /// </summary> VideoRate = 14, Duration = 15, Color = 16, ChannelLayout = 17, Bool = 18, } /// <summary> /// Types and functions for working with AVPacket. @{ /// </summary> public enum AVPacketSideDataType : int { /// <summary> /// An AV_PKT_DATA_PALETTE side data packet contains exactly AVPALETTE_SIZE bytes worth of palette. This side data signals that a new palette is present. /// </summary> Palette = 0, /// <summary> /// The AV_PKT_DATA_NEW_EXTRADATA is used to notify the codec or the format that the extradata buffer was changed and the receiving side should act upon it appropriately. The new extradata is embedded in the side data buffer and should be immediately used for processing the current frame or packet. /// </summary> NewExtradata = 1, /// <summary> /// An AV_PKT_DATA_PARAM_CHANGE side data packet is laid out as follows: /// </summary> ParamChange = 2, /// <summary> /// An AV_PKT_DATA_H263_MB_INFO side data packet contains a number of structures with info about macroblocks relevant to splitting the packet into smaller packets on macroblock edges (e.g. as for RFC 2190). That is, it does not necessarily contain info about all macroblocks, as long as the distance between macroblocks in the info is smaller than the target payload size. Each MB info structure is 12 bytes, and is laid out as follows: /// </summary> H263MbInfo = 3, /// <summary> /// This side data should be associated with an audio stream and contains ReplayGain information in form of the AVReplayGain struct. /// </summary> Replaygain = 4, /// <summary> /// This side data contains a 3x3 transformation matrix describing an affine transformation that needs to be applied to the decoded video frames for correct presentation. /// </summary> Displaymatrix = 5, /// <summary> /// This side data should be associated with a video stream and contains Stereoscopic 3D information in form of the AVStereo3D struct. /// </summary> Stereo3d = 6, /// <summary> /// This side data should be associated with an audio stream and corresponds to enum AVAudioServiceType. /// </summary> AudioServiceType = 7, /// <summary> /// This side data contains quality related information from the encoder. /// </summary> QualityStats = 8, /// <summary> /// This side data contains an integer value representing the stream index of a &quot;fallback&quot; track. A fallback track indicates an alternate track to use when the current track can not be decoded for some reason. e.g. no decoder available for codec. /// </summary> FallbackTrack = 9, /// <summary> /// This side data corresponds to the AVCPBProperties struct. /// </summary> CpbProperties = 10, /// <summary> /// Recommmends skipping the specified number of samples /// </summary> SkipSamples = 11, /// <summary> /// An AV_PKT_DATA_JP_DUALMONO side data packet indicates that the packet may contain &quot;dual mono&quot; audio specific to Japanese DTV and if it is true, recommends only the selected channel to be used. /// </summary> JpDualmono = 12, /// <summary> /// A list of zero terminated key/value strings. There is no end marker for the list, so it is required to rely on the side data size to stop. /// </summary> StringsMetadata = 13, /// <summary> /// Subtitle event position /// </summary> SubtitlePosition = 14, /// <summary> /// Data found in BlockAdditional element of matroska container. There is no end marker for the data, so it is required to rely on the side data size to recognize the end. 8 byte id (as found in BlockAddId) followed by data. /// </summary> MatroskaBlockadditional = 15, /// <summary> /// The optional first identifier line of a WebVTT cue. /// </summary> WebvttIdentifier = 16, /// <summary> /// The optional settings (rendering instructions) that immediately follow the timestamp specifier of a WebVTT cue. /// </summary> WebvttSettings = 17, /// <summary> /// A list of zero terminated key/value strings. There is no end marker for the list, so it is required to rely on the side data size to stop. This side data includes updated metadata which appeared in the stream. /// </summary> MetadataUpdate = 18, /// <summary> /// MPEGTS stream ID, this is required to pass the stream ID information from the demuxer to the corresponding muxer. /// </summary> MpegtsStreamId = 19, /// <summary> /// Mastering display metadata (based on SMPTE-2086:2014). This metadata should be associated with a video stream and contains data in the form of the AVMasteringDisplayMetadata struct. /// </summary> MasteringDisplayMetadata = 20, /// <summary> /// This side data should be associated with a video stream and corresponds to the AVSphericalMapping structure. /// </summary> Spherical = 21, /// <summary> /// Content light level (based on CTA-861.3). This metadata should be associated with a video stream and contains data in the form of the AVContentLightMetadata struct. /// </summary> ContentLightLevel = 22, /// <summary> /// ATSC A53 Part 4 Closed Captions. This metadata should be associated with a video stream. A53 CC bitstream is stored as uint8_t in AVPacketSideData.data. The number of bytes of CC data is AVPacketSideData.size. /// </summary> A53Cc = 23, /// <summary> /// This side data is encryption initialization data. The format is not part of ABI, use av_encryption_init_info_* methods to access. /// </summary> EncryptionInitInfo = 24, /// <summary> /// This side data contains encryption info for how to decrypt the packet. The format is not part of ABI, use av_encryption_info_* methods to access. /// </summary> EncryptionInfo = 25, /// <summary> /// Active Format Description data consisting of a single byte as specified in ETSI TS 101 154 using AVActiveFormatDescription enum. /// </summary> Afd = 26, /// <summary> /// The number of side data types. This is not part of the public API/ABI in the sense that it may change when new side data types are added. This must stay the last enum value. If its value becomes huge, some code using it needs to be updated as it assumes it to be smaller than other limits. /// </summary> Nb = 27, } public enum AVPalette : long { Count = 0x100, Size = 0x400, } /// <summary> /// @{ /// </summary> public enum AVPictureStructure : int { Unknown = 0, TopField = 1, BottomField = 2, Frame = 3, } /// <summary> /// @} @} /// </summary> public enum AVPictureType : int { /// <summary> /// Undefined /// </summary> None = 0, /// <summary> /// Intra /// </summary> I = 1, /// <summary> /// Predicted /// </summary> P = 2, /// <summary> /// Bi-dir predicted /// </summary> B = 3, /// <summary> /// S(GMC)-VOP MPEG-4 /// </summary> S = 4, /// <summary> /// Switching Intra /// </summary> Si = 5, /// <summary> /// Switching Predicted /// </summary> Sp = 6, /// <summary> /// BI type /// </summary> Bi = 7, } /// <summary> /// Pixel format. /// </summary> public enum AVPixelFormat : int { None = -1, /// <summary> /// planar YUV 4:2:0, 12bpp, (1 Cr &amp; Cb sample per 2x2 Y samples) /// </summary> Yuv420p = 0, /// <summary> /// packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr /// </summary> Yuyv422 = 1, /// <summary> /// packed RGB 8:8:8, 24bpp, RGBRGB... /// </summary> Rgb24 = 2, /// <summary> /// packed RGB 8:8:8, 24bpp, BGRBGR... /// </summary> Bgr24 = 3, /// <summary> /// planar YUV 4:2:2, 16bpp, (1 Cr &amp; Cb sample per 2x1 Y samples) /// </summary> Yuv422p = 4, /// <summary> /// planar YUV 4:4:4, 24bpp, (1 Cr &amp; Cb sample per 1x1 Y samples) /// </summary> Yuv444p = 5, /// <summary> /// planar YUV 4:1:0, 9bpp, (1 Cr &amp; Cb sample per 4x4 Y samples) /// </summary> Yuv410p = 6, /// <summary> /// planar YUV 4:1:1, 12bpp, (1 Cr &amp; Cb sample per 4x1 Y samples) /// </summary> Yuv411p = 7, /// <summary> /// Y , 8bpp /// </summary> Gray8 = 8, /// <summary> /// Y , 1bpp, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb /// </summary> Monowhite = 9, /// <summary> /// Y , 1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb /// </summary> Monoblack = 10, /// <summary> /// 8 bits with AV_PIX_FMT_RGB32 palette /// </summary> Pal8 = 11, /// <summary> /// planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV420P and setting color_range /// </summary> Yuvj420p = 12, /// <summary> /// planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV422P and setting color_range /// </summary> Yuvj422p = 13, /// <summary> /// planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV444P and setting color_range /// </summary> Yuvj444p = 14, /// <summary> /// packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1 /// </summary> Uyvy422 = 15, /// <summary> /// packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3 /// </summary> Uyyvyy411 = 16, /// <summary> /// packed RGB 3:3:2, 8bpp, (msb)2B 3G 3R(lsb) /// </summary> Bgr8 = 17, /// <summary> /// packed RGB 1:2:1 bitstream, 4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits /// </summary> Bgr4 = 18, /// <summary> /// packed RGB 1:2:1, 8bpp, (msb)1B 2G 1R(lsb) /// </summary> Bgr4Byte = 19, /// <summary> /// packed RGB 3:3:2, 8bpp, (msb)2R 3G 3B(lsb) /// </summary> Rgb8 = 20, /// <summary> /// packed RGB 1:2:1 bitstream, 4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits /// </summary> Rgb4 = 21, /// <summary> /// packed RGB 1:2:1, 8bpp, (msb)1R 2G 1B(lsb) /// </summary> Rgb4Byte = 22, /// <summary> /// planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V) /// </summary> Nv12 = 23, /// <summary> /// as above, but U and V bytes are swapped /// </summary> Nv21 = 24, /// <summary> /// packed ARGB 8:8:8:8, 32bpp, ARGBARGB... /// </summary> Argb = 25, /// <summary> /// packed RGBA 8:8:8:8, 32bpp, RGBARGBA... /// </summary> Rgba = 26, /// <summary> /// packed ABGR 8:8:8:8, 32bpp, ABGRABGR... /// </summary> Abgr = 27, /// <summary> /// packed BGRA 8:8:8:8, 32bpp, BGRABGRA... /// </summary> Bgra = 28, /// <summary> /// Y , 16bpp, big-endian /// </summary> Gray16be = 29, /// <summary> /// Y , 16bpp, little-endian /// </summary> Gray16le = 30, /// <summary> /// planar YUV 4:4:0 (1 Cr &amp; Cb sample per 1x2 Y samples) /// </summary> Yuv440p = 31, /// <summary> /// planar YUV 4:4:0 full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV440P and setting color_range /// </summary> Yuvj440p = 32, /// <summary> /// planar YUV 4:2:0, 20bpp, (1 Cr &amp; Cb sample per 2x2 Y &amp; A samples) /// </summary> Yuva420p = 33, /// <summary> /// packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian /// </summary> Rgb48be = 34, /// <summary> /// packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian /// </summary> Rgb48le = 35, /// <summary> /// packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), big-endian /// </summary> Rgb565be = 36, /// <summary> /// packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), little-endian /// </summary> Rgb565le = 37, /// <summary> /// packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), big-endian , X=unused/undefined /// </summary> Rgb555be = 38, /// <summary> /// packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), little-endian, X=unused/undefined /// </summary> Rgb555le = 39, /// <summary> /// packed BGR 5:6:5, 16bpp, (msb) 5B 6G 5R(lsb), big-endian /// </summary> Bgr565be = 40, /// <summary> /// packed BGR 5:6:5, 16bpp, (msb) 5B 6G 5R(lsb), little-endian /// </summary> Bgr565le = 41, /// <summary> /// packed BGR 5:5:5, 16bpp, (msb)1X 5B 5G 5R(lsb), big-endian , X=unused/undefined /// </summary> Bgr555be = 42, /// <summary> /// packed BGR 5:5:5, 16bpp, (msb)1X 5B 5G 5R(lsb), little-endian, X=unused/undefined /// </summary> Bgr555le = 43, /// <summary> /// HW acceleration through VA API at motion compensation entry-point, Picture.data[3] contains a vaapi_render_state struct which contains macroblocks as well as various fields extracted from headers /// </summary> VaapiMoco = 44, /// <summary> /// HW acceleration through VA API at IDCT entry-point, Picture.data[3] contains a vaapi_render_state struct which contains fields extracted from headers /// </summary> VaapiIdct = 45, /// <summary> /// HW decoding through VA API, Picture.data[3] contains a VASurfaceID /// </summary> VaapiVld = 46, /// <summary> /// @} /// </summary> Vaapi = 46, /// <summary> /// planar YUV 4:2:0, 24bpp, (1 Cr &amp; Cb sample per 2x2 Y samples), little-endian /// </summary> Yuv420p16le = 47, /// <summary> /// planar YUV 4:2:0, 24bpp, (1 Cr &amp; Cb sample per 2x2 Y samples), big-endian /// </summary> Yuv420p16be = 48, /// <summary> /// planar YUV 4:2:2, 32bpp, (1 Cr &amp; Cb sample per 2x1 Y samples), little-endian /// </summary> Yuv422p16le = 49, /// <summary> /// planar YUV 4:2:2, 32bpp, (1 Cr &amp; Cb sample per 2x1 Y samples), big-endian /// </summary> Yuv422p16be = 50, /// <summary> /// planar YUV 4:4:4, 48bpp, (1 Cr &amp; Cb sample per 1x1 Y samples), little-endian /// </summary> Yuv444p16le = 51, /// <summary> /// planar YUV 4:4:4, 48bpp, (1 Cr &amp; Cb sample per 1x1 Y samples), big-endian /// </summary> Yuv444p16be = 52, /// <summary> /// HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer /// </summary> Dxva2Vld = 53, /// <summary> /// packed RGB 4:4:4, 16bpp, (msb)4X 4R 4G 4B(lsb), little-endian, X=unused/undefined /// </summary> Rgb444le = 54, /// <summary> /// packed RGB 4:4:4, 16bpp, (msb)4X 4R 4G 4B(lsb), big-endian, X=unused/undefined /// </summary> Rgb444be = 55, /// <summary> /// packed BGR 4:4:4, 16bpp, (msb)4X 4B 4G 4R(lsb), little-endian, X=unused/undefined /// </summary> Bgr444le = 56, /// <summary> /// packed BGR 4:4:4, 16bpp, (msb)4X 4B 4G 4R(lsb), big-endian, X=unused/undefined /// </summary> Bgr444be = 57, /// <summary> /// 8 bits gray, 8 bits alpha /// </summary> Ya8 = 58, /// <summary> /// alias for AV_PIX_FMT_YA8 /// </summary> Y400a = 58, /// <summary> /// alias for AV_PIX_FMT_YA8 /// </summary> Gray8a = 58, /// <summary> /// packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as big-endian /// </summary> Bgr48be = 59, /// <summary> /// packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as little-endian /// </summary> Bgr48le = 60, /// <summary> /// planar YUV 4:2:0, 13.5bpp, (1 Cr &amp; Cb sample per 2x2 Y samples), big-endian /// </summary> Yuv420p9be = 61, /// <summary> /// planar YUV 4:2:0, 13.5bpp, (1 Cr &amp; Cb sample per 2x2 Y samples), little-endian /// </summary> Yuv420p9le = 62, /// <summary> /// planar YUV 4:2:0, 15bpp, (1 Cr &amp; Cb sample per 2x2 Y samples), big-endian /// </summary> Yuv420p10be = 63, /// <summary> /// planar YUV 4:2:0, 15bpp, (1 Cr &amp; Cb sample per 2x2 Y samples), little-endian /// </summary> Yuv420p10le = 64, /// <summary> /// planar YUV 4:2:2, 20bpp, (1 Cr &amp; Cb sample per 2x1 Y samples), big-endian /// </summary> Yuv422p10be = 65, /// <summary> /// planar YUV 4:2:2, 20bpp, (1 Cr &amp; Cb sample per 2x1 Y samples), little-endian /// </summary> Yuv422p10le = 66, /// <summary> /// planar YUV 4:4:4, 27bpp, (1 Cr &amp; Cb sample per 1x1 Y samples), big-endian /// </summary> Yuv444p9be = 67, /// <summary> /// planar YUV 4:4:4, 27bpp, (1 Cr &amp; Cb sample per 1x1 Y samples), little-endian /// </summary> Yuv444p9le = 68, /// <summary> /// planar YUV 4:4:4, 30bpp, (1 Cr &amp; Cb sample per 1x1 Y samples), big-endian /// </summary> Yuv444p10be = 69, /// <summary> /// planar YUV 4:4:4, 30bpp, (1 Cr &amp; Cb sample per 1x1 Y samples), little-endian /// </summary> Yuv444p10le = 70, /// <summary> /// planar YUV 4:2:2, 18bpp, (1 Cr &amp; Cb sample per 2x1 Y samples), big-endian /// </summary> Yuv422p9be = 71, /// <summary> /// planar YUV 4:2:2, 18bpp, (1 Cr &amp; Cb sample per 2x1 Y samples), little-endian /// </summary> Yuv422p9le = 72, /// <summary> /// planar GBR 4:4:4 24bpp /// </summary> Gbrp = 73, Gbr24p = 73, /// <summary> /// planar GBR 4:4:4 27bpp, big-endian /// </summary> Gbrp9be = 74, /// <summary> /// planar GBR 4:4:4 27bpp, little-endian /// </summary> Gbrp9le = 75, /// <summary> /// planar GBR 4:4:4 30bpp, big-endian /// </summary> Gbrp10be = 76, /// <summary> /// planar GBR 4:4:4 30bpp, little-endian /// </summary> Gbrp10le = 77, /// <summary> /// planar GBR 4:4:4 48bpp, big-endian /// </summary> Gbrp16be = 78, /// <summary> /// planar GBR 4:4:4 48bpp, little-endian /// </summary> Gbrp16le = 79, /// <summary> /// planar YUV 4:2:2 24bpp, (1 Cr &amp; Cb sample per 2x1 Y &amp; A samples) /// </summary> Yuva422p = 80, /// <summary> /// planar YUV 4:4:4 32bpp, (1 Cr &amp; Cb sample per 1x1 Y &amp; A samples) /// </summary> Yuva444p = 81, /// <summary> /// planar YUV 4:2:0 22.5bpp, (1 Cr &amp; Cb sample per 2x2 Y &amp; A samples), big-endian /// </summary> Yuva420p9be = 82, /// <summary> /// planar YUV 4:2:0 22.5bpp, (1 Cr &amp; Cb sample per 2x2 Y &amp; A samples), little-endian /// </summary> Yuva420p9le = 83, /// <summary> /// planar YUV 4:2:2 27bpp, (1 Cr &amp; Cb sample per 2x1 Y &amp; A samples), big-endian /// </summary> Yuva422p9be = 84, /// <summary> /// planar YUV 4:2:2 27bpp, (1 Cr &amp; Cb sample per 2x1 Y &amp; A samples), little-endian /// </summary> Yuva422p9le = 85, /// <summary> /// planar YUV 4:4:4 36bpp, (1 Cr &amp; Cb sample per 1x1 Y &amp; A samples), big-endian /// </summary> Yuva444p9be = 86, /// <summary> /// planar YUV 4:4:4 36bpp, (1 Cr &amp; Cb sample per 1x1 Y &amp; A samples), little-endian /// </summary> Yuva444p9le = 87, /// <summary> /// planar YUV 4:2:0 25bpp, (1 Cr &amp; Cb sample per 2x2 Y &amp; A samples, big-endian) /// </summary> Yuva420p10be = 88, /// <summary> /// planar YUV 4:2:0 25bpp, (1 Cr &amp; Cb sample per 2x2 Y &amp; A samples, little-endian) /// </summary> Yuva420p10le = 89, /// <summary> /// planar YUV 4:2:2 30bpp, (1 Cr &amp; Cb sample per 2x1 Y &amp; A samples, big-endian) /// </summary> Yuva422p10be = 90, /// <summary> /// planar YUV 4:2:2 30bpp, (1 Cr &amp; Cb sample per 2x1 Y &amp; A samples, little-endian) /// </summary> Yuva422p10le = 91, /// <summary> /// planar YUV 4:4:4 40bpp, (1 Cr &amp; Cb sample per 1x1 Y &amp; A samples, big-endian) /// </summary> Yuva444p10be = 92, /// <summary> /// planar YUV 4:4:4 40bpp, (1 Cr &amp; Cb sample per 1x1 Y &amp; A samples, little-endian) /// </summary> Yuva444p10le = 93, /// <summary> /// planar YUV 4:2:0 40bpp, (1 Cr &amp; Cb sample per 2x2 Y &amp; A samples, big-endian) /// </summary> Yuva420p16be = 94, /// <summary> /// planar YUV 4:2:0 40bpp, (1 Cr &amp; Cb sample per 2x2 Y &amp; A samples, little-endian) /// </summary> Yuva420p16le = 95, /// <summary> /// planar YUV 4:2:2 48bpp, (1 Cr &amp; Cb sample per 2x1 Y &amp; A samples, big-endian) /// </summary> Yuva422p16be = 96, /// <summary> /// planar YUV 4:2:2 48bpp, (1 Cr &amp; Cb sample per 2x1 Y &amp; A samples, little-endian) /// </summary> Yuva422p16le = 97, /// <summary> /// planar YUV 4:4:4 64bpp, (1 Cr &amp; Cb sample per 1x1 Y &amp; A samples, big-endian) /// </summary> Yuva444p16be = 98, /// <summary> /// planar YUV 4:4:4 64bpp, (1 Cr &amp; Cb sample per 1x1 Y &amp; A samples, little-endian) /// </summary> Yuva444p16le = 99, /// <summary> /// HW acceleration through VDPAU, Picture.data[3] contains a VdpVideoSurface /// </summary> Vdpau = 100, /// <summary> /// packed XYZ 4:4:4, 36 bpp, (msb) 12X, 12Y, 12Z (lsb), the 2-byte value for each X/Y/Z is stored as little-endian, the 4 lower bits are set to 0 /// </summary> Xyz12le = 101, /// <summary> /// packed XYZ 4:4:4, 36 bpp, (msb) 12X, 12Y, 12Z (lsb), the 2-byte value for each X/Y/Z is stored as big-endian, the 4 lower bits are set to 0 /// </summary> Xyz12be = 102, /// <summary> /// interleaved chroma YUV 4:2:2, 16bpp, (1 Cr &amp; Cb sample per 2x1 Y samples) /// </summary> Nv16 = 103, /// <summary> /// interleaved chroma YUV 4:2:2, 20bpp, (1 Cr &amp; Cb sample per 2x1 Y samples), little-endian /// </summary> Nv20le = 104, /// <summary> /// interleaved chroma YUV 4:2:2, 20bpp, (1 Cr &amp; Cb sample per 2x1 Y samples), big-endian /// </summary> Nv20be = 105, /// <summary> /// packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian /// </summary> Rgba64be = 106, /// <summary> /// packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian /// </summary> Rgba64le = 107, /// <summary> /// packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian /// </summary> Bgra64be = 108, /// <summary> /// packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian /// </summary> Bgra64le = 109, /// <summary> /// packed YUV 4:2:2, 16bpp, Y0 Cr Y1 Cb /// </summary> Yvyu422 = 110, /// <summary> /// 16 bits gray, 16 bits alpha (big-endian) /// </summary> Ya16be = 111, /// <summary> /// 16 bits gray, 16 bits alpha (little-endian) /// </summary> Ya16le = 112, /// <summary> /// planar GBRA 4:4:4:4 32bpp /// </summary> Gbrap = 113, /// <summary> /// planar GBRA 4:4:4:4 64bpp, big-endian /// </summary> Gbrap16be = 114, /// <summary> /// planar GBRA 4:4:4:4 64bpp, little-endian /// </summary> Gbrap16le = 115, /// <summary> /// HW acceleration through QSV, data[3] contains a pointer to the mfxFrameSurface1 structure. /// </summary> Qsv = 116, /// <summary> /// HW acceleration though MMAL, data[3] contains a pointer to the MMAL_BUFFER_HEADER_T structure. /// </summary> Mmal = 117, /// <summary> /// HW decoding through Direct3D11 via old API, Picture.data[3] contains a ID3D11VideoDecoderOutputView pointer /// </summary> D3d11vaVld = 118, /// <summary> /// HW acceleration through CUDA. data[i] contain CUdeviceptr pointers exactly as for system memory frames. /// </summary> Cuda = 119, /// <summary> /// packed RGB 8:8:8, 32bpp, XRGBXRGB... X=unused/undefined /// </summary> _0RGB = 120, /// <summary> /// packed RGB 8:8:8, 32bpp, RGBXRGBX... X=unused/undefined /// </summary> Rgb0 = 121, /// <summary> /// packed BGR 8:8:8, 32bpp, XBGRXBGR... X=unused/undefined /// </summary> _0BGR = 122, /// <summary> /// packed BGR 8:8:8, 32bpp, BGRXBGRX... X=unused/undefined /// </summary> Bgr0 = 123, /// <summary> /// planar YUV 4:2:0,18bpp, (1 Cr &amp; Cb sample per 2x2 Y samples), big-endian /// </summary> Yuv420p12be = 124, /// <summary> /// planar YUV 4:2:0,18bpp, (1 Cr &amp; Cb sample per 2x2 Y samples), little-endian /// </summary> Yuv420p12le = 125, /// <summary> /// planar YUV 4:2:0,21bpp, (1 Cr &amp; Cb sample per 2x2 Y samples), big-endian /// </summary> Yuv420p14be = 126, /// <summary> /// planar YUV 4:2:0,21bpp, (1 Cr &amp; Cb sample per 2x2 Y samples), little-endian /// </summary> Yuv420p14le = 127, /// <summary> /// planar YUV 4:2:2,24bpp, (1 Cr &amp; Cb sample per 2x1 Y samples), big-endian /// </summary> Yuv422p12be = 128, /// <summary> /// planar YUV 4:2:2,24bpp, (1 Cr &amp; Cb sample per 2x1 Y samples), little-endian /// </summary> Yuv422p12le = 129, /// <summary> /// planar YUV 4:2:2,28bpp, (1 Cr &amp; Cb sample per 2x1 Y samples), big-endian /// </summary> Yuv422p14be = 130, /// <summary> /// planar YUV 4:2:2,28bpp, (1 Cr &amp; Cb sample per 2x1 Y samples), little-endian /// </summary> Yuv422p14le = 131, /// <summary> /// planar YUV 4:4:4,36bpp, (1 Cr &amp; Cb sample per 1x1 Y samples), big-endian /// </summary> Yuv444p12be = 132, /// <summary> /// planar YUV 4:4:4,36bpp, (1 Cr &amp; Cb sample per 1x1 Y samples), little-endian /// </summary> Yuv444p12le = 133, /// <summary> /// planar YUV 4:4:4,42bpp, (1 Cr &amp; Cb sample per 1x1 Y samples), big-endian /// </summary> Yuv444p14be = 134, /// <summary> /// planar YUV 4:4:4,42bpp, (1 Cr &amp; Cb sample per 1x1 Y samples), little-endian /// </summary> Yuv444p14le = 135, /// <summary> /// planar GBR 4:4:4 36bpp, big-endian /// </summary> Gbrp12be = 136, /// <summary> /// planar GBR 4:4:4 36bpp, little-endian /// </summary> Gbrp12le = 137, /// <summary> /// planar GBR 4:4:4 42bpp, big-endian /// </summary> Gbrp14be = 138, /// <summary> /// planar GBR 4:4:4 42bpp, little-endian /// </summary> Gbrp14le = 139, /// <summary> /// planar YUV 4:1:1, 12bpp, (1 Cr &amp; Cb sample per 4x1 Y samples) full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV411P and setting color_range /// </summary> Yuvj411p = 140, /// <summary> /// bayer, BGBG..(odd line), GRGR..(even line), 8-bit samples */ /// </summary> BayerBggr8 = 141, /// <summary> /// bayer, RGRG..(odd line), GBGB..(even line), 8-bit samples */ /// </summary> BayerRggb8 = 142, /// <summary> /// bayer, GBGB..(odd line), RGRG..(even line), 8-bit samples */ /// </summary> BayerGbrg8 = 143, /// <summary> /// bayer, GRGR..(odd line), BGBG..(even line), 8-bit samples */ /// </summary> BayerGrbg8 = 144, /// <summary> /// bayer, BGBG..(odd line), GRGR..(even line), 16-bit samples, little-endian */ /// </summary> BayerBggr16le = 145, /// <summary> /// bayer, BGBG..(odd line), GRGR..(even line), 16-bit samples, big-endian */ /// </summary> BayerBggr16be = 146, /// <summary> /// bayer, RGRG..(odd line), GBGB..(even line), 16-bit samples, little-endian */ /// </summary> BayerRggb16le = 147, /// <summary> /// bayer, RGRG..(odd line), GBGB..(even line), 16-bit samples, big-endian */ /// </summary> BayerRggb16be = 148, /// <summary> /// bayer, GBGB..(odd line), RGRG..(even line), 16-bit samples, little-endian */ /// </summary> BayerGbrg16le = 149, /// <summary> /// bayer, GBGB..(odd line), RGRG..(even line), 16-bit samples, big-endian */ /// </summary> BayerGbrg16be = 150, /// <summary> /// bayer, GRGR..(odd line), BGBG..(even line), 16-bit samples, little-endian */ /// </summary> BayerGrbg16le = 151, /// <summary> /// bayer, GRGR..(odd line), BGBG..(even line), 16-bit samples, big-endian */ /// </summary> BayerGrbg16be = 152, /// <summary> /// XVideo Motion Acceleration via common packet passing /// </summary> Xvmc = 153, /// <summary> /// planar YUV 4:4:0,20bpp, (1 Cr &amp; Cb sample per 1x2 Y samples), little-endian /// </summary> Yuv440p10le = 154, /// <summary> /// planar YUV 4:4:0,20bpp, (1 Cr &amp; Cb sample per 1x2 Y samples), big-endian /// </summary> Yuv440p10be = 155, /// <summary> /// planar YUV 4:4:0,24bpp, (1 Cr &amp; Cb sample per 1x2 Y samples), little-endian /// </summary> Yuv440p12le = 156, /// <summary> /// planar YUV 4:4:0,24bpp, (1 Cr &amp; Cb sample per 1x2 Y samples), big-endian /// </summary> Yuv440p12be = 157, /// <summary> /// packed AYUV 4:4:4,64bpp (1 Cr &amp; Cb sample per 1x1 Y &amp; A samples), little-endian /// </summary> Ayuv64le = 158, /// <summary> /// packed AYUV 4:4:4,64bpp (1 Cr &amp; Cb sample per 1x1 Y &amp; A samples), big-endian /// </summary> Ayuv64be = 159, /// <summary> /// hardware decoding through Videotoolbox /// </summary> Videotoolbox = 160, /// <summary> /// like NV12, with 10bpp per component, data in the high bits, zeros in the low bits, little-endian /// </summary> P010le = 161, /// <summary> /// like NV12, with 10bpp per component, data in the high bits, zeros in the low bits, big-endian /// </summary> P010be = 162, /// <summary> /// planar GBR 4:4:4:4 48bpp, big-endian /// </summary> Gbrap12be = 163, /// <summary> /// planar GBR 4:4:4:4 48bpp, little-endian /// </summary> Gbrap12le = 164, /// <summary> /// planar GBR 4:4:4:4 40bpp, big-endian /// </summary> Gbrap10be = 165, /// <summary> /// planar GBR 4:4:4:4 40bpp, little-endian /// </summary> Gbrap10le = 166, /// <summary> /// hardware decoding through MediaCodec /// </summary> Mediacodec = 167, /// <summary> /// Y , 12bpp, big-endian /// </summary> Gray12be = 168, /// <summary> /// Y , 12bpp, little-endian /// </summary> Gray12le = 169, /// <summary> /// Y , 10bpp, big-endian /// </summary> Gray10be = 170, /// <summary> /// Y , 10bpp, little-endian /// </summary> Gray10le = 171, /// <summary> /// like NV12, with 16bpp per component, little-endian /// </summary> P016le = 172, /// <summary> /// like NV12, with 16bpp per component, big-endian /// </summary> P016be = 173, /// <summary> /// Hardware surfaces for Direct3D11. /// </summary> D3d11 = 174, /// <summary> /// Y , 9bpp, big-endian /// </summary> Gray9be = 175, /// <summary> /// Y , 9bpp, little-endian /// </summary> Gray9le = 176, /// <summary> /// IEEE-754 single precision planar GBR 4:4:4, 96bpp, big-endian /// </summary> Gbrpf32be = 177, /// <summary> /// IEEE-754 single precision planar GBR 4:4:4, 96bpp, little-endian /// </summary> Gbrpf32le = 178, /// <summary> /// IEEE-754 single precision planar GBRA 4:4:4:4, 128bpp, big-endian /// </summary> Gbrapf32be = 179, /// <summary> /// IEEE-754 single precision planar GBRA 4:4:4:4, 128bpp, little-endian /// </summary> Gbrapf32le = 180, /// <summary> /// DRM-managed buffers exposed through PRIME buffer sharing. /// </summary> DrmPrime = 181, /// <summary> /// Hardware surfaces for OpenCL. /// </summary> Opencl = 182, /// <summary> /// Y , 14bpp, big-endian /// </summary> Gray14be = 183, /// <summary> /// Y , 14bpp, little-endian /// </summary> Gray14le = 184, /// <summary> /// IEEE-754 single precision Y, 32bpp, big-endian /// </summary> Grayf32be = 185, /// <summary> /// IEEE-754 single precision Y, 32bpp, little-endian /// </summary> Grayf32le = 186, /// <summary> /// number of pixel formats, DO NOT USE THIS if you want to link with shared libav* because the number of formats might differ between versions /// </summary> Nb = 187, } public enum AVPixFmtFlag : int { Alpha = 0x1 << 0x7, Bayer = 0x1 << 0x8, Be = 0x1 << 0x0, Bitstream = 0x1 << 0x2, Float = 0x1 << 0x9, Hwaccel = 0x1 << 0x3, Pal = 0x1 << 0x1, Planar = 0x1 << 0x4, Pseudopal = 0x1 << 0x6, Rgb = 0x1 << 0x5, } public enum AVPktFlag : int { Corrupt = 0x2, Discard = 0x4, Disposable = 0x10, Key = 0x1, Trusted = 0x8, } public enum AVProbe : int { ScoreStreamRetry = ScoreMax / 0x4 - 0x1, ScoreRetry = ScoreMax / 0x4, ScoreMime = 0x4b, ScoreMax = 0x64, ScoreExtension = 0x32, PaddingSize = 0x20, } public enum AVPtsWrap : int { SubOffset = -0x1, Ignore = 0x0, AddOffset = 0x1, } /// <summary> /// Rounding methods. /// </summary> public enum AVRounding : int { /// <summary> /// Round toward zero. /// </summary> Zero = 0, /// <summary> /// Round away from zero. /// </summary> Inf = 1, /// <summary> /// Round toward -infinity. /// </summary> Down = 2, /// <summary> /// Round toward +infinity. /// </summary> Up = 3, /// <summary> /// Round to nearest and halfway cases away from zero. /// </summary> NearInf = 5, /// <summary> /// Flag telling rescaling functions to pass `INT64_MIN`/`MAX` through unchanged, avoiding special cases for #AV_NOPTS_VALUE. /// </summary> PassMinmax = 8192, } /// <summary> /// Audio sample formats /// </summary> public enum AVSampleFormat : int { None = -1, UInt8, Int16, Int32, Float, Double, UInt8Planar, Int16Planar, Int32Planar, FloatPlanar, DoublePlanar, Int64, Int64Planar, Count, } public enum AVSeek : int { Force = 0x20000, Size = 0x10000, } public enum AVSeekFlag : int { Frame = 0x8, Byte = 0x2, Backward = 0x1, Any = 0x4, } public enum AVSideDataParamChangeFlags : int { ChannelCount = 1, ChannelLayout = 2, SampleRate = 4, Dimensions = 8, } /// <summary> /// @} /// </summary> public enum AVStreamParseType : int { None = 0, /// <summary> /// full parsing and repack /// </summary> Full = 1, /// <summary> /// Only parse headers, do not repack. /// </summary> Headers = 2, /// <summary> /// full parsing and interpolation of timestamps for frames not starting on a packet boundary /// </summary> Timestamps = 3, /// <summary> /// full parsing and repack of the first frame only, only implemented for H.264 currently /// </summary> FullOnce = 4, /// <summary> /// full parsing and repack with timestamp and position generation by parser for raw this assumes that each packet in the file contains no demuxer level headers and just codec level data, otherwise position generation would fail /// </summary> FullRaw = 5, } public enum AVSubtitleType : int { None = 0, /// <summary> /// A bitmap, pict will be set /// </summary> Bitmap = 1, /// <summary> /// Plain text, the text field must be set by the decoder and is authoritative. ass and pict fields may contain approximations. /// </summary> Text = 2, /// <summary> /// Formatted text, the ass field must be set by the decoder and is authoritative. pict and text fields may contain approximations. /// </summary> Ass = 3, } public enum AVTimebaseSource : int { Auto = -1, Decoder = 0, Demuxer = 1, RFramerate = 2, } public enum AVTimecodeFlag : int { /// <summary> /// timecode is drop frame /// </summary> Dropframe = 1, /// <summary> /// timecode wraps after 24 hours /// </summary> _24HOURSMAX = 2, /// <summary> /// negative time values are allowed /// </summary> Allownegative = 4, } public enum FFBug : uint { Amv = 0x20, Autodetect = 0x1, DcClip = 0x1000, DirectBlocksize = 0x200, Edge = 0x400, HpelChroma = 0x800, Iedge = 0x8000, Ms = 0x2000, NoPadding = 0x10, QpelChroma = 0x40, QpelChroma2 = 0x100, StdQpel = 0x80, Truncated = 0x4000, Ump4 = 0x8, XvidIlace = 0x4, } public enum FFCmp : uint { Bit = 0x5, Chroma = 0x100, Dct = 0x3, Dct264 = 0xe, Dctmax = 0xd, MedianSad = 0xf, Nsse = 0xa, Psnr = 0x4, Rd = 0x6, Sad = 0x0, Satd = 0x2, Sse = 0x1, Vsad = 0x8, Vsse = 0x9, W53 = 0xb, W97 = 0xc, Zero = 0x7, } public enum FFCodecProperty : int { ClosedCaptions = 0x2, Lossless = 0x1, } public enum FFCoderType : int { Ac = 0x1, Raw = 0x2, Rle = 0x3, Vlc = 0x0, } public enum FFCompliance : int { Experimental = -0x2, Normal = 0x0, Strict = 0x1, Unofficial = -0x1, VeryStrict = 0x2, } public enum FFDct : int { Altivec = 0x5, Auto = 0x0, Faan = 0x6, Fastint = 0x1, Int = 0x2, Mmx = 0x3, } public enum FFDebug : uint { Bitstream = 0x4, Buffers = 0x8000, Bugs = 0x1000, DctCoeff = 0x40, Er = 0x400, GreenMd = 0x800000, MbType = 0x8, Mmco = 0x800, Nomc = 0x1000000, PictInfo = 0x1, Qp = 0x10, Rc = 0x2, Skip = 0x80, Startcode = 0x100, Threads = 0x10000, VisMvBBack = 0x4, VisMvBFor = 0x2, VisMvPFor = 0x1, } public enum FFDecodeError : int { MissingReference = 0x2, InvalidBitstream = 0x1, } public enum FFDxva2Workaround : int { ScalingListZigzag = 0x1, IntelClearvideo = 0x2, } public enum FFEc : int { Deblock = 0x2, FavorInter = 0x100, GuessMvs = 0x1, } public enum FFIdct : uint { Altivec = 0x8, Arm = 0x7, Auto = 0x0, Faan = 0x14, Int = 0x1, None = 0x18, Simple = 0x2, Simplearm = 0xa, Simplearmv5te = 0x10, Simplearmv6 = 0x11, Simpleauto = 0x80, Simplemmx = 0x3, Simpleneon = 0x16, Xvid = 0xe, } public enum FFLoss : int { Alpha = 0x8, Chroma = 0x20, Colorquant = 0x10, Colorspace = 0x4, Depth = 0x2, Resolution = 0x1, } public enum FFMbDecision : int { Bits = 0x1, Rd = 0x2, Simple = 0x0, } public enum FFPred : int { Left = 0x0, Median = 0x2, Plane = 0x1, } public enum FFProfile : int { AacEld = 0x26, AacHe = 0x4, AacHeV2 = 0x1c, AacLd = 0x16, AacLow = 0x1, AacLtp = 0x3, AacMain = 0x0, AacSsr = 0x2, Av_1High = 0x1, Av_1Main = 0x0, Av_1Professional = 0x2, Dnxhd = 0x0, Dnxhr_444 = 0x5, DnxhrHq = 0x3, DnxhrHqx = 0x4, DnxhrLb = 0x1, DnxhrSq = 0x2, Dts = 0x14, Dts_96_24 = 0x28, DtsEs = 0x1e, DtsExpress = 0x46, DtsHdHra = 0x32, DtsHdMa = 0x3c, H264Baseline = 0x42, H264Cavlc_444 = 0x2c, H264Constrained = 0x1 << 0x9, H264ConstrainedBaseline = 0x42 | H264Constrained, H264Extended = 0x58, H264High = 0x64, H264High_10 = 0x6e, H264High_10Intra = 0x6e | H264Intra, H264High_422 = 0x7a, H264High_422Intra = 0x7a | H264Intra, H264High_444 = 0x90, H264High_444Intra = 0xf4 | H264Intra, H264High_444Predictive = 0xf4, H264Intra = 0x1 << 0xb, H264Main = 0x4d, H264MultiviewHigh = 0x76, H264StereoHigh = 0x80, HevcMain = 0x1, HevcMain_10 = 0x2, HevcMainStillPicture = 0x3, HevcRext = 0x4, Jpeg2000CstreamNoRestriction = 0x8000, Jpeg2000CstreamRestriction_0 = 0x1, Jpeg2000CstreamRestriction_1 = 0x2, Jpeg2000Dcinema_2k = 0x3, Jpeg2000Dcinema_4k = 0x4, MjpegHuffmanBaselineDct = 0xc0, MjpegHuffmanExtendedSequentialDct = 0xc1, MjpegHuffmanLossless = 0xc3, MjpegHuffmanProgressiveDct = 0xc2, MjpegJpegLs = 0xf7, Mpeg2_422 = 0x0, Mpeg2AacHe = 0x83, Mpeg2AacLow = 0x80, Mpeg2High = 0x1, Mpeg2Main = 0x4, Mpeg2Simple = 0x5, Mpeg2SnrScalable = 0x3, Mpeg2Ss = 0x2, Mpeg4AdvancedCoding = 0xb, Mpeg4AdvancedCore = 0xc, Mpeg4AdvancedRealTime = 0x9, Mpeg4AdvancedScalableTexture = 0xd, Mpeg4AdvancedSimple = 0xf, Mpeg4BasicAnimatedTexture = 0x7, Mpeg4Core = 0x2, Mpeg4CoreScalable = 0xa, Mpeg4Hybrid = 0x8, Mpeg4Main = 0x3, Mpeg4NBit = 0x4, Mpeg4ScalableTexture = 0x5, Mpeg4Simple = 0x0, Mpeg4SimpleFaceAnimation = 0x6, Mpeg4SimpleScalable = 0x1, Mpeg4SimpleStudio = 0xe, Reserved = -0x64, SbcMsbc = 0x1, Unknown = -0x63, Vc1Advanced = 0x3, Vc1Complex = 0x2, Vc1Main = 0x1, Vc1Simple = 0x0, Vp9_0 = 0x0, Vp9_1 = 0x1, Vp9_2 = 0x2, Vp9_3 = 0x3, } public enum FFSub : int { CharencModeAutomatic = 0x0, CharencModeDoNothing = -0x1, CharencModeIgnore = 0x2, CharencModePreDecoder = 0x1, TextFmtAss = 0x0, TextFmtAssWithTimings = 0x1, } public enum FFThread : int { Frame = 0x1, Slice = 0x2, } public enum Max : int { StdTimebases = 0x1e * 0xc + 0x1e + 0x3 + 0x6, ReorderDelay = 0x10, } public enum ParserFlag : int { CompleteFrames = 0x1, FetchedOffset = 0x4, Once = 0x2, UseCodecTs = 0x1000, } public enum SliceFlag : int { AllowField = 0x2, AllowPlane = 0x4, CodedOrder = 0x1, } /// <summary> /// Dithering algorithms /// </summary> public enum SwrDitherType : int { None = 0, Rectangular = 1, Triangular = 2, TriangularHighpass = 3, /// <summary> /// not part of API/ABI /// </summary> Ns = 64, NsLipshitz = 65, NsFWeighted = 66, NsModifiedEWeighted = 67, NsImprovedEWeighted = 68, NsShibata = 69, NsLowShibata = 70, NsHighShibata = 71, /// <summary> /// not part of API/ABI /// </summary> Nb = 72, } /// <summary> /// Resampling Engines /// </summary> public enum SwrEngine : int { /// <summary> /// SW Resampler /// </summary> Swr = 0, /// <summary> /// SoX Resampler /// </summary> Soxr = 1, /// <summary> /// not part of API/ABI /// </summary> Nb = 2, } /// <summary> /// Resampling Filter Types /// </summary> public enum SwrFilterType : int { /// <summary> /// Cubic /// </summary> Cubic = 0, /// <summary> /// Blackman Nuttall windowed sinc /// </summary> BlackmanNuttall = 1, /// <summary> /// Kaiser windowed sinc /// </summary> Kaiser = 2, } [Flags] public enum SwsFlags : int { AccurateRnd = 0x40000, Area = 0x20, Bicubic = 0x4, Bicublin = 0x40, Bilinear = 0x2, Bitexact = 0x80000, CsBt2020 = 0x9, CsDefault = 0x5, CsFcc = 0x4, CsItu601 = 0x5, CsItu624 = 0x5, CsItu709 = 0x1, CsSmpte170m = 0x5, CsSmpte240m = 0x7, DirectBgr = 0x8000, ErrorDiffusion = 0x800000, FastBilinear = 0x1, FullChrHInp = 0x4000, FullChrHInt = 0x2000, Gauss = 0x80, Lanczos = 0x200, ParamDefault = 0x1e240, Point = 0x10, PrintInfo = 0x1000, Sinc = 0x100, Spline = 0x400, SrcVChrDropMask = 0x30000, SrcVChrDropShift = 0x10, X = 0x8, } }
26.024191
438
0.620026
[ "MIT" ]
ibukisaar/SaarFFmpeg
SaarFFmpeg/FFmpeg/FFmpeg.Enums.cs
79,611
C#
singleton Material(TempleRuin_02_ConcreteStain1) { mapTo = "ConcreteStain1"; diffuseMap[0] = "3td_ConcreteStain_01"; specular[0] = "0.9 0.9 0.9 1"; specularPower[0] = "64"; translucentBlendOp = "None"; normalMap[0] = "3td_BrickOldSharp_01_NRM.png"; useAnisotropic[0] = "1"; pixelSpecular[0] = "1"; }; singleton Material(TempleRuin_02_OverhangVino1) { mapTo = "OverhangVino1"; diffuseMap[0] = "3td_OverhangVino_01"; specular[0] = "0.956863 0.972549 0.898039 1"; specularPower[0] = "71"; translucentBlendOp = "None"; useAnisotropic[0] = "1"; doubleSided = "1"; alphaTest = "1"; alphaRef = "150"; subSurface[0] = "1"; subSurfaceColor[0] = "0.882353 1 0 1"; normalMap[0] = "3td_OverhangVino_01_NRM.png"; pixelSpecular[0] = "1"; }; singleton Material(TempleRuin_02_OverhangVino2) { mapTo = "OverhangVino2"; diffuseMap[0] = "3td_OverhangVino_02"; specular[0] = "0.968628 0.996078 0.854902 1"; specularPower[0] = "51"; translucentBlendOp = "None"; useAnisotropic[0] = "1"; subSurface[0] = "1"; subSurfaceColor[0] = "0.858824 1 0 1"; doubleSided = "1"; alphaTest = "1"; alphaRef = "150"; normalMap[0] = "3td_OverhangVino_02_NRM.png"; pixelSpecular[0] = "1"; }; singleton Material(TempleRuin_02_ColorEffectR153G228B214_material) { mapTo = "ColorEffectR153G228B214-material"; diffuseColor[0] = "0.6 0.894118 0.839216 1"; specularPower[0] = "10"; translucentBlendOp = "None"; }; singleton Material(TempleRuin_02_ColorEffectR225G87B143_material) { mapTo = "ColorEffectR225G87B143-material"; diffuseColor[0] = "0.882353 0.341177 0.560784 1"; specularPower[0] = "10"; translucentBlendOp = "None"; }; singleton Material(TempleRuin_02_BrickFloor1) { mapTo = "BrickFloor1"; diffuseMap[0] = "3td_BrickFloorOld_01"; specular[0] = "0.9 0.9 0.9 1"; specularPower[0] = "50"; translucentBlendOp = "None"; normalMap[0] = "3td_BrickFloorOld_01_NRM.png"; useAnisotropic[0] = "1"; pixelSpecular[0] = "1"; };
27.16
66
0.669121
[ "Unlicense" ]
Torque3D-Games-Demos/FreeRPG
art/shapes/Ruins/TempleRuin_02/materials.cs
2,037
C#
using System; namespace OpenCvSharp.ImgHash { /// <inheritdoc /> /// <summary> /// Image hash based on block mean. /// </summary> public class BlockMeanHash : ImgHashBase { /// <summary> /// cv::Ptr&lt;T&gt; /// </summary> private Ptr? ptrObj; /// <summary> /// /// </summary> protected BlockMeanHash(IntPtr p) { ptrObj = new Ptr(p); ptr = ptrObj.Get(); } /// <summary> /// Create BlockMeanHash object /// </summary> /// <param name="mode"></param> /// <returns></returns> public static BlockMeanHash Create(BlockMeanHashMode mode = BlockMeanHashMode.Mode0) { NativeMethods.HandleException( NativeMethods.img_hash_BlockMeanHash_create((int)mode, out var p)); return new BlockMeanHash(p); } /// <inheritdoc /> /// <summary> /// Releases managed resources /// </summary> protected override void DisposeManaged() { ptrObj?.Dispose(); ptrObj = null; base.DisposeManaged(); } /// <summary> /// /// </summary> /// <param name="mode"></param> public void SetMode(BlockMeanHashMode mode) { ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.img_hash_BlockMeanHash_setMode(ptr, (int)mode)); GC.KeepAlive(this); } /// <summary> /// /// </summary> /// <returns></returns> public double[] GetMean() { ThrowIfDisposed(); using var meanVec = new VectorOfDouble(); NativeMethods.HandleException( NativeMethods.img_hash_BlockMeanHash_getMean(ptr, meanVec.CvPtr)); GC.KeepAlive(this); return meanVec.ToArray(); } /* /// <inheritdoc /> /// <summary> /// Computes block mean hash of the input image /// </summary> /// <param name="inputArr">input image want to compute hash value, type should be CV_8UC4, CV_8UC3 or CV_8UC1.</param> /// <param name="outputArr">Hash value of input, it will contain 16 hex decimal number, return type is CV_8U</param> /// <returns></returns> public override void Compute(InputArray inputArr, OutputArray outputArr) { base.Compute(inputArr, outputArr); }*/ internal class Ptr : OpenCvSharp.Ptr { public Ptr(IntPtr ptr) : base(ptr) { } public override IntPtr Get() { NativeMethods.HandleException( NativeMethods.img_hash_Ptr_BlockMeanHash_get(ptr, out var ret)); GC.KeepAlive(this); return ret; } protected override void DisposeUnmanaged() { NativeMethods.HandleException( NativeMethods.img_hash_Ptr_BlockMeanHash_delete(ptr)); base.DisposeUnmanaged(); } } } }
29.66055
126
0.514074
[ "BSD-3-Clause" ]
AJEETX/opencvsharp
src/OpenCvSharp/Modules/img_hash/BlockMeanHash.cs
3,233
C#
using System; using System.Collections.Generic; using UnityEngine.Experimental.Rendering; namespace UnityEngine.Rendering.HighDefinition { static class VisibleLightExtensionMethods { public struct VisibleLightAxisAndPosition { public Vector3 Position; public Vector3 Forward; public Vector3 Up; public Vector3 Right; } public static Vector3 GetPosition(this VisibleLight value) { return value.localToWorldMatrix.GetColumn(3); } public static Vector3 GetForward(this VisibleLight value) { return value.localToWorldMatrix.GetColumn(2); } public static Vector3 GetUp(this VisibleLight value) { return value.localToWorldMatrix.GetColumn(1); } public static Vector3 GetRight(this VisibleLight value) { return value.localToWorldMatrix.GetColumn(0); } public static VisibleLightAxisAndPosition GetAxisAndPosition(this VisibleLight value) { var matrix = value.localToWorldMatrix; VisibleLightAxisAndPosition output; output.Position = matrix.GetColumn(3); output.Forward = matrix.GetColumn(2); output.Up = matrix.GetColumn(1); output.Right = matrix.GetColumn(0); return output; } } //----------------------------------------------------------------------------- // structure definition //----------------------------------------------------------------------------- [GenerateHLSL] internal enum LightVolumeType { Cone, Sphere, Box, Count } [GenerateHLSL] internal enum LightCategory { Punctual, Area, Env, ProbeVolume, Decal, DensityVolume, // WARNING: Currently lightlistbuild.compute assumes density volume is the last element in the LightCategory enum. Do not append new LightCategory types after DensityVolume. TODO: Fix .compute code. Count } [GenerateHLSL] internal enum LightFeatureFlags { // Light bit mask must match LightDefinitions.s_LightFeatureMaskFlags value Punctual = 1 << 12, Area = 1 << 13, Directional = 1 << 14, Env = 1 << 15, Sky = 1 << 16, SSRefraction = 1 << 17, SSReflection = 1 << 18, ProbeVolume = 1 << 19 // If adding more light be sure to not overflow LightDefinitions.s_LightFeatureMaskFlags } [GenerateHLSL] class LightDefinitions { public static int s_MaxNrBigTileLightsPlusOne = 512; // may be overkill but the footprint is 2 bits per pixel using uint16. public static float s_ViewportScaleZ = 1.0f; public static int s_UseLeftHandCameraSpace = 1; public static int s_TileSizeFptl = 16; public static int s_TileSizeClustered = 32; public static int s_TileSizeBigTile = 64; // Tile indexing constants for indirect dispatch deferred pass : [2 bits for eye index | 15 bits for tileX | 15 bits for tileY] public static int s_TileIndexMask = 0x7FFF; public static int s_TileIndexShiftX = 0; public static int s_TileIndexShiftY = 15; public static int s_TileIndexShiftEye = 30; // feature variants public static int s_NumFeatureVariants = 29; // light list limits public static int s_LightListMaxCoarseEntries = 64; public static int s_LightListMaxPrunedEntries = 24; public static int s_LightClusterMaxCoarseEntries = 128; // Following define the maximum number of bits use in each feature category. public static uint s_LightFeatureMaskFlags = 0xFFF000; public static uint s_LightFeatureMaskFlagsOpaque = 0xFFF000 & ~((uint)LightFeatureFlags.SSRefraction); // Opaque don't support screen space refraction public static uint s_LightFeatureMaskFlagsTransparent = 0xFFF000 & ~((uint)LightFeatureFlags.SSReflection); // Transparent don't support screen space reflection public static uint s_MaterialFeatureMaskFlags = 0x000FFF; // don't use all bits just to be safe from signed and/or float conversions :/ // Screen space shadow flags public static uint s_RayTracedScreenSpaceShadowFlag = 0x1000; public static uint s_ScreenSpaceColorShadowFlag = 0x100; public static uint s_InvalidScreenSpaceShadow = 0xff; public static uint s_ScreenSpaceShadowIndexMask = 0xff; } [GenerateHLSL] struct SFiniteLightBound { public Vector3 boxAxisX; // Scaled by the extents (half-size) public Vector3 boxAxisY; // Scaled by the extents (half-size) public Vector3 boxAxisZ; // Scaled by the extents (half-size) public Vector3 center; // Center of the bounds (box) in camera space public float scaleXY; // Scale applied to the top of the box to turn it into a truncated pyramid (X = Y) public float radius; // Circumscribed sphere for the bounds (box) }; [GenerateHLSL] struct LightVolumeData { public Vector3 lightPos; // Of light's "origin" public uint lightVolume; // Type index public Vector3 lightAxisX; // Normalized public uint lightCategory; // Category index public Vector3 lightAxisY; // Normalized public float radiusSq; // Cone and sphere: light range squared public Vector3 lightAxisZ; // Normalized public float cotan; // Cone: cotan of the aperture (half-angle) public Vector3 boxInnerDist; // Box: extents (half-size) of the inner box public uint featureFlags; public Vector3 boxInvRange; // Box: 1 / (OuterBoxExtents - InnerBoxExtents) public float unused2; }; /// <summary> /// Tile and Cluster Debug Mode. /// </summary> public enum TileClusterDebug : int { /// <summary>No Tile and Cluster debug.</summary> None, /// <summary>Display lighting tiles debug.</summary> Tile, /// <summary>Display lighting clusters debug.</summary> Cluster, /// <summary>Display material feautre variants.</summary> MaterialFeatureVariants }; /// <summary> /// Cluster visualization mode. /// </summary> [GenerateHLSL] public enum ClusterDebugMode : int { /// <summary>Visualize Cluster on opaque objects.</summary> VisualizeOpaque, /// <summary>Visualize a slice of the Cluster at a given distance.</summary> VisualizeSlice } /// <summary> /// Light Volume Debug Mode. /// </summary> public enum LightVolumeDebug : int { /// <summary>Display light volumes as a gradient.</summary> Gradient, /// <summary>Display light volumes as shapes will color and edges depending on the light type.</summary> ColorAndEdge }; /// <summary> /// Tile and Cluster Debug Categories. /// </summary> public enum TileClusterCategoryDebug : int { /// <summary>Punctual lights.</summary> Punctual = 1, /// <summary>Area lights.</summary> Area = 2, /// <summary>Area and punctual lights.</summary> AreaAndPunctual = 3, /// <summary>Environment lights.</summary> Environment = 4, /// <summary>Environment and punctual lights.</summary> EnvironmentAndPunctual = 5, /// <summary>Environment and area lights.</summary> EnvironmentAndArea = 6, /// <summary>All lights.</summary> EnvironmentAndAreaAndPunctual = 7, /// <summary>Probe Volumes.</summary> ProbeVolumes = 8, /// <summary>Decals.</summary> Decal = 16, /// <summary>Density Volumes.</summary> DensityVolumes = 32 }; [GenerateHLSL(needAccessors = false, generateCBuffer = true)] unsafe struct ShaderVariablesLightList { [HLSLArray(ShaderConfig.k_XRMaxViewsForCBuffer, typeof(Matrix4x4))] public fixed float g_mInvScrProjectionArr[ShaderConfig.k_XRMaxViewsForCBuffer * 16]; [HLSLArray(ShaderConfig.k_XRMaxViewsForCBuffer, typeof(Matrix4x4))] public fixed float g_mScrProjectionArr[ShaderConfig.k_XRMaxViewsForCBuffer * 16]; [HLSLArray(ShaderConfig.k_XRMaxViewsForCBuffer, typeof(Matrix4x4))] public fixed float g_mInvProjectionArr[ShaderConfig.k_XRMaxViewsForCBuffer * 16]; [HLSLArray(ShaderConfig.k_XRMaxViewsForCBuffer, typeof(Matrix4x4))] public fixed float g_mProjectionArr[ShaderConfig.k_XRMaxViewsForCBuffer * 16]; public Vector4 g_screenSize; public Vector2Int g_viDimensions; public int g_iNrVisibLights; public uint g_isOrthographic; public uint g_BaseFeatureFlags; public int g_iNumSamplesMSAA; public uint _EnvLightIndexShift; public uint _DecalIndexShift; public uint _DensityVolumeIndexShift; public uint _ProbeVolumeIndexShift; public uint _Pad0_SVLL; public uint _Pad1_SVLL; } internal struct ProcessedLightData { public HDAdditionalLightData additionalLightData; public HDLightType lightType; public LightCategory lightCategory; public GPULightType gpuLightType; public LightVolumeType lightVolumeType; public float distanceToCamera; public float lightDistanceFade; public float volumetricDistanceFade; public bool isBakedShadowMask; } internal struct ProcessedProbeData { public HDProbe hdProbe; public float weight; } public partial class HDRenderPipeline { internal const int k_MaxCacheSize = 2000000000; //2 GigaByte internal const int k_MaxDirectionalLightsOnScreen = 512; internal const int k_MaxPunctualLightsOnScreen = 2048; internal const int k_MaxAreaLightsOnScreen = 1024; internal const int k_MaxDecalsOnScreen = 2048; internal const int k_MaxLightsOnScreen = k_MaxDirectionalLightsOnScreen + k_MaxPunctualLightsOnScreen + k_MaxAreaLightsOnScreen + k_MaxEnvLightsOnScreen; internal const int k_MaxEnvLightsOnScreen = 1024; internal const int k_MaxLightsPerClusterCell = 24; internal static readonly Vector3 k_BoxCullingExtentThreshold = Vector3.one * 0.01f; #if UNITY_SWITCH static bool k_PreferFragment = true; #else static bool k_PreferFragment = false; #endif #if !UNITY_EDITOR && UNITY_SWITCH const bool k_HasNativeQuadSupport = true; #else const bool k_HasNativeQuadSupport = false; #endif #if !UNITY_EDITOR && UNITY_SWITCH const int k_ThreadGroupOptimalSize = 32; #else const int k_ThreadGroupOptimalSize = 64; #endif int m_MaxDirectionalLightsOnScreen; int m_MaxPunctualLightsOnScreen; int m_MaxAreaLightsOnScreen; int m_MaxDecalsOnScreen; int m_MaxLightsOnScreen; int m_MaxEnvLightsOnScreen; int m_MaxPlanarReflectionOnScreen; Texture2DArray m_DefaultTexture2DArray; Cubemap m_DefaultTextureCube; internal class LightLoopTextureCaches { // Structure for cookies used by directional and spotlights public LightCookieManager lightCookieManager { get; private set; } public ReflectionProbeCache reflectionProbeCache { get; private set; } public PlanarReflectionProbeCache reflectionPlanarProbeCache { get; private set; } public List<Matrix4x4> env2DCaptureVP { get; private set; } public List<Vector4> env2DCaptureForward { get; private set; } public List<Vector4> env2DAtlasScaleOffset {get; private set; } = new List<Vector4>(); public void Initialize(HDRenderPipelineAsset hdrpAsset, RenderPipelineResources defaultResources, IBLFilterBSDF[] iBLFilterBSDFArray) { var lightLoopSettings = hdrpAsset.currentPlatformRenderPipelineSettings.lightLoopSettings; lightCookieManager = new LightCookieManager(hdrpAsset, k_MaxCacheSize); env2DCaptureVP = new List<Matrix4x4>(); env2DCaptureForward = new List<Vector4>(); for (int i = 0, c = Mathf.Max(1, lightLoopSettings.maxPlanarReflectionOnScreen); i < c; ++i) { env2DCaptureVP.Add(Matrix4x4.identity); env2DCaptureForward.Add(Vector4.zero); env2DAtlasScaleOffset.Add(Vector4.zero); } // For regular reflection probes, we need to convolve with all the BSDF functions GraphicsFormat probeCacheFormat = lightLoopSettings.reflectionProbeFormat == ReflectionAndPlanarProbeFormat.R11G11B10 ? GraphicsFormat.B10G11R11_UFloatPack32 : GraphicsFormat.R16G16B16A16_SFloat; // BC6H requires CPP feature not yet available //if (lightLoopSettings.reflectionCacheCompressed) //{ // probeCacheFormat = GraphicsFormat.RGB_BC6H_SFloat; //} int reflectionCubeSize = lightLoopSettings.reflectionProbeCacheSize; int reflectionCubeResolution = (int)lightLoopSettings.reflectionCubemapSize; if (ReflectionProbeCache.GetApproxCacheSizeInByte(reflectionCubeSize, reflectionCubeResolution, iBLFilterBSDFArray.Length) > k_MaxCacheSize) reflectionCubeSize = ReflectionProbeCache.GetMaxCacheSizeForWeightInByte(k_MaxCacheSize, reflectionCubeResolution, iBLFilterBSDFArray.Length); reflectionProbeCache = new ReflectionProbeCache(defaultResources, iBLFilterBSDFArray, reflectionCubeSize, reflectionCubeResolution, probeCacheFormat, true); // For planar reflection we only convolve with the GGX filter, otherwise it would be too expensive GraphicsFormat planarProbeCacheFormat = (GraphicsFormat)hdrpAsset.currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionProbeFormat; int reflectionPlanarResolution = (int)lightLoopSettings.planarReflectionAtlasSize; reflectionPlanarProbeCache = new PlanarReflectionProbeCache(defaultResources, (IBLFilterGGX)iBLFilterBSDFArray[0], reflectionPlanarResolution, planarProbeCacheFormat, true); } public void Cleanup() { reflectionProbeCache.Release(); reflectionPlanarProbeCache.Release(); lightCookieManager.Release(); } public void NewFrame() { lightCookieManager.NewFrame(); reflectionProbeCache.NewFrame(); reflectionPlanarProbeCache.NewFrame(); } } internal class LightLoopLightData { public ComputeBuffer directionalLightData { get; private set; } public ComputeBuffer lightData { get; private set; } public ComputeBuffer envLightData { get; private set; } public ComputeBuffer decalData { get; private set; } public void Initialize(int directionalCount, int punctualCount, int areaLightCount, int envLightCount, int decalCount) { directionalLightData = new ComputeBuffer(directionalCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DirectionalLightData))); lightData = new ComputeBuffer(punctualCount + areaLightCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(LightData))); envLightData = new ComputeBuffer(envLightCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(EnvLightData))); decalData = new ComputeBuffer(decalCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DecalData))); } public void Cleanup() { CoreUtils.SafeRelease(directionalLightData); CoreUtils.SafeRelease(lightData); CoreUtils.SafeRelease(envLightData); CoreUtils.SafeRelease(decalData); } } // TODO RENDERGRAPH: When we remove the old pass, we need to remove/refactor this class // With render graph it's only useful for 3 buffers and a boolean value. class TileAndClusterData { // Internal to light list building public ComputeBuffer lightVolumeDataBuffer { get; private set; } public ComputeBuffer convexBoundsBuffer { get; private set; } public ComputeBuffer globalLightListAtomic { get; private set; } public bool listsAreClear = false; public bool clusterNeedsDepth { get; private set; } public bool hasTileBuffers { get; private set; } public int maxLightCount { get; private set; } public void Initialize(bool allocateTileBuffers, bool clusterNeedsDepth, int maxLightCount) { hasTileBuffers = allocateTileBuffers; this.clusterNeedsDepth = clusterNeedsDepth; this.maxLightCount = maxLightCount; globalLightListAtomic = new ComputeBuffer(1, sizeof(uint)); } public void AllocateResolutionDependentBuffers(HDCamera hdCamera, int width, int height, int viewCount, int maxLightOnScreen) { convexBoundsBuffer = new ComputeBuffer(viewCount * maxLightOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(SFiniteLightBound))); lightVolumeDataBuffer = new ComputeBuffer(viewCount * maxLightOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(LightVolumeData))); // Make sure to invalidate the content of the buffers listsAreClear = false; } public void ReleaseResolutionDependentBuffers() { CoreUtils.SafeRelease(convexBoundsBuffer); CoreUtils.SafeRelease(lightVolumeDataBuffer); convexBoundsBuffer = null; lightVolumeDataBuffer = null; } public void Cleanup() { CoreUtils.SafeRelease(globalLightListAtomic); ReleaseResolutionDependentBuffers(); } } // TODO: Remove the internal internal LightLoopTextureCaches m_TextureCaches = new LightLoopTextureCaches(); // TODO: Remove the internal internal LightLoopLightData m_LightLoopLightData = new LightLoopLightData(); TileAndClusterData m_TileAndClusterData = new TileAndClusterData(); // This control if we use cascade borders for directional light by default static internal readonly bool s_UseCascadeBorders = true; // Keep sorting array around to avoid garbage uint[] m_SortKeys = null; DynamicArray<ProcessedLightData> m_ProcessedLightData = new DynamicArray<ProcessedLightData>(); DynamicArray<ProcessedProbeData> m_ProcessedReflectionProbeData = new DynamicArray<ProcessedProbeData>(); DynamicArray<ProcessedProbeData> m_ProcessedPlanarProbeData = new DynamicArray<ProcessedProbeData>(); void UpdateSortKeysArray(int count) { if (m_SortKeys == null || count > m_SortKeys.Length) { m_SortKeys = new uint[count]; } } static readonly Matrix4x4 s_FlipMatrixLHSRHS = Matrix4x4.Scale(new Vector3(1, 1, -1)); Matrix4x4 GetWorldToViewMatrix(HDCamera hdCamera, int viewIndex) { var viewMatrix = (hdCamera.xr.enabled ? hdCamera.xr.GetViewMatrix(viewIndex) : hdCamera.camera.worldToCameraMatrix); // camera.worldToCameraMatrix is RHS and Unity's transforms are LHS, we need to flip it to work with transforms. // Note that this is equivalent to s_FlipMatrixLHSRHS * viewMatrix, but faster given that it doesn't need full matrix multiply // However if for some reason s_FlipMatrixLHSRHS changes from Matrix4x4.Scale(new Vector3(1, 1, -1)), this need to change as well. viewMatrix.m20 *= -1; viewMatrix.m21 *= -1; viewMatrix.m22 *= -1; viewMatrix.m23 *= -1; return viewMatrix; } // Matrix used for LightList building, keep them around to avoid GC Matrix4x4[] m_LightListProjMatrices = new Matrix4x4[ShaderConfig.s_XrMaxViews]; internal class LightList { public List<DirectionalLightData> directionalLights; public List<LightData> lights; public List<EnvLightData> envLights; public int punctualLightCount; public int areaLightCount; public struct LightsPerView { public List<SFiniteLightBound> bounds; public List<LightVolumeData> lightVolumes; public List<SFiniteLightBound> probeVolumesBounds; public List<LightVolumeData> probeVolumesLightVolumes; } public List<LightsPerView> lightsPerView; public void Clear() { directionalLights.Clear(); lights.Clear(); envLights.Clear(); punctualLightCount = 0; areaLightCount = 0; for (int i = 0; i < lightsPerView.Count; ++i) { lightsPerView[i].bounds.Clear(); lightsPerView[i].lightVolumes.Clear(); lightsPerView[i].probeVolumesBounds.Clear(); lightsPerView[i].probeVolumesLightVolumes.Clear(); } } public void Allocate() { directionalLights = new List<DirectionalLightData>(); lights = new List<LightData>(); envLights = new List<EnvLightData>(); lightsPerView = new List<LightsPerView>(); for (int i = 0; i < TextureXR.slices; ++i) { lightsPerView.Add(new LightsPerView { bounds = new List<SFiniteLightBound>(), lightVolumes = new List<LightVolumeData>(), probeVolumesBounds = new List<SFiniteLightBound>(), probeVolumesLightVolumes = new List<LightVolumeData>() }); } } } internal LightList m_lightList; int m_TotalLightCount = 0; int m_DensityVolumeCount = 0; int m_ProbeVolumeCount = 0; bool m_EnableBakeShadowMask = false; // Track if any light require shadow mask. In this case we will need to enable the keyword shadow mask ComputeShader buildScreenAABBShader { get { return defaultResources.shaders.buildScreenAABBCS; } } ComputeShader buildPerTileLightListShader { get { return defaultResources.shaders.buildPerTileLightListCS; } } ComputeShader buildPerBigTileLightListShader { get { return defaultResources.shaders.buildPerBigTileLightListCS; } } ComputeShader buildPerVoxelLightListShader { get { return defaultResources.shaders.buildPerVoxelLightListCS; } } ComputeShader clearClusterAtomicIndexShader { get { return defaultResources.shaders.lightListClusterClearAtomicIndexCS; } } ComputeShader buildMaterialFlagsShader { get { return defaultResources.shaders.buildMaterialFlagsCS; } } ComputeShader buildDispatchIndirectShader { get { return defaultResources.shaders.buildDispatchIndirectCS; } } ComputeShader clearDispatchIndirectShader { get { return defaultResources.shaders.clearDispatchIndirectCS; } } ComputeShader deferredComputeShader { get { return defaultResources.shaders.deferredCS; } } ComputeShader contactShadowComputeShader { get { return defaultResources.shaders.contactShadowCS; } } Shader screenSpaceShadowsShader { get { return defaultResources.shaders.screenSpaceShadowPS; } } Shader deferredTilePixelShader { get { return defaultResources.shaders.deferredTilePS; } } ShaderVariablesLightList m_ShaderVariablesLightListCB = new ShaderVariablesLightList(); enum ClusterPrepassSource : int { None = 0, BigTile = 1, Count = 2, } enum ClusterDepthSource : int { NoDepth = 0, Depth = 1, MSAA_Depth = 2, Count = 3, } static string[,] s_ClusterKernelNames = new string[(int)ClusterPrepassSource.Count, (int)ClusterDepthSource.Count] { { "TileLightListGen_NoDepthRT", "TileLightListGen_DepthRT", "TileLightListGen_DepthRT_MSAA" }, { "TileLightListGen_NoDepthRT_SrcBigTile", "TileLightListGen_DepthRT_SrcBigTile", "TileLightListGen_DepthRT_MSAA_SrcBigTile" } }; static string[,] s_ClusterObliqueKernelNames = new string[(int)ClusterPrepassSource.Count, (int)ClusterDepthSource.Count] { { "TileLightListGen_NoDepthRT", "TileLightListGen_DepthRT_Oblique", "TileLightListGen_DepthRT_MSAA_Oblique" }, { "TileLightListGen_NoDepthRT_SrcBigTile", "TileLightListGen_DepthRT_SrcBigTile_Oblique", "TileLightListGen_DepthRT_MSAA_SrcBigTile_Oblique" } }; static int s_GenListPerTileKernel; static int[,] s_ClusterKernels = new int[(int)ClusterPrepassSource.Count, (int)ClusterDepthSource.Count]; static int[,] s_ClusterObliqueKernels = new int[(int)ClusterPrepassSource.Count, (int)ClusterDepthSource.Count]; static int s_ClearVoxelAtomicKernel; static int s_ClearDispatchIndirectKernel; static int s_BuildIndirectKernel; static int s_ClearDrawProceduralIndirectKernel; static int s_BuildMaterialFlagsWriteKernel; static int s_BuildMaterialFlagsOrKernel; static int s_shadeOpaqueDirectFptlKernel; static int s_shadeOpaqueDirectFptlDebugDisplayKernel; static int s_shadeOpaqueDirectShadowMaskFptlKernel; static int s_shadeOpaqueDirectShadowMaskFptlDebugDisplayKernel; static int[] s_shadeOpaqueIndirectFptlKernels = new int[LightDefinitions.s_NumFeatureVariants]; static int s_deferredContactShadowKernel; static int s_GenListPerBigTileKernel; const bool k_UseDepthBuffer = true; // only has an impact when EnableClustered is true (requires a depth-prepass) #if !UNITY_EDITOR && UNITY_SWITCH const int k_Log2NumClusters = 5; // accepted range is from 0 to 5 (NR_THREADS is set to 32 on Switch). NumClusters is 1<<g_iLog2NumClusters #else const int k_Log2NumClusters = 6; // accepted range is from 0 to 6 (NR_THREADS is set to 64 on other platforms). NumClusters is 1<<g_iLog2NumClusters #endif const float k_ClustLogBase = 1.02f; // each slice 2% bigger than the previous float m_ClusterScale; static DebugLightVolumes s_lightVolumes = null; static Material s_DeferredTileRegularLightingMat; // stencil-test set to touch regular pixels only static Material s_DeferredTileSplitLightingMat; // stencil-test set to touch split-lighting pixels only static Material s_DeferredTileMat; // fallback when regular and split-lighting pixels must be touch static String[] s_variantNames = new String[LightDefinitions.s_NumFeatureVariants]; ContactShadows m_ContactShadows = null; bool m_EnableContactShadow = false; IndirectLightingController m_indirectLightingController = null; // Following is an array of material of size eight for all combination of keyword: OUTPUT_SPLIT_LIGHTING - LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - SHADOWS_SHADOWMASK - USE_FPTL_LIGHTLIST/USE_CLUSTERED_LIGHTLIST - DEBUG_DISPLAY Material[] m_deferredLightingMaterial; Material m_DebugViewTilesMaterial; Material m_DebugHDShadowMapMaterial; Material m_DebugBlitMaterial; Material m_DebugDisplayProbeVolumeMaterial; HashSet<HDAdditionalLightData> m_ScreenSpaceShadowsUnion = new HashSet<HDAdditionalLightData>(); // Directional light Light m_CurrentSunLight; int m_CurrentShadowSortedSunLightIndex = -1; HDAdditionalLightData m_CurrentSunLightAdditionalLightData; DirectionalLightData m_CurrentSunLightDirectionalLightData; Light GetCurrentSunLight() { return m_CurrentSunLight; } // Screen space shadow data struct ScreenSpaceShadowData { public HDAdditionalLightData additionalLightData; public int lightDataIndex; public bool valid; } int m_ScreenSpaceShadowIndex = 0; int m_ScreenSpaceShadowChannelSlot = 0; ScreenSpaceShadowData[] m_CurrentScreenSpaceShadowData; // Contact shadow index reseted at the beginning of each frame, used to generate the contact shadow mask int m_ContactShadowIndex; // shadow related stuff HDShadowManager m_ShadowManager; HDShadowInitParameters m_ShadowInitParameters; // Used to shadow shadow maps with use selection enabled in the debug menu int m_DebugSelectedLightShadowIndex; int m_DebugSelectedLightShadowCount; // Data needed for the PrepareGPULightdata List<Matrix4x4> m_WorldToViewMatrices = new List<Matrix4x4>(ShaderConfig.s_XrMaxViews); static MaterialPropertyBlock m_LightLoopDebugMaterialProperties = new MaterialPropertyBlock(); bool HasLightToCull() { return m_TotalLightCount > 0; } static int GetNumTileBigTileX(HDCamera hdCamera) { return HDUtils.DivRoundUp((int)hdCamera.screenSize.x, LightDefinitions.s_TileSizeBigTile); } static int GetNumTileBigTileY(HDCamera hdCamera) { return HDUtils.DivRoundUp((int)hdCamera.screenSize.y, LightDefinitions.s_TileSizeBigTile); } static int GetNumTileFtplX(HDCamera hdCamera) { return HDUtils.DivRoundUp((int)hdCamera.screenSize.x, LightDefinitions.s_TileSizeFptl); } static int GetNumTileFtplY(HDCamera hdCamera) { return HDUtils.DivRoundUp((int)hdCamera.screenSize.y, LightDefinitions.s_TileSizeFptl); } static int GetNumTileClusteredX(HDCamera hdCamera) { return HDUtils.DivRoundUp((int)hdCamera.screenSize.x, LightDefinitions.s_TileSizeClustered); } static int GetNumTileClusteredY(HDCamera hdCamera) { return HDUtils.DivRoundUp((int)hdCamera.screenSize.y, LightDefinitions.s_TileSizeClustered); } void InitShadowSystem(HDRenderPipelineAsset hdAsset, RenderPipelineResources defaultResources) { m_ShadowInitParameters = hdAsset.currentPlatformRenderPipelineSettings.hdShadowInitParams; m_ShadowManager = new HDShadowManager(); m_ShadowManager.InitShadowManager( defaultResources, m_ShadowInitParameters, m_RenderGraph, defaultResources.shaders.shadowClearPS ); } void DeinitShadowSystem() { if (m_ShadowManager != null) { m_ShadowManager.Cleanup(m_RenderGraph); m_ShadowManager = null; } } static bool GetFeatureVariantsEnabled(FrameSettings frameSettings) => frameSettings.litShaderMode == LitShaderMode.Deferred && frameSettings.IsEnabled(FrameSettingsField.DeferredTile) && (frameSettings.IsEnabled(FrameSettingsField.ComputeLightVariants) || frameSettings.IsEnabled(FrameSettingsField.ComputeMaterialVariants)); int GetDeferredLightingMaterialIndex(int outputSplitLighting, int shadowMask, int debugDisplay) { return (outputSplitLighting) | (shadowMask << 1) | (debugDisplay << 2); } Material GetDeferredLightingMaterial(bool outputSplitLighting, bool shadowMask, bool debugDisplayEnabled) { int index = GetDeferredLightingMaterialIndex(outputSplitLighting ? 1 : 0, shadowMask ? 1 : 0, debugDisplayEnabled ? 1 : 0); return m_deferredLightingMaterial[index]; } void InitializeLightLoop(IBLFilterBSDF[] iBLFilterBSDFArray) { var lightLoopSettings = asset.currentPlatformRenderPipelineSettings.lightLoopSettings; m_lightList = new LightList(); m_lightList.Allocate(); m_DebugViewTilesMaterial = CoreUtils.CreateEngineMaterial(defaultResources.shaders.debugViewTilesPS); m_DebugHDShadowMapMaterial = CoreUtils.CreateEngineMaterial(defaultResources.shaders.debugHDShadowMapPS); m_DebugBlitMaterial = CoreUtils.CreateEngineMaterial(defaultResources.shaders.debugBlitQuad); m_DebugDisplayProbeVolumeMaterial = CoreUtils.CreateEngineMaterial(defaultResources.shaders.debugDisplayProbeVolumePS); m_MaxDirectionalLightsOnScreen = lightLoopSettings.maxDirectionalLightsOnScreen; m_MaxPunctualLightsOnScreen = lightLoopSettings.maxPunctualLightsOnScreen; m_MaxAreaLightsOnScreen = lightLoopSettings.maxAreaLightsOnScreen; m_MaxDecalsOnScreen = lightLoopSettings.maxDecalsOnScreen; m_MaxEnvLightsOnScreen = lightLoopSettings.maxEnvLightsOnScreen; m_MaxLightsOnScreen = m_MaxDirectionalLightsOnScreen + m_MaxPunctualLightsOnScreen + m_MaxAreaLightsOnScreen + m_MaxEnvLightsOnScreen; m_MaxPlanarReflectionOnScreen = lightLoopSettings.maxPlanarReflectionOnScreen; // Cluster { s_ClearVoxelAtomicKernel = clearClusterAtomicIndexShader.FindKernel("ClearAtomic"); for (int i = 0; i < (int)ClusterPrepassSource.Count; ++i) { for (int j = 0; j < (int)ClusterDepthSource.Count; ++j) { s_ClusterKernels[i, j] = buildPerVoxelLightListShader.FindKernel(s_ClusterKernelNames[i, j]); s_ClusterObliqueKernels[i, j] = buildPerVoxelLightListShader.FindKernel(s_ClusterObliqueKernelNames[i, j]); } } } s_GenListPerTileKernel = buildPerTileLightListShader.FindKernel("TileLightListGen"); s_GenListPerBigTileKernel = buildPerBigTileLightListShader.FindKernel("BigTileLightListGen"); s_BuildIndirectKernel = buildDispatchIndirectShader.FindKernel("BuildIndirect"); s_ClearDispatchIndirectKernel = clearDispatchIndirectShader.FindKernel("ClearDispatchIndirect"); s_ClearDrawProceduralIndirectKernel = clearDispatchIndirectShader.FindKernel("ClearDrawProceduralIndirect"); s_BuildMaterialFlagsWriteKernel = buildMaterialFlagsShader.FindKernel("MaterialFlagsGen"); s_shadeOpaqueDirectFptlKernel = deferredComputeShader.FindKernel("Deferred_Direct_Fptl"); s_shadeOpaqueDirectFptlDebugDisplayKernel = deferredComputeShader.FindKernel("Deferred_Direct_Fptl_DebugDisplay"); s_deferredContactShadowKernel = contactShadowComputeShader.FindKernel("DeferredContactShadow"); for (int variant = 0; variant < LightDefinitions.s_NumFeatureVariants; variant++) { s_shadeOpaqueIndirectFptlKernels[variant] = deferredComputeShader.FindKernel("Deferred_Indirect_Fptl_Variant" + variant); } m_TextureCaches.Initialize(asset, defaultResources, iBLFilterBSDFArray); // All the allocation of the compute buffers need to happened after the kernel finding in order to avoid the leak loop when a shader does not compile or is not available m_LightLoopLightData.Initialize(m_MaxDirectionalLightsOnScreen, m_MaxPunctualLightsOnScreen, m_MaxAreaLightsOnScreen, m_MaxEnvLightsOnScreen, m_MaxDecalsOnScreen); m_TileAndClusterData.Initialize(allocateTileBuffers: true, clusterNeedsDepth: k_UseDepthBuffer, maxLightCount: m_MaxLightsOnScreen); // OUTPUT_SPLIT_LIGHTING - SHADOWS_SHADOWMASK - DEBUG_DISPLAY m_deferredLightingMaterial = new Material[8]; int stencilMask = (int)StencilUsage.RequiresDeferredLighting | (int)StencilUsage.SubsurfaceScattering; for (int outputSplitLighting = 0; outputSplitLighting < 2; ++outputSplitLighting) { for (int shadowMask = 0; shadowMask < 2; ++shadowMask) { for (int debugDisplay = 0; debugDisplay < 2; ++debugDisplay) { int index = GetDeferredLightingMaterialIndex(outputSplitLighting, shadowMask, debugDisplay); m_deferredLightingMaterial[index] = CoreUtils.CreateEngineMaterial(defaultResources.shaders.deferredPS); m_deferredLightingMaterial[index].name = string.Format("{0}_{1}", defaultResources.shaders.deferredPS.name, index); CoreUtils.SetKeyword(m_deferredLightingMaterial[index], "OUTPUT_SPLIT_LIGHTING", outputSplitLighting == 1); CoreUtils.SetKeyword(m_deferredLightingMaterial[index], "SHADOWS_SHADOWMASK", shadowMask == 1); CoreUtils.SetKeyword(m_deferredLightingMaterial[index], "DEBUG_DISPLAY", debugDisplay == 1); int stencilRef = (int)StencilUsage.RequiresDeferredLighting; if (outputSplitLighting == 1) { stencilRef |= (int)StencilUsage.SubsurfaceScattering; } m_deferredLightingMaterial[index].SetInt(HDShaderIDs._StencilMask, stencilMask); m_deferredLightingMaterial[index].SetInt(HDShaderIDs._StencilRef, stencilRef); m_deferredLightingMaterial[index].SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal); } } } // Stencil set to only touch "regular lighting" pixels. s_DeferredTileRegularLightingMat = CoreUtils.CreateEngineMaterial(deferredTilePixelShader); s_DeferredTileRegularLightingMat.SetInt(HDShaderIDs._StencilMask, (int)StencilUsage.RequiresDeferredLighting | (int)StencilUsage.SubsurfaceScattering); s_DeferredTileRegularLightingMat.SetInt(HDShaderIDs._StencilRef, (int)StencilUsage.RequiresDeferredLighting); s_DeferredTileRegularLightingMat.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal); // Stencil set to only touch "split-lighting" pixels. s_DeferredTileSplitLightingMat = CoreUtils.CreateEngineMaterial(deferredTilePixelShader); s_DeferredTileSplitLightingMat.SetInt(HDShaderIDs._StencilMask, (int)StencilUsage.SubsurfaceScattering); s_DeferredTileSplitLightingMat.SetInt(HDShaderIDs._StencilRef, (int)StencilUsage.SubsurfaceScattering); s_DeferredTileSplitLightingMat.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal); // Stencil set to touch all pixels excepted background/sky. s_DeferredTileMat = CoreUtils.CreateEngineMaterial(deferredTilePixelShader); s_DeferredTileMat.SetInt(HDShaderIDs._StencilMask, (int)StencilUsage.RequiresDeferredLighting); s_DeferredTileMat.SetInt(HDShaderIDs._StencilRef, (int)StencilUsage.Clear); s_DeferredTileMat.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.NotEqual); for (int i = 0; i < LightDefinitions.s_NumFeatureVariants; ++i) s_variantNames[i] = "VARIANT" + i; m_DefaultTexture2DArray = new Texture2DArray(1, 1, 1, TextureFormat.ARGB32, false); m_DefaultTexture2DArray.hideFlags = HideFlags.HideAndDontSave; m_DefaultTexture2DArray.name = CoreUtils.GetTextureAutoName(1, 1, TextureFormat.ARGB32, depth: 1, dim: TextureDimension.Tex2DArray, name: "LightLoopDefault"); m_DefaultTexture2DArray.SetPixels32(new Color32[1] { new Color32(128, 128, 128, 128) }, 0); m_DefaultTexture2DArray.Apply(); m_DefaultTextureCube = new Cubemap(16, TextureFormat.ARGB32, false); m_DefaultTextureCube.Apply(); // Setup shadow algorithms var shadowParams = asset.currentPlatformRenderPipelineSettings.hdShadowInitParams; var shadowKeywords = new[] {"SHADOW_LOW", "SHADOW_MEDIUM", "SHADOW_HIGH"}; foreach (var p in shadowKeywords) Shader.DisableKeyword(p); Shader.EnableKeyword(shadowKeywords[(int)shadowParams.shadowFilteringQuality]); // Setup screen space shadow map usage. // Screen space shadow map are currently only used with Raytracing and are a global keyword. // either we support it and then use the variant that allow to enable/disable them, or we don't // and use the variant that have them disabled. // So this mean that even if we disable screen space shadow in frame settings, the version // of the shader for the variant SCREEN_SPACE_SHADOWS is used, but a dynamic branch disable it. if (shadowParams.supportScreenSpaceShadows) { Shader.EnableKeyword("SCREEN_SPACE_SHADOWS_ON"); Shader.DisableKeyword("SCREEN_SPACE_SHADOWS_OFF"); } else { Shader.DisableKeyword("SCREEN_SPACE_SHADOWS_ON"); Shader.EnableKeyword("SCREEN_SPACE_SHADOWS_OFF"); } InitShadowSystem(asset, defaultResources); s_lightVolumes = new DebugLightVolumes(); s_lightVolumes.InitData(defaultResources); // Screen space shadow int numMaxShadows = Math.Max(m_Asset.currentPlatformRenderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots, 1); m_CurrentScreenSpaceShadowData = new ScreenSpaceShadowData[numMaxShadows]; } void CleanupLightLoop() { s_lightVolumes.ReleaseData(); DeinitShadowSystem(); CoreUtils.Destroy(m_DefaultTexture2DArray); CoreUtils.Destroy(m_DefaultTextureCube); m_TextureCaches.Cleanup(); m_LightLoopLightData.Cleanup(); m_TileAndClusterData.Cleanup(); LightLoopReleaseResolutionDependentBuffers(); for (int outputSplitLighting = 0; outputSplitLighting < 2; ++outputSplitLighting) { for (int shadowMask = 0; shadowMask < 2; ++shadowMask) { for (int debugDisplay = 0; debugDisplay < 2; ++debugDisplay) { int index = GetDeferredLightingMaterialIndex(outputSplitLighting, shadowMask, debugDisplay); CoreUtils.Destroy(m_deferredLightingMaterial[index]); } } } CoreUtils.Destroy(s_DeferredTileRegularLightingMat); CoreUtils.Destroy(s_DeferredTileSplitLightingMat); CoreUtils.Destroy(s_DeferredTileMat); CoreUtils.Destroy(m_DebugViewTilesMaterial); CoreUtils.Destroy(m_DebugHDShadowMapMaterial); CoreUtils.Destroy(m_DebugBlitMaterial); CoreUtils.Destroy(m_DebugDisplayProbeVolumeMaterial); } void LightLoopNewRender() { m_ScreenSpaceShadowsUnion.Clear(); } void LightLoopNewFrame(CommandBuffer cmd, HDCamera hdCamera) { var frameSettings = hdCamera.frameSettings; m_ContactShadows = hdCamera.volumeStack.GetComponent<ContactShadows>(); m_EnableContactShadow = frameSettings.IsEnabled(FrameSettingsField.ContactShadows) && m_ContactShadows.enable.value && m_ContactShadows.length.value > 0; m_indirectLightingController = hdCamera.volumeStack.GetComponent<IndirectLightingController>(); m_ContactShadowIndex = 0; m_TextureCaches.NewFrame(); m_WorldToViewMatrices.Clear(); int viewCount = hdCamera.viewCount; for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex) { m_WorldToViewMatrices.Add(GetWorldToViewMatrix(hdCamera, viewIndex)); } // Clear the cookie atlas if needed at the beginning of the frame. if (m_DebugDisplaySettings.data.lightingDebugSettings.clearCookieAtlas) { m_TextureCaches.lightCookieManager.ResetAllocator(); m_TextureCaches.lightCookieManager.ClearAtlasTexture(cmd); } } static int NumLightIndicesPerClusteredTile() { return 32 * (1 << k_Log2NumClusters); // total footprint for all layers of the tile (measured in light index entries) } void LightLoopAllocResolutionDependentBuffers(HDCamera hdCamera, int width, int height) { m_TileAndClusterData.AllocateResolutionDependentBuffers(hdCamera, width, height, m_MaxViewCount, m_MaxLightsOnScreen); } void LightLoopReleaseResolutionDependentBuffers() { m_TileAndClusterData.ReleaseResolutionDependentBuffers(); } internal static Matrix4x4 WorldToCamera(Camera camera) { // camera.worldToCameraMatrix is RHS and Unity's transforms are LHS // We need to flip it to work with transforms return s_FlipMatrixLHSRHS * camera.worldToCameraMatrix; } // For light culling system, we need non oblique projection matrices static Matrix4x4 CameraProjectionNonObliqueLHS(HDCamera camera) { // camera.projectionMatrix expect RHS data and Unity's transforms are LHS // We need to flip it to work with transforms return camera.nonObliqueProjMatrix * s_FlipMatrixLHSRHS; } internal static Vector3 GetLightColor(VisibleLight light) { return new Vector3(light.finalColor.r, light.finalColor.g, light.finalColor.b); } static float Saturate(float x) { return Mathf.Max(0, Mathf.Min(x, 1)); } static float Rcp(float x) { return 1.0f / x; } static float Rsqrt(float x) { return Rcp(Mathf.Sqrt(x)); } static float ComputeCosineOfHorizonAngle(float r, float R) { float sinHoriz = R * Rcp(r); return -Mathf.Sqrt(Saturate(1 - sinHoriz * sinHoriz)); } static float ChapmanUpperApprox(float z, float cosTheta) { float c = cosTheta; float n = 0.761643f * ((1 + 2 * z) - (c * c * z)); float d = c * z + Mathf.Sqrt(z * (1.47721f + 0.273828f * (c * c * z))); return 0.5f * c + (n * Rcp(d)); } static float ChapmanHorizontal(float z) { float r = Rsqrt(z); float s = z * r; // sqrt(z) return 0.626657f * (r + 2 * s); } static Vector3 ComputeAtmosphericOpticalDepth(PhysicallyBasedSky skySettings, float r, float cosTheta, bool alwaysAboveHorizon = false) { float R = skySettings.GetPlanetaryRadius(); Vector2 H = new Vector2(skySettings.GetAirScaleHeight(), skySettings.GetAerosolScaleHeight()); Vector2 rcpH = new Vector2(Rcp(H.x), Rcp(H.y)); Vector2 z = r * rcpH; Vector2 Z = R * rcpH; float cosHoriz = ComputeCosineOfHorizonAngle(r, R); float sinTheta = Mathf.Sqrt(Saturate(1 - cosTheta * cosTheta)); Vector2 ch; ch.x = ChapmanUpperApprox(z.x, Mathf.Abs(cosTheta)) * Mathf.Exp(Z.x - z.x); // Rescaling adds 'exp' ch.y = ChapmanUpperApprox(z.y, Mathf.Abs(cosTheta)) * Mathf.Exp(Z.y - z.y); // Rescaling adds 'exp' if ((!alwaysAboveHorizon) && (cosTheta < cosHoriz)) // Below horizon, intersect sphere { float sinGamma = (r / R) * sinTheta; float cosGamma = Mathf.Sqrt(Saturate(1 - sinGamma * sinGamma)); Vector2 ch_2; ch_2.x = ChapmanUpperApprox(Z.x, cosGamma); // No need to rescale ch_2.y = ChapmanUpperApprox(Z.y, cosGamma); // No need to rescale ch = ch_2 - ch; } else if (cosTheta < 0) // Above horizon, lower hemisphere { // z_0 = n * r_0 = (n * r) * sin(theta) = z * sin(theta). // Ch(z, theta) = 2 * exp(z - z_0) * Ch(z_0, Pi/2) - Ch(z, Pi - theta). Vector2 z_0 = z * sinTheta; Vector2 b = new Vector2(Mathf.Exp(Z.x - z_0.x), Mathf.Exp(Z.x - z_0.x)); // Rescaling cancels out 'z' and adds 'Z' Vector2 a; a.x = 2 * ChapmanHorizontal(z_0.x); a.y = 2 * ChapmanHorizontal(z_0.y); Vector2 ch_2 = a * b; ch = ch_2 - ch; } Vector2 optDepth = ch * H; Vector3 airExtinction = skySettings.GetAirExtinctionCoefficient(); float aerosolExtinction = skySettings.GetAerosolExtinctionCoefficient(); return new Vector3(optDepth.x * airExtinction.x + optDepth.y * aerosolExtinction, optDepth.x * airExtinction.y + optDepth.y * aerosolExtinction, optDepth.x * airExtinction.z + optDepth.y * aerosolExtinction); } // Computes transmittance along the light path segment. static Vector3 EvaluateAtmosphericAttenuation(PhysicallyBasedSky skySettings, Vector3 L, Vector3 X) { Vector3 C = skySettings.GetPlanetCenterPosition(X); // X = camPosWS float r = Vector3.Distance(X, C); float R = skySettings.GetPlanetaryRadius(); float cosHoriz = ComputeCosineOfHorizonAngle(r, R); float cosTheta = Vector3.Dot(X - C, L) * Rcp(r); if (cosTheta > cosHoriz) // Above horizon { Vector3 oDepth = ComputeAtmosphericOpticalDepth(skySettings, r, cosTheta, true); Vector3 transm; transm.x = Mathf.Exp(-oDepth.x); transm.y = Mathf.Exp(-oDepth.y); transm.z = Mathf.Exp(-oDepth.z); return transm; } else { return Vector3.zero; } } internal void GetDirectionalLightData(CommandBuffer cmd, HDCamera hdCamera, VisibleLight light, Light lightComponent, int lightIndex, int shadowIndex, int sortedIndex, bool isPhysicallyBasedSkyActive, ref int screenSpaceShadowIndex, ref int screenSpaceShadowslot) { var processedData = m_ProcessedLightData[lightIndex]; var additionalLightData = processedData.additionalLightData; var gpuLightType = processedData.gpuLightType; var lightData = new DirectionalLightData(); lightData.lightLayers = hdCamera.frameSettings.IsEnabled(FrameSettingsField.LightLayers) ? additionalLightData.GetLightLayers() : uint.MaxValue; // Light direction for directional is opposite to the forward direction lightData.forward = light.GetForward(); // Rescale for cookies and windowing. lightData.right = light.GetRight() * 2 / Mathf.Max(additionalLightData.shapeWidth, 0.001f); lightData.up = light.GetUp() * 2 / Mathf.Max(additionalLightData.shapeHeight, 0.001f); lightData.positionRWS = light.GetPosition(); lightData.color = GetLightColor(light); // Caution: This is bad but if additionalData == HDUtils.s_DefaultHDAdditionalLightData it mean we are trying to promote legacy lights, which is the case for the preview for example, so we need to multiply by PI as legacy Unity do implicit divide by PI for direct intensity. // So we expect that all light with additionalData == HDUtils.s_DefaultHDAdditionalLightData are currently the one from the preview, light in scene MUST have additionalData lightData.color *= (HDUtils.s_DefaultHDAdditionalLightData == additionalLightData) ? Mathf.PI : 1.0f; lightData.lightDimmer = additionalLightData.lightDimmer; lightData.diffuseDimmer = additionalLightData.affectDiffuse ? additionalLightData.lightDimmer : 0; lightData.specularDimmer = additionalLightData.affectSpecular ? additionalLightData.lightDimmer * hdCamera.frameSettings.specularGlobalDimmer : 0; lightData.volumetricLightDimmer = additionalLightData.volumetricDimmer; lightData.shadowIndex = -1; lightData.screenSpaceShadowIndex = (int)LightDefinitions.s_InvalidScreenSpaceShadow; lightData.isRayTracedContactShadow = 0.0f; if (lightComponent != null && lightComponent.cookie != null) { lightData.cookieMode = lightComponent.cookie.wrapMode == TextureWrapMode.Repeat ? CookieMode.Repeat : CookieMode.Clamp; lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.Fetch2DCookie(cmd, lightComponent.cookie); } else { lightData.cookieMode = CookieMode.None; } if (additionalLightData.surfaceTexture == null) { lightData.surfaceTextureScaleOffset = Vector4.zero; } else { lightData.surfaceTextureScaleOffset = m_TextureCaches.lightCookieManager.Fetch2DCookie(cmd, additionalLightData.surfaceTexture); } lightData.shadowDimmer = additionalLightData.shadowDimmer; lightData.volumetricShadowDimmer = additionalLightData.volumetricShadowDimmer; GetContactShadowMask(additionalLightData, HDAdditionalLightData.ScalableSettings.UseContactShadow(m_Asset), hdCamera, isRasterization: true, ref lightData.contactShadowMask, ref lightData.isRayTracedContactShadow); // We want to have a colored penumbra if the flag is on and the color is not gray bool penumbraTint = additionalLightData.penumbraTint && ((additionalLightData.shadowTint.r != additionalLightData.shadowTint.g) || (additionalLightData.shadowTint.g != additionalLightData.shadowTint.b)); lightData.penumbraTint = penumbraTint ? 1.0f : 0.0f; if (penumbraTint) lightData.shadowTint = new Vector3(additionalLightData.shadowTint.r * additionalLightData.shadowTint.r, additionalLightData.shadowTint.g * additionalLightData.shadowTint.g, additionalLightData.shadowTint.b * additionalLightData.shadowTint.b); else lightData.shadowTint = new Vector3(additionalLightData.shadowTint.r, additionalLightData.shadowTint.g, additionalLightData.shadowTint.b); // fix up shadow information lightData.shadowIndex = shadowIndex; if (shadowIndex != -1) { if (additionalLightData.WillRenderScreenSpaceShadow()) { lightData.screenSpaceShadowIndex = screenSpaceShadowslot; if (additionalLightData.colorShadow && additionalLightData.WillRenderRayTracedShadow()) { screenSpaceShadowslot += 3; lightData.screenSpaceShadowIndex |= (int)LightDefinitions.s_ScreenSpaceColorShadowFlag; } else { screenSpaceShadowslot++; } // Raise the ray tracing flag in case the light is ray traced if (additionalLightData.WillRenderRayTracedShadow()) lightData.screenSpaceShadowIndex |= (int)LightDefinitions.s_RayTracedScreenSpaceShadowFlag; screenSpaceShadowIndex++; m_ScreenSpaceShadowsUnion.Add(additionalLightData); } m_CurrentSunLight = lightComponent; m_CurrentSunLightAdditionalLightData = additionalLightData; m_CurrentSunLightDirectionalLightData = lightData; m_CurrentShadowSortedSunLightIndex = sortedIndex; } //Value of max smoothness is derived from AngularDiameter. Formula results from eyeballing. Angular diameter of 0 results in 1 and angular diameter of 80 results in 0. float maxSmoothness = Mathf.Clamp01(1.35f / (1.0f + Mathf.Pow(1.15f * (0.0315f * additionalLightData.angularDiameter + 0.4f), 2f)) - 0.11f); // Value of max smoothness is from artists point of view, need to convert from perceptual smoothness to roughness lightData.minRoughness = (1.0f - maxSmoothness) * (1.0f - maxSmoothness); lightData.shadowMaskSelector = Vector4.zero; if (processedData.isBakedShadowMask) { lightData.shadowMaskSelector[lightComponent.bakingOutput.occlusionMaskChannel] = 1.0f; lightData.nonLightMappedOnly = lightComponent.lightShadowCasterMode == LightShadowCasterMode.NonLightmappedOnly ? 1 : 0; } else { // use -1 to say that we don't use shadow mask lightData.shadowMaskSelector.x = -1.0f; lightData.nonLightMappedOnly = 0; } bool interactsWithSky = isPhysicallyBasedSkyActive && additionalLightData.interactsWithSky; lightData.distanceFromCamera = -1; // Encode 'interactsWithSky' if (interactsWithSky) { lightData.distanceFromCamera = additionalLightData.distance; if (ShaderConfig.s_PrecomputedAtmosphericAttenuation != 0) { var skySettings = hdCamera.volumeStack.GetComponent<PhysicallyBasedSky>(); // Ignores distance (at infinity). Vector3 transm = EvaluateAtmosphericAttenuation(skySettings, -lightData.forward, hdCamera.camera.transform.position); lightData.color.x *= transm.x; lightData.color.y *= transm.y; lightData.color.z *= transm.z; } } lightData.angularDiameter = additionalLightData.angularDiameter * Mathf.Deg2Rad; lightData.flareSize = Mathf.Max(additionalLightData.flareSize * Mathf.Deg2Rad, 5.960464478e-8f); lightData.flareFalloff = additionalLightData.flareFalloff; lightData.flareTint = (Vector3)(Vector4)additionalLightData.flareTint; lightData.surfaceTint = (Vector3)(Vector4)additionalLightData.surfaceTint; // Fallback to the first non shadow casting directional light. m_CurrentSunLight = m_CurrentSunLight == null ? lightComponent : m_CurrentSunLight; m_lightList.directionalLights.Add(lightData); } // This function evaluates if there is currently enough screen space sahdow slots of a given light based on its light type bool EnoughScreenSpaceShadowSlots(GPULightType gpuLightType, int screenSpaceChannelSlot) { if (gpuLightType == GPULightType.Rectangle) { // Area lights require two shadow slots return (screenSpaceChannelSlot + 1) < m_Asset.currentPlatformRenderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots; } else { return screenSpaceChannelSlot < m_Asset.currentPlatformRenderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots; } } internal void GetLightData(CommandBuffer cmd, HDCamera hdCamera, HDShadowSettings shadowSettings, VisibleLight light, Light lightComponent, in ProcessedLightData processedData, int shadowIndex, BoolScalableSetting contactShadowsScalableSetting, bool isRasterization, ref Vector3 lightDimensions, ref int screenSpaceShadowIndex, ref int screenSpaceChannelSlot, ref LightData lightData) { var additionalLightData = processedData.additionalLightData; var gpuLightType = processedData.gpuLightType; var lightType = processedData.lightType; var visibleLightAxisAndPosition = light.GetAxisAndPosition(); lightData.lightLayers = hdCamera.frameSettings.IsEnabled(FrameSettingsField.LightLayers) ? additionalLightData.GetLightLayers() : uint.MaxValue; lightData.lightType = gpuLightType; lightData.positionRWS = visibleLightAxisAndPosition.Position; lightData.range = light.range; if (additionalLightData.applyRangeAttenuation) { lightData.rangeAttenuationScale = 1.0f / (light.range * light.range); lightData.rangeAttenuationBias = 1.0f; if (lightData.lightType == GPULightType.Rectangle) { // Rect lights are currently a special case because they use the normalized // [0, 1] attenuation range rather than the regular [0, r] one. lightData.rangeAttenuationScale = 1.0f; } } else // Don't apply any attenuation but do a 'step' at range { // Solve f(x) = b - (a * x)^2 where x = (d/r)^2. // f(0) = huge -> b = huge. // f(1) = 0 -> huge - a^2 = 0 -> a = sqrt(huge). const float hugeValue = 16777216.0f; const float sqrtHuge = 4096.0f; lightData.rangeAttenuationScale = sqrtHuge / (light.range * light.range); lightData.rangeAttenuationBias = hugeValue; if (lightData.lightType == GPULightType.Rectangle) { // Rect lights are currently a special case because they use the normalized // [0, 1] attenuation range rather than the regular [0, r] one. lightData.rangeAttenuationScale = sqrtHuge; } } lightData.color = GetLightColor(light); lightData.forward = visibleLightAxisAndPosition.Forward; lightData.up = visibleLightAxisAndPosition.Up; lightData.right = visibleLightAxisAndPosition.Right; lightDimensions.x = additionalLightData.shapeWidth; lightDimensions.y = additionalLightData.shapeHeight; lightDimensions.z = light.range; lightData.boxLightSafeExtent = 1.0f; if (lightData.lightType == GPULightType.ProjectorBox) { // Rescale for cookies and windowing. lightData.right *= 2.0f / Mathf.Max(additionalLightData.shapeWidth, 0.001f); lightData.up *= 2.0f / Mathf.Max(additionalLightData.shapeHeight, 0.001f); // If we have shadows, we need to shrink the valid range so that we don't leak light due to filtering going out of bounds. if (shadowIndex >= 0) { // We subtract a bit from the safe extent depending on shadow resolution float shadowRes = additionalLightData.shadowResolution.Value(m_ShadowInitParameters.shadowResolutionPunctual); shadowRes = Mathf.Clamp(shadowRes, 128.0f, 2048.0f); // Clamp in a somewhat plausible range. // The idea is to subtract as much as 0.05 for small resolutions. float shadowResFactor = Mathf.Lerp(0.05f, 0.01f, Mathf.Max(shadowRes / 2048.0f, 0.0f)); lightData.boxLightSafeExtent = 1.0f - shadowResFactor; } } else if (lightData.lightType == GPULightType.ProjectorPyramid) { // Get width and height for the current frustum var spotAngle = light.spotAngle; float frustumWidth, frustumHeight; if (additionalLightData.aspectRatio >= 1.0f) { frustumHeight = 2.0f * Mathf.Tan(spotAngle * 0.5f * Mathf.Deg2Rad); frustumWidth = frustumHeight * additionalLightData.aspectRatio; } else { frustumWidth = 2.0f * Mathf.Tan(spotAngle * 0.5f * Mathf.Deg2Rad); frustumHeight = frustumWidth / additionalLightData.aspectRatio; } // Adjust based on the new parametrization. lightDimensions.x = frustumWidth; lightDimensions.y = frustumHeight; // Rescale for cookies and windowing. lightData.right *= 2.0f / frustumWidth; lightData.up *= 2.0f / frustumHeight; } if (lightData.lightType == GPULightType.Spot) { var spotAngle = light.spotAngle; var innerConePercent = additionalLightData.innerSpotPercent01; var cosSpotOuterHalfAngle = Mathf.Clamp(Mathf.Cos(spotAngle * 0.5f * Mathf.Deg2Rad), 0.0f, 1.0f); var sinSpotOuterHalfAngle = Mathf.Sqrt(1.0f - cosSpotOuterHalfAngle * cosSpotOuterHalfAngle); var cosSpotInnerHalfAngle = Mathf.Clamp(Mathf.Cos(spotAngle * 0.5f * innerConePercent * Mathf.Deg2Rad), 0.0f, 1.0f); // inner cone var val = Mathf.Max(0.0001f, (cosSpotInnerHalfAngle - cosSpotOuterHalfAngle)); lightData.angleScale = 1.0f / val; lightData.angleOffset = -cosSpotOuterHalfAngle * lightData.angleScale; lightData.iesCut = additionalLightData.spotIESCutoffPercent01; // Rescale for cookies and windowing. float cotOuterHalfAngle = cosSpotOuterHalfAngle / sinSpotOuterHalfAngle; lightData.up *= cotOuterHalfAngle; lightData.right *= cotOuterHalfAngle; } else { // These are the neutral values allowing GetAngleAnttenuation in shader code to return 1.0 lightData.angleScale = 0.0f; lightData.angleOffset = 1.0f; lightData.iesCut = 1.0f; } if (lightData.lightType != GPULightType.Directional && lightData.lightType != GPULightType.ProjectorBox) { // Store the squared radius of the light to simulate a fill light. lightData.size = new Vector4(additionalLightData.shapeRadius * additionalLightData.shapeRadius, 0, 0, 0); } if (lightData.lightType == GPULightType.Rectangle || lightData.lightType == GPULightType.Tube) { lightData.size = new Vector4(additionalLightData.shapeWidth, additionalLightData.shapeHeight, Mathf.Cos(additionalLightData.barnDoorAngle * Mathf.PI / 180.0f), additionalLightData.barnDoorLength); } lightData.lightDimmer = processedData.lightDistanceFade * (additionalLightData.lightDimmer); lightData.diffuseDimmer = processedData.lightDistanceFade * (additionalLightData.affectDiffuse ? additionalLightData.lightDimmer : 0); lightData.specularDimmer = processedData.lightDistanceFade * (additionalLightData.affectSpecular ? additionalLightData.lightDimmer * hdCamera.frameSettings.specularGlobalDimmer : 0); lightData.volumetricLightDimmer = Mathf.Min(processedData.volumetricDistanceFade, processedData.lightDistanceFade) * (additionalLightData.volumetricDimmer); lightData.cookieMode = CookieMode.None; lightData.shadowIndex = -1; lightData.screenSpaceShadowIndex = (int)LightDefinitions.s_InvalidScreenSpaceShadow; lightData.isRayTracedContactShadow = 0.0f; if (lightComponent != null && additionalLightData != null && ( (lightType == HDLightType.Spot && (lightComponent.cookie != null || additionalLightData.IESPoint != null)) || ((lightType == HDLightType.Area && lightData.lightType == GPULightType.Rectangle) && (lightComponent.cookie != null || additionalLightData.IESSpot != null)) || (lightType == HDLightType.Point && (lightComponent.cookie != null || additionalLightData.IESPoint != null)) ) ) { switch (lightType) { case HDLightType.Spot: lightData.cookieMode = (lightComponent.cookie?.wrapMode == TextureWrapMode.Repeat) ? CookieMode.Repeat : CookieMode.Clamp; if (additionalLightData.IESSpot != null && lightComponent.cookie != null && additionalLightData.IESSpot != lightComponent.cookie) lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.Fetch2DCookie(cmd, lightComponent.cookie, additionalLightData.IESSpot); else if (lightComponent.cookie != null) lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.Fetch2DCookie(cmd, lightComponent.cookie); else if (additionalLightData.IESSpot != null) lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.Fetch2DCookie(cmd, additionalLightData.IESSpot); else lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.Fetch2DCookie(cmd, Texture2D.whiteTexture); break; case HDLightType.Point: lightData.cookieMode = CookieMode.Repeat; if (additionalLightData.IESPoint != null && lightComponent.cookie != null && additionalLightData.IESPoint != lightComponent.cookie) lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.FetchCubeCookie(cmd, lightComponent.cookie, additionalLightData.IESPoint); else if (lightComponent.cookie != null) lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.FetchCubeCookie(cmd, lightComponent.cookie); else if (additionalLightData.IESPoint != null) lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.FetchCubeCookie(cmd, additionalLightData.IESPoint); break; case HDLightType.Area: lightData.cookieMode = CookieMode.Clamp; if (additionalLightData.areaLightCookie != null && additionalLightData.IESSpot != null && additionalLightData.areaLightCookie != additionalLightData.IESSpot) lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.FetchAreaCookie(cmd, additionalLightData.areaLightCookie, additionalLightData.IESSpot); else if (additionalLightData.IESSpot != null) lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.FetchAreaCookie(cmd, additionalLightData.IESSpot); else if (additionalLightData.areaLightCookie != null) lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.FetchAreaCookie(cmd, additionalLightData.areaLightCookie); break; } } else if (lightType == HDLightType.Spot && additionalLightData.spotLightShape != SpotLightShape.Cone) { // Projectors lights must always have a cookie texture. // As long as the cache is a texture array and not an atlas, the 4x4 white texture will be rescaled to 128 lightData.cookieMode = CookieMode.Clamp; lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.Fetch2DCookie(cmd, Texture2D.whiteTexture); } else if (lightData.lightType == GPULightType.Rectangle) { if (additionalLightData.areaLightCookie != null || additionalLightData.IESPoint != null) { lightData.cookieMode = CookieMode.Clamp; if (additionalLightData.areaLightCookie != null && additionalLightData.IESSpot != null && additionalLightData.areaLightCookie != additionalLightData.IESSpot) lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.FetchAreaCookie(cmd, additionalLightData.areaLightCookie, additionalLightData.IESSpot); else if (additionalLightData.IESSpot != null) lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.FetchAreaCookie(cmd, additionalLightData.IESSpot); else if (additionalLightData.areaLightCookie != null) lightData.cookieScaleOffset = m_TextureCaches.lightCookieManager.FetchAreaCookie(cmd, additionalLightData.areaLightCookie); } } float shadowDistanceFade = HDUtils.ComputeLinearDistanceFade(processedData.distanceToCamera, Mathf.Min(shadowSettings.maxShadowDistance.value, additionalLightData.shadowFadeDistance)); lightData.shadowDimmer = shadowDistanceFade * additionalLightData.shadowDimmer; lightData.volumetricShadowDimmer = shadowDistanceFade * additionalLightData.volumetricShadowDimmer; GetContactShadowMask(additionalLightData, contactShadowsScalableSetting, hdCamera, isRasterization: isRasterization, ref lightData.contactShadowMask, ref lightData.isRayTracedContactShadow); // We want to have a colored penumbra if the flag is on and the color is not gray bool penumbraTint = additionalLightData.penumbraTint && ((additionalLightData.shadowTint.r != additionalLightData.shadowTint.g) || (additionalLightData.shadowTint.g != additionalLightData.shadowTint.b)); lightData.penumbraTint = penumbraTint ? 1.0f : 0.0f; if (penumbraTint) lightData.shadowTint = new Vector3(Mathf.Pow(additionalLightData.shadowTint.r, 2.2f), Mathf.Pow(additionalLightData.shadowTint.g, 2.2f), Mathf.Pow(additionalLightData.shadowTint.b, 2.2f)); else lightData.shadowTint = new Vector3(additionalLightData.shadowTint.r, additionalLightData.shadowTint.g, additionalLightData.shadowTint.b); // If there is still a free slot in the screen space shadow array and this needs to render a screen space shadow if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && EnoughScreenSpaceShadowSlots(lightData.lightType, screenSpaceChannelSlot) && additionalLightData.WillRenderScreenSpaceShadow() && isRasterization) { if (lightData.lightType == GPULightType.Rectangle) { // Rectangle area lights require 2 consecutive slots. // Meaning if (screenSpaceChannelSlot % 4 ==3), we'll need to skip a slot // so that the area shadow gets the first two slots of the next following texture if (screenSpaceChannelSlot % 4 == 3) { screenSpaceChannelSlot++; } } // Bind the next available slot to the light lightData.screenSpaceShadowIndex = screenSpaceChannelSlot; // Keep track of the screen space shadow data m_CurrentScreenSpaceShadowData[screenSpaceShadowIndex].additionalLightData = additionalLightData; m_CurrentScreenSpaceShadowData[screenSpaceShadowIndex].lightDataIndex = m_lightList.lights.Count; m_CurrentScreenSpaceShadowData[screenSpaceShadowIndex].valid = true; m_ScreenSpaceShadowsUnion.Add(additionalLightData); // increment the number of screen space shadows screenSpaceShadowIndex++; // Based on the light type, increment the slot usage if (lightData.lightType == GPULightType.Rectangle) screenSpaceChannelSlot += 2; else screenSpaceChannelSlot++; } lightData.shadowIndex = shadowIndex; if (isRasterization) { // Keep track of the shadow map (for indirect lighting and transparents) additionalLightData.shadowIndex = shadowIndex; } //Value of max smoothness is derived from Radius. Formula results from eyeballing. Radius of 0 results in 1 and radius of 2.5 results in 0. float maxSmoothness = Mathf.Clamp01(1.1725f / (1.01f + Mathf.Pow(1.0f * (additionalLightData.shapeRadius + 0.1f), 2f)) - 0.15f); // Value of max smoothness is from artists point of view, need to convert from perceptual smoothness to roughness lightData.minRoughness = (1.0f - maxSmoothness) * (1.0f - maxSmoothness); lightData.shadowMaskSelector = Vector4.zero; if (processedData.isBakedShadowMask) { lightData.shadowMaskSelector[lightComponent.bakingOutput.occlusionMaskChannel] = 1.0f; lightData.nonLightMappedOnly = lightComponent.lightShadowCasterMode == LightShadowCasterMode.NonLightmappedOnly ? 1 : 0; } else { // use -1 to say that we don't use shadow mask lightData.shadowMaskSelector.x = -1.0f; lightData.nonLightMappedOnly = 0; } } // TODO: we should be able to do this calculation only with LightData without VisibleLight light, but for now pass both void GetLightVolumeDataAndBound(LightCategory lightCategory, GPULightType gpuLightType, LightVolumeType lightVolumeType, VisibleLight light, LightData lightData, Vector3 lightDimensions, Matrix4x4 worldToView, int viewIndex) { // Then Culling side var range = lightDimensions.z; var lightToWorld = light.localToWorldMatrix; Vector3 positionWS = lightData.positionRWS; Vector3 positionVS = worldToView.MultiplyPoint(positionWS); Vector3 xAxisVS = worldToView.MultiplyVector(lightToWorld.GetColumn(0)); Vector3 yAxisVS = worldToView.MultiplyVector(lightToWorld.GetColumn(1)); Vector3 zAxisVS = worldToView.MultiplyVector(lightToWorld.GetColumn(2)); // Fill bounds var bound = new SFiniteLightBound(); var lightVolumeData = new LightVolumeData(); lightVolumeData.lightCategory = (uint)lightCategory; lightVolumeData.lightVolume = (uint)lightVolumeType; if (gpuLightType == GPULightType.Spot || gpuLightType == GPULightType.ProjectorPyramid) { Vector3 lightDir = lightToWorld.GetColumn(2); // represents a left hand coordinate system in world space since det(worldToView)<0 Vector3 vx = xAxisVS; Vector3 vy = yAxisVS; Vector3 vz = zAxisVS; var sa = light.spotAngle; var cs = Mathf.Cos(0.5f * sa * Mathf.Deg2Rad); var si = Mathf.Sin(0.5f * sa * Mathf.Deg2Rad); if (gpuLightType == GPULightType.ProjectorPyramid) { Vector3 lightPosToProjWindowCorner = (0.5f * lightDimensions.x) * vx + (0.5f * lightDimensions.y) * vy + 1.0f * vz; cs = Vector3.Dot(vz, Vector3.Normalize(lightPosToProjWindowCorner)); si = Mathf.Sqrt(1.0f - cs * cs); } const float FltMax = 3.402823466e+38F; var ta = cs > 0.0f ? (si / cs) : FltMax; var cota = si > 0.0f ? (cs / si) : FltMax; //const float cotasa = l.GetCotanHalfSpotAngle(); // apply nonuniform scale to OBB of spot light var squeeze = true;//sa < 0.7f * 90.0f; // arb heuristic var fS = squeeze ? ta : si; bound.center = worldToView.MultiplyPoint(positionWS + ((0.5f * range) * lightDir)); // use mid point of the spot as the center of the bounding volume for building screen-space AABB for tiled lighting. // scale axis to match box or base of pyramid bound.boxAxisX = (fS * range) * vx; bound.boxAxisY = (fS * range) * vy; bound.boxAxisZ = (0.5f * range) * vz; // generate bounding sphere radius var fAltDx = si; var fAltDy = cs; fAltDy = fAltDy - 0.5f; //if(fAltDy<0) fAltDy=-fAltDy; fAltDx *= range; fAltDy *= range; // Handle case of pyramid with this select (currently unused) var altDist = Mathf.Sqrt(fAltDy * fAltDy + (true ? 1.0f : 2.0f) * fAltDx * fAltDx); bound.radius = altDist > (0.5f * range) ? altDist : (0.5f * range); // will always pick fAltDist bound.scaleXY = squeeze ? 0.01f : 1.0f; lightVolumeData.lightAxisX = vx; lightVolumeData.lightAxisY = vy; lightVolumeData.lightAxisZ = vz; lightVolumeData.lightPos = positionVS; lightVolumeData.radiusSq = range * range; lightVolumeData.cotan = cota; lightVolumeData.featureFlags = (uint)LightFeatureFlags.Punctual; } else if (gpuLightType == GPULightType.Point) { // Construct a view-space axis-aligned bounding cube around the bounding sphere. // This allows us to utilize the same polygon clipping technique for all lights. // Non-axis-aligned vectors may result in a larger screen-space AABB. Vector3 vx = new Vector3(1, 0, 0); Vector3 vy = new Vector3(0, 1, 0); Vector3 vz = new Vector3(0, 0, 1); bound.center = positionVS; bound.boxAxisX = vx * range; bound.boxAxisY = vy * range; bound.boxAxisZ = vz * range; bound.scaleXY = 1.0f; bound.radius = range; // fill up ldata lightVolumeData.lightAxisX = vx; lightVolumeData.lightAxisY = vy; lightVolumeData.lightAxisZ = vz; lightVolumeData.lightPos = bound.center; lightVolumeData.radiusSq = range * range; lightVolumeData.featureFlags = (uint)LightFeatureFlags.Punctual; } else if (gpuLightType == GPULightType.Tube) { Vector3 dimensions = new Vector3(lightDimensions.x + 2 * range, 2 * range, 2 * range); // Omni-directional Vector3 extents = 0.5f * dimensions; Vector3 centerVS = positionVS; bound.center = centerVS; bound.boxAxisX = extents.x * xAxisVS; bound.boxAxisY = extents.y * yAxisVS; bound.boxAxisZ = extents.z * zAxisVS; bound.radius = extents.x; bound.scaleXY = 1.0f; lightVolumeData.lightPos = centerVS; lightVolumeData.lightAxisX = xAxisVS; lightVolumeData.lightAxisY = yAxisVS; lightVolumeData.lightAxisZ = zAxisVS; lightVolumeData.boxInvRange.Set(1.0f / extents.x, 1.0f / extents.y, 1.0f / extents.z); lightVolumeData.featureFlags = (uint)LightFeatureFlags.Area; } else if (gpuLightType == GPULightType.Rectangle) { Vector3 dimensions = new Vector3(lightDimensions.x + 2 * range, lightDimensions.y + 2 * range, range); // One-sided Vector3 extents = 0.5f * dimensions; Vector3 centerVS = positionVS + extents.z * zAxisVS; float d = range + 0.5f * Mathf.Sqrt(lightDimensions.x * lightDimensions.x + lightDimensions.y * lightDimensions.y); bound.center = centerVS; bound.boxAxisX = extents.x * xAxisVS; bound.boxAxisY = extents.y * yAxisVS; bound.boxAxisZ = extents.z * zAxisVS; bound.radius = Mathf.Sqrt(d * d + (0.5f * range) * (0.5f * range)); bound.scaleXY = 1.0f; lightVolumeData.lightPos = centerVS; lightVolumeData.lightAxisX = xAxisVS; lightVolumeData.lightAxisY = yAxisVS; lightVolumeData.lightAxisZ = zAxisVS; lightVolumeData.boxInvRange.Set(1.0f / extents.x, 1.0f / extents.y, 1.0f / extents.z); lightVolumeData.featureFlags = (uint)LightFeatureFlags.Area; } else if (gpuLightType == GPULightType.ProjectorBox) { Vector3 dimensions = new Vector3(lightDimensions.x, lightDimensions.y, range); // One-sided Vector3 extents = 0.5f * dimensions; Vector3 centerVS = positionVS + extents.z * zAxisVS; bound.center = centerVS; bound.boxAxisX = extents.x * xAxisVS; bound.boxAxisY = extents.y * yAxisVS; bound.boxAxisZ = extents.z * zAxisVS; bound.radius = extents.magnitude; bound.scaleXY = 1.0f; lightVolumeData.lightPos = centerVS; lightVolumeData.lightAxisX = xAxisVS; lightVolumeData.lightAxisY = yAxisVS; lightVolumeData.lightAxisZ = zAxisVS; lightVolumeData.boxInvRange.Set(1.0f / extents.x, 1.0f / extents.y, 1.0f / extents.z); lightVolumeData.featureFlags = (uint)LightFeatureFlags.Punctual; } else if (gpuLightType == GPULightType.Disc) { //not supported at real time at the moment } else { Debug.Assert(false, "TODO: encountered an unknown GPULightType."); } m_lightList.lightsPerView[viewIndex].bounds.Add(bound); m_lightList.lightsPerView[viewIndex].lightVolumes.Add(lightVolumeData); } internal bool GetEnvLightData(CommandBuffer cmd, HDCamera hdCamera, in ProcessedProbeData processedProbe, ref EnvLightData envLightData) { // By default, rough reflections are enabled for both types of probes. envLightData.roughReflections = 1.0f; envLightData.distanceBasedRoughness = 0.0f; Camera camera = hdCamera.camera; HDProbe probe = processedProbe.hdProbe; // Skip the probe if the probe has never rendered (in realtime cases) or if texture is null if (!probe.HasValidRenderedData()) return false; var capturePosition = Vector3.zero; var influenceToWorld = probe.influenceToWorld; Vector4 atlasScaleOffset = Vector4.zero; // 31 bits index, 1 bit cache type var envIndex = int.MinValue; switch (probe) { case PlanarReflectionProbe planarProbe: { if (probe.mode == ProbeSettings.Mode.Realtime && !hdCamera.frameSettings.IsEnabled(FrameSettingsField.PlanarProbe)) break; // Grab the render data that was used to render the probe var renderData = planarProbe.renderData; // Grab the world to camera matrix of the capture camera var worldToCameraRHSMatrix = renderData.worldToCameraRHS; // Grab the projection matrix that was used to render var projectionMatrix = renderData.projectionMatrix; // Build an alternative matrix for projection that is not oblique var projectionMatrixNonOblique = Matrix4x4.Perspective(renderData.fieldOfView, probe.texture.width / probe.texture.height, probe.settings.cameraSettings.frustum.nearClipPlaneRaw, probe.settings.cameraSettings.frustum.farClipPlane); // Convert the projection matrices to their GPU version var gpuProj = GL.GetGPUProjectionMatrix(projectionMatrix, true); var gpuProjNonOblique = GL.GetGPUProjectionMatrix(projectionMatrixNonOblique, true); // Build the oblique and non oblique view projection matrices var vp = gpuProj * worldToCameraRHSMatrix; var vpNonOblique = gpuProjNonOblique * worldToCameraRHSMatrix; // We need to collect the set of parameters required for the filtering IBLFilterBSDF.PlanarTextureFilteringParameters planarTextureFilteringParameters = new IBLFilterBSDF.PlanarTextureFilteringParameters(); planarTextureFilteringParameters.smoothPlanarReflection = !probe.settings.roughReflections; planarTextureFilteringParameters.probeNormal = Vector3.Normalize(hdCamera.camera.transform.position - renderData.capturePosition); planarTextureFilteringParameters.probePosition = probe.gameObject.transform.position; planarTextureFilteringParameters.captureCameraDepthBuffer = planarProbe.realtimeDepthTexture; planarTextureFilteringParameters.captureCameraScreenSize = new Vector4(probe.texture.width, probe.texture.height, 1.0f / probe.texture.width, 1.0f / probe.texture.height); planarTextureFilteringParameters.captureCameraIVP = vp.inverse; planarTextureFilteringParameters.captureCameraIVP_NonOblique = vpNonOblique.inverse; planarTextureFilteringParameters.captureCameraVP_NonOblique = vpNonOblique; planarTextureFilteringParameters.captureCameraPosition = renderData.capturePosition; planarTextureFilteringParameters.captureFOV = renderData.fieldOfView; planarTextureFilteringParameters.captureNearPlane = probe.settings.cameraSettings.frustum.nearClipPlaneRaw; planarTextureFilteringParameters.captureFarPlane = probe.settings.cameraSettings.frustum.farClipPlane; // Fetch the slice and do the filtering var scaleOffset = m_TextureCaches.reflectionPlanarProbeCache.FetchSlice(cmd, probe.texture, ref planarTextureFilteringParameters, out int fetchIndex); // We don't need to provide the capture position // It is already encoded in the 'worldToCameraRHSMatrix' capturePosition = Vector3.zero; // Indices start at 1, because -0 == 0, we can know from the bit sign which cache to use envIndex = scaleOffset == Vector4.zero ? int.MinValue : -(fetchIndex + 1); // If the max number of planar on screen is reached if (fetchIndex >= m_MaxPlanarReflectionOnScreen) { Debug.LogWarning("Maximum planar reflection probe on screen reached. To fix this error, increase the maximum number of planar reflections on screen in the HDRP asset."); break; } atlasScaleOffset = scaleOffset; m_TextureCaches.env2DAtlasScaleOffset[fetchIndex] = scaleOffset; m_TextureCaches.env2DCaptureVP[fetchIndex] = vp; // Propagate the smoothness information to the env light data envLightData.roughReflections = probe.settings.roughReflections ? 1.0f : 0.0f; var capturedForwardWS = renderData.captureRotation * Vector3.forward; //capturedForwardWS.z *= -1; // Transform to RHS standard m_TextureCaches.env2DCaptureForward[fetchIndex] = new Vector4(capturedForwardWS.x, capturedForwardWS.y, capturedForwardWS.z, 0.0f); //We must use the setting resolved from the probe, not from the frameSettings. //Using the frmaeSettings from the probe is wrong because it can be disabled (not ticking on using custom frame settings in the probe reflection component) if (probe.ExposureControlEnabled) envLightData.rangeCompressionFactorCompensation = 1.0f / probe.ProbeExposureValue(); else envLightData.rangeCompressionFactorCompensation = Mathf.Max(probe.rangeCompressionFactor, 1e-6f); break; } case HDAdditionalReflectionData _: { envIndex = m_TextureCaches.reflectionProbeCache.FetchSlice(cmd, probe.texture); // Indices start at 1, because -0 == 0, we can know from the bit sign which cache to use envIndex = envIndex == -1 ? int.MinValue : (envIndex + 1); // Calculate settings to use for the probe var probePositionSettings = ProbeCapturePositionSettings.ComputeFrom(probe, camera.transform); HDRenderUtilities.ComputeCameraSettingsFromProbeSettings( probe.settings, probePositionSettings, out _, out var cameraPositionSettings, 0 ); capturePosition = cameraPositionSettings.position; envLightData.rangeCompressionFactorCompensation = Mathf.Max(probe.rangeCompressionFactor, 1e-6f); // Propagate the distance based information to the env light data (only if we are not an infinite projection) envLightData.distanceBasedRoughness = probe.settings.distanceBasedRoughness && !probe.isProjectionInfinite ? 1.0f : 0.0f; break; } } // int.MinValue means that the texture is not ready yet (ie not convolved/compressed yet) if (envIndex == int.MinValue) return false; InfluenceVolume influence = probe.influenceVolume; envLightData.lightLayers = hdCamera.frameSettings.IsEnabled(FrameSettingsField.LightLayers) ? probe.lightLayersAsUInt : uint.MaxValue; envLightData.influenceShapeType = influence.envShape; envLightData.weight = processedProbe.weight; envLightData.multiplier = probe.multiplier * m_indirectLightingController.reflectionProbeIntensityMultiplier.value; envLightData.influenceExtents = influence.extents; switch (influence.envShape) { case EnvShapeType.Box: envLightData.blendDistancePositive = influence.boxBlendDistancePositive; envLightData.blendDistanceNegative = influence.boxBlendDistanceNegative; if (envIndex >= 0) // Reflection Probes { envLightData.blendNormalDistancePositive = influence.boxBlendNormalDistancePositive; envLightData.blendNormalDistanceNegative = influence.boxBlendNormalDistanceNegative; envLightData.boxSideFadePositive = influence.boxSideFadePositive; envLightData.boxSideFadeNegative = influence.boxSideFadeNegative; } else // Planar Probes { envLightData.blendNormalDistancePositive = Vector3.zero; envLightData.blendNormalDistanceNegative = Vector3.zero; envLightData.boxSideFadePositive = Vector3.one; envLightData.boxSideFadeNegative = Vector3.one; } break; case EnvShapeType.Sphere: envLightData.blendDistancePositive.x = influence.sphereBlendDistance; if (envIndex >= 0) // Reflection Probes envLightData.blendNormalDistancePositive.x = influence.sphereBlendNormalDistance; else // Planar Probes envLightData.blendNormalDistancePositive.x = 0; break; default: throw new ArgumentOutOfRangeException("Unknown EnvShapeType"); } envLightData.influenceRight = influenceToWorld.GetColumn(0).normalized; envLightData.influenceUp = influenceToWorld.GetColumn(1).normalized; envLightData.influenceForward = influenceToWorld.GetColumn(2).normalized; envLightData.capturePositionRWS = capturePosition; envLightData.influencePositionRWS = influenceToWorld.GetColumn(3); envLightData.envIndex = envIndex; // Proxy data var proxyToWorld = probe.proxyToWorld; envLightData.proxyExtents = probe.proxyExtents; envLightData.minProjectionDistance = probe.isProjectionInfinite ? 65504f : 0; envLightData.proxyRight = proxyToWorld.GetColumn(0).normalized; envLightData.proxyUp = proxyToWorld.GetColumn(1).normalized; envLightData.proxyForward = proxyToWorld.GetColumn(2).normalized; envLightData.proxyPositionRWS = proxyToWorld.GetColumn(3); return true; } void GetEnvLightVolumeDataAndBound(HDProbe probe, LightVolumeType lightVolumeType, Matrix4x4 worldToView, int viewIndex) { var bound = new SFiniteLightBound(); var lightVolumeData = new LightVolumeData(); // C is reflection volume center in world space (NOT same as cube map capture point) var influenceExtents = probe.influenceExtents; // 0.5f * Vector3.Max(-boxSizes[p], boxSizes[p]); var influenceToWorld = probe.influenceToWorld; // transform to camera space (becomes a left hand coordinate frame in Unity since Determinant(worldToView)<0) var influenceRightVS = worldToView.MultiplyVector(influenceToWorld.GetColumn(0).normalized); var influenceUpVS = worldToView.MultiplyVector(influenceToWorld.GetColumn(1).normalized); var influenceForwardVS = worldToView.MultiplyVector(influenceToWorld.GetColumn(2).normalized); var influencePositionVS = worldToView.MultiplyPoint(influenceToWorld.GetColumn(3)); lightVolumeData.lightCategory = (uint)LightCategory.Env; lightVolumeData.lightVolume = (uint)lightVolumeType; lightVolumeData.featureFlags = (uint)LightFeatureFlags.Env; switch (lightVolumeType) { case LightVolumeType.Sphere: { lightVolumeData.lightPos = influencePositionVS; lightVolumeData.radiusSq = influenceExtents.x * influenceExtents.x; lightVolumeData.lightAxisX = influenceRightVS; lightVolumeData.lightAxisY = influenceUpVS; lightVolumeData.lightAxisZ = influenceForwardVS; bound.center = influencePositionVS; bound.boxAxisX = influenceRightVS * influenceExtents.x; bound.boxAxisY = influenceUpVS * influenceExtents.x; bound.boxAxisZ = influenceForwardVS * influenceExtents.x; bound.scaleXY = 1.0f; bound.radius = influenceExtents.x; break; } case LightVolumeType.Box: { bound.center = influencePositionVS; bound.boxAxisX = influenceExtents.x * influenceRightVS; bound.boxAxisY = influenceExtents.y * influenceUpVS; bound.boxAxisZ = influenceExtents.z * influenceForwardVS; bound.scaleXY = 1.0f; bound.radius = influenceExtents.magnitude; // The culling system culls pixels that are further // than a threshold to the box influence extents. // So we use an arbitrary threshold here (k_BoxCullingExtentOffset) lightVolumeData.lightPos = influencePositionVS; lightVolumeData.lightAxisX = influenceRightVS; lightVolumeData.lightAxisY = influenceUpVS; lightVolumeData.lightAxisZ = influenceForwardVS; lightVolumeData.boxInnerDist = influenceExtents - k_BoxCullingExtentThreshold; lightVolumeData.boxInvRange.Set(1.0f / k_BoxCullingExtentThreshold.x, 1.0f / k_BoxCullingExtentThreshold.y, 1.0f / k_BoxCullingExtentThreshold.z); break; } } m_lightList.lightsPerView[viewIndex].bounds.Add(bound); m_lightList.lightsPerView[viewIndex].lightVolumes.Add(lightVolumeData); } void CreateBoxVolumeDataAndBound(OrientedBBox obb, LightCategory category, LightFeatureFlags featureFlags, Matrix4x4 worldToView, float normalBiasDilation, out LightVolumeData volumeData, out SFiniteLightBound bound) { volumeData = new LightVolumeData(); bound = new SFiniteLightBound(); // Used in Probe Volumes: // Conservatively dilate bounds used for tile / cluster assignment by normal bias. // Otherwise, surfaces could bias outside of valid data within a tile. var extentConservativeX = obb.extentX + normalBiasDilation; var extentConservativeY = obb.extentY + normalBiasDilation; var extentConservativeZ = obb.extentZ + normalBiasDilation; var extentConservativeMagnitude = Mathf.Sqrt(extentConservativeX * extentConservativeX + extentConservativeY * extentConservativeY + extentConservativeZ * extentConservativeZ); // transform to camera space (becomes a left hand coordinate frame in Unity since Determinant(worldToView)<0) var positionVS = worldToView.MultiplyPoint(obb.center); var rightVS = worldToView.MultiplyVector(obb.right); var upVS = worldToView.MultiplyVector(obb.up); var forwardVS = Vector3.Cross(upVS, rightVS); var extents = new Vector3(extentConservativeX, extentConservativeY, extentConservativeZ); volumeData.lightVolume = (uint)LightVolumeType.Box; volumeData.lightCategory = (uint)category; volumeData.featureFlags = (uint)featureFlags; bound.center = positionVS; bound.boxAxisX = extentConservativeX * rightVS; bound.boxAxisY = extentConservativeY * upVS; bound.boxAxisZ = extentConservativeZ * forwardVS; bound.radius = extentConservativeMagnitude; bound.scaleXY = 1.0f; // The culling system culls pixels that are further // than a threshold to the box influence extents. // So we use an arbitrary threshold here (k_BoxCullingExtentOffset) volumeData.lightPos = positionVS; volumeData.lightAxisX = rightVS; volumeData.lightAxisY = upVS; volumeData.lightAxisZ = forwardVS; volumeData.boxInnerDist = extents - k_BoxCullingExtentThreshold; // We have no blend range, but the culling code needs a small EPS value for some reason??? volumeData.boxInvRange.Set(1.0f / k_BoxCullingExtentThreshold.x, 1.0f / k_BoxCullingExtentThreshold.y, 1.0f / k_BoxCullingExtentThreshold.z); } internal int GetCurrentShadowCount() { return m_ShadowManager.GetShadowRequestCount(); } void LightLoopUpdateCullingParameters(ref ScriptableCullingParameters cullingParams, HDCamera hdCamera) { var shadowMaxDistance = hdCamera.volumeStack.GetComponent<HDShadowSettings>().maxShadowDistance.value; m_ShadowManager.UpdateCullingParameters(ref cullingParams, shadowMaxDistance); // In HDRP we don't need per object light/probe info so we disable the native code that handles it. cullingParams.cullingOptions |= CullingOptions.DisablePerObjectCulling; } internal static bool IsBakedShadowMaskLight(Light light) { // This can happen for particle lights. if (light == null) return false; return light.bakingOutput.lightmapBakeType == LightmapBakeType.Mixed && light.bakingOutput.mixedLightingMode == MixedLightingMode.Shadowmask && light.bakingOutput.occlusionMaskChannel != -1; // We need to have an occlusion mask channel assign, else we have no shadow mask } internal static void EvaluateGPULightType(HDLightType lightType, SpotLightShape spotLightShape, AreaLightShape areaLightShape, ref LightCategory lightCategory, ref GPULightType gpuLightType, ref LightVolumeType lightVolumeType) { lightCategory = LightCategory.Count; gpuLightType = GPULightType.Point; lightVolumeType = LightVolumeType.Count; switch (lightType) { case HDLightType.Spot: lightCategory = LightCategory.Punctual; switch (spotLightShape) { case SpotLightShape.Cone: gpuLightType = GPULightType.Spot; lightVolumeType = LightVolumeType.Cone; break; case SpotLightShape.Pyramid: gpuLightType = GPULightType.ProjectorPyramid; lightVolumeType = LightVolumeType.Cone; break; case SpotLightShape.Box: gpuLightType = GPULightType.ProjectorBox; lightVolumeType = LightVolumeType.Box; break; default: Debug.Assert(false, "Encountered an unknown SpotLightShape."); break; } break; case HDLightType.Directional: lightCategory = LightCategory.Punctual; gpuLightType = GPULightType.Directional; // No need to add volume, always visible lightVolumeType = LightVolumeType.Count; // Count is none break; case HDLightType.Point: lightCategory = LightCategory.Punctual; gpuLightType = GPULightType.Point; lightVolumeType = LightVolumeType.Sphere; break; case HDLightType.Area: lightCategory = LightCategory.Area; switch (areaLightShape) { case AreaLightShape.Rectangle: gpuLightType = GPULightType.Rectangle; lightVolumeType = LightVolumeType.Box; break; case AreaLightShape.Tube: gpuLightType = GPULightType.Tube; lightVolumeType = LightVolumeType.Box; break; case AreaLightShape.Disc: //not used in real-time at the moment anyway gpuLightType = GPULightType.Disc; lightVolumeType = LightVolumeType.Sphere; break; default: Debug.Assert(false, "Encountered an unknown AreaLightShape."); break; } break; default: Debug.Assert(false, "Encountered an unknown LightType."); break; } } bool TrivialRejectLight(VisibleLight light, HDCamera hdCamera, in AOVRequestData aovRequest) { // We can skip the processing of lights that are so small to not affect at least a pixel on screen. // TODO: The minimum pixel size on screen should really be exposed as parameter, to allow small lights to be culled to user's taste. const int minimumPixelAreaOnScreen = 1; if ((light.screenRect.height * hdCamera.actualHeight) * (light.screenRect.width * hdCamera.actualWidth) < minimumPixelAreaOnScreen) { return true; } if (light.light != null && !aovRequest.IsLightEnabled(light.light.gameObject)) return true; return false; } // Compute data that will be used during the light loop for a particular light. void PreprocessLightData(ref ProcessedLightData processedData, VisibleLight light, HDCamera hdCamera) { Light lightComponent = light.light; HDAdditionalLightData additionalLightData = GetHDAdditionalLightData(lightComponent); processedData.additionalLightData = additionalLightData; processedData.lightType = additionalLightData.ComputeLightType(lightComponent); processedData.distanceToCamera = (additionalLightData.transform.position - hdCamera.camera.transform.position).magnitude; // Evaluate the types that define the current light processedData.lightCategory = LightCategory.Count; processedData.gpuLightType = GPULightType.Point; processedData.lightVolumeType = LightVolumeType.Count; HDRenderPipeline.EvaluateGPULightType(processedData.lightType, processedData.additionalLightData.spotLightShape, processedData.additionalLightData.areaLightShape, ref processedData.lightCategory, ref processedData.gpuLightType, ref processedData.lightVolumeType); processedData.lightDistanceFade = processedData.gpuLightType == GPULightType.Directional ? 1.0f : HDUtils.ComputeLinearDistanceFade(processedData.distanceToCamera, additionalLightData.fadeDistance); processedData.volumetricDistanceFade = processedData.gpuLightType == GPULightType.Directional ? 1.0f : HDUtils.ComputeLinearDistanceFade(processedData.distanceToCamera, additionalLightData.volumetricFadeDistance); processedData.isBakedShadowMask = IsBakedShadowMaskLight(lightComponent); } // This will go through the list of all visible light and do two main things: // - Precompute data that will be reused through the light loop // - Discard all lights considered unnecessary (too far away, explicitly discarded by type, ...) int PreprocessVisibleLights(HDCamera hdCamera, CullingResults cullResults, DebugDisplaySettings debugDisplaySettings, in AOVRequestData aovRequest) { var hdShadowSettings = hdCamera.volumeStack.GetComponent<HDShadowSettings>(); var debugLightFilter = debugDisplaySettings.GetDebugLightFilterMode(); var hasDebugLightFilter = debugLightFilter != DebugLightFilterMode.None; // 1. Count the number of lights and sort all lights by category, type and volume - This is required for the fptl/cluster shader code // If we reach maximum of lights available on screen, then we discard the light. // Lights are processed in order, so we don't discards light based on their importance but based on their ordering in visible lights list. int directionalLightcount = 0; int punctualLightcount = 0; int areaLightCount = 0; m_ProcessedLightData.Resize(cullResults.visibleLights.Length); int lightCount = Math.Min(cullResults.visibleLights.Length, m_MaxLightsOnScreen); UpdateSortKeysArray(lightCount); int sortCount = 0; for (int lightIndex = 0, numLights = cullResults.visibleLights.Length; (lightIndex < numLights) && (sortCount < lightCount); ++lightIndex) { var light = cullResults.visibleLights[lightIndex]; // First we do all the trivial rejects. if (TrivialRejectLight(light, hdCamera, aovRequest)) continue; // Then we compute all light data that will be reused for the rest of the light loop. ref ProcessedLightData processedData = ref m_ProcessedLightData[lightIndex]; PreprocessLightData(ref processedData, light, hdCamera); // Then we can reject lights based on processed data. var additionalData = processedData.additionalLightData; // If the camera is in ray tracing mode and the light is disabled in ray tracing mode, we skip this light. if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && !additionalData.includeForRayTracing) continue; var lightType = processedData.lightType; if (ShaderConfig.s_AreaLights == 0 && (lightType == HDLightType.Area && (additionalData.areaLightShape == AreaLightShape.Rectangle || additionalData.areaLightShape == AreaLightShape.Tube))) continue; bool contributesToLighting = ((additionalData.lightDimmer > 0) && (additionalData.affectDiffuse || additionalData.affectSpecular)) || (additionalData.volumetricDimmer > 0); contributesToLighting = contributesToLighting && (processedData.lightDistanceFade > 0); if (!contributesToLighting) continue; // Do NOT process lights beyond the specified limit! switch (processedData.lightCategory) { case LightCategory.Punctual: if (processedData.gpuLightType == GPULightType.Directional) // Our directional lights are "punctual"... { if (!debugDisplaySettings.data.lightingDebugSettings.showDirectionalLight || directionalLightcount >= m_MaxDirectionalLightsOnScreen) continue; directionalLightcount++; break; } if (!debugDisplaySettings.data.lightingDebugSettings.showPunctualLight || punctualLightcount >= m_MaxPunctualLightsOnScreen) continue; punctualLightcount++; break; case LightCategory.Area: if (!debugDisplaySettings.data.lightingDebugSettings.showAreaLight || areaLightCount >= m_MaxAreaLightsOnScreen) continue; areaLightCount++; break; default: break; } // First we should evaluate the shadow information for this frame additionalData.EvaluateShadowState(hdCamera, processedData, cullResults, hdCamera.frameSettings, lightIndex); // Reserve shadow map resolutions and check if light needs to render shadows if (additionalData.WillRenderShadowMap()) { additionalData.ReserveShadowMap(hdCamera.camera, m_ShadowManager, hdShadowSettings, m_ShadowInitParameters, light, lightType); } // Reserve the cookie resolution in the 2D atlas ReserveCookieAtlasTexture(additionalData, light.light, lightType); if (hasDebugLightFilter && !debugLightFilter.IsEnabledFor(processedData.gpuLightType, additionalData.spotLightShape)) continue; // 5 bit (0x1F) light category, 5 bit (0x1F) GPULightType, 5 bit (0x1F) lightVolume, 1 bit for shadow casting, 16 bit index m_SortKeys[sortCount++] = (uint)processedData.lightCategory << 27 | (uint)processedData.gpuLightType << 22 | (uint)processedData.lightVolumeType << 17 | (uint)lightIndex; } CoreUnsafeUtils.QuickSort(m_SortKeys, 0, sortCount - 1); // Call our own quicksort instead of Array.Sort(sortKeys, 0, sortCount) so we don't allocate memory (note the SortCount-1 that is different from original call). return sortCount; } void PrepareGPULightdata(CommandBuffer cmd, HDCamera hdCamera, CullingResults cullResults, int processedLightCount) { Vector3 camPosWS = hdCamera.mainViewConstants.worldSpaceCameraPos; int directionalLightcount = 0; int punctualLightcount = 0; int areaLightCount = 0; // Now that all the lights have requested a shadow resolution, we can layout them in the atlas // And if needed rescale the whole atlas m_ShadowManager.LayoutShadowMaps(m_CurrentDebugDisplaySettings.data.lightingDebugSettings); // Using the same pattern than shadowmaps, light have requested space in the atlas for their // cookies and now we can layout the atlas (re-insert all entries by order of size) if needed m_TextureCaches.lightCookieManager.LayoutIfNeeded(); var visualEnvironment = hdCamera.volumeStack.GetComponent<VisualEnvironment>(); Debug.Assert(visualEnvironment != null); bool isPbrSkyActive = visualEnvironment.skyType.value == (int)SkyType.PhysicallyBased; var hdShadowSettings = hdCamera.volumeStack.GetComponent<HDShadowSettings>(); // TODO: Refactor shadow management // The good way of managing shadow: // Here we sort everyone and we decide which light is important or not (this is the responsibility of the lightloop) // we allocate shadow slot based on maximum shadow allowed on screen and attribute slot by bigger solid angle // THEN we ask to the ShadowRender to render the shadow, not the reverse as it is today (i.e render shadow than expect they // will be use...) // The lightLoop is in charge, not the shadow pass. // For now we will still apply the maximum of shadow here but we don't apply the sorting by priority + slot allocation yet BoolScalableSetting contactShadowScalableSetting = HDAdditionalLightData.ScalableSettings.UseContactShadow(m_Asset); var shadowFilteringQuality = HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.hdShadowInitParams.shadowFilteringQuality; // 2. Go through all lights, convert them to GPU format. // Simultaneously create data for culling (LightVolumeData and SFiniteLightBound) for (int sortIndex = 0; sortIndex < processedLightCount; ++sortIndex) { // In 1. we have already classify and sorted the light, we need to use this sorted order here uint sortKey = m_SortKeys[sortIndex]; LightCategory lightCategory = (LightCategory)((sortKey >> 27) & 0x1F); GPULightType gpuLightType = (GPULightType)((sortKey >> 22) & 0x1F); LightVolumeType lightVolumeType = (LightVolumeType)((sortKey >> 17) & 0x1F); int lightIndex = (int)(sortKey & 0xFFFF); var light = cullResults.visibleLights[lightIndex]; var lightComponent = light.light; ProcessedLightData processedData = m_ProcessedLightData[lightIndex]; m_EnableBakeShadowMask = m_EnableBakeShadowMask || processedData.isBakedShadowMask; // Light should always have additional data, however preview light right don't have, so we must handle the case by assigning HDUtils.s_DefaultHDAdditionalLightData var additionalLightData = processedData.additionalLightData; int shadowIndex = -1; // Manage shadow requests if (additionalLightData.WillRenderShadowMap()) { int shadowRequestCount; shadowIndex = additionalLightData.UpdateShadowRequest(hdCamera, m_ShadowManager, hdShadowSettings, light, cullResults, lightIndex, m_CurrentDebugDisplaySettings.data.lightingDebugSettings, shadowFilteringQuality, out shadowRequestCount); #if UNITY_EDITOR if ((m_CurrentDebugDisplaySettings.data.lightingDebugSettings.shadowDebugUseSelection || m_CurrentDebugDisplaySettings.data.lightingDebugSettings.shadowDebugMode == ShadowMapDebugMode.SingleShadow) && UnityEditor.Selection.activeGameObject == lightComponent.gameObject) { m_DebugSelectedLightShadowIndex = shadowIndex; m_DebugSelectedLightShadowCount = shadowRequestCount; } #endif } // Directional rendering side, it is separated as it is always visible so no volume to handle here if (gpuLightType == GPULightType.Directional) { GetDirectionalLightData(cmd, hdCamera, light, lightComponent, lightIndex, shadowIndex, directionalLightcount, isPbrSkyActive, ref m_ScreenSpaceShadowIndex, ref m_ScreenSpaceShadowChannelSlot); directionalLightcount++; // We make the light position camera-relative as late as possible in order // to allow the preceding code to work with the absolute world space coordinates. if (ShaderConfig.s_CameraRelativeRendering != 0) { // Caution: 'DirectionalLightData.positionWS' is camera-relative after this point. int last = m_lightList.directionalLights.Count - 1; DirectionalLightData lightData = m_lightList.directionalLights[last]; lightData.positionRWS -= camPosWS; m_lightList.directionalLights[last] = lightData; } } else { Vector3 lightDimensions = new Vector3(); // X = length or width, Y = height, Z = range (depth) // Allocate a light data LightData lightData = new LightData(); // Punctual, area, projector lights - the rendering side. GetLightData(cmd, hdCamera, hdShadowSettings, light, lightComponent, in m_ProcessedLightData[lightIndex], shadowIndex, contactShadowScalableSetting, isRasterization: true, ref lightDimensions, ref m_ScreenSpaceShadowIndex, ref m_ScreenSpaceShadowChannelSlot, ref lightData); // Add the previously created light data m_lightList.lights.Add(lightData); switch (lightCategory) { case LightCategory.Punctual: punctualLightcount++; break; case LightCategory.Area: areaLightCount++; break; default: Debug.Assert(false, "TODO: encountered an unknown LightCategory."); break; } // Then culling side. Must be call in this order as we pass the created Light data to the function for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) { GetLightVolumeDataAndBound(lightCategory, gpuLightType, lightVolumeType, light, m_lightList.lights[m_lightList.lights.Count - 1], lightDimensions, m_WorldToViewMatrices[viewIndex], viewIndex); } // We make the light position camera-relative as late as possible in order // to allow the preceding code to work with the absolute world space coordinates. if (ShaderConfig.s_CameraRelativeRendering != 0) { // Caution: 'LightData.positionWS' is camera-relative after this point. int last = m_lightList.lights.Count - 1; lightData = m_lightList.lights[last]; lightData.positionRWS -= camPosWS; m_lightList.lights[last] = lightData; } } } // Sanity check Debug.Assert(m_lightList.directionalLights.Count == directionalLightcount); Debug.Assert(m_lightList.lights.Count == areaLightCount + punctualLightcount); m_lightList.punctualLightCount = punctualLightcount; m_lightList.areaLightCount = areaLightCount; } bool TrivialRejectProbe(in ProcessedProbeData processedProbe, HDCamera hdCamera) { // For now we won't display real time probe when rendering one. // TODO: We may want to display last frame result but in this case we need to be careful not to update the atlas before all realtime probes are rendered (for frame coherency). // Unfortunately we don't have this information at the moment. if (processedProbe.hdProbe.mode == ProbeSettings.Mode.Realtime && hdCamera.camera.cameraType == CameraType.Reflection) return true; // Discard probe if disabled in debug menu if (!m_CurrentDebugDisplaySettings.data.lightingDebugSettings.showReflectionProbe) return true; // Discard probe if its distance is too far or if its weight is at 0 if (processedProbe.weight <= 0f) return true; // Exclude env lights based on hdCamera.probeLayerMask if ((hdCamera.probeLayerMask.value & (1 << processedProbe.hdProbe.gameObject.layer)) == 0) return true; // probe.texture can be null when we are adding a reflection probe in the editor if (processedProbe.hdProbe.texture == null) return true; return false; } internal static void PreprocessReflectionProbeData(ref ProcessedProbeData processedData, VisibleReflectionProbe probe, HDCamera hdCamera) { var add = probe.reflectionProbe.GetComponent<HDAdditionalReflectionData>(); if (add == null) { add = HDUtils.s_DefaultHDAdditionalReflectionData; Vector3 distance = Vector3.one * probe.blendDistance; add.influenceVolume.boxBlendDistancePositive = distance; add.influenceVolume.boxBlendDistanceNegative = distance; add.influenceVolume.shape = InfluenceShape.Box; } PreprocessProbeData(ref processedData, add, hdCamera); } internal static void PreprocessProbeData(ref ProcessedProbeData processedData, HDProbe probe, HDCamera hdCamera) { processedData.hdProbe = probe; processedData.weight = HDUtils.ComputeWeightedLinearFadeDistance(processedData.hdProbe.transform.position, hdCamera.camera.transform.position, processedData.hdProbe.weight, processedData.hdProbe.fadeDistance); } int PreprocessVisibleProbes(HDCamera hdCamera, CullingResults cullResults, HDProbeCullingResults hdProbeCullingResults, in AOVRequestData aovRequest) { var debugLightFilter = m_CurrentDebugDisplaySettings.GetDebugLightFilterMode(); var hasDebugLightFilter = debugLightFilter != DebugLightFilterMode.None; // Redo everything but this time with envLights Debug.Assert(m_MaxEnvLightsOnScreen <= 256); //for key construction int envLightCount = 0; var totalProbes = cullResults.visibleReflectionProbes.Length + hdProbeCullingResults.visibleProbes.Count; m_ProcessedReflectionProbeData.Resize(cullResults.visibleReflectionProbes.Length); m_ProcessedPlanarProbeData.Resize(hdProbeCullingResults.visibleProbes.Count); int maxProbeCount = Math.Min(totalProbes, m_MaxEnvLightsOnScreen); UpdateSortKeysArray(maxProbeCount); var enableReflectionProbes = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ReflectionProbe) && (!hasDebugLightFilter || debugLightFilter.IsEnabledFor(ProbeSettings.ProbeType.ReflectionProbe)); var enablePlanarProbes = hdCamera.frameSettings.IsEnabled(FrameSettingsField.PlanarProbe) && (!hasDebugLightFilter || debugLightFilter.IsEnabledFor(ProbeSettings.ProbeType.PlanarProbe)); if (enableReflectionProbes) { for (int probeIndex = 0; probeIndex < cullResults.visibleReflectionProbes.Length; probeIndex++) { var probe = cullResults.visibleReflectionProbes[probeIndex]; if (probe.reflectionProbe == null || probe.reflectionProbe.Equals(null) || !probe.reflectionProbe.isActiveAndEnabled || !aovRequest.IsLightEnabled(probe.reflectionProbe.gameObject)) continue; ref ProcessedProbeData processedData = ref m_ProcessedReflectionProbeData[probeIndex]; PreprocessReflectionProbeData(ref processedData, probe, hdCamera); if (TrivialRejectProbe(processedData, hdCamera)) continue; // Work around the data issues. if (probe.localToWorldMatrix.determinant == 0) { Debug.LogError("Reflection probe " + probe.reflectionProbe.name + " has an invalid local frame and needs to be fixed."); continue; } // This test needs to be the last one otherwise we may consume an available slot and then discard the probe. if (envLightCount >= maxProbeCount) continue; LightVolumeType lightVolumeType = LightVolumeType.Box; if (processedData.hdProbe != null && processedData.hdProbe.influenceVolume.shape == InfluenceShape.Sphere) lightVolumeType = LightVolumeType.Sphere; var logVolume = CalculateProbeLogVolume(probe.bounds); m_SortKeys[envLightCount++] = PackProbeKey(logVolume, lightVolumeType, 0u, probeIndex); // Sort by volume } } if (enablePlanarProbes) { for (int planarProbeIndex = 0; planarProbeIndex < hdProbeCullingResults.visibleProbes.Count; planarProbeIndex++) { var probe = hdProbeCullingResults.visibleProbes[planarProbeIndex]; ref ProcessedProbeData processedData = ref m_ProcessedPlanarProbeData[planarProbeIndex]; PreprocessProbeData(ref processedData, probe, hdCamera); if (!aovRequest.IsLightEnabled(probe.gameObject)) continue; // This test needs to be the last one otherwise we may consume an available slot and then discard the probe. if (envLightCount >= maxProbeCount) continue; var lightVolumeType = LightVolumeType.Box; if (probe.influenceVolume.shape == InfluenceShape.Sphere) lightVolumeType = LightVolumeType.Sphere; var logVolume = CalculateProbeLogVolume(probe.bounds); m_SortKeys[envLightCount++] = PackProbeKey(logVolume, lightVolumeType, 1u, planarProbeIndex); // Sort by volume } } // Not necessary yet but call it for future modification with sphere influence volume CoreUnsafeUtils.QuickSort(m_SortKeys, 0, envLightCount - 1); // Call our own quicksort instead of Array.Sort(sortKeys, 0, sortCount) so we don't allocate memory (note the SortCount-1 that is different from original call). return envLightCount; } void PrepareGPUProbeData(CommandBuffer cmd, HDCamera hdCamera, CullingResults cullResults, HDProbeCullingResults hdProbeCullingResults, int processedLightCount) { Vector3 camPosWS = hdCamera.mainViewConstants.worldSpaceCameraPos; for (int sortIndex = 0; sortIndex < processedLightCount; ++sortIndex) { // In 1. we have already classify and sorted the light, we need to use this sorted order here uint sortKey = m_SortKeys[sortIndex]; LightVolumeType lightVolumeType; int probeIndex; int listType; UnpackProbeSortKey(sortKey, out lightVolumeType, out probeIndex, out listType); ProcessedProbeData processedProbe = (listType == 0) ? m_ProcessedReflectionProbeData[probeIndex] : m_ProcessedPlanarProbeData[probeIndex]; EnvLightData envLightData = new EnvLightData(); if (GetEnvLightData(cmd, hdCamera, processedProbe, ref envLightData)) { // it has been filled m_lightList.envLights.Add(envLightData); for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) { var worldToView = GetWorldToViewMatrix(hdCamera, viewIndex); GetEnvLightVolumeDataAndBound(processedProbe.hdProbe, lightVolumeType, worldToView, viewIndex); } // We make the light position camera-relative as late as possible in order // to allow the preceding code to work with the absolute world space coordinates. UpdateEnvLighCameraRelativetData(ref envLightData, camPosWS); int last = m_lightList.envLights.Count - 1; m_lightList.envLights[last] = envLightData; } } } // Return true if BakedShadowMask are enabled bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cullResults, HDProbeCullingResults hdProbeCullingResults, DensityVolumeList densityVolumes, ProbeVolumeList probeVolumes, DebugDisplaySettings debugDisplaySettings, AOVRequestData aovRequest) { var debugLightFilter = debugDisplaySettings.GetDebugLightFilterMode(); var hasDebugLightFilter = debugLightFilter != DebugLightFilterMode.None; HDShadowManager.cachedShadowManager.AssignSlotsInAtlases(); using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PrepareLightsForGPU))) { Camera camera = hdCamera.camera; // If any light require it, we need to enabled bake shadow mask feature m_EnableBakeShadowMask = false; m_lightList.Clear(); // We need to properly reset this here otherwise if we go from 1 light to no visible light we would keep the old reference active. m_CurrentSunLight = null; m_CurrentSunLightAdditionalLightData = null; m_CurrentShadowSortedSunLightIndex = -1; m_DebugSelectedLightShadowIndex = -1; m_DebugSelectedLightShadowCount = 0; int decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); // We must clear the shadow requests before checking if they are any visible light because we would have requests from the last frame executed in the case where we don't see any lights m_ShadowManager.Clear(); // Because we don't support baking planar reflection probe, we can clear the atlas. // Every visible probe will be blitted again. m_TextureCaches.reflectionPlanarProbeCache.ClearAtlasAllocator(); m_ScreenSpaceShadowIndex = 0; m_ScreenSpaceShadowChannelSlot = 0; // Set all the light data to invalid for (int i = 0; i < m_Asset.currentPlatformRenderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots; ++i) { m_CurrentScreenSpaceShadowData[i].additionalLightData = null; m_CurrentScreenSpaceShadowData[i].lightDataIndex = -1; m_CurrentScreenSpaceShadowData[i].valid = false; } // Note: Light with null intensity/Color are culled by the C++, no need to test it here if (cullResults.visibleLights.Length != 0) { int processedLightCount = PreprocessVisibleLights(hdCamera, cullResults, debugDisplaySettings, aovRequest); // In case ray tracing supported and a light cluster is built, we need to make sure to reserve all the cookie slots we need if (m_RayTracingSupported) ReserveRayTracingCookieAtlasSlots(); PrepareGPULightdata(cmd, hdCamera, cullResults, processedLightCount); // Update the compute buffer with the shadow request datas m_ShadowManager.PrepareGPUShadowDatas(cullResults, hdCamera); } else if (m_RayTracingSupported) { // In case there is no rasterization lights, we stil need to do it for ray tracing ReserveRayTracingCookieAtlasSlots(); m_TextureCaches.lightCookieManager.LayoutIfNeeded(); } if (cullResults.visibleReflectionProbes.Length != 0 || hdProbeCullingResults.visibleProbes.Count != 0) { int processedProbesCount = PreprocessVisibleProbes(hdCamera, cullResults, hdProbeCullingResults, aovRequest); PrepareGPUProbeData(cmd, hdCamera, cullResults, hdProbeCullingResults, processedProbesCount); } if (decalDatasCount > 0) { for (int i = 0; i < decalDatasCount; i++) { for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) { m_lightList.lightsPerView[viewIndex].bounds.Add(DecalSystem.m_Bounds[i]); m_lightList.lightsPerView[viewIndex].lightVolumes.Add(DecalSystem.m_LightVolumes[i]); } } } // Inject density volumes into the clustered data structure for efficient look up. m_DensityVolumeCount = densityVolumes.bounds != null ? densityVolumes.bounds.Count : 0; m_ProbeVolumeCount = probeVolumes.bounds != null ? probeVolumes.bounds.Count : 0; bool probeVolumeNormalBiasEnabled = false; if (ShaderConfig.s_EnableProbeVolumes == 1) { var settings = hdCamera.volumeStack.GetComponent<ProbeVolumeController>(); probeVolumeNormalBiasEnabled = !(settings == null || (settings.leakMitigationMode.value != LeakMitigationMode.NormalBias && settings.leakMitigationMode.value != LeakMitigationMode.OctahedralDepthOcclusionFilter)); } for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) { Matrix4x4 worldToViewCR = GetWorldToViewMatrix(hdCamera, viewIndex); if (ShaderConfig.s_CameraRelativeRendering != 0) { // The OBBs are camera-relative, the matrix is not. Fix it. worldToViewCR.SetColumn(3, new Vector4(0, 0, 0, 1)); } for (int i = 0, n = m_DensityVolumeCount; i < n; i++) { // Density volumes are not lights and therefore should not affect light classification. LightFeatureFlags featureFlags = 0; CreateBoxVolumeDataAndBound(densityVolumes.bounds[i], LightCategory.DensityVolume, featureFlags, worldToViewCR, 0.0f, out LightVolumeData volumeData, out SFiniteLightBound bound); m_lightList.lightsPerView[viewIndex].lightVolumes.Add(volumeData); m_lightList.lightsPerView[viewIndex].bounds.Add(bound); } for (int i = 0, n = m_ProbeVolumeCount; i < n; i++) { // Probe volumes are not lights and therefore should not affect light classification. LightFeatureFlags featureFlags = 0; float probeVolumeNormalBiasWS = probeVolumeNormalBiasEnabled ? probeVolumes.data[i].normalBiasWS : 0.0f; CreateBoxVolumeDataAndBound(probeVolumes.bounds[i], LightCategory.ProbeVolume, featureFlags, worldToViewCR, probeVolumeNormalBiasWS, out LightVolumeData volumeData, out SFiniteLightBound bound); m_lightList.lightsPerView[viewIndex].lightVolumes.Add(volumeData); m_lightList.lightsPerView[viewIndex].bounds.Add(bound); } } m_TotalLightCount = m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount + m_DensityVolumeCount; if (ShaderConfig.s_EnableProbeVolumes == 1) { m_TotalLightCount += m_ProbeVolumeCount; } Debug.Assert(m_TotalLightCount == m_lightList.lightsPerView[0].bounds.Count); Debug.Assert(m_TotalLightCount == m_lightList.lightsPerView[0].lightVolumes.Count); // Aggregate the remaining views into the first entry of the list (view 0) for (int viewIndex = 1; viewIndex < hdCamera.viewCount; ++viewIndex) { Debug.Assert(m_lightList.lightsPerView[viewIndex].bounds.Count == m_TotalLightCount); m_lightList.lightsPerView[0].bounds.AddRange(m_lightList.lightsPerView[viewIndex].bounds); Debug.Assert(m_lightList.lightsPerView[viewIndex].lightVolumes.Count == m_TotalLightCount); m_lightList.lightsPerView[0].lightVolumes.AddRange(m_lightList.lightsPerView[viewIndex].lightVolumes); } PushLightDataGlobalParams(cmd); PushShadowGlobalParams(cmd); } m_EnableBakeShadowMask = m_EnableBakeShadowMask && hdCamera.frameSettings.IsEnabled(FrameSettingsField.Shadowmask); return m_EnableBakeShadowMask; } internal void ReserveCookieAtlasTexture(HDAdditionalLightData hdLightData, Light light, HDLightType lightType) { // Note: light component can be null if a Light is used for shuriken particle lighting. lightType = light == null ? HDLightType.Point : lightType; switch (lightType) { case HDLightType.Directional: m_TextureCaches.lightCookieManager.ReserveSpace(hdLightData.surfaceTexture); m_TextureCaches.lightCookieManager.ReserveSpace(light?.cookie); break; case HDLightType.Point: if (light?.cookie != null && hdLightData.IESPoint != null && light.cookie != hdLightData.IESPoint) m_TextureCaches.lightCookieManager.ReserveSpaceCube(light.cookie, hdLightData.IESPoint); else if (light?.cookie != null) m_TextureCaches.lightCookieManager.ReserveSpaceCube(light.cookie); else if (hdLightData.IESPoint != null) m_TextureCaches.lightCookieManager.ReserveSpaceCube(hdLightData.IESPoint); break; case HDLightType.Spot: if (light?.cookie != null && hdLightData.IESSpot != null && light.cookie != hdLightData.IESSpot) m_TextureCaches.lightCookieManager.ReserveSpace(light.cookie, hdLightData.IESSpot); else if (light?.cookie != null) m_TextureCaches.lightCookieManager.ReserveSpace(light.cookie); else if (hdLightData.IESSpot != null) m_TextureCaches.lightCookieManager.ReserveSpace(hdLightData.IESSpot); // Projectors lights must always have a cookie texture. else if (hdLightData.spotLightShape != SpotLightShape.Cone) m_TextureCaches.lightCookieManager.ReserveSpace(Texture2D.whiteTexture); break; case HDLightType.Area: // Only rectangle can have cookies if (hdLightData.areaLightShape == AreaLightShape.Rectangle) { if (hdLightData.IESSpot != null && hdLightData.areaLightCookie != null && hdLightData.IESSpot != hdLightData.areaLightCookie) m_TextureCaches.lightCookieManager.ReserveSpace(hdLightData.areaLightCookie, hdLightData.IESSpot); else if (hdLightData.IESSpot != null) m_TextureCaches.lightCookieManager.ReserveSpace(hdLightData.IESSpot); else if (hdLightData.areaLightCookie != null) m_TextureCaches.lightCookieManager.ReserveSpace(hdLightData.areaLightCookie); } break; } } internal static void UpdateLightCameraRelativetData(ref LightData lightData, Vector3 camPosWS) { if (ShaderConfig.s_CameraRelativeRendering != 0) { lightData.positionRWS -= camPosWS; } } internal static void UpdateEnvLighCameraRelativetData(ref EnvLightData envLightData, Vector3 camPosWS) { if (ShaderConfig.s_CameraRelativeRendering != 0) { // Caution: 'EnvLightData.positionRWS' is camera-relative after this point. envLightData.capturePositionRWS -= camPosWS; envLightData.influencePositionRWS -= camPosWS; envLightData.proxyPositionRWS -= camPosWS; } } static float CalculateProbeLogVolume(Bounds bounds) { //Notes: // - 1+ term is to prevent having negative values in the log result // - 1000* is too keep 3 digit after the dot while we truncate the result later // - 1048575 is 2^20-1 as we pack the result on 20bit later float boxVolume = 8f * bounds.extents.x * bounds.extents.y * bounds.extents.z; float logVolume = Mathf.Clamp(Mathf.Log(1 + boxVolume, 1.05f) * 1000, 0, 1048575); return logVolume; } static void UnpackProbeSortKey(uint sortKey, out LightVolumeType lightVolumeType, out int probeIndex, out int listType) { lightVolumeType = (LightVolumeType)((sortKey >> 9) & 0x3); probeIndex = (int)(sortKey & 0xFF); listType = (int)((sortKey >> 8) & 1); } static uint PackProbeKey(float logVolume, LightVolumeType lightVolumeType, uint listType, int probeIndex) { // 20 bit volume, 3 bit LightVolumeType, 1 bit list type, 8 bit index return (uint)logVolume << 12 | (uint)lightVolumeType << 9 | listType << 8 | ((uint)probeIndex & 0xFF); } struct BuildGPULightListParameters { // Common public int totalLightCount; // Regular + Env + Decal + Density Volumes public int viewCount; public bool runLightList; public bool clearLightLists; public bool enableFeatureVariants; public bool computeMaterialVariants; public bool computeLightVariants; public bool skyEnabled; public bool probeVolumeEnabled; public LightList lightList; // Clear Light lists public ComputeShader clearLightListCS; public int clearLightListKernel; // Screen Space AABBs public ComputeShader screenSpaceAABBShader; public int screenSpaceAABBKernel; // Big Tile public ComputeShader bigTilePrepassShader; public int bigTilePrepassKernel; public bool runBigTilePrepass; public int numBigTilesX, numBigTilesY; // FPTL public ComputeShader buildPerTileLightListShader; public int buildPerTileLightListKernel; public bool runFPTL; public int numTilesFPTLX; public int numTilesFPTLY; public int numTilesFPTL; // Cluster public ComputeShader buildPerVoxelLightListShader; public ComputeShader clearClusterAtomicIndexShader; public int buildPerVoxelLightListKernel; public int numTilesClusterX; public int numTilesClusterY; public bool clusterNeedsDepth; // Build dispatch indirect public ComputeShader buildMaterialFlagsShader; public ComputeShader clearDispatchIndirectShader; public ComputeShader buildDispatchIndirectShader; public bool useComputeAsPixel; public ShaderVariablesLightList lightListCB; } struct BuildGPULightListResources { public RTHandle depthBuffer; public RTHandle stencilTexture; public RTHandle[] gBuffer; // Internal to light list building public ComputeBuffer lightVolumeDataBuffer; public ComputeBuffer convexBoundsBuffer; public ComputeBuffer AABBBoundsBuffer; public ComputeBuffer globalLightListAtomic; // Output public ComputeBuffer tileFeatureFlags; // Deferred public ComputeBuffer dispatchIndirectBuffer; // Deferred public ComputeBuffer perVoxelOffset; // Cluster public ComputeBuffer perTileLogBaseTweak; // Cluster public ComputeBuffer tileList; // Deferred // used for pre-pass coarse culling on 64x64 tiles public ComputeBuffer bigTileLightList; // Volumetrics public ComputeBuffer perVoxelLightLists; // Cluster public ComputeBuffer lightList; // ContactShadows, Deferred, Forward w/ fptl } static void ClearLightList(in BuildGPULightListParameters parameters, CommandBuffer cmd, ComputeBuffer bufferToClear) { cmd.SetComputeBufferParam(parameters.clearLightListCS, parameters.clearLightListKernel, HDShaderIDs._LightListToClear, bufferToClear); Vector2 countAndOffset = new Vector2Int(bufferToClear.count, 0); int groupSize = 64; int totalNumberOfGroupsNeeded = (bufferToClear.count + groupSize - 1) / groupSize; const int maxAllowedGroups = 65535; // On higher resolutions we might end up with more than 65535 group which is not allowed, so we need to to have multiple dispatches. int i = 0; while (totalNumberOfGroupsNeeded > 0) { countAndOffset.y = maxAllowedGroups * i; cmd.SetComputeVectorParam(parameters.clearLightListCS, HDShaderIDs._LightListEntriesAndOffset, countAndOffset); int currGroupCount = Math.Min(maxAllowedGroups, totalNumberOfGroupsNeeded); cmd.DispatchCompute(parameters.clearLightListCS, parameters.clearLightListKernel, currGroupCount, 1, 1); totalNumberOfGroupsNeeded -= currGroupCount; i++; } } static void ClearLightLists(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { if (parameters.clearLightLists) { // Note we clear the whole content and not just the header since it is fast enough, happens only in one frame and is a bit more robust // to changes to the inner workings of the lists. // Also, we clear all the lists and to be resilient to changes in pipeline. if (parameters.runBigTilePrepass) ClearLightList(parameters, cmd, resources.bigTileLightList); if (resources.lightList != null) // This can happen for probe volume light list build where we only generate clusters. ClearLightList(parameters, cmd, resources.lightList); ClearLightList(parameters, cmd, resources.perVoxelOffset); } } // generate screen-space AABBs (used for both fptl and clustered). static void GenerateLightsScreenSpaceAABBs(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { if (parameters.totalLightCount != 0) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.GenerateLightAABBs))) { // With XR single-pass, we have one set of light bounds per view to iterate over (bounds are in view space for each view) cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs.g_data, resources.convexBoundsBuffer); cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs.g_vBoundsBuffer, resources.AABBBoundsBuffer); ConstantBuffer.Push(cmd, parameters.lightListCB, parameters.screenSpaceAABBShader, HDShaderIDs._ShaderVariablesLightList); const int threadsPerLight = 4; // Shader: THREADS_PER_LIGHT (4) const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) int groupCount = HDUtils.DivRoundUp(parameters.totalLightCount * threadsPerLight, threadsPerGroup); cmd.DispatchCompute(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, groupCount, parameters.viewCount, 1); } } } // enable coarse 2D pass on 64x64 tiles (used for both fptl and clustered). static void BigTilePrepass(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { if (parameters.runLightList && parameters.runBigTilePrepass) { cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs.g_vLightList, resources.bigTileLightList); cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs.g_vBoundsBuffer, resources.AABBBoundsBuffer); cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs._LightVolumeData, resources.lightVolumeDataBuffer); cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs.g_data, resources.convexBoundsBuffer); ConstantBuffer.Push(cmd, parameters.lightListCB, parameters.bigTilePrepassShader, HDShaderIDs._ShaderVariablesLightList); cmd.DispatchCompute(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, parameters.numBigTilesX, parameters.numBigTilesY, parameters.viewCount); } } static void BuildPerTileLightList(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, ref bool tileFlagsWritten, CommandBuffer cmd) { // optimized for opaques only if (parameters.runLightList && parameters.runFPTL) { cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_vBoundsBuffer, resources.AABBBoundsBuffer); cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs._LightVolumeData, resources.lightVolumeDataBuffer); cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_data, resources.convexBoundsBuffer); cmd.SetComputeTextureParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_depth_tex, resources.depthBuffer); cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_vLightList, resources.lightList); if (parameters.runBigTilePrepass) cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_vBigTileLightList, resources.bigTileLightList); var localLightListCB = parameters.lightListCB; if (parameters.enableFeatureVariants) { uint baseFeatureFlags = 0; if (parameters.lightList.directionalLights.Count > 0) { baseFeatureFlags |= (uint)LightFeatureFlags.Directional; } if (parameters.skyEnabled) { baseFeatureFlags |= (uint)LightFeatureFlags.Sky; } if (!parameters.computeMaterialVariants) { baseFeatureFlags |= LightDefinitions.s_MaterialFeatureMaskFlags; } if (parameters.probeVolumeEnabled) { // If probe volume feature is enabled, we toggle this feature on for all tiles. // This is necessary because all tiles must sample ambient probe fallback. // It is possible we could save a little bit of work by having 2x feature flags for probe volumes: // one specifiying which tiles contain probe volumes, // and another triggered for all tiles to handle fallback. baseFeatureFlags |= (uint)LightFeatureFlags.ProbeVolume; } localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); tileFlagsWritten = true; } ConstantBuffer.Push(cmd, localLightListCB, parameters.buildPerTileLightListShader, HDShaderIDs._ShaderVariablesLightList); cmd.DispatchCompute(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, parameters.numTilesFPTLX, parameters.numTilesFPTLY, parameters.viewCount); } } static void VoxelLightListGeneration(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { if (parameters.runLightList) { // clear atomic offset index cmd.SetComputeBufferParam(parameters.clearClusterAtomicIndexShader, s_ClearVoxelAtomicKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, resources.globalLightListAtomic); cmd.DispatchCompute(parameters.clearClusterAtomicIndexShader, s_ClearVoxelAtomicKernel, 1, 1, 1); cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, resources.globalLightListAtomic); cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_vLayeredLightList, resources.perVoxelLightLists); cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_LayeredOffset, resources.perVoxelOffset); cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, resources.globalLightListAtomic); if (parameters.runBigTilePrepass) cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_vBigTileLightList, resources.bigTileLightList); if (parameters.clusterNeedsDepth) { cmd.SetComputeTextureParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_depth_tex, resources.depthBuffer); cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_logBaseBuffer, resources.perTileLogBaseTweak); } cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_vBoundsBuffer, resources.AABBBoundsBuffer); cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs._LightVolumeData, resources.lightVolumeDataBuffer); cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_data, resources.convexBoundsBuffer); ConstantBuffer.Push(cmd, parameters.lightListCB, parameters.buildPerVoxelLightListShader, HDShaderIDs._ShaderVariablesLightList); cmd.DispatchCompute(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, parameters.numTilesClusterX, parameters.numTilesClusterY, parameters.viewCount); } } static void BuildDispatchIndirectArguments(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, bool tileFlagsWritten, CommandBuffer cmd) { if (parameters.enableFeatureVariants) { // We need to touch up the tile flags if we need material classification or, if disabled, to patch up for missing flags during the skipped light tile gen bool needModifyingTileFeatures = !tileFlagsWritten || parameters.computeMaterialVariants; if (needModifyingTileFeatures) { int buildMaterialFlagsKernel = s_BuildMaterialFlagsWriteKernel; parameters.buildMaterialFlagsShader.shaderKeywords = null; if (tileFlagsWritten && parameters.computeLightVariants) { parameters.buildMaterialFlagsShader.EnableKeyword("USE_OR"); } uint baseFeatureFlags = 0; if (!parameters.computeLightVariants) { baseFeatureFlags |= LightDefinitions.s_LightFeatureMaskFlags; } if (parameters.probeVolumeEnabled) { // TODO: Verify that we should be globally enabling ProbeVolume feature for all tiles here, or if we should be using per-tile culling. baseFeatureFlags |= (uint)LightFeatureFlags.ProbeVolume; } // If we haven't run the light list building, we are missing some basic lighting flags. if (!tileFlagsWritten) { if (parameters.lightList.directionalLights.Count > 0) { baseFeatureFlags |= (uint)LightFeatureFlags.Directional; } if (parameters.skyEnabled) { baseFeatureFlags |= (uint)LightFeatureFlags.Sky; } if (!parameters.computeMaterialVariants) { baseFeatureFlags |= LightDefinitions.s_MaterialFeatureMaskFlags; } } var localLightListCB = parameters.lightListCB; localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; cmd.SetComputeBufferParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); for (int i = 0; i < resources.gBuffer.Length; ++i) cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture[i], resources.gBuffer[i]); if (resources.stencilTexture.rt == null || resources.stencilTexture.rt.stencilFormat == GraphicsFormat.None) // We are accessing MSAA resolved version and not the depth stencil buffer directly. { cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture); } else { cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture, 0, RenderTextureSubElement.Stencil); } ConstantBuffer.Push(cmd, localLightListCB, parameters.buildMaterialFlagsShader, HDShaderIDs._ShaderVariablesLightList); cmd.DispatchCompute(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, parameters.numTilesFPTLX, parameters.numTilesFPTLY, parameters.viewCount); } // clear dispatch indirect buffer if (parameters.useComputeAsPixel) { cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_VertexPerTile, k_HasNativeQuadSupport ? 4 : 6); cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, 1, 1, 1); } else { cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, 1, 1, 1); } // add tiles to indirect buffer cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileList, resources.tileList); cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTilesX, parameters.numTilesFPTLX); // Round on k_ThreadGroupOptimalSize so we have optimal thread for buildDispatchIndirectShader kernel cmd.DispatchCompute(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, (parameters.numTilesFPTL + k_ThreadGroupOptimalSize - 1) / k_ThreadGroupOptimalSize, 1, parameters.viewCount); } } static bool DeferredUseComputeAsPixel(FrameSettings frameSettings) { return frameSettings.IsEnabled(FrameSettingsField.DeferredTile) && (!frameSettings.IsEnabled(FrameSettingsField.ComputeLightEvaluation) || k_PreferFragment); } unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera hdCamera, TileAndClusterData tileAndClusterData, ref ShaderVariablesLightList constantBuffer, int totalLightCount) { BuildGPULightListParameters parameters = new BuildGPULightListParameters(); var camera = hdCamera.camera; var w = (int)hdCamera.screenSize.x; var h = (int)hdCamera.screenSize.y; // Fill the shared constant buffer. // We don't fill directly the one in the parameter struct because we will need those parameters for volumetric lighting as well. ref var cb = ref constantBuffer; var temp = new Matrix4x4(); temp.SetRow(0, new Vector4(0.5f * w, 0.0f, 0.0f, 0.5f * w)); temp.SetRow(1, new Vector4(0.0f, 0.5f * h, 0.0f, 0.5f * h)); temp.SetRow(2, new Vector4(0.0f, 0.0f, 0.5f, 0.5f)); temp.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); // camera to screen matrix (and it's inverse) for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) { var proj = hdCamera.xr.enabled ? hdCamera.xr.GetProjMatrix(viewIndex) : camera.projectionMatrix; m_LightListProjMatrices[viewIndex] = proj * s_FlipMatrixLHSRHS; for (int i = 0; i < 16; ++i) { var tempMatrix = temp * m_LightListProjMatrices[viewIndex]; var invTempMatrix = tempMatrix.inverse; cb.g_mScrProjectionArr[viewIndex * 16 + i] = tempMatrix[i]; cb.g_mInvScrProjectionArr[viewIndex * 16 + i] = invTempMatrix[i]; } } // camera to screen matrix (and it's inverse) for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) { temp.SetRow(0, new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); temp.SetRow(1, new Vector4(0.0f, 1.0f, 0.0f, 0.0f)); temp.SetRow(2, new Vector4(0.0f, 0.0f, 0.5f, 0.5f)); temp.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); for (int i = 0; i < 16; ++i) { var tempMatrix = temp * m_LightListProjMatrices[viewIndex]; var invTempMatrix = tempMatrix.inverse; cb.g_mProjectionArr[viewIndex * 16 + i] = tempMatrix[i]; cb.g_mInvProjectionArr[viewIndex * 16 + i] = invTempMatrix[i]; } } var decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); cb.g_iNrVisibLights = totalLightCount; cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. cb.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y); cb.g_isOrthographic = camera.orthographic ? 1u : 0u; cb.g_BaseFeatureFlags = 0; // Filled for each individual pass. cb.g_iNumSamplesMSAA = (int)hdCamera.msaaSamples; cb._EnvLightIndexShift = (uint)m_lightList.lights.Count; cb._DecalIndexShift = (uint)(m_lightList.lights.Count + m_lightList.envLights.Count); cb._DensityVolumeIndexShift = (uint)(m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount); int probeVolumeIndexShift = (ShaderConfig.s_EnableProbeVolumes == 1) ? (m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount + m_DensityVolumeCount) : 0; cb._ProbeVolumeIndexShift = (uint)probeVolumeIndexShift; // Copy the constant buffer into the parameter struct. parameters.lightListCB = cb; parameters.totalLightCount = totalLightCount; parameters.runLightList = parameters.totalLightCount > 0; parameters.clearLightLists = false; // TODO RENDERGRAPH: This logic is flawed with Render Graph. // In theory buffers memory might be reused from another usage entirely so keeping track of its "cleared" state does not represent the truth of their content. // In practice though, when resolution stays the same, buffers will be the same reused from one frame to another // because for now buffers are pooled based on their parameters. When we do proper aliasing though, we might end up with any random chunk of memory. // Always build the light list in XR mode to avoid issues with multi-pass if (hdCamera.xr.enabled) { parameters.runLightList = true; } else if (!parameters.runLightList && !tileAndClusterData.listsAreClear) { parameters.clearLightLists = true; // After that, No need to clear it anymore until we start and stop running light list building. tileAndClusterData.listsAreClear = true; } else if (parameters.runLightList) { tileAndClusterData.listsAreClear = false; } parameters.viewCount = hdCamera.viewCount; parameters.enableFeatureVariants = GetFeatureVariantsEnabled(hdCamera.frameSettings) && tileAndClusterData.hasTileBuffers; parameters.computeMaterialVariants = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ComputeMaterialVariants); parameters.computeLightVariants = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ComputeLightVariants); parameters.lightList = m_lightList; parameters.skyEnabled = m_SkyManager.IsLightingSkyValid(hdCamera); parameters.useComputeAsPixel = DeferredUseComputeAsPixel(hdCamera.frameSettings); parameters.probeVolumeEnabled = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ProbeVolume) && m_ProbeVolumeCount > 0; bool isProjectionOblique = GeometryUtils.IsProjectionMatrixOblique(m_LightListProjMatrices[0]); // Clear light lsts parameters.clearLightListCS = defaultResources.shaders.clearLightListsCS; parameters.clearLightListKernel = parameters.clearLightListCS.FindKernel("ClearList"); // Screen space AABB parameters.screenSpaceAABBShader = buildScreenAABBShader; parameters.screenSpaceAABBKernel = 0; // Big tile prepass parameters.runBigTilePrepass = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass); parameters.bigTilePrepassShader = buildPerBigTileLightListShader; parameters.bigTilePrepassKernel = s_GenListPerBigTileKernel; parameters.numBigTilesX = (w + 63) / 64; parameters.numBigTilesY = (h + 63) / 64; // Fptl parameters.runFPTL = hdCamera.frameSettings.fptl && tileAndClusterData.hasTileBuffers; parameters.buildPerTileLightListShader = buildPerTileLightListShader; parameters.buildPerTileLightListShader.shaderKeywords = null; if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass)) { parameters.buildPerTileLightListShader.EnableKeyword("USE_TWO_PASS_TILED_LIGHTING"); } if (isProjectionOblique) { parameters.buildPerTileLightListShader.EnableKeyword("USE_OBLIQUE_MODE"); } if (GetFeatureVariantsEnabled(hdCamera.frameSettings)) { parameters.buildPerTileLightListShader.EnableKeyword("USE_FEATURE_FLAGS"); } parameters.buildPerTileLightListKernel = s_GenListPerTileKernel; parameters.numTilesFPTLX = GetNumTileFtplX(hdCamera); parameters.numTilesFPTLY = GetNumTileFtplY(hdCamera); parameters.numTilesFPTL = parameters.numTilesFPTLX * parameters.numTilesFPTLY; // Cluster bool msaa = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); var clustPrepassSourceIdx = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass) ? ClusterPrepassSource.BigTile : ClusterPrepassSource.None; var clustDepthSourceIdx = ClusterDepthSource.NoDepth; if (tileAndClusterData.clusterNeedsDepth) clustDepthSourceIdx = msaa ? ClusterDepthSource.MSAA_Depth : ClusterDepthSource.Depth; parameters.buildPerVoxelLightListShader = buildPerVoxelLightListShader; parameters.clearClusterAtomicIndexShader = clearClusterAtomicIndexShader; parameters.buildPerVoxelLightListKernel = isProjectionOblique ? s_ClusterObliqueKernels[(int)clustPrepassSourceIdx, (int)clustDepthSourceIdx] : s_ClusterKernels[(int)clustPrepassSourceIdx, (int)clustDepthSourceIdx]; parameters.numTilesClusterX = GetNumTileClusteredX(hdCamera); parameters.numTilesClusterY = GetNumTileClusteredY(hdCamera); parameters.clusterNeedsDepth = tileAndClusterData.clusterNeedsDepth; // Build dispatch indirect parameters.buildMaterialFlagsShader = buildMaterialFlagsShader; parameters.clearDispatchIndirectShader = clearDispatchIndirectShader; parameters.buildDispatchIndirectShader = buildDispatchIndirectShader; parameters.buildDispatchIndirectShader.shaderKeywords = null; if (parameters.useComputeAsPixel) { parameters.buildDispatchIndirectShader.EnableKeyword("IS_DRAWPROCEDURALINDIRECT"); } return parameters; } HDAdditionalLightData GetHDAdditionalLightData(Light light) { HDAdditionalLightData add = null; // Light reference can be null for particle lights. if (light != null) light.TryGetComponent<HDAdditionalLightData>(out add); // Light should always have additional data, however preview light right don't have, so we must handle the case by assigning HDUtils.s_DefaultHDAdditionalLightData if (add == null) add = HDUtils.s_DefaultHDAdditionalLightData; return add; } struct LightLoopGlobalParameters { public HDCamera hdCamera; public TileAndClusterData tileAndClusterData; } unsafe void UpdateShaderVariablesGlobalLightLoop(ref ShaderVariablesGlobal cb, HDCamera hdCamera) { // Atlases cb._CookieAtlasSize = m_TextureCaches.lightCookieManager.GetCookieAtlasSize(); cb._CookieAtlasData = m_TextureCaches.lightCookieManager.GetCookieAtlasDatas(); cb._PlanarAtlasData = m_TextureCaches.reflectionPlanarProbeCache.GetAtlasDatas(); cb._EnvSliceSize = m_TextureCaches.reflectionProbeCache.GetEnvSliceSize(); // Planar reflections for (int i = 0; i < asset.currentPlatformRenderPipelineSettings.lightLoopSettings.maxPlanarReflectionOnScreen; ++i) { for (int j = 0; j < 16; ++j) cb._Env2DCaptureVP[i * 16 + j] = m_TextureCaches.env2DCaptureVP[i][j]; for (int j = 0; j < 4; ++j) cb._Env2DCaptureForward[i * 4 + j] = m_TextureCaches.env2DCaptureForward[i][j]; for (int j = 0; j < 4; ++j) cb._Env2DAtlasScaleOffset[i * 4 + j] = m_TextureCaches.env2DAtlasScaleOffset[i][j]; } // Light info cb._PunctualLightCount = (uint)m_lightList.punctualLightCount; cb._AreaLightCount = (uint)m_lightList.areaLightCount; cb._EnvLightCount = (uint)m_lightList.envLights.Count; cb._DirectionalLightCount = (uint)m_lightList.directionalLights.Count; cb._DecalCount = (uint)DecalSystem.m_DecalDatasCount; HDAdditionalLightData sunLightData = GetHDAdditionalLightData(m_CurrentSunLight); bool sunLightShadow = sunLightData != null && m_CurrentShadowSortedSunLightIndex >= 0; cb._DirectionalShadowIndex = sunLightShadow ? m_CurrentShadowSortedSunLightIndex : -1; cb._EnableLightLayers = hdCamera.frameSettings.IsEnabled(FrameSettingsField.LightLayers) ? 1u : 0u; cb._EnableDecalLayers = hdCamera.frameSettings.IsEnabled(FrameSettingsField.DecalLayers) ? 1u : 0u; cb._EnvLightSkyEnabled = m_SkyManager.IsLightingSkyValid(hdCamera) ? 1 : 0; const float C = (float)(1 << k_Log2NumClusters); var geomSeries = (1.0 - Mathf.Pow(k_ClustLogBase, C)) / (1 - k_ClustLogBase); // geometric series: sum_k=0^{C-1} base^k // Tile/Cluster cb._NumTileFtplX = (uint)GetNumTileFtplX(hdCamera); cb._NumTileFtplY = (uint)GetNumTileFtplY(hdCamera); cb.g_fClustScale = (float)(geomSeries / (hdCamera.camera.farClipPlane - hdCamera.camera.nearClipPlane));; cb.g_fClustBase = k_ClustLogBase; cb.g_fNearPlane = hdCamera.camera.nearClipPlane; cb.g_fFarPlane = hdCamera.camera.farClipPlane; cb.g_iLog2NumClusters = k_Log2NumClusters; cb.g_isLogBaseBufferEnabled = k_UseDepthBuffer ? 1 : 0; cb._NumTileClusteredX = (uint)GetNumTileClusteredX(hdCamera); cb._NumTileClusteredY = (uint)GetNumTileClusteredY(hdCamera); // Misc cb._EnableSSRefraction = hdCamera.frameSettings.IsEnabled(FrameSettingsField.Refraction) ? 1u : 0u; } void PushLightDataGlobalParams(CommandBuffer cmd) { m_LightLoopLightData.directionalLightData.SetData(m_lightList.directionalLights); m_LightLoopLightData.lightData.SetData(m_lightList.lights); m_LightLoopLightData.envLightData.SetData(m_lightList.envLights); m_LightLoopLightData.decalData.SetData(DecalSystem.m_DecalDatas, 0, 0, Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen)); // don't add more than the size of the buffer // These two buffers have been set in Rebuild(). At this point, view 0 contains combined data from all views m_TileAndClusterData.convexBoundsBuffer.SetData(m_lightList.lightsPerView[0].bounds); m_TileAndClusterData.lightVolumeDataBuffer.SetData(m_lightList.lightsPerView[0].lightVolumes); cmd.SetGlobalTexture(HDShaderIDs._CookieAtlas, m_TextureCaches.lightCookieManager.atlasTexture); cmd.SetGlobalTexture(HDShaderIDs._EnvCubemapTextures, m_TextureCaches.reflectionProbeCache.GetTexCache()); cmd.SetGlobalTexture(HDShaderIDs._Env2DTextures, m_TextureCaches.reflectionPlanarProbeCache.GetTexCache()); cmd.SetGlobalBuffer(HDShaderIDs._LightDatas, m_LightLoopLightData.lightData); cmd.SetGlobalBuffer(HDShaderIDs._EnvLightDatas, m_LightLoopLightData.envLightData); cmd.SetGlobalBuffer(HDShaderIDs._DecalDatas, m_LightLoopLightData.decalData); cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, m_LightLoopLightData.directionalLightData); } void PushShadowGlobalParams(CommandBuffer cmd) { m_ShadowManager.PushGlobalParameters(cmd); } bool WillRenderContactShadow() { // When contact shadow index is 0, then there is no light casting contact shadow in the view return m_EnableContactShadow && m_ContactShadowIndex != 0; } // The first rendered 24 lights that have contact shadow enabled have a mask used to select the bit that contains // the contact shadow shadowed information (occluded or not). Otherwise -1 is written void GetContactShadowMask(HDAdditionalLightData hdAdditionalLightData, BoolScalableSetting contactShadowEnabled, HDCamera hdCamera, bool isRasterization, ref int contactShadowMask, ref float rayTracingShadowFlag) { contactShadowMask = 0; rayTracingShadowFlag = 0.0f; // If contact shadows are not enabled or we already reached the manimal number of contact shadows // or this is not rasterization if ((!hdAdditionalLightData.useContactShadow.Value(contactShadowEnabled)) || m_ContactShadowIndex >= LightDefinitions.s_LightListMaxPrunedEntries || !isRasterization) return; // Evaluate the contact shadow index of this light contactShadowMask = 1 << m_ContactShadowIndex++; // If this light has ray traced contact shadow if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && hdAdditionalLightData.rayTraceContactShadow) rayTracingShadowFlag = 1.0f; } struct ContactShadowsParameters { public ComputeShader contactShadowsCS; public int kernel; public Vector4 params1; public Vector4 params2; public Vector4 params3; public int numTilesX; public int numTilesY; public int viewCount; public bool rayTracingEnabled; public RayTracingShader contactShadowsRTS; public RayTracingAccelerationStructure accelerationStructure; public int actualWidth; public int actualHeight; public int depthTextureParameterName; } ContactShadowsParameters PrepareContactShadowsParameters(HDCamera hdCamera, float firstMipOffsetY) { var parameters = new ContactShadowsParameters(); parameters.contactShadowsCS = contactShadowComputeShader; parameters.contactShadowsCS.shaderKeywords = null; if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)) { parameters.contactShadowsCS.EnableKeyword("ENABLE_MSAA"); } parameters.rayTracingEnabled = RayTracedContactShadowsRequired(); if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) { parameters.contactShadowsRTS = m_Asset.renderPipelineRayTracingResources.contactShadowRayTracingRT; parameters.accelerationStructure = RequestAccelerationStructure(); parameters.actualWidth = hdCamera.actualWidth; parameters.actualHeight = hdCamera.actualHeight; } parameters.kernel = s_deferredContactShadowKernel; float contactShadowRange = Mathf.Clamp(m_ContactShadows.fadeDistance.value, 0.0f, m_ContactShadows.maxDistance.value); float contactShadowFadeEnd = m_ContactShadows.maxDistance.value; float contactShadowOneOverFadeRange = 1.0f / Math.Max(1e-6f, contactShadowRange); float contactShadowMinDist = Mathf.Min(m_ContactShadows.minDistance.value, contactShadowFadeEnd); float contactShadowFadeIn = Mathf.Clamp(m_ContactShadows.fadeInDistance.value, 1e-6f, contactShadowFadeEnd); parameters.params1 = new Vector4(m_ContactShadows.length.value, m_ContactShadows.distanceScaleFactor.value, contactShadowFadeEnd, contactShadowOneOverFadeRange); parameters.params2 = new Vector4(firstMipOffsetY, contactShadowMinDist, contactShadowFadeIn, m_ContactShadows.rayBias.value * 0.01f); parameters.params3 = new Vector4(m_ContactShadows.sampleCount, m_ContactShadows.thicknessScale.value * 10.0f , 0.0f, 0.0f); int deferredShadowTileSize = 8; // Must match ContactShadows.compute parameters.numTilesX = (hdCamera.actualWidth + (deferredShadowTileSize - 1)) / deferredShadowTileSize; parameters.numTilesY = (hdCamera.actualHeight + (deferredShadowTileSize - 1)) / deferredShadowTileSize; parameters.viewCount = hdCamera.viewCount; // TODO: Remove once we switch fully to render graph (auto binding of textures) parameters.depthTextureParameterName = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA) ? HDShaderIDs._CameraDepthValuesTexture : HDShaderIDs._CameraDepthTexture; return parameters; } static void RenderContactShadows(in ContactShadowsParameters parameters, RTHandle contactShadowRT, RTHandle depthTexture, LightLoopLightData lightLoopLightData, ComputeBuffer lightList, CommandBuffer cmd) { cmd.SetComputeVectorParam(parameters.contactShadowsCS, HDShaderIDs._ContactShadowParamsParameters, parameters.params1); cmd.SetComputeVectorParam(parameters.contactShadowsCS, HDShaderIDs._ContactShadowParamsParameters2, parameters.params2); cmd.SetComputeVectorParam(parameters.contactShadowsCS, HDShaderIDs._ContactShadowParamsParameters3, parameters.params3); cmd.SetComputeBufferParam(parameters.contactShadowsCS, parameters.kernel, HDShaderIDs._DirectionalLightDatas, lightLoopLightData.directionalLightData); // Send light list to the compute cmd.SetComputeBufferParam(parameters.contactShadowsCS, parameters.kernel, HDShaderIDs._LightDatas, lightLoopLightData.lightData); cmd.SetComputeBufferParam(parameters.contactShadowsCS, parameters.kernel, HDShaderIDs.g_vLightListGlobal, lightList); cmd.SetComputeTextureParam(parameters.contactShadowsCS, parameters.kernel, parameters.depthTextureParameterName, depthTexture); cmd.SetComputeTextureParam(parameters.contactShadowsCS, parameters.kernel, HDShaderIDs._ContactShadowTextureUAV, contactShadowRT); cmd.DispatchCompute(parameters.contactShadowsCS, parameters.kernel, parameters.numTilesX, parameters.numTilesY, parameters.viewCount); if (parameters.rayTracingEnabled) { cmd.SetRayTracingShaderPass(parameters.contactShadowsRTS, "VisibilityDXR"); cmd.SetRayTracingAccelerationStructure(parameters.contactShadowsRTS, HDShaderIDs._RaytracingAccelerationStructureName, parameters.accelerationStructure); cmd.SetRayTracingVectorParam(parameters.contactShadowsRTS, HDShaderIDs._ContactShadowParamsParameters, parameters.params1); cmd.SetRayTracingVectorParam(parameters.contactShadowsRTS, HDShaderIDs._ContactShadowParamsParameters2, parameters.params2); cmd.SetRayTracingBufferParam(parameters.contactShadowsRTS, HDShaderIDs._DirectionalLightDatas, lightLoopLightData.directionalLightData); // Send light list to the compute cmd.SetRayTracingBufferParam(parameters.contactShadowsRTS, HDShaderIDs._LightDatas, lightLoopLightData.lightData); cmd.SetRayTracingBufferParam(parameters.contactShadowsRTS, HDShaderIDs.g_vLightListGlobal, lightList); cmd.SetRayTracingTextureParam(parameters.contactShadowsRTS, HDShaderIDs._DepthTexture, depthTexture); cmd.SetRayTracingTextureParam(parameters.contactShadowsRTS, HDShaderIDs._ContactShadowTextureUAV, contactShadowRT); cmd.DispatchRays(parameters.contactShadowsRTS, "RayGenContactShadows", (uint)parameters.actualWidth, (uint)parameters.actualHeight, (uint)parameters.viewCount); } } struct DeferredLightingParameters { public int numTilesX; public int numTilesY; public int numTiles; public bool enableTile; public bool outputSplitLighting; public bool useComputeLightingEvaluation; public bool enableFeatureVariants; public bool enableShadowMasks; public int numVariants; public DebugDisplaySettings debugDisplaySettings; // Compute Lighting public ComputeShader deferredComputeShader; public int viewCount; // Full Screen Pixel (debug) public Material splitLightingMat; public Material regularLightingMat; } DeferredLightingParameters PrepareDeferredLightingParameters(HDCamera hdCamera, DebugDisplaySettings debugDisplaySettings) { var parameters = new DeferredLightingParameters(); bool debugDisplayOrSceneLightOff = CoreUtils.IsSceneLightingDisabled(hdCamera.camera) || debugDisplaySettings.IsDebugDisplayEnabled(); int w = hdCamera.actualWidth; int h = hdCamera.actualHeight; parameters.numTilesX = (w + 15) / 16; parameters.numTilesY = (h + 15) / 16; parameters.numTiles = parameters.numTilesX * parameters.numTilesY; parameters.enableTile = hdCamera.frameSettings.IsEnabled(FrameSettingsField.DeferredTile); parameters.outputSplitLighting = hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering); parameters.useComputeLightingEvaluation = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ComputeLightEvaluation); parameters.enableFeatureVariants = GetFeatureVariantsEnabled(hdCamera.frameSettings) && !debugDisplayOrSceneLightOff; parameters.enableShadowMasks = m_EnableBakeShadowMask; parameters.numVariants = LightDefinitions.s_NumFeatureVariants; parameters.debugDisplaySettings = debugDisplaySettings; // Compute Lighting parameters.deferredComputeShader = deferredComputeShader; parameters.viewCount = hdCamera.viewCount; // Full Screen Pixel (debug) parameters.splitLightingMat = GetDeferredLightingMaterial(true /*split lighting*/, parameters.enableShadowMasks, debugDisplayOrSceneLightOff); parameters.regularLightingMat = GetDeferredLightingMaterial(false /*split lighting*/, parameters.enableShadowMasks, debugDisplayOrSceneLightOff); return parameters; } struct DeferredLightingResources { public RenderTargetIdentifier[] colorBuffers; public RTHandle depthStencilBuffer; public RTHandle depthTexture; public ComputeBuffer lightListBuffer; public ComputeBuffer tileFeatureFlagsBuffer; public ComputeBuffer tileListBuffer; public ComputeBuffer dispatchIndirectBuffer; } static void RenderComputeDeferredLighting(in DeferredLightingParameters parameters, in DeferredLightingResources resources, CommandBuffer cmd) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderDeferredLightingCompute))) { cmd.SetGlobalBuffer(HDShaderIDs.g_vLightListGlobal, resources.lightListBuffer); parameters.deferredComputeShader.shaderKeywords = null; switch (HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.hdShadowInitParams.shadowFilteringQuality) { case HDShadowFilteringQuality.Low: parameters.deferredComputeShader.EnableKeyword("SHADOW_LOW"); break; case HDShadowFilteringQuality.Medium: parameters.deferredComputeShader.EnableKeyword("SHADOW_MEDIUM"); break; case HDShadowFilteringQuality.High: parameters.deferredComputeShader.EnableKeyword("SHADOW_HIGH"); break; default: parameters.deferredComputeShader.EnableKeyword("SHADOW_MEDIUM"); break; } if (parameters.enableShadowMasks) { parameters.deferredComputeShader.EnableKeyword("SHADOWS_SHADOWMASK"); } for (int variant = 0; variant < parameters.numVariants; variant++) { int kernel; if (parameters.enableFeatureVariants) { kernel = s_shadeOpaqueIndirectFptlKernels[variant]; } else { kernel = parameters.debugDisplaySettings.IsDebugDisplayEnabled() ? s_shadeOpaqueDirectFptlDebugDisplayKernel : s_shadeOpaqueDirectFptlKernel; } cmd.SetComputeTextureParam(parameters.deferredComputeShader, kernel, HDShaderIDs._CameraDepthTexture, resources.depthTexture); // TODO: Is it possible to setup this outside the loop ? Can figure out how, get this: Property (specularLightingUAV) at kernel index (21) is not set cmd.SetComputeTextureParam(parameters.deferredComputeShader, kernel, HDShaderIDs.specularLightingUAV, resources.colorBuffers[0]); cmd.SetComputeTextureParam(parameters.deferredComputeShader, kernel, HDShaderIDs.diffuseLightingUAV, resources.colorBuffers[1]); cmd.SetComputeTextureParam(parameters.deferredComputeShader, kernel, HDShaderIDs._StencilTexture, resources.depthStencilBuffer, 0, RenderTextureSubElement.Stencil); // always do deferred lighting in blocks of 16x16 (not same as tiled light size) if (parameters.enableFeatureVariants) { cmd.SetComputeBufferParam(parameters.deferredComputeShader, kernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlagsBuffer); cmd.SetComputeIntParam(parameters.deferredComputeShader, HDShaderIDs.g_TileListOffset, variant * parameters.numTiles * parameters.viewCount); cmd.SetComputeBufferParam(parameters.deferredComputeShader, kernel, HDShaderIDs.g_TileList, resources.tileListBuffer); cmd.DispatchCompute(parameters.deferredComputeShader, kernel, resources.dispatchIndirectBuffer, (uint)variant * 3 * sizeof(uint)); } else { // 4x 8x8 groups per a 16x16 tile. cmd.DispatchCompute(parameters.deferredComputeShader, kernel, parameters.numTilesX * 2, parameters.numTilesY * 2, parameters.viewCount); } } } } static void RenderComputeAsPixelDeferredLighting(in DeferredLightingParameters parameters, in DeferredLightingResources resources, Material deferredMat, bool outputSplitLighting, CommandBuffer cmd) { CoreUtils.SetKeyword(cmd, "OUTPUT_SPLIT_LIGHTING", outputSplitLighting); CoreUtils.SetKeyword(cmd, "SHADOWS_SHADOWMASK", parameters.enableShadowMasks); if (parameters.enableFeatureVariants) { if (outputSplitLighting) CoreUtils.SetRenderTarget(cmd, resources.colorBuffers, resources.depthStencilBuffer); else CoreUtils.SetRenderTarget(cmd, resources.colorBuffers[0], resources.depthStencilBuffer); for (int variant = 0; variant < parameters.numVariants; variant++) { cmd.SetGlobalInt(HDShaderIDs.g_TileListOffset, variant * parameters.numTiles); cmd.EnableShaderKeyword(s_variantNames[variant]); MeshTopology topology = k_HasNativeQuadSupport ? MeshTopology.Quads : MeshTopology.Triangles; cmd.DrawProceduralIndirect(Matrix4x4.identity, deferredMat, 0, topology, resources.dispatchIndirectBuffer, variant * 4 * sizeof(uint), null); // Must disable variant keyword because it will not get overridden. cmd.DisableShaderKeyword(s_variantNames[variant]); } } else { CoreUtils.SetKeyword(cmd, "DEBUG_DISPLAY", parameters.debugDisplaySettings.IsDebugDisplayEnabled()); if (outputSplitLighting) CoreUtils.DrawFullScreen(cmd, deferredMat, resources.colorBuffers, resources.depthStencilBuffer, null, 1); else CoreUtils.DrawFullScreen(cmd, deferredMat, resources.colorBuffers[0], resources.depthStencilBuffer, null, 1); } } static void RenderComputeAsPixelDeferredLighting(in DeferredLightingParameters parameters, in DeferredLightingResources resources, CommandBuffer cmd) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderDeferredLightingComputeAsPixel))) { cmd.SetGlobalBuffer(HDShaderIDs.g_vLightListGlobal, resources.lightListBuffer); cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, resources.depthTexture); cmd.SetGlobalBuffer(HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlagsBuffer); cmd.SetGlobalBuffer(HDShaderIDs.g_TileList, resources.tileListBuffer); // If SSS is disabled, do lighting for both split lighting and no split lighting // Must set stencil parameters through Material. if (parameters.outputSplitLighting) { RenderComputeAsPixelDeferredLighting(parameters, resources, s_DeferredTileSplitLightingMat, true, cmd); RenderComputeAsPixelDeferredLighting(parameters, resources, s_DeferredTileRegularLightingMat, false, cmd); } else { RenderComputeAsPixelDeferredLighting(parameters, resources, s_DeferredTileMat, false, cmd); } } } static void RenderPixelDeferredLighting(in DeferredLightingParameters parameters, in DeferredLightingResources resources, CommandBuffer cmd) { cmd.SetGlobalBuffer(HDShaderIDs.g_vLightListGlobal, resources.lightListBuffer); // First, render split lighting. if (parameters.outputSplitLighting) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderDeferredLightingSinglePassMRT))) { CoreUtils.DrawFullScreen(cmd, parameters.splitLightingMat, resources.colorBuffers, resources.depthStencilBuffer); } } using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderDeferredLightingSinglePass))) { var currentLightingMaterial = parameters.regularLightingMat; // If SSS is disable, do lighting for both split lighting and no split lighting // This is for debug purpose, so fine to use immediate material mode here to modify render state if (!parameters.outputSplitLighting) { currentLightingMaterial.SetInt(HDShaderIDs._StencilRef, (int)StencilUsage.Clear); currentLightingMaterial.SetInt(HDShaderIDs._StencilMask, (int)StencilUsage.RequiresDeferredLighting | (int)StencilUsage.SubsurfaceScattering); currentLightingMaterial.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.NotEqual); } else { currentLightingMaterial.SetInt(HDShaderIDs._StencilRef, (int)StencilUsage.RequiresDeferredLighting); currentLightingMaterial.SetInt(HDShaderIDs._StencilMask, (int)StencilUsage.RequiresDeferredLighting); currentLightingMaterial.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal); } CoreUtils.DrawFullScreen(cmd, currentLightingMaterial, resources.colorBuffers[0], resources.depthStencilBuffer); } } struct LightLoopDebugOverlayParameters { public Material debugViewTilesMaterial; public HDShadowManager shadowManager; public int debugSelectedLightShadowIndex; public int debugSelectedLightShadowCount; public Material debugShadowMapMaterial; public Material debugBlitMaterial; public LightCookieManager cookieManager; public PlanarReflectionProbeCache planarProbeCache; } LightLoopDebugOverlayParameters PrepareLightLoopDebugOverlayParameters() { var parameters = new LightLoopDebugOverlayParameters(); parameters.debugViewTilesMaterial = m_DebugViewTilesMaterial; parameters.shadowManager = m_ShadowManager; parameters.debugSelectedLightShadowIndex = m_DebugSelectedLightShadowIndex; parameters.debugSelectedLightShadowCount = m_DebugSelectedLightShadowCount; parameters.debugShadowMapMaterial = m_DebugHDShadowMapMaterial; parameters.debugBlitMaterial = m_DebugBlitMaterial; parameters.cookieManager = m_TextureCaches.lightCookieManager; parameters.planarProbeCache = m_TextureCaches.reflectionPlanarProbeCache; return parameters; } static void RenderLightLoopDebugOverlay(in DebugParameters debugParameters, CommandBuffer cmd, ComputeBuffer tileBuffer, ComputeBuffer lightListBuffer, ComputeBuffer perVoxelLightListBuffer, ComputeBuffer dispatchIndirectBuffer, RTHandle depthTexture) { var hdCamera = debugParameters.hdCamera; var parameters = debugParameters.lightingOverlayParameters; LightingDebugSettings lightingDebug = debugParameters.debugDisplaySettings.data.lightingDebugSettings; if (lightingDebug.tileClusterDebug != TileClusterDebug.None) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.TileClusterLightingDebug))) { int w = hdCamera.actualWidth; int h = hdCamera.actualHeight; int numTilesX = (w + 15) / 16; int numTilesY = (h + 15) / 16; int numTiles = numTilesX * numTilesY; // Debug tiles if (lightingDebug.tileClusterDebug == TileClusterDebug.MaterialFeatureVariants) { if (GetFeatureVariantsEnabled(hdCamera.frameSettings)) { // featureVariants parameters.debugViewTilesMaterial.SetInt(HDShaderIDs._NumTiles, numTiles); parameters.debugViewTilesMaterial.SetInt(HDShaderIDs._ViewTilesFlags, (int)lightingDebug.tileClusterDebugByCategory); parameters.debugViewTilesMaterial.SetVector(HDShaderIDs._MousePixelCoord, HDUtils.GetMouseCoordinates(hdCamera)); parameters.debugViewTilesMaterial.SetVector(HDShaderIDs._MouseClickPixelCoord, HDUtils.GetMouseClickCoordinates(hdCamera)); parameters.debugViewTilesMaterial.SetBuffer(HDShaderIDs.g_TileList, tileBuffer); parameters.debugViewTilesMaterial.SetBuffer(HDShaderIDs.g_DispatchIndirectBuffer, dispatchIndirectBuffer); parameters.debugViewTilesMaterial.EnableKeyword("USE_FPTL_LIGHTLIST"); parameters.debugViewTilesMaterial.DisableKeyword("USE_CLUSTERED_LIGHTLIST"); parameters.debugViewTilesMaterial.DisableKeyword("SHOW_LIGHT_CATEGORIES"); parameters.debugViewTilesMaterial.EnableKeyword("SHOW_FEATURE_VARIANTS"); if (DeferredUseComputeAsPixel(hdCamera.frameSettings)) parameters.debugViewTilesMaterial.EnableKeyword("IS_DRAWPROCEDURALINDIRECT"); else parameters.debugViewTilesMaterial.DisableKeyword("IS_DRAWPROCEDURALINDIRECT"); cmd.DrawProcedural(Matrix4x4.identity, parameters.debugViewTilesMaterial, 0, MeshTopology.Triangles, numTiles * 6); } } else // tile or cluster { bool bUseClustered = lightingDebug.tileClusterDebug == TileClusterDebug.Cluster; // lightCategories parameters.debugViewTilesMaterial.SetInt(HDShaderIDs._ViewTilesFlags, (int)lightingDebug.tileClusterDebugByCategory); parameters.debugViewTilesMaterial.SetInt(HDShaderIDs._ClusterDebugMode, bUseClustered ? (int)lightingDebug.clusterDebugMode : (int)ClusterDebugMode.VisualizeOpaque); parameters.debugViewTilesMaterial.SetFloat(HDShaderIDs._ClusterDebugDistance, lightingDebug.clusterDebugDistance); parameters.debugViewTilesMaterial.SetVector(HDShaderIDs._MousePixelCoord, HDUtils.GetMouseCoordinates(hdCamera)); parameters.debugViewTilesMaterial.SetVector(HDShaderIDs._MouseClickPixelCoord, HDUtils.GetMouseClickCoordinates(hdCamera)); parameters.debugViewTilesMaterial.SetBuffer(HDShaderIDs.g_vLightListGlobal, bUseClustered ? perVoxelLightListBuffer : lightListBuffer); parameters.debugViewTilesMaterial.SetTexture(HDShaderIDs._CameraDepthTexture, depthTexture); parameters.debugViewTilesMaterial.EnableKeyword(bUseClustered ? "USE_CLUSTERED_LIGHTLIST" : "USE_FPTL_LIGHTLIST"); parameters.debugViewTilesMaterial.DisableKeyword(!bUseClustered ? "USE_CLUSTERED_LIGHTLIST" : "USE_FPTL_LIGHTLIST"); parameters.debugViewTilesMaterial.EnableKeyword("SHOW_LIGHT_CATEGORIES"); parameters.debugViewTilesMaterial.DisableKeyword("SHOW_FEATURE_VARIANTS"); if (!bUseClustered && hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)) parameters.debugViewTilesMaterial.EnableKeyword("DISABLE_TILE_MODE"); else parameters.debugViewTilesMaterial.DisableKeyword("DISABLE_TILE_MODE"); CoreUtils.DrawFullScreen(cmd, parameters.debugViewTilesMaterial, 0); } } } if (lightingDebug.displayCookieAtlas) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.DisplayCookieAtlas))) { m_LightLoopDebugMaterialProperties.SetFloat(HDShaderIDs._ApplyExposure, 0.0f); m_LightLoopDebugMaterialProperties.SetFloat(HDShaderIDs._Mipmap, lightingDebug.cookieAtlasMipLevel); m_LightLoopDebugMaterialProperties.SetTexture(HDShaderIDs._InputTexture, parameters.cookieManager.atlasTexture); debugParameters.debugOverlay.SetViewport(cmd); cmd.DrawProcedural(Matrix4x4.identity, parameters.debugBlitMaterial, 0, MeshTopology.Triangles, 3, 1, m_LightLoopDebugMaterialProperties); debugParameters.debugOverlay.Next(); } } if (lightingDebug.clearPlanarReflectionProbeAtlas) { parameters.planarProbeCache.Clear(cmd); } if (lightingDebug.displayPlanarReflectionProbeAtlas) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.DisplayPlanarReflectionProbeAtlas))) { m_LightLoopDebugMaterialProperties.SetFloat(HDShaderIDs._ApplyExposure, 1.0f); m_LightLoopDebugMaterialProperties.SetFloat(HDShaderIDs._Mipmap, lightingDebug.planarReflectionProbeMipLevel); m_LightLoopDebugMaterialProperties.SetTexture(HDShaderIDs._InputTexture, parameters.planarProbeCache.GetTexCache()); debugParameters.debugOverlay.SetViewport(cmd); cmd.DrawProcedural(Matrix4x4.identity, parameters.debugBlitMaterial, 0, MeshTopology.Triangles, 3, 1, m_LightLoopDebugMaterialProperties); debugParameters.debugOverlay.Next(); } } } static void RenderShadowsDebugOverlay(in DebugParameters debugParameters, in HDShadowManager.ShadowDebugAtlasTextures atlasTextures, CommandBuffer cmd, MaterialPropertyBlock mpb) { if (HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.hdShadowInitParams.maxShadowRequests == 0) return; LightingDebugSettings lightingDebug = debugParameters.debugDisplaySettings.data.lightingDebugSettings; if (lightingDebug.shadowDebugMode != ShadowMapDebugMode.None) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.DisplayShadows))) { var hdCamera = debugParameters.hdCamera; var parameters = debugParameters.lightingOverlayParameters; switch (lightingDebug.shadowDebugMode) { case ShadowMapDebugMode.VisualizeShadowMap: int startShadowIndex = (int)lightingDebug.shadowMapIndex; int shadowRequestCount = 1; #if UNITY_EDITOR if (lightingDebug.shadowDebugUseSelection) { if (parameters.debugSelectedLightShadowIndex != -1 && parameters.debugSelectedLightShadowCount != 0) { startShadowIndex = parameters.debugSelectedLightShadowIndex; shadowRequestCount = parameters.debugSelectedLightShadowCount; } else { // We don't display any shadow map if the selected object is not a light shadowRequestCount = 0; } } #endif for (int shadowIndex = startShadowIndex; shadowIndex < startShadowIndex + shadowRequestCount; shadowIndex++) { parameters.shadowManager.DisplayShadowMap(atlasTextures, shadowIndex, cmd, parameters.debugShadowMapMaterial, debugParameters.debugOverlay.x, debugParameters.debugOverlay.y, debugParameters.debugOverlay.overlaySize, debugParameters.debugOverlay.overlaySize, lightingDebug.shadowMinValue, lightingDebug.shadowMaxValue, mpb); debugParameters.debugOverlay.Next(); } break; case ShadowMapDebugMode.VisualizePunctualLightAtlas: parameters.shadowManager.DisplayShadowAtlas(atlasTextures.punctualShadowAtlas, cmd, parameters.debugShadowMapMaterial, debugParameters.debugOverlay.x, debugParameters.debugOverlay.y, debugParameters.debugOverlay.overlaySize, debugParameters.debugOverlay.overlaySize, lightingDebug.shadowMinValue, lightingDebug.shadowMaxValue, mpb); debugParameters.debugOverlay.Next(); break; case ShadowMapDebugMode.VisualizeCachedPunctualLightAtlas: parameters.shadowManager.DisplayCachedPunctualShadowAtlas(atlasTextures.cachedPunctualShadowAtlas, cmd, parameters.debugShadowMapMaterial, debugParameters.debugOverlay.x, debugParameters.debugOverlay.y, debugParameters.debugOverlay.overlaySize, debugParameters.debugOverlay.overlaySize, lightingDebug.shadowMinValue, lightingDebug.shadowMaxValue, mpb); debugParameters.debugOverlay.Next(); break; case ShadowMapDebugMode.VisualizeDirectionalLightAtlas: parameters.shadowManager.DisplayShadowCascadeAtlas(atlasTextures.cascadeShadowAtlas, cmd, parameters.debugShadowMapMaterial, debugParameters.debugOverlay.x, debugParameters.debugOverlay.y, debugParameters.debugOverlay.overlaySize, debugParameters.debugOverlay.overlaySize, lightingDebug.shadowMinValue, lightingDebug.shadowMaxValue, mpb); debugParameters.debugOverlay.Next(); break; case ShadowMapDebugMode.VisualizeAreaLightAtlas: parameters.shadowManager.DisplayAreaLightShadowAtlas(atlasTextures.areaShadowAtlas, cmd, parameters.debugShadowMapMaterial, debugParameters.debugOverlay.x, debugParameters.debugOverlay.y, debugParameters.debugOverlay.overlaySize, debugParameters.debugOverlay.overlaySize, lightingDebug.shadowMinValue, lightingDebug.shadowMaxValue, mpb); debugParameters.debugOverlay.Next(); break; case ShadowMapDebugMode.VisualizeCachedAreaLightAtlas: parameters.shadowManager.DisplayCachedAreaShadowAtlas(atlasTextures.cachedAreaShadowAtlas, cmd, parameters.debugShadowMapMaterial, debugParameters.debugOverlay.x, debugParameters.debugOverlay.y, debugParameters.debugOverlay.overlaySize, debugParameters.debugOverlay.overlaySize, lightingDebug.shadowMinValue, lightingDebug.shadowMaxValue, mpb); debugParameters.debugOverlay.Next(); break; default: break; } } } } } } // Memo used when debugging to remember order of dispatch and value // GenerateLightsScreenSpaceAABBs // cmd.DispatchCompute(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, (parameters.totalLightCount + 7) / 8, parameters.viewCount, 1); // BigTilePrepass(ScreenX / 64, ScreenY / 64) // cmd.DispatchCompute(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, parameters.numBigTilesX, parameters.numBigTilesY, parameters.viewCount); // BuildPerTileLightList(ScreenX / 16, ScreenY / 16) // cmd.DispatchCompute(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, parameters.numTilesFPTLX, parameters.numTilesFPTLY, parameters.viewCount); // VoxelLightListGeneration(ScreenX / 32, ScreenY / 32) // cmd.DispatchCompute(parameters.buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, 1, 1, 1); // cmd.DispatchCompute(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, parameters.numTilesClusterX, parameters.numTilesClusterY, parameters.viewCount); // buildMaterialFlags (ScreenX / 16, ScreenY / 16) // cmd.DispatchCompute(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, parameters.numTilesFPTLX, parameters.numTilesFPTLY, parameters.viewCount); // cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, 1, 1, 1); // BuildDispatchIndirectArguments // cmd.DispatchCompute(parameters.buildDispatchIndirectShader, s_BuildDispatchIndirectKernel, (parameters.numTilesFPTL + k_ThreadGroupOptimalSize - 1) / k_ThreadGroupOptimalSize, 1, parameters.viewCount); // Then dispatch indirect will trigger the number of tile for a variant x4 as we process by wavefront of 64 (16x16 => 4 x 8x8)
55.38951
380
0.64059
[ "MIT" ]
turesnake/tpr_Unity_Render_Pipeline_LearningNotes
11.0/HDRP_11.0/Runtime/Lighting/LightLoop/LightLoop.cs
222,832
C#
using System.Collections.Generic; using TorrentBox.Api.Models; using TorrentBox.Api.Rss.Models; namespace TorrentBox.Api.Rss { public class RssLoader { internal static IEnumerable<ResolvedRssItem> GetItemFromRss(JobConfiguration job) { var rssItems = RssReader.GetRssObject(job.RssUrl); return RssItemResolver.ResolveRssItems(job, rssItems); } } }
25.625
89
0.697561
[ "MIT" ]
Kosrabt/torrentbox
src/TorrentBox.Api/Rss/RssLoader.cs
412
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Media.Rtsp")] [assembly: AssemblyDescription("Provides a managed implementation of RFC2326")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(true)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b9788cdc-7365-4117-9711-2cfa2057e417")]
44.222222
84
0.786432
[ "Apache-2.0" ]
Sergey-Terekhin/net7mma
Rtsp/Properties/AssemblyInfo.cs
798
C#
using DataHub.OperationalDataStore; namespace OpenTemenos.Tests.DataHub.OperationalDataStore.Product; [TestClass, TestCategory("DataHub.OperationalDataStore")] public class ProductDetailServiceTests : CredentialManagement { private const string ProductLineId = ""; private readonly IProductClient _client = new ProductClient(HttpClient) { ReadResponseAsString = true }; [TestMethod] public void GetProductGroupAsync() { var result = _client.ProductDetailService.GetProductGroupAsync(ProductLineId).Result; Assert.IsNotNull(result.Data); } [TestMethod] public void GetProductLineActivitiesAsync() { var result = _client.ProductDetailService.GetProductLineActivitiesAsync(ProductLineId).Result; Assert.IsNotNull(result.Data); } [TestMethod] public void GetProductLinesAsync() { var result = _client.ProductDetailService.GetProductLinesAsync().Result; Assert.IsNotNull(result.Data); } [TestMethod] public void GetProductGroupsAsync() { var result = _client.ProductDetailService.GetProductGroupsAsync().Result; Assert.IsNotNull(result.Data); } [TestMethod] public void GetPropertyClassesAsync() { var result = _client.ProductDetailService.GetPropertyClassesAsync().Result; Assert.IsNotNull(result.Data); } }
30.644444
108
0.724438
[ "MIT" ]
ElevateData/OpenTemenos
tests/OpenTemenos.Tests/DataHub/OperationalDataStore/Product/ProductDetailsServiceTests.cs
1,381
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using IdentityServer4.Models; using Microsoft.Extensions.Configuration; using Volo.Abp.Authorization.Permissions; using Volo.Abp.Data; using Volo.Abp.DependencyInjection; using Volo.Abp.Guids; using Volo.Abp.IdentityServer.ApiResources; using Volo.Abp.IdentityServer.ApiScopes; using Volo.Abp.IdentityServer.Clients; using Volo.Abp.IdentityServer.IdentityResources; using Volo.Abp.MultiTenancy; using Volo.Abp.PermissionManagement; using Volo.Abp.Uow; using ApiResource = Volo.Abp.IdentityServer.ApiResources.ApiResource; using ApiScope = Volo.Abp.IdentityServer.ApiScopes.ApiScope; using Client = Volo.Abp.IdentityServer.Clients.Client; namespace AbpTailwindMvc.IdentityServer { public class IdentityServerDataSeedContributor : IDataSeedContributor, ITransientDependency { private readonly IApiResourceRepository _apiResourceRepository; private readonly IApiScopeRepository _apiScopeRepository; private readonly IClientRepository _clientRepository; private readonly IIdentityResourceDataSeeder _identityResourceDataSeeder; private readonly IGuidGenerator _guidGenerator; private readonly IPermissionDataSeeder _permissionDataSeeder; private readonly IConfiguration _configuration; private readonly ICurrentTenant _currentTenant; public IdentityServerDataSeedContributor( IClientRepository clientRepository, IApiResourceRepository apiResourceRepository, IApiScopeRepository apiScopeRepository, IIdentityResourceDataSeeder identityResourceDataSeeder, IGuidGenerator guidGenerator, IPermissionDataSeeder permissionDataSeeder, IConfiguration configuration, ICurrentTenant currentTenant) { _clientRepository = clientRepository; _apiResourceRepository = apiResourceRepository; _apiScopeRepository = apiScopeRepository; _identityResourceDataSeeder = identityResourceDataSeeder; _guidGenerator = guidGenerator; _permissionDataSeeder = permissionDataSeeder; _configuration = configuration; _currentTenant = currentTenant; } [UnitOfWork] public virtual async Task SeedAsync(DataSeedContext context) { using (_currentTenant.Change(context?.TenantId)) { await _identityResourceDataSeeder.CreateStandardResourcesAsync(); await CreateApiResourcesAsync(); await CreateApiScopesAsync(); await CreateClientsAsync(); } } private async Task CreateApiScopesAsync() { await CreateApiScopeAsync("AbpTailwindMvc"); } private async Task CreateApiResourcesAsync() { var commonApiUserClaims = new[] { "email", "email_verified", "name", "phone_number", "phone_number_verified", "role" }; await CreateApiResourceAsync("AbpTailwindMvc", commonApiUserClaims); } private async Task<ApiResource> CreateApiResourceAsync(string name, IEnumerable<string> claims) { var apiResource = await _apiResourceRepository.FindByNameAsync(name); if (apiResource == null) { apiResource = await _apiResourceRepository.InsertAsync( new ApiResource( _guidGenerator.Create(), name, name + " API" ), autoSave: true ); } foreach (var claim in claims) { if (apiResource.FindClaim(claim) == null) { apiResource.AddUserClaim(claim); } } return await _apiResourceRepository.UpdateAsync(apiResource); } private async Task<ApiScope> CreateApiScopeAsync(string name) { var apiScope = await _apiScopeRepository.FindByNameAsync(name); if (apiScope == null) { apiScope = await _apiScopeRepository.InsertAsync( new ApiScope( _guidGenerator.Create(), name, name + " API" ), autoSave: true ); } return apiScope; } private async Task CreateClientsAsync() { var commonScopes = new[] { "email", "openid", "profile", "role", "phone", "address", "AbpTailwindMvc" }; var configurationSection = _configuration.GetSection("IdentityServer:Clients"); //Console Test / Angular Client var consoleAndAngularClientId = configurationSection["AbpTailwindMvc_App:ClientId"]; if (!consoleAndAngularClientId.IsNullOrWhiteSpace()) { var webClientRootUrl = configurationSection["AbpTailwindMvc_App:RootUrl"]?.TrimEnd('/'); await CreateClientAsync( name: consoleAndAngularClientId, scopes: commonScopes, grantTypes: new[] { "password", "client_credentials", "authorization_code" }, secret: (configurationSection["AbpTailwindMvc_App:ClientSecret"] ?? "1q2w3e*").Sha256(), requireClientSecret: false, redirectUri: webClientRootUrl, postLogoutRedirectUri: webClientRootUrl, corsOrigins: new[] { webClientRootUrl.RemovePostFix("/") } ); } // Swagger Client var swaggerClientId = configurationSection["AbpTailwindMvc_Swagger:ClientId"]; if (!swaggerClientId.IsNullOrWhiteSpace()) { var swaggerRootUrl = configurationSection["AbpTailwindMvc_Swagger:RootUrl"].TrimEnd('/'); await CreateClientAsync( name: swaggerClientId, scopes: commonScopes, grantTypes: new[] { "authorization_code" }, secret: configurationSection["AbpTailwindMvc_Swagger:ClientSecret"]?.Sha256(), requireClientSecret: false, redirectUri: $"{swaggerRootUrl}/swagger/oauth2-redirect.html", corsOrigins: new[] { swaggerRootUrl.RemovePostFix("/") } ); } } private async Task<Client> CreateClientAsync( string name, IEnumerable<string> scopes, IEnumerable<string> grantTypes, string secret = null, string redirectUri = null, string postLogoutRedirectUri = null, string frontChannelLogoutUri = null, bool requireClientSecret = true, bool requirePkce = false, IEnumerable<string> permissions = null, IEnumerable<string> corsOrigins = null) { var client = await _clientRepository.FindByClientIdAsync(name); if (client == null) { client = await _clientRepository.InsertAsync( new Client( _guidGenerator.Create(), name ) { ClientName = name, ProtocolType = "oidc", Description = name, AlwaysIncludeUserClaimsInIdToken = true, AllowOfflineAccess = true, AbsoluteRefreshTokenLifetime = 31536000, //365 days AccessTokenLifetime = 31536000, //365 days AuthorizationCodeLifetime = 300, IdentityTokenLifetime = 300, RequireConsent = false, FrontChannelLogoutUri = frontChannelLogoutUri, RequireClientSecret = requireClientSecret, RequirePkce = requirePkce }, autoSave: true ); } foreach (var scope in scopes) { if (client.FindScope(scope) == null) { client.AddScope(scope); } } foreach (var grantType in grantTypes) { if (client.FindGrantType(grantType) == null) { client.AddGrantType(grantType); } } if (!secret.IsNullOrEmpty()) { if (client.FindSecret(secret) == null) { client.AddSecret(secret); } } if (redirectUri != null) { if (client.FindRedirectUri(redirectUri) == null) { client.AddRedirectUri(redirectUri); } } if (postLogoutRedirectUri != null) { if (client.FindPostLogoutRedirectUri(postLogoutRedirectUri) == null) { client.AddPostLogoutRedirectUri(postLogoutRedirectUri); } } if (permissions != null) { await _permissionDataSeeder.SeedAsync( ClientPermissionValueProvider.ProviderName, name, permissions, null ); } if (corsOrigins != null) { foreach (var origin in corsOrigins) { if (!origin.IsNullOrWhiteSpace() && client.FindCorsOrigin(origin) == null) { client.AddCorsOrigin(origin); } } } return await _clientRepository.UpdateAsync(client); } } }
36.121107
108
0.536641
[ "MIT" ]
antosubash/AbpTailwindMvcUI
src/AbpTailwindMvc.Domain/IdentityServer/IdentityServerDataSeedContributor.cs
10,439
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections.Generic; using UnityEngine; using UnityEngine.VR.WSA.Input; namespace HoloToolkit.Unity.InputModule { /// <summary> /// Input source for raw interactions sources information, which gives finer details about current source state and position /// than the standard GestureRecognizer. /// This mostly allows users to access the source up/down and detected/lost events, /// which are not communicated as part of standard Windows gestures. /// </summary> /// <remarks> /// This input source only triggers SourceUp/SourceDown and SourceDetected/SourceLost. /// Everything else is handled by GesturesInput. /// </remarks> public class RawInteractionSourcesInput : BaseInputSource { /// <summary> /// Data for an interaction source. /// </summary> private class SourceData { public SourceData(uint sourceId) { SourceId = sourceId; HasPosition = false; SourcePosition = Vector3.zero; IsSourceDown = false; IsSourceDownPending = false; SourceStateChanged = false; SourceStateUpdateTimer = -1; } public readonly uint SourceId; public bool HasPosition; public Vector3 SourcePosition; public bool IsSourceDown; public bool IsSourceDownPending; public bool SourceStateChanged; public float SourceStateUpdateTimer; } /// <summary> /// Delay before a source press is considered. /// This mitigates fake source taps that can sometimes be detected while the input source is moving. /// </summary> private const float SourcePressDelay = 0.07f; [Tooltip("Use unscaled time. This is useful for games that have a pause mechanism or otherwise adjust the game timescale.")] public bool UseUnscaledTime = true; /// <summary> /// Dictionary linking each source ID to its data. /// </summary> private readonly Dictionary<uint, SourceData> sourceIdToData = new Dictionary<uint, SourceData>(4); private readonly List<uint> pendingSourceIdDeletes = new List<uint>(); // HashSets used to be able to quickly update the sources data when they become visible / not visible private readonly HashSet<uint> currentSources = new HashSet<uint>(); private readonly HashSet<uint> newSources = new HashSet<uint>(); public override SupportedInputInfo GetSupportedInputInfo(uint sourceId) { SupportedInputInfo retVal = SupportedInputInfo.None; SourceData sourceData; if (sourceIdToData.TryGetValue(sourceId, out sourceData)) { if (sourceData.HasPosition) { retVal |= SupportedInputInfo.Position; } } return retVal; } public override bool TryGetPosition(uint sourceId, out Vector3 position) { SourceData sourceData; if (sourceIdToData.TryGetValue(sourceId, out sourceData)) { if (sourceData.HasPosition) { position = sourceData.SourcePosition; return true; } } // Else, the source doesn't have positional information position = Vector3.zero; return false; } public override bool TryGetOrientation(uint sourceId, out Quaternion orientation) { // Orientation is not supported by any Windows interaction sources orientation = Quaternion.identity; return false; } private void Update() { newSources.Clear(); currentSources.Clear(); UpdateSourceData(); SendSourceVisibilityEvents(); } /// <summary> /// Update the source data for the currently detected sources. /// </summary> private void UpdateSourceData() { // Poll for updated reading from hands InteractionSourceState[] sourceStates = InteractionManager.GetCurrentReading(); if (sourceStates != null) { for (var i = 0; i < sourceStates.Length; ++i) { InteractionSourceState handSource = sourceStates[i]; SourceData sourceData = GetOrAddSourceData(handSource.source); currentSources.Add(handSource.source.id); UpdateSourceState(handSource, sourceData); } } } /// <summary> /// Gets the source data for the specified interaction source if it already exists, otherwise creates it. /// </summary> /// <param name="interactionSource">Interaction source for which data should be retrieved.</param> /// <returns>The source data requested.</returns> private SourceData GetOrAddSourceData(InteractionSource interactionSource) { SourceData sourceData; if (!sourceIdToData.TryGetValue(interactionSource.id, out sourceData)) { sourceData = new SourceData(interactionSource.id); sourceIdToData.Add(sourceData.SourceId, sourceData); newSources.Add(sourceData.SourceId); } return sourceData; } /// <summary> /// Updates the source positional information. /// </summary> /// <param name="interactionSource">Interaction source to use to update the position.</param> /// <param name="sourceData">SourceData structure to update.</param> private void UpdateSourceState(InteractionSourceState interactionSource, SourceData sourceData) { // Update source position Vector3 sourcePosition; if (interactionSource.properties.location.TryGetPosition(out sourcePosition)) { sourceData.HasPosition = true; sourceData.SourcePosition = sourcePosition; } // Check for source presses if (interactionSource.pressed != sourceData.IsSourceDownPending) { sourceData.IsSourceDownPending = interactionSource.pressed; sourceData.SourceStateUpdateTimer = SourcePressDelay; } // Source presses are delayed to mitigate issue with hand position shifting during air tap sourceData.SourceStateChanged = false; if (sourceData.SourceStateUpdateTimer >= 0) { float deltaTime = UseUnscaledTime ? Time.unscaledDeltaTime : Time.deltaTime; sourceData.SourceStateUpdateTimer -= deltaTime; if (sourceData.SourceStateUpdateTimer < 0) { sourceData.IsSourceDown = sourceData.IsSourceDownPending; sourceData.SourceStateChanged = true; } } SendSourceStateEvents(sourceData); } /// <summary> /// Sends the events for source state changes. /// </summary> /// <param name="sourceData">Source data for which events should be sent.</param> private void SendSourceStateEvents(SourceData sourceData) { // Source pressed/released events if (sourceData.SourceStateChanged) { if (sourceData.IsSourceDown) { inputManager.RaiseSourceDown(this, sourceData.SourceId); } else { inputManager.RaiseSourceUp(this, sourceData.SourceId); } } } /// <summary> /// Sends the events for source visibility changes. /// </summary> private void SendSourceVisibilityEvents() { // Send event for new sources that were added foreach (uint newSource in newSources) { inputManager.RaiseSourceDetected(this, newSource); } // Send event for sources that are no longer visible and remove them from our dictionary foreach (uint existingSource in sourceIdToData.Keys) { if (!currentSources.Contains(existingSource)) { pendingSourceIdDeletes.Add(existingSource); inputManager.RaiseSourceLost(this, existingSource); } } // Remove pending source IDs for (int i = 0; i < pendingSourceIdDeletes.Count; ++i) { sourceIdToData.Remove(pendingSourceIdDeletes[i]); } pendingSourceIdDeletes.Clear(); } } }
37.680328
132
0.581466
[ "MIT" ]
AmrARaouf/WDM-hololens
WoundManagementUnity/WoundManagement/Assets/HoloToolkit/Input/Scripts/InputSources/RawInteractionSourcesInput.cs
9,196
C#
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Ship_Game.AI; using Ship_Game.Ships; namespace Ship_Game { public sealed class DimensionalPrison : Anomaly, IDisposable { public string PlatformName = "Mysterious Platform"; public Vector2 PlaformCenter; public string PrisonerId; private BackgroundItem Prison; private readonly Ship Platform1; private readonly Ship Platform2; private readonly Ship Platform3; private int NumSpawnedRemnants; private int NumRemnantsToSpawn = 9; private float SpawnCountdown; public DimensionalPrison(Vector2 plaformCenter) { PlaformCenter = plaformCenter; CreateDimensionalPrison(plaformCenter, 400); Platform1 = SpawnAncientRepulsor(plaformCenter + new Vector2(0f, -400f)); Platform2 = SpawnAncientRepulsor(plaformCenter + new Vector2(-400f, 400f)); Platform3 = SpawnAncientRepulsor(plaformCenter + new Vector2(400f, -400f)); } private Ship SpawnAncientRepulsor(Vector2 repulsorPos) { Ship repulsor = Ship.CreateShipAtPoint(PlatformName, EmpireManager.Unknown, repulsorPos); var beam = new Beam(repulsor, PlaformCenter, 75) { Weapon = ResourceManager.GetWeaponTemplate("AncientRepulsor") }; repulsor.AddBeam(beam); beam.Infinite = true; beam.Range = 2500f; beam.PowerCost = 0f; beam.DamageAmount = 0f; return repulsor; } private void CreateDimensionalPrison(Vector2 center, int radius) { var screen = Empire.Universe; var r = new Rectangle((int)center.X - radius, (int)center.Y - radius, radius*2, radius*2); Prison = new BackgroundItem(); Prison.LoadContent(screen.ScreenManager); Prison.UpperLeft = new Vector3(r.X, r.Y, 0f); Prison.LowerLeft = Prison.UpperLeft + new Vector3(0f, r.Height, 0f); Prison.UpperRight = Prison.UpperLeft + new Vector3(r.Width, 0f, 0f); Prison.LowerRight = Prison.UpperLeft + new Vector3(r.Width, r.Height, 0f); Prison.Texture = ResourceManager.Texture("star_neutron"); Prison.FillVertices(); } public override void Draw() { var screen = Empire.Universe; var manager = screen.ScreenManager; manager.GraphicsDevice.SamplerStates[0].AddressU = TextureAddressMode.Wrap; manager.GraphicsDevice.SamplerStates[0].AddressV = TextureAddressMode.Wrap; manager.GraphicsDevice.RenderState.AlphaBlendEnable = true; manager.GraphicsDevice.RenderState.AlphaBlendOperation = BlendFunction.Add; manager.GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha; manager.GraphicsDevice.RenderState.DestinationBlend = Blend.One; manager.GraphicsDevice.RenderState.DepthBufferWriteEnable = false; manager.GraphicsDevice.RenderState.CullMode = CullMode.None; for (int i = 0; i < 20; i++) { screen.sparks.AddParticleThreadA(new Vector3(PlaformCenter, 0f) + GenerateRandomWithin(100f), GenerateRandomWithin(25f)); } if (RandomMath.RandomBetween(0f, 100f) > 97f) { screen.flash.AddParticleThreadA(new Vector3(PlaformCenter, 0f), Vector3.Zero); } Prison.Draw(manager, screen.View, screen.Projection, 1f); } private Vector2 GenerateRandomV2(float radius) { return new Vector2(RandomMath.RandomBetween(-radius, radius), RandomMath.RandomBetween(-radius, radius)); } private Vector3 GenerateRandomWithin(float radius) { return new Vector3(RandomMath.RandomBetween(-radius, radius), RandomMath.RandomBetween(-radius, radius), RandomMath.RandomBetween(-radius, radius)); } public override void Update(float elapsedTime) { // spawn a bunch of drones when the player has killed all platforms :))) if (!Platform1.Active && !Platform2.Active && !Platform3.Active) { SpawnCountdown -= elapsedTime; if (SpawnCountdown <= 0f) { Ship enemy = Ship.CreateShipAtPoint("Heavy Drone", EmpireManager.Remnants, PlaformCenter); enemy.Velocity = GenerateRandomV2(100f); enemy.AI.State = AIState.AwaitingOrders; SpawnCountdown = 2f; ++NumSpawnedRemnants; } if (NumSpawnedRemnants == NumRemnantsToSpawn) { Empire.Universe.anomalyManager.AnomaliesList.QueuePendingRemoval(this); } } } public void Dispose() { Destroy(); GC.SuppressFinalize(this); } ~DimensionalPrison() { Destroy(); } private void Destroy() { Prison?.Dispose(ref Prison); } } }
41.898438
161
0.592952
[ "MIT" ]
UnGaucho/StarDrive
Ship_Game/StoryAndEvents/DimensionalPrison.cs
5,363
C#
/* Copyright (C) 2018-2019 de4dot@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #if FAST_FMT using Iced.Intel; using Xunit; namespace Iced.UnitTests.Intel.FormatterTests.Fast { public sealed class FastStringOutputTests { [Theory] [InlineData(-1)] [InlineData(0)] [InlineData(1)] [InlineData(1000)] void AppendChars(int capacity) { var output = capacity < 0 ? new FastStringOutput() : new FastStringOutput(capacity); Assert.Empty(output.ToString()); output.Append('a'); Assert.Equal("a", output.ToString()); output.Append('b'); Assert.Equal("ab", output.ToString()); for (int i = 0; i < 1000; i++) output.Append('c'); Assert.Equal("ab" + new string('c', 1000), output.ToString()); } [Theory] [InlineData("")] [InlineData("q")] [InlineData("qw")] [InlineData("qwerty")] void AppendString(string s) { var capacities = new int[] { -1, 0, 1, 1000 }; foreach (var capacity in capacities) { var output = capacity < 0 ? new FastStringOutput() : new FastStringOutput(capacity); Assert.Empty(output.ToString()); output.Append(s); Assert.Equal(s, output.ToString()); output.Append("abc"); Assert.Equal(s + "abc", output.ToString()); for (int i = 0; i < 200; i++) output.Append("x"); Assert.Equal(s + "abc" + new string('x', 200), output.ToString()); for (int i = 0; i < 200; i++) output.Append("yy"); Assert.Equal(s + "abc" + new string('x', 200) + new string('y', 400), output.ToString()); } } [Fact] void AppendNullWorks() { var output = new FastStringOutput(); Assert.Empty(output.ToString()); output.Append(null); Assert.Empty(output.ToString()); output.Append('a'); Assert.Equal("a", output.ToString()); output.Append(null); Assert.Equal("a", output.ToString()); } [Fact] void ClearWorks() { var output = new FastStringOutput(); Assert.Empty(output.ToString()); output.Append('a'); Assert.Equal("a", output.ToString()); output.Clear(); Assert.Empty(output.ToString()); output.Append("abc"); Assert.Equal("abc", output.ToString()); output.Clear(); Assert.Empty(output.ToString()); } [Fact] void LengthWorks() { var output = new FastStringOutput(); Assert.Equal(0, output.Length); output.Append('a'); Assert.Equal(1, output.Length); output.Append('b'); Assert.Equal(2, output.Length); output.Append("cde"); Assert.Equal(5, output.Length); output.Clear(); Assert.Equal(0, output.Length); output.Append("abc"); Assert.Equal(3, output.Length); output.Clear(); Assert.Equal(0, output.Length); } #if HAS_SPAN [Fact] void AsSpanWorks() { var output = new FastStringOutput(); Assert.Empty(output.AsSpan().ToString()); output.Append('a'); Assert.Equal("a", output.AsSpan().ToString()); output.Append('b'); Assert.Equal("ab", output.AsSpan().ToString()); for (int i = 0; i < 1000; i++) output.Append('c'); Assert.Equal("ab" + new string('c', 1000), output.AsSpan().ToString()); output.Clear(); Assert.Empty(output.AsSpan().ToString()); } #endif [Theory] [InlineData(0, "", "abcdefgh")] [InlineData(8, "", "abcdefgh")] [InlineData(0, "x", "xbcdefgh")] [InlineData(3, "x", "abcxefgh")] [InlineData(7, "x", "abcdefgx")] [InlineData(0, "xyz", "xyzdefgh")] [InlineData(3, "xyz", "abcxyzgh")] [InlineData(5, "xyz", "abcdexyz")] void CopyToWorks(int index, string data, string expected) { var charData = "abcdefgh".ToCharArray(); var output = new FastStringOutput(); output.Append(data); output.CopyTo(charData, index); var s = new string(charData); Assert.Equal(expected, s); } } } #endif
30.966887
93
0.668092
[ "MIT" ]
moodykeke/iced
src/csharp/Intel/Iced.UnitTests/Intel/FormatterTests/Fast/FastStringOutputTests.cs
4,676
C#
// // RemoveRedundantCatchTypeTests.cs // // Author: // Simon Lindgren <simon.n.lindgren@gmail.com> // // Copyright (c) 2012 Simon Lindgren // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using NUnit.Framework; using ICSharpCode.NRefactory.CSharp.Refactoring; namespace ICSharpCode.NRefactory.CSharp.CodeActions { [TestFixture] public class RemoveRedundantCatchTypeTests : ContextActionTestBase { [Test] public void RemovesSimpleExceptionMatch() { Test<RemoveRedundantCatchTypeAction>(@" class TestClass { public void F() { try { } catch $(System.Exception) { } } }", @" class TestClass { public void F() { try { } catch { } } }"); } [Test] public void PreservesBody() { Test<RemoveRedundantCatchTypeAction>(@" class TestClass { public void F() { try { } catch $(System.Exception e) { System.Console.WriteLine (""Hi""); } } }", @" class TestClass { public void F() { try { } catch { System.Console.WriteLine (""Hi""); } } }"); } [Test] [Ignore("Needs whitespace ast nodes")] public void PreservesWhitespaceInBody() { Test<RemoveRedundantCatchTypeAction>(@" class TestClass { public void F() { try { } catch $(System.Exception e) { } } }", @" class TestClass { public void F() { try { } catch { } } }"); } [Test] public void IgnoresReferencedExceptionMatch() { TestWrongContext<RemoveRedundantCatchTypeAction>(@" class TestClass { public void F() { try { } catch $(System.Exception e) { System.Console.WriteLine (e); } } }"); } } }
18.913043
80
0.689655
[ "MIT" ]
4lab/ILSpy
NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeActions/RemoveRedundantCatchTypeTests.cs
2,610
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.Tests.FeedRange { using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Cosmos.Handlers; using Microsoft.Azure.Cosmos.Routing; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; [TestClass] public class ReadFeedIteratorCoreTests { [TestMethod] public void ReadFeedIteratorCore_HasMoreResultsDefault() { FeedRangeIteratorCore iterator = FeedRangeIteratorCore.Create(Mock.Of<ContainerInternal>(), Mock.Of<FeedRangeInternal>(), null, null); Assert.IsTrue(iterator.HasMoreResults); } [TestMethod] public void ReadFeedIteratorCore_Create_Default() { FeedRangeIteratorCore feedTokenIterator = FeedRangeIteratorCore.Create(Mock.Of<ContainerInternal>(), null, null, null); FeedRangeEpk defaultRange = feedTokenIterator.FeedRangeInternal as FeedRangeEpk; Assert.AreEqual(FeedRangeEpk.FullRange.Range.Min, defaultRange.Range.Min); Assert.AreEqual(FeedRangeEpk.FullRange.Range.Max, defaultRange.Range.Max); Assert.IsNull(feedTokenIterator.FeedRangeContinuation); } [TestMethod] public void ReadFeedIteratorCore_Create_WithRange() { Documents.Routing.Range<string> range = new Documents.Routing.Range<string>("A", "B", true, false); FeedRangeEpk feedRangeEPK = new FeedRangeEpk(range); FeedRangeIteratorCore feedTokenIterator = FeedRangeIteratorCore.Create(Mock.Of<ContainerInternal>(), feedRangeEPK, null, null); Assert.AreEqual(feedRangeEPK, feedTokenIterator.FeedRangeInternal); Assert.IsNull(feedTokenIterator.FeedRangeContinuation); } [TestMethod] public void ReadFeedIteratorCore_Create_WithContinuation() { string continuation = Guid.NewGuid().ToString(); FeedRangeIteratorCore feedTokenIterator = FeedRangeIteratorCore.Create(Mock.Of<ContainerInternal>(), null, continuation, null); FeedRangeEpk defaultRange = feedTokenIterator.FeedRangeInternal as FeedRangeEpk; Assert.AreEqual(FeedRangeEpk.FullRange.Range.Min, defaultRange.Range.Min); Assert.AreEqual(FeedRangeEpk.FullRange.Range.Max, defaultRange.Range.Max); Assert.IsNotNull(feedTokenIterator.FeedRangeContinuation); Assert.AreEqual(continuation, feedTokenIterator.FeedRangeContinuation.GetContinuation()); } [TestMethod] public void ReadFeedIteratorCore_Create_WithFeedContinuation() { string continuation = Guid.NewGuid().ToString(); FeedRangeEpk feedRangeEPK = FeedRangeEpk.FullRange; FeedRangeCompositeContinuation feedRangeSimpleContinuation = new FeedRangeCompositeContinuation(Guid.NewGuid().ToString(), feedRangeEPK, new List<Documents.Routing.Range<string>>() { feedRangeEPK.Range }, continuation); FeedRangeIteratorCore feedTokenIterator = FeedRangeIteratorCore.Create(Mock.Of<ContainerInternal>(), null, feedRangeSimpleContinuation.ToString(), null); FeedRangeEpk defaultRange = feedTokenIterator.FeedRangeInternal as FeedRangeEpk; Assert.AreEqual(FeedRangeEpk.FullRange.Range.Min, defaultRange.Range.Min); Assert.AreEqual(FeedRangeEpk.FullRange.Range.Max, defaultRange.Range.Max); Assert.IsNotNull(feedTokenIterator.FeedRangeContinuation); Assert.AreEqual(continuation, feedTokenIterator.FeedRangeContinuation.GetContinuation()); } [TestMethod] public async Task ReadFeedIteratorCore_ReadNextAsync() { string continuation = "TBD"; ResponseMessage responseMessage = new ResponseMessage(HttpStatusCode.OK); responseMessage.Headers.ContinuationToken = continuation; responseMessage.Headers[Documents.HttpConstants.HttpHeaders.ItemCount] = "1"; responseMessage.Content = new MemoryStream(Encoding.UTF8.GetBytes("{}")); Mock<CosmosClientContext> cosmosClientContext = new Mock<CosmosClientContext>(); cosmosClientContext.Setup(c => c.ClientOptions).Returns(new CosmosClientOptions()); cosmosClientContext .Setup(c => c.ProcessResourceOperationStreamAsync( It.IsAny<string>(), It.Is<Documents.ResourceType>(rt => rt == Documents.ResourceType.Document), It.IsAny<Documents.OperationType>(), It.IsAny<RequestOptions>(), It.IsAny<ContainerInternal>(), It.IsAny<PartitionKey?>(), It.IsAny<Stream>(), It.IsAny<Action<RequestMessage>>(), It.IsAny<CosmosDiagnosticsContext>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(responseMessage)); ContainerInternal containerCore = Mock.Of<ContainerInternal>(); Mock.Get(containerCore) .Setup(c => c.ClientContext) .Returns(cosmosClientContext.Object); FeedRangeInternal range = Mock.Of<FeedRangeInternal>(); Mock.Get(range) .Setup(f => f.Accept(It.IsAny<FeedRangeRequestMessagePopulatorVisitor>())); FeedRangeContinuation feedToken = Mock.Of<FeedRangeContinuation>(); Mock.Get(feedToken) .Setup(f => f.FeedRange) .Returns(range); Mock.Get(feedToken) .Setup(f => f.HandleSplitAsync(It.Is<ContainerInternal>(c => c == containerCore), It.IsAny<ResponseMessage>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(Documents.ShouldRetryResult.NoRetry())); Mock.Get(feedToken) .Setup(f => f.GetContinuation()) .Returns(continuation); Mock.Get(feedToken) .Setup(f => f.IsDone) .Returns(true); FeedRangeIteratorCore feedTokenIterator = new FeedRangeIteratorCore(containerCore, feedToken, new QueryRequestOptions(), Documents.ResourceType.Document, queryDefinition: null); ResponseMessage response = await feedTokenIterator.ReadNextAsync(); Mock.Get(feedToken) .Verify(f => f.ReplaceContinuation(It.Is<string>(ct => ct == continuation)), Times.Once); Mock.Get(feedToken) .Verify(f => f.HandleSplitAsync(It.Is<ContainerInternal>(c => c == containerCore), It.IsAny<ResponseMessage>(), It.IsAny<CancellationToken>()), Times.Once); } [TestMethod] public async Task ReadFeedIteratorCore_ReadNextAsync_Conflicts() { string continuation = "TBD"; ResponseMessage responseMessage = new ResponseMessage(HttpStatusCode.OK); responseMessage.Headers.ContinuationToken = continuation; responseMessage.Headers[Documents.HttpConstants.HttpHeaders.ItemCount] = "1"; responseMessage.Content = new MemoryStream(Encoding.UTF8.GetBytes("{}")); Mock<CosmosClientContext> cosmosClientContext = new Mock<CosmosClientContext>(); cosmosClientContext.Setup(c => c.ClientOptions).Returns(new CosmosClientOptions()); cosmosClientContext .Setup(c => c.ProcessResourceOperationStreamAsync( It.IsAny<string>(), It.Is<Documents.ResourceType>(rt => rt == Documents.ResourceType.Conflict), It.IsAny<Documents.OperationType>(), It.IsAny<RequestOptions>(), It.IsAny<ContainerInternal>(), It.IsAny<PartitionKey?>(), It.IsAny<Stream>(), It.IsAny<Action<RequestMessage>>(), It.IsAny<CosmosDiagnosticsContext>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(responseMessage)); ContainerInternal containerCore = Mock.Of<ContainerInternal>(); Mock.Get(containerCore) .Setup(c => c.ClientContext) .Returns(cosmosClientContext.Object); FeedRangeInternal range = Mock.Of<FeedRangeInternal>(); Mock.Get(range) .Setup(f => f.Accept(It.IsAny<FeedRangeRequestMessagePopulatorVisitor>())); FeedRangeContinuation feedToken = Mock.Of<FeedRangeContinuation>(); Mock.Get(feedToken) .Setup(f => f.FeedRange) .Returns(range); Mock.Get(feedToken) .Setup(f => f.HandleSplitAsync(It.Is<ContainerInternal>(c => c == containerCore), It.IsAny<ResponseMessage>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(Documents.ShouldRetryResult.NoRetry())); Mock.Get(feedToken) .Setup(f => f.GetContinuation()) .Returns(continuation); Mock.Get(feedToken) .Setup(f => f.IsDone) .Returns(true); FeedRangeIteratorCore feedTokenIterator = new FeedRangeIteratorCore(containerCore, feedToken, new QueryRequestOptions(), Documents.ResourceType.Conflict, queryDefinition: null); ResponseMessage response = await feedTokenIterator.ReadNextAsync(); Mock.Get(feedToken) .Verify(f => f.ReplaceContinuation(It.Is<string>(ct => ct == continuation)), Times.Once); Mock.Get(feedToken) .Verify(f => f.HandleSplitAsync(It.Is<ContainerInternal>(c => c == containerCore), It.IsAny<ResponseMessage>(), It.IsAny<CancellationToken>()), Times.Once); } [TestMethod] public async Task ReadFeedIteratorCore_ReadNextAsync_Conflicts_Query() { string continuation = "TBD"; ResponseMessage responseMessage = new ResponseMessage(HttpStatusCode.OK); responseMessage.Headers.ContinuationToken = continuation; responseMessage.Headers[Documents.HttpConstants.HttpHeaders.ItemCount] = "1"; responseMessage.Content = new MemoryStream(Encoding.UTF8.GetBytes("{}")); Mock<CosmosClientContext> cosmosClientContext = new Mock<CosmosClientContext>(); cosmosClientContext.Setup(c => c.SerializerCore).Returns(new CosmosSerializerCore()); cosmosClientContext.Setup(c => c.ClientOptions).Returns(new CosmosClientOptions()); cosmosClientContext .Setup(c => c.ProcessResourceOperationStreamAsync( It.IsAny<string>(), It.Is<Documents.ResourceType>(rt => rt == Documents.ResourceType.Conflict), It.Is<Documents.OperationType>(ot => ot == Documents.OperationType.Query), It.IsAny<RequestOptions>(), It.IsAny<ContainerInternal>(), It.IsAny<PartitionKey?>(), It.Is<Stream>(stream => stream != null), It.IsAny<Action<RequestMessage>>(), It.IsAny<CosmosDiagnosticsContext>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(responseMessage)); ContainerInternal containerCore = Mock.Of<ContainerInternal>(); Mock.Get(containerCore) .Setup(c => c.ClientContext) .Returns(cosmosClientContext.Object); FeedRangeInternal range = Mock.Of<FeedRangeInternal>(); Mock.Get(range) .Setup(f => f.Accept(It.IsAny<FeedRangeRequestMessagePopulatorVisitor>())); FeedRangeContinuation feedToken = Mock.Of<FeedRangeContinuation>(); Mock.Get(feedToken) .Setup(f => f.FeedRange) .Returns(range); Mock.Get(feedToken) .Setup(f => f.HandleSplitAsync(It.Is<ContainerInternal>(c => c == containerCore), It.IsAny<ResponseMessage>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(Documents.ShouldRetryResult.NoRetry())); Mock.Get(feedToken) .Setup(f => f.GetContinuation()) .Returns(continuation); Mock.Get(feedToken) .Setup(f => f.IsDone) .Returns(true); FeedRangeIteratorCore feedTokenIterator = new FeedRangeIteratorCore(containerCore, feedToken, new QueryRequestOptions(), Documents.ResourceType.Conflict, queryDefinition: new QueryDefinition("select * from c")); ResponseMessage response = await feedTokenIterator.ReadNextAsync(); Mock.Get(feedToken) .Verify(f => f.ReplaceContinuation(It.Is<string>(ct => ct == continuation)), Times.Once); Mock.Get(feedToken) .Verify(f => f.HandleSplitAsync(It.Is<ContainerInternal>(c => c == containerCore), It.IsAny<ResponseMessage>(), It.IsAny<CancellationToken>()), Times.Once); } [TestMethod] public async Task ReadFeedIteratorCore_OfT_ReadNextAsync() { string continuation = "TBD"; ResponseMessage responseMessage = new ResponseMessage(HttpStatusCode.OK); responseMessage.Headers.ContinuationToken = continuation; responseMessage.Headers[Documents.HttpConstants.HttpHeaders.ItemCount] = "1"; responseMessage.Content = new MemoryStream(Encoding.UTF8.GetBytes("{}")); Mock<CosmosClientContext> cosmosClientContext = new Mock<CosmosClientContext>(); cosmosClientContext.Setup(c => c.ClientOptions).Returns(new CosmosClientOptions()); cosmosClientContext .Setup(c => c.ProcessResourceOperationStreamAsync( It.IsAny<string>(), It.Is<Documents.ResourceType>(rt => rt == Documents.ResourceType.Document), It.IsAny<Documents.OperationType>(), It.IsAny<RequestOptions>(), It.IsAny<ContainerInternal>(), It.IsAny<PartitionKey?>(), It.IsAny<Stream>(), It.IsAny<Action<RequestMessage>>(), It.IsAny<CosmosDiagnosticsContext>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(responseMessage)); ContainerInternal containerCore = Mock.Of<ContainerInternal>(); Mock.Get(containerCore) .Setup(c => c.ClientContext) .Returns(cosmosClientContext.Object); FeedRangeInternal range = Mock.Of<FeedRangeInternal>(); Mock.Get(range) .Setup(f => f.Accept(It.IsAny<FeedRangeRequestMessagePopulatorVisitor>())); FeedRangeContinuation feedToken = Mock.Of<FeedRangeContinuation>(); Mock.Get(feedToken) .Setup(f => f.FeedRange) .Returns(range); Mock.Get(feedToken) .Setup(f => f.HandleSplitAsync(It.Is<ContainerInternal>(c => c == containerCore), It.IsAny<ResponseMessage>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(Documents.ShouldRetryResult.NoRetry())); Mock.Get(feedToken) .Setup(f => f.GetContinuation()) .Returns(continuation); Mock.Get(feedToken) .Setup(f => f.IsDone) .Returns(true); FeedRangeIteratorCore feedTokenIterator = new FeedRangeIteratorCore(containerCore, feedToken, new QueryRequestOptions(), Documents.ResourceType.Document, queryDefinition: null); bool creatorCalled = false; Func<ResponseMessage, FeedResponse<dynamic>> creator = (ResponseMessage r) => { creatorCalled = true; return Mock.Of<FeedResponse<dynamic>>(); }; FeedIteratorCore<dynamic> feedTokenIteratorOfT = new FeedIteratorCore<dynamic>(feedTokenIterator, creator); FeedResponse<dynamic> response = await feedTokenIteratorOfT.ReadNextAsync(); Assert.IsTrue(creatorCalled, "Response creator not called"); Mock.Get(feedToken) .Verify(f => f.ReplaceContinuation(It.Is<string>(ct => ct == continuation)), Times.Once); Mock.Get(feedToken) .Verify(f => f.HandleSplitAsync(It.Is<ContainerInternal>(c => c == containerCore), It.IsAny<ResponseMessage>(), It.IsAny<CancellationToken>()), Times.Once); } [TestMethod] public async Task ReadFeedIteratorCore_UpdatesContinuation_OnOK() { string continuation = "TBD"; ResponseMessage responseMessage = new ResponseMessage(HttpStatusCode.OK); responseMessage.Headers.ContinuationToken = continuation; responseMessage.Headers[Documents.HttpConstants.HttpHeaders.ItemCount] = "1"; responseMessage.Content = new MemoryStream(Encoding.UTF8.GetBytes("{}")); Mock<CosmosClientContext> cosmosClientContext = new Mock<CosmosClientContext>(); cosmosClientContext.Setup(c => c.ClientOptions).Returns(new CosmosClientOptions()); cosmosClientContext .Setup(c => c.ProcessResourceOperationStreamAsync( It.IsAny<string>(), It.Is<Documents.ResourceType>(rt => rt == Documents.ResourceType.Document), It.IsAny<Documents.OperationType>(), It.IsAny<RequestOptions>(), It.IsAny<ContainerInternal>(), It.IsAny<PartitionKey?>(), It.IsAny<Stream>(), It.IsAny<Action<RequestMessage>>(), It.IsAny<CosmosDiagnosticsContext>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(responseMessage)); ContainerInternal containerCore = Mock.Of<ContainerInternal>(); Mock.Get(containerCore) .Setup(c => c.ClientContext) .Returns(cosmosClientContext.Object); FeedRangeInternal range = Mock.Of<FeedRangeInternal>(); Mock.Get(range) .Setup(f => f.Accept(It.IsAny<FeedRangeRequestMessagePopulatorVisitor>())); FeedRangeContinuation feedToken = Mock.Of<FeedRangeContinuation>(); Mock.Get(feedToken) .Setup(f => f.FeedRange) .Returns(range); Mock.Get(feedToken) .Setup(f => f.HandleSplitAsync(It.Is<ContainerInternal>(c => c == containerCore), It.IsAny<ResponseMessage>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(Documents.ShouldRetryResult.NoRetry())); Mock.Get(feedToken) .Setup(f => f.GetContinuation()) .Returns(continuation); Mock.Get(feedToken) .Setup(f => f.IsDone) .Returns(true); FeedRangeIteratorCore feedTokenIterator = new FeedRangeIteratorCore(containerCore, feedToken, new QueryRequestOptions(), Documents.ResourceType.Document, queryDefinition: null); ResponseMessage response = await feedTokenIterator.ReadNextAsync(); Mock.Get(feedToken) .Verify(f => f.ReplaceContinuation(It.Is<string>(ct => ct == continuation)), Times.Once); Mock.Get(feedToken) .Verify(f => f.HandleSplitAsync(It.Is<ContainerInternal>(c => c == containerCore), It.IsAny<ResponseMessage>(), It.IsAny<CancellationToken>()), Times.Once); } [TestMethod] public async Task ReadFeedIteratorCore_DoesNotUpdateContinuation_OnError() { string continuation = "TBD"; ResponseMessage responseMessage = new ResponseMessage(HttpStatusCode.Gone); responseMessage.Headers.ContinuationToken = continuation; responseMessage.Headers[Documents.HttpConstants.HttpHeaders.ItemCount] = "1"; responseMessage.Content = new MemoryStream(Encoding.UTF8.GetBytes("{}")); Mock<CosmosClientContext> cosmosClientContext = new Mock<CosmosClientContext>(); cosmosClientContext.Setup(c => c.ClientOptions).Returns(new CosmosClientOptions()); cosmosClientContext .Setup(c => c.ProcessResourceOperationStreamAsync( It.IsAny<string>(), It.Is<Documents.ResourceType>(rt => rt == Documents.ResourceType.Document), It.IsAny<Documents.OperationType>(), It.IsAny<RequestOptions>(), It.IsAny<ContainerInternal>(), It.IsAny<PartitionKey?>(), It.IsAny<Stream>(), It.IsAny<Action<RequestMessage>>(), It.IsAny<CosmosDiagnosticsContext>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(responseMessage)); ContainerInternal containerCore = Mock.Of<ContainerInternal>(); Mock.Get(containerCore) .Setup(c => c.ClientContext) .Returns(cosmosClientContext.Object); FeedRangeInternal range = Mock.Of<FeedRangeInternal>(); Mock.Get(range) .Setup(f => f.Accept(It.IsAny<FeedRangeRequestMessagePopulatorVisitor>())); FeedRangeContinuation feedToken = Mock.Of<FeedRangeContinuation>(); Mock.Get(feedToken) .Setup(f => f.FeedRange) .Returns(range); Mock.Get(feedToken) .Setup(f => f.HandleSplitAsync(It.Is<ContainerInternal>(c => c == containerCore), It.IsAny<ResponseMessage>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(Documents.ShouldRetryResult.NoRetry())); Mock.Get(feedToken) .Setup(f => f.GetContinuation()) .Returns(continuation); Mock.Get(feedToken) .Setup(f => f.IsDone) .Returns(true); FeedRangeIteratorCore feedTokenIterator = new FeedRangeIteratorCore(containerCore, feedToken, new QueryRequestOptions(), Documents.ResourceType.Document, queryDefinition: null); ResponseMessage response = await feedTokenIterator.ReadNextAsync(); Mock.Get(feedToken) .Verify(f => f.ReplaceContinuation(It.Is<string>(ct => ct == continuation)), Times.Never); Mock.Get(feedToken) .Verify(f => f.HandleSplitAsync(It.Is<ContainerInternal>(c => c == containerCore), It.IsAny<ResponseMessage>(), It.IsAny<CancellationToken>()), Times.Once); Mock.Get(feedToken) .Verify(f => f.IsDone, Times.Never); } [TestMethod] public async Task ReadFeedIteratorCore_WithNoInitialState_ReadNextAsync() { string continuation = "TBD"; ResponseMessage responseMessage = new ResponseMessage(HttpStatusCode.OK); responseMessage.Headers.ContinuationToken = continuation; responseMessage.Headers[Documents.HttpConstants.HttpHeaders.ItemCount] = "1"; responseMessage.Content = new MemoryStream(Encoding.UTF8.GetBytes("{}")); MultiRangeMockDocumentClient documentClient = new MultiRangeMockDocumentClient(); Mock<CosmosClientContext> cosmosClientContext = new Mock<CosmosClientContext>(); cosmosClientContext.Setup(c => c.ClientOptions).Returns(new CosmosClientOptions()); cosmosClientContext.Setup(c => c.DocumentClient).Returns(documentClient); cosmosClientContext .Setup(c => c.ProcessResourceOperationStreamAsync( It.IsAny<string>(), It.Is<Documents.ResourceType>(rt => rt == Documents.ResourceType.Document), It.IsAny<Documents.OperationType>(), It.IsAny<RequestOptions>(), It.IsAny<ContainerInternal>(), It.IsAny<PartitionKey?>(), It.IsAny<Stream>(), It.IsAny<Action<RequestMessage>>(), It.IsAny<CosmosDiagnosticsContext>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(responseMessage)); ContainerInternal containerCore = Mock.Of<ContainerInternal>(); Mock.Get(containerCore) .Setup(c => c.ClientContext) .Returns(cosmosClientContext.Object); Mock.Get(containerCore) .Setup(c => c.GetRIDAsync(It.IsAny<CancellationToken>())) .ReturnsAsync(Guid.NewGuid().ToString()); FeedRangeIteratorCore feedTokenIterator = FeedRangeIteratorCore.Create(containerCore, null, null, new QueryRequestOptions()); ResponseMessage response = await feedTokenIterator.ReadNextAsync(); Assert.IsTrue(FeedRangeContinuation.TryParse(response.ContinuationToken, out FeedRangeContinuation parsedToken)); FeedRangeCompositeContinuation feedRangeCompositeContinuation = parsedToken as FeedRangeCompositeContinuation; FeedRangeEpk feedTokenEPKRange = feedRangeCompositeContinuation.FeedRange as FeedRangeEpk; // Assert that a FeedToken for the entire range is used Assert.AreEqual(Documents.Routing.PartitionKeyInternal.MinimumInclusiveEffectivePartitionKey, feedTokenEPKRange.Range.Min); Assert.AreEqual(Documents.Routing.PartitionKeyInternal.MaximumExclusiveEffectivePartitionKey, feedTokenEPKRange.Range.Max); Assert.AreEqual(continuation, feedRangeCompositeContinuation.CompositeContinuationTokens.Peek().Token); Assert.IsFalse(feedRangeCompositeContinuation.IsDone); } [TestMethod] public async Task ReadFeedIteratorCore_HandlesSplitsThroughPipeline() { int executionCount = 0; CosmosClientContext cosmosClientContext = GetMockedClientContext((RequestMessage requestMessage, CancellationToken cancellationToken) => { // Force OnBeforeRequestActions call requestMessage.ToDocumentServiceRequest(); if (executionCount++ == 0) { return TestHandler.ReturnStatusCode(HttpStatusCode.Gone, Documents.SubStatusCodes.PartitionKeyRangeGone); } return TestHandler.ReturnStatusCode(HttpStatusCode.OK); }); ContainerInternal containerCore = Mock.Of<ContainerInternal>(); Mock.Get(containerCore) .Setup(c => c.ClientContext) .Returns(cosmosClientContext); Mock.Get(containerCore) .Setup(c => c.LinkUri) .Returns("/dbs/db/colls/colls"); FeedRangeInternal range = Mock.Of<FeedRangeInternal>(); Mock.Get(range) .Setup(f => f.Accept(It.IsAny<FeedRangeRequestMessagePopulatorVisitor>())); FeedRangeContinuation feedToken = Mock.Of<FeedRangeContinuation>(); Mock.Get(feedToken) .Setup(f => f.FeedRange) .Returns(range); Mock.Get(feedToken) .Setup(f => f.HandleSplitAsync(It.Is<ContainerInternal>(c => c == containerCore), It.IsAny<ResponseMessage>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(Documents.ShouldRetryResult.NoRetry())); FeedRangeIteratorCore changeFeedIteratorCore = new FeedRangeIteratorCore(containerCore, feedToken, new QueryRequestOptions(), Documents.ResourceType.Document, queryDefinition: null); ResponseMessage response = await changeFeedIteratorCore.ReadNextAsync(); Assert.AreEqual(1, executionCount, "Pipeline handled the Split"); Assert.AreEqual(HttpStatusCode.Gone, response.StatusCode); } private static CosmosClientContext GetMockedClientContext( Func<RequestMessage, CancellationToken, Task<ResponseMessage>> handlerFunc) { CosmosClient client = MockCosmosUtil.CreateMockCosmosClient(); CosmosClientContext clientContext = ClientContextCore.Create( client, new MockDocumentClient(), new CosmosClientOptions()); Mock<PartitionRoutingHelper> partitionRoutingHelperMock = MockCosmosUtil.GetPartitionRoutingHelperMock("0"); TestHandler testHandler = new TestHandler(handlerFunc); // Similar to FeedPipeline but with replaced transport RequestHandler[] feedPipeline = new RequestHandler[] { new NamedCacheRetryHandler(), new PartitionKeyRangeHandler(client), testHandler, }; RequestHandler feedHandler = ClientPipelineBuilder.CreatePipeline(feedPipeline); RequestHandler handler = clientContext.RequestHandler.InnerHandler; while (handler != null) { if (handler.InnerHandler is RouterHandler) { handler.InnerHandler = new RouterHandler(feedHandler, testHandler); break; } handler = handler.InnerHandler; } return clientContext; } private class MultiRangeMockDocumentClient : MockDocumentClient { private List<Documents.PartitionKeyRange> availablePartitionKeyRanges = new List<Documents.PartitionKeyRange>() { new Documents.PartitionKeyRange() { MinInclusive = Documents.Routing.PartitionKeyInternal.MinimumInclusiveEffectivePartitionKey, MaxExclusive = Documents.Routing.PartitionKeyInternal.MaximumExclusiveEffectivePartitionKey, Id = "0" } }; internal override IReadOnlyList<Documents.PartitionKeyRange> ResolveOverlapingPartitionKeyRanges(string collectionRid, Documents.Routing.Range<string> range, bool forceRefresh) { return this.availablePartitionKeyRanges; } } } }
53.783451
248
0.625029
[ "MIT" ]
Liphi/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/FeedRange/ReadFeedTokenIteratorCoreTests.cs
30,551
C#
using CSharpMath.FrontEnd; using TFont = CSharpMath.Apple.AppleMathFont; using TGlyph = System.UInt16; using System.Globalization; using System.Collections.Generic; using System.Linq; using System; using CoreText; namespace CSharpMath.Apple { public class CtFontGlyphFinder : IGlyphFinder<TFont, TGlyph> { private CtFontGlyphFinder() { } public static CtFontGlyphFinder Instance { get; } = new CtFontGlyphFinder(); private IEnumerable<TGlyph> ToUintEnumerable(byte[] bytes) { for (int i = 0; i < bytes.Length; i += 2) { if (i == bytes.Length - 1) { yield return bytes[i]; } else { yield return BitConverter.ToUInt16(bytes, i); } } } public TGlyph[] ToUintArray(byte[] bytes) { return ToUintEnumerable(bytes).ToArray(); } public byte[] ToByteArray(TGlyph[] glyphs) { byte[] r = new byte[glyphs.Length * 2]; for (int i = 0; i < glyphs.Length; i++) { byte[] localBytes = BitConverter.GetBytes(glyphs[i]); r[2 * i] = localBytes[0]; r[1 + 2 * i] = localBytes[1]; } return r; } public IEnumerable<ushort> FindGlyphs(TFont font, string str) { // not completely sure this is correct. Need an actual // example of a composed character sequence coming from LaTeX. var unicodeIndexes = StringInfo.ParseCombiningCharacters(str); foreach (var index in unicodeIndexes) { yield return FindGlyphForCharacterAtIndex(font, index, str); } } public bool GlyphIsEmpty(TGlyph glyph) => glyph == 0; public TGlyph EmptyGlyph => 0; public TGlyph FindGlyphForCharacterAtIndex(TFont font, int index, string str) { var unicodeIndices = StringInfo.ParseCombiningCharacters(str); int start = 0; int end = str.Length; foreach (var unicodeIndex in unicodeIndices) { if (unicodeIndex <= index) { start = unicodeIndex; } else { end = unicodeIndex; break; } } int length = end - start; TGlyph[] glyphs = new TGlyph[length]; char[] chars = str.Substring(start, length).ToCharArray(); font.CtFont.GetGlyphsForCharacters(chars, glyphs, length); return glyphs[0]; } } }
29.868421
83
0.631718
[ "MIT" ]
hflexgrig/CSharpMath
CSharpMath.Apple/Font/CtFontGlyphFinder.cs
2,270
C#