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.IO; using System.Text.RegularExpressions; using StbImageSharp; using TriLibCore.Extensions; using TriLibCore.General; using TriLibCore.Interfaces; using TriLibCore.Mappers; using TriLibCore.Utils; using UnityEngine; using FileMode = System.IO.FileMode; using HumanDescription = UnityEngine.HumanDescription; using Object = UnityEngine.Object; #if TRILIB_DRACO using TriLibCore.Gltf.Draco; #endif #if UNITY_EDITOR using UnityEditor; #endif namespace TriLibCore { /// <summary>Represents the main class containing methods to load the Models.</summary> public static class AssetLoader { /// <summary>Loads a Model from the given path asynchronously.</summary> /// <param name="path">The Model file path.</param> /// <param name="onLoad">The Method to call on the Main Thread when the Model Meshes and hierarchy are loaded.</param> /// <param name="onMaterialsLoad">The Method to call on the Main Thread when the Model (including Textures and Materials) has been fully loaded.</param> /// <param name="onProgress">The Method to call when the Model loading progress changes.</param> /// <param name="onError">The Method to call on the Main Thread when any error occurs.</param> /// <param name="wrapperGameObject">The Game Object that will be the parent of the loaded Game Object. Can be null.</param> /// <param name="assetLoaderOptions">The Asset Loader Options reference. Asset Loader Options contains various options used during the Model loading process.</param> /// <param name="customContextData">The Custom Data that will be passed along the AssetLoaderContext.</param> /// <returns>The Asset Loader Context, containing Model loading information and the output Game Object.</returns> public static AssetLoaderContext LoadModelFromFile(string path, Action<AssetLoaderContext> onLoad, Action<AssetLoaderContext> onMaterialsLoad, Action<AssetLoaderContext, float> onProgress, Action<IContextualizedError> onError = null, GameObject wrapperGameObject = null, AssetLoaderOptions assetLoaderOptions = null, object customContextData = null) { #if UNITY_WEBGL || UNITY_UWP AssetLoaderContext assetLoaderContext = null; try { assetLoaderContext = LoadModelFromFileNoThread(path, onError, wrapperGameObject, assetLoaderOptions, customContextData); onLoad(assetLoaderContext); onMaterialsLoad(assetLoaderContext); } catch (Exception exception) { if (exception is IContextualizedError contextualizedError) { HandleError(contextualizedError); } else { HandleError(new ContextualizedError<AssetLoaderContext>(exception, null)); } } return assetLoaderContext; #else var assetLoaderContext = new AssetLoaderContext { Options = assetLoaderOptions ? assetLoaderOptions : CreateDefaultLoaderOptions(), Filename = path, BasePath = FileUtils.GetFileDirectory(path), WrapperGameObject = wrapperGameObject, OnMaterialsLoad = onMaterialsLoad, OnLoad = onLoad, OnProgress = onProgress, HandleError = HandleError, OnError = onError, CustomData = customContextData, }; assetLoaderContext.Tasks.Add(ThreadUtils.RunThread(assetLoaderContext, ref assetLoaderContext.CancellationToken, LoadModel, ProcessRootModel, HandleError, assetLoaderContext.Options != null ? assetLoaderContext.Options.Timeout : 0)); return assetLoaderContext; #endif } /// <summary>Loads a Model from the given Stream asynchronously.</summary> /// <param name="stream">The Stream containing the Model data.</param> /// <param name="filename">The Model filename.</param> /// <param name="fileExtension">The Model file extension. (Eg.: fbx)</param> /// <param name="onLoad">The Method to call on the Main Thread when the Model Meshes and hierarchy are loaded.</param> /// <param name="onMaterialsLoad">The Method to call on the Main Thread when the Model (including Textures and Materials) has been fully loaded.</param> /// <param name="onProgress">The Method to call when the Model loading progress changes.</param> /// <param name="onError">The Method to call on the Main Thread when any error occurs.</param> /// <param name="wrapperGameObject">The Game Object that will be the parent of the loaded Game Object. Can be null.</param> /// <param name="assetLoaderOptions">The Asset Loader Options reference. Asset Loader Options contains various options used during the Model loading process.</param> /// <param name="customContextData">The Custom Data that will be passed along the AssetLoaderContext.</param> /// <returns>The Asset Loader Context, containing Model loading information and the output Game Object.</returns> public static AssetLoaderContext LoadModelFromStream(Stream stream, string filename = null, string fileExtension = null, Action<AssetLoaderContext> onLoad = null, Action<AssetLoaderContext> onMaterialsLoad = null, Action<AssetLoaderContext, float> onProgress = null, Action<IContextualizedError> onError = null, GameObject wrapperGameObject = null, AssetLoaderOptions assetLoaderOptions = null, object customContextData = null) { #if UNITY_WEBGL || UNITY_UWP AssetLoaderContext assetLoaderContext = null; try { assetLoaderContext = LoadModelFromStreamNoThread(stream, filename, fileExtension, onError, wrapperGameObject, assetLoaderOptions, customContextData); onLoad(assetLoaderContext); onMaterialsLoad(assetLoaderContext); } catch (Exception exception) { if (exception is IContextualizedError contextualizedError) { HandleError(contextualizedError); } else { HandleError(new ContextualizedError<AssetLoaderContext>(exception, null)); } } return assetLoaderContext; #else var assetLoaderContext = new AssetLoaderContext { Options = assetLoaderOptions == null ? CreateDefaultLoaderOptions() : assetLoaderOptions, Stream = stream, FileExtension = fileExtension ?? FileUtils.GetFileExtension(filename, false), BasePath = FileUtils.GetFileDirectory(filename), WrapperGameObject = wrapperGameObject, OnMaterialsLoad = onMaterialsLoad, OnLoad = onLoad, HandleError = HandleError, OnError = onError, CustomData = customContextData }; assetLoaderContext.Tasks.Add(ThreadUtils.RunThread(assetLoaderContext, ref assetLoaderContext.CancellationToken, LoadModel, ProcessRootModel, HandleError, assetLoaderContext.Options.Timeout)); return assetLoaderContext; #endif } /// <summary>Loads a Model from the given path synchronously.</summary> /// <param name="path">The Model file path.</param> /// <param name="onError">The Method to call on the Main Thread when any error occurs.</param> /// <param name="wrapperGameObject">The Game Object that will be the parent of the loaded Game Object. Can be null.</param> /// <param name="assetLoaderOptions">The Asset Loader Options reference. Asset Loader Options contains various options used during the Model loading process.</param> /// <param name="customContextData">The Custom Data that will be passed along the AssetLoaderContext.</param> /// <returns>The Asset Loader Context, containing Model loading information and the output Game Object.</returns> public static AssetLoaderContext LoadModelFromFileNoThread(string path, Action<IContextualizedError> onError = null, GameObject wrapperGameObject = null, AssetLoaderOptions assetLoaderOptions = null, object customContextData = null) { var assetLoaderContext = new AssetLoaderContext { Options = assetLoaderOptions == null ? CreateDefaultLoaderOptions() : assetLoaderOptions, Filename = path, BasePath = FileUtils.GetFileDirectory(path), CustomData = customContextData, HandleError = HandleError, OnError = onError, WrapperGameObject = wrapperGameObject, Async = false }; try { LoadModel(assetLoaderContext); ProcessRootModel(assetLoaderContext); } catch (Exception exception) { HandleError(new ContextualizedError<AssetLoaderContext>(exception, assetLoaderContext)); } return assetLoaderContext; } /// <summary>Loads a Model from the given Stream synchronously.</summary> /// <param name="stream">The Stream containing the Model data.</param> /// <param name="filename">The Model filename.</param> /// <param name="fileExtension">The Model file extension. (Eg.: fbx)</param> /// <param name="onError">The Method to call on the Main Thread when any error occurs.</param> /// <param name="wrapperGameObject">The Game Object that will be the parent of the loaded Game Object. Can be null.</param> /// <param name="assetLoaderOptions">The Asset Loader Options reference. Asset Loader Options contains various options used during the Model loading process.</param> /// <param name="customContextData">The Custom Data that will be passed along the AssetLoaderContext.</param> /// <returns>The Asset Loader Context, containing Model loading information and the output Game Object.</returns> public static AssetLoaderContext LoadModelFromStreamNoThread(Stream stream, string filename = null, string fileExtension = null, Action<IContextualizedError> onError = null, GameObject wrapperGameObject = null, AssetLoaderOptions assetLoaderOptions = null, object customContextData = null) { var assetLoaderContext = new AssetLoaderContext { Options = assetLoaderOptions ? assetLoaderOptions : CreateDefaultLoaderOptions(), Stream = stream, FileExtension = fileExtension ?? FileUtils.GetFileExtension(filename, false), BasePath = FileUtils.GetFileDirectory(filename), CustomData = customContextData, HandleError = HandleError, OnError = onError, WrapperGameObject = wrapperGameObject, Async = false }; try { LoadModel(assetLoaderContext); ProcessRootModel(assetLoaderContext); } catch (Exception exception) { HandleError(new ContextualizedError<AssetLoaderContext>(exception, assetLoaderContext)); } return assetLoaderContext; } #if UNITY_EDITOR private static Object LoadOrCreateScriptableObject(string type, string subFolder) { string mappersFilePath; var triLibMapperAssets = AssetDatabase.FindAssets("TriLibMappersPlaceholder"); if (triLibMapperAssets.Length > 0) { mappersFilePath = AssetDatabase.GUIDToAssetPath(triLibMapperAssets[0]); } else { throw new Exception("Could not find \"TriLibMappersPlaceholder\" file. Please re-import TriLib package."); } var mappersDirectory = $"{FileUtils.GetFileDirectory(mappersFilePath)}"; var assetDirectory = $"{mappersDirectory}/{subFolder}"; if (!AssetDatabase.IsValidFolder(assetDirectory)) { AssetDatabase.CreateFolder(mappersDirectory, subFolder); } var assetPath = $"{assetDirectory}/{type}.asset"; var scriptableObject = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Object)); if (scriptableObject == null) { scriptableObject = ScriptableObject.CreateInstance(type); AssetDatabase.CreateAsset(scriptableObject, assetPath); } return scriptableObject; } #endif /// <summary>Creates an Asset Loader Options with the default options and Mappers using an existing pre-allocations List.</summary> /// <param name="generateAssets">Indicates whether created Scriptable Objects will be saved as assets.</param> /// <returns>The Asset Loader Options containing the default settings.</returns> public static AssetLoaderOptions CreateDefaultLoaderOptions(bool generateAssets = false) { var assetLoaderOptions = ScriptableObject.CreateInstance<AssetLoaderOptions>(); ByNameRootBoneMapper byNameRootBoneMapper; #if UNITY_EDITOR if (generateAssets) { byNameRootBoneMapper = (ByNameRootBoneMapper)LoadOrCreateScriptableObject("ByNameRootBoneMapper", "RootBone"); } else { byNameRootBoneMapper = ScriptableObject.CreateInstance<ByNameRootBoneMapper>(); } #else byNameRootBoneMapper = ScriptableObject.CreateInstance<ByNameRootBoneMapper>(); #endif byNameRootBoneMapper.name = "ByNameRootBoneMapper"; assetLoaderOptions.RootBoneMapper = byNameRootBoneMapper; if (MaterialMapper.RegisteredMappers.Count == 0) { Debug.LogWarning("Please add at least one MaterialMapper name to the MaterialMapper.RegisteredMappers static field to create the right MaterialMapper for the Render Pipeline you are using."); } else { var materialMappers = new List<MaterialMapper>(); foreach (var materialMapperName in MaterialMapper.RegisteredMappers) { if (materialMapperName == null) { continue; } MaterialMapper materialMapper; #if UNITY_EDITOR if (generateAssets) { materialMapper = (MaterialMapper)LoadOrCreateScriptableObject(materialMapperName, "Material"); } else { materialMapper = (MaterialMapper)ScriptableObject.CreateInstance(materialMapperName); } #else materialMapper = ScriptableObject.CreateInstance(materialMapperName) as MaterialMapper; #endif if (materialMapper != null) { materialMapper.name = materialMapperName; if (materialMapper.IsCompatible(null)) { materialMappers.Add(materialMapper); assetLoaderOptions.FixedAllocations.Add(materialMapper); } else { #if UNITY_EDITOR var assetPath = AssetDatabase.GetAssetPath(materialMapper); if (assetPath == null) { Object.DestroyImmediate(materialMapper); } #else Object.Destroy(materialMapper); #endif } } } if (materialMappers.Count == 0) { Debug.LogWarning("TriLib could not find any suitable MaterialMapper on the project."); } else { assetLoaderOptions.MaterialMappers = materialMappers.ToArray(); } } //These two animation clip mappers are used to convert legacy to humanoid animations and add a simple generic animation playback component to the model, which will be disabled by default. LegacyToHumanoidAnimationClipMapper legacyToHumanoidAnimationClipMapper; SimpleAnimationPlayerAnimationClipMapper simpleAnimationPlayerAnimationClipMapper; #if UNITY_EDITOR if (generateAssets) { legacyToHumanoidAnimationClipMapper = (LegacyToHumanoidAnimationClipMapper)LoadOrCreateScriptableObject("LegacyToHumanoidAnimationClipMapper", "AnimationClip"); simpleAnimationPlayerAnimationClipMapper = (SimpleAnimationPlayerAnimationClipMapper)LoadOrCreateScriptableObject("SimpleAnimationPlayerAnimationClipMapper", "AnimationClip"); } else { legacyToHumanoidAnimationClipMapper = ScriptableObject.CreateInstance<LegacyToHumanoidAnimationClipMapper>(); simpleAnimationPlayerAnimationClipMapper = ScriptableObject.CreateInstance<SimpleAnimationPlayerAnimationClipMapper>(); } #else legacyToHumanoidAnimationClipMapper = ScriptableObject.CreateInstance<LegacyToHumanoidAnimationClipMapper>(); simpleAnimationPlayerAnimationClipMapper = ScriptableObject.CreateInstance<SimpleAnimationPlayerAnimationClipMapper>(); #endif legacyToHumanoidAnimationClipMapper.name = "LegacyToHumanoidAnimationClipMapper"; simpleAnimationPlayerAnimationClipMapper.name = "SimpleAnimationPlayerAnimationClipMapper"; assetLoaderOptions.AnimationClipMappers = new AnimationClipMapper[] { legacyToHumanoidAnimationClipMapper, simpleAnimationPlayerAnimationClipMapper }; assetLoaderOptions.FixedAllocations.Add(assetLoaderOptions); assetLoaderOptions.FixedAllocations.Add(legacyToHumanoidAnimationClipMapper); assetLoaderOptions.FixedAllocations.Add(simpleAnimationPlayerAnimationClipMapper); return assetLoaderOptions; } /// <summary>Processes the Model from the given context and begin to build the Game Objects.</summary> /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param> private static void ProcessModel(AssetLoaderContext assetLoaderContext) { if (assetLoaderContext.RootModel != null) { ParseModel(assetLoaderContext, assetLoaderContext.WrapperGameObject != null ? assetLoaderContext.WrapperGameObject.transform : null, assetLoaderContext.RootModel, out assetLoaderContext.RootGameObject); assetLoaderContext.RootGameObject.transform.localScale = Vector3.one; if (assetLoaderContext.Options.AnimationType != AnimationType.None || assetLoaderContext.Options.ImportBlendShapes) { SetupRootBone(assetLoaderContext); SetupModelBones(assetLoaderContext, assetLoaderContext.RootModel); SetupModelLod(assetLoaderContext, assetLoaderContext.RootModel); BuildGameObjectsPaths(assetLoaderContext); SetupRig(assetLoaderContext); } if (assetLoaderContext.Options.Static) { assetLoaderContext.RootGameObject.isStatic = true; } } assetLoaderContext.OnLoad?.Invoke(assetLoaderContext); assetLoaderContext.ModelsProcessed = true; } /// <summary>Configures the context Model LODs (levels-of-detail) if there are any.</summary> /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param> /// <param name="model">The Model containing the LOD data.</param> private static void SetupModelLod(AssetLoaderContext assetLoaderContext, IModel model) { if (model.Children != null && model.Children.Count > 0) { var lodModels = new Dictionary<int, Renderer[]>(model.Children.Count); var minLod = int.MaxValue; var maxLod = 0; foreach (var child in model.Children) { var match = Regex.Match(child.Name, "_LOD(?<number>[0-9]+)|LOD_(?<number>[0-9]+)"); if (match.Success) { var lodNumber = Convert.ToInt32(match.Groups["number"].Value); if (lodModels.ContainsKey(lodNumber)) { continue; } minLod = Mathf.Min(lodNumber, minLod); maxLod = Mathf.Max(lodNumber, maxLod); lodModels.Add(lodNumber, assetLoaderContext.GameObjects[child].GetComponentsInChildren<Renderer>()); } } if (lodModels.Count > 1) { var newGameObject = assetLoaderContext.GameObjects[model]; var lods = new LOD[lodModels.Count + 1]; var lodGroup = newGameObject.AddComponent<LODGroup>(); var index = 0; var lastPosition = 1f; for (var i = minLod; i <= maxLod; i++) { if (lodModels.TryGetValue(i, out var renderers)) { lods[index++] = new LOD(lastPosition, renderers); lastPosition *= 0.5f; } } lods[index] = new LOD(lastPosition, null); lodGroup.SetLODs(lods); } } } /// <summary>Tries to find the Context Model root-bone.</summary> /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param> private static void SetupRootBone(AssetLoaderContext assetLoaderContext) { var bones = new List<Transform>(assetLoaderContext.Models.Count); assetLoaderContext.RootModel.GetBones(assetLoaderContext, bones); assetLoaderContext.BoneTransforms = bones.ToArray(); if (assetLoaderContext.Options.RootBoneMapper != null) { assetLoaderContext.RootBone = assetLoaderContext.Options.RootBoneMapper.Map(assetLoaderContext); } } /// <summary>Builds the Game Object Converts hierarchy paths.</summary> /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param> private static void BuildGameObjectsPaths(AssetLoaderContext assetLoaderContext) { foreach (var gameObject in assetLoaderContext.GameObjects.Values) { assetLoaderContext.GameObjectPaths.Add(gameObject, gameObject.transform.BuildPath(assetLoaderContext.RootGameObject.transform)); } } /// <summary>Configures the context Model rigging if there is any.</summary> /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param> private static void SetupRig(AssetLoaderContext assetLoaderContext) { var animations = assetLoaderContext.RootModel.AllAnimations; AnimationClip[] animationClips = null; switch (assetLoaderContext.Options.AnimationType) { case AnimationType.Legacy: { if (animations != null) { animationClips = new AnimationClip[animations.Count]; var unityAnimation = assetLoaderContext.RootGameObject.AddComponent<Animation>(); for (var i = 0; i < animations.Count; i++) { var triLibAnimation = animations[i]; var animationClip = ParseAnimation(assetLoaderContext, triLibAnimation); unityAnimation.AddClip(animationClip, animationClip.name); unityAnimation.clip = animationClip; unityAnimation.wrapMode = assetLoaderContext.Options.AnimationWrapMode; animationClips[i] = animationClip; } } break; } case AnimationType.Generic: { var animator = assetLoaderContext.RootGameObject.AddComponent<Animator>(); if (assetLoaderContext.Options.AvatarDefinition == AvatarDefinitionType.CopyFromOtherAvatar) { animator.avatar = assetLoaderContext.Options.Avatar; } else { SetupGenericAvatar(assetLoaderContext, animator); } if (animations != null) { animationClips = new AnimationClip[animations.Count]; for (var i = 0; i < animations.Count; i++) { var triLibAnimation = animations[i]; var animationClip = ParseAnimation(assetLoaderContext, triLibAnimation); animationClips[i] = animationClip; } } break; } case AnimationType.Humanoid: { var animator = assetLoaderContext.RootGameObject.AddComponent<Animator>(); if (assetLoaderContext.Options.AvatarDefinition == AvatarDefinitionType.CopyFromOtherAvatar) { animator.avatar = assetLoaderContext.Options.Avatar; } else if (assetLoaderContext.Options.HumanoidAvatarMapper != null) { SetupHumanoidAvatar(assetLoaderContext, animator); } if (animations != null) { animationClips = new AnimationClip[animations.Count]; for (var i = 0; i < animations.Count; i++) { var triLibAnimation = animations[i]; var animationClip = ParseAnimation(assetLoaderContext, triLibAnimation); animationClips[i] = animationClip; } } break; } } if (animationClips != null) { if (assetLoaderContext.Options.AnimationClipMappers != null) { foreach (var animationClipMapper in assetLoaderContext.Options.AnimationClipMappers) { if (animationClipMapper == null) { continue; } animationClips = animationClipMapper.MapArray(assetLoaderContext, animationClips); } } foreach (var animationClip in animationClips) { assetLoaderContext.Allocations.Add(animationClip); } } } /// <summary>Creates a Skeleton Bone for the given Transform.</summary> /// <param name="boneTransform">The bone Transform to use on the Skeleton Bone.</param> /// <returns>The created Skeleton Bone.</returns> private static SkeletonBone CreateSkeletonBone(Transform boneTransform) { var skeletonBone = new SkeletonBone { name = boneTransform.name, position = boneTransform.localPosition, rotation = boneTransform.localRotation, scale = boneTransform.localScale }; return skeletonBone; } /// <summary>Creates a Human Bone for the given Bone Mapping, containing the relationship between the Transform and Bone.</summary> /// <param name="boneMapping">The Bone Mapping used to create the Human Bone, containing the information used to search for bones.</param> /// <param name="boneName">The bone name to use on the created Human Bone.</param> /// <returns>The created Human Bone.</returns> private static HumanBone CreateHumanBone(BoneMapping boneMapping, string boneName) { var humanBone = new HumanBone { boneName = boneName, humanName = GetHumanBodyName(boneMapping.HumanBone), limit = { useDefaultValues = boneMapping.HumanLimit.useDefaultValues, axisLength = boneMapping.HumanLimit.axisLength, center = boneMapping.HumanLimit.center, max = boneMapping.HumanLimit.max, min = boneMapping.HumanLimit.min } }; return humanBone; } /// <summary>Returns the given Human Body Bones name as String.</summary> /// <param name="humanBodyBones">The Human Body Bones to get the name from.</param> /// <returns>The Human Body Bones name.</returns> private static string GetHumanBodyName(HumanBodyBones humanBodyBones) { return HumanTrait.BoneName[(int)humanBodyBones]; } /// <summary>Creates a Generic Avatar to the given context Model.</summary> /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param> /// <param name="animator">The Animator assigned to the given Context Root Game Object.</param> private static void SetupGenericAvatar(AssetLoaderContext assetLoaderContext, Animator animator) { var parent = assetLoaderContext.RootGameObject.transform.parent; assetLoaderContext.RootGameObject.transform.SetParent(null, true); var avatar = AvatarBuilder.BuildGenericAvatar(assetLoaderContext.RootGameObject, assetLoaderContext.RootBone != null ? assetLoaderContext.RootBone.name : ""); avatar.name = $"{assetLoaderContext.RootGameObject.name}Avatar"; animator.avatar = avatar; assetLoaderContext.RootGameObject.transform.SetParent(parent, true); } /// <summary>Creates a Humanoid Avatar to the given context Model.</summary> /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param> /// <param name="animator">The Animator assigned to the given Context Root Game Object.</param> private static void SetupHumanoidAvatar(AssetLoaderContext assetLoaderContext, Animator animator) { var index = 0; var mapping = assetLoaderContext.Options.HumanoidAvatarMapper.Map(assetLoaderContext); if (mapping.Count > 0) { assetLoaderContext.Options.HumanoidAvatarMapper.PostSetup(assetLoaderContext, mapping); var parent = assetLoaderContext.RootGameObject.transform.parent; assetLoaderContext.RootGameObject.transform.SetParent(null, true); var humanBones = new HumanBone[mapping.Count]; foreach (var kvp in mapping) { humanBones[index] = CreateHumanBone(kvp.Key, kvp.Value.name); index++; } var skeletonBones = new List<SkeletonBone>(assetLoaderContext.BoneTransforms.Length); //todo: check if all loaders can get bone information foreach (var humanBone in humanBones) { AddBoneChain(skeletonBones, humanBone.boneName, assetLoaderContext.RootGameObject.transform); } HumanDescription humanDescription; if (assetLoaderContext.Options.HumanDescription == null) { humanDescription = new HumanDescription { skeleton = skeletonBones.ToArray(), human = humanBones }; } else { humanDescription = new HumanDescription { armStretch = assetLoaderContext.Options.HumanDescription.armStretch, feetSpacing = assetLoaderContext.Options.HumanDescription.feetSpacing, hasTranslationDoF = assetLoaderContext.Options.HumanDescription.hasTranslationDof, legStretch = assetLoaderContext.Options.HumanDescription.legStretch, lowerArmTwist = assetLoaderContext.Options.HumanDescription.lowerArmTwist, lowerLegTwist = assetLoaderContext.Options.HumanDescription.lowerLegTwist, upperArmTwist = assetLoaderContext.Options.HumanDescription.upperArmTwist, upperLegTwist = assetLoaderContext.Options.HumanDescription.upperLegTwist, skeleton = skeletonBones.ToArray(), human = humanBones }; } var avatar = AvatarBuilder.BuildHumanAvatar(assetLoaderContext.RootGameObject, humanDescription); avatar.name = $"{assetLoaderContext.RootGameObject.name}Avatar"; animator.avatar = avatar; assetLoaderContext.RootGameObject.transform.SetParent(parent, true); } } /// <summary>Adds a bone to a bone chain.</summary> /// <param name="skeletonBones">The Skeleton Bones list.</param> /// <param name="humanBoneBoneName">The Human bone name to search.</param> /// <param name="rootTransform">The Game Object root Transform.</param> private static void AddBoneChain(List<SkeletonBone> skeletonBones, string humanBoneBoneName, Transform rootTransform) { var transform = rootTransform.FindDeepChild(humanBoneBoneName, StringComparisonMode.RightEqualsLeft, false); if (transform != null) { do { var existing = false; foreach (var skeletonBone in skeletonBones) { if (skeletonBone.name == transform.name) { existing = true; break; } } if (!existing) { skeletonBones.Add(CreateSkeletonBone(transform)); } transform = transform.parent; } while (transform != null); } } /// <summary>Converts the given Model into a Game Object.</summary> /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param> /// <param name="parentTransform">The parent Game Object Transform.</param> /// <param name="model">The Model to convert.</param> /// <param name="newGameObject">The Game Object to receive the converted Model.</param> private static void ParseModel(AssetLoaderContext assetLoaderContext, Transform parentTransform, IModel model, out GameObject newGameObject) { newGameObject = new GameObject(model.Name); assetLoaderContext.GameObjects.Add(model, newGameObject); assetLoaderContext.Models.Add(newGameObject, model); newGameObject.transform.parent = parentTransform; newGameObject.transform.localPosition = model.LocalPosition; newGameObject.transform.localRotation = model.LocalRotation; newGameObject.transform.localScale = model.LocalScale; if (model.GeometryGroup != null) { ParseGeometry(assetLoaderContext, newGameObject, model); } if (model.Children != null && model.Children.Count > 0) { foreach (var child in model.Children) { ParseModel(assetLoaderContext, newGameObject.transform, child, out _); } } } /// <summary>Configures the given Model skinning if there is any.</summary> /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param> /// <param name="model">The Model containing the bones.</param> private static void SetupModelBones(AssetLoaderContext assetLoaderContext, IModel model) { var loadedGameObject = assetLoaderContext.GameObjects[model]; var skinnedMeshRenderer = loadedGameObject.GetComponent<SkinnedMeshRenderer>(); if (skinnedMeshRenderer != null) { var bones = model.Bones; if (bones != null && bones.Count > 0) { var boneIndex = 0; var gameObjectBones = new Transform[bones.Count]; foreach (var bone in bones) { gameObjectBones[boneIndex++] = assetLoaderContext.GameObjects[bone].transform; } skinnedMeshRenderer.bones = gameObjectBones; skinnedMeshRenderer.rootBone = assetLoaderContext.RootBone; } } if (model.Children != null && model.Children.Count > 0) { foreach (var subModel in model.Children) { SetupModelBones(assetLoaderContext, subModel); } } } /// <summary>Converts the given Animation into an Animation Clip.</summary> /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param> /// <param name="animation">The Animation to convert.</param> /// <returns>The converted Animation Clip.</returns> private static AnimationClip ParseAnimation(AssetLoaderContext assetLoaderContext, IAnimation animation) { var animationClip = new AnimationClip { name = animation.Name, legacy = assetLoaderContext.Options.AnimationType != AnimationType.Generic, frameRate = animation.FrameRate }; var animationCurveBindings = animation.AnimationCurveBindings; var rootModel = assetLoaderContext.RootBone != null ? assetLoaderContext.Models[assetLoaderContext.RootBone.gameObject] : null; foreach (var animationCurveBinding in animationCurveBindings) { var animationCurves = animationCurveBinding.AnimationCurves; var gameObject = assetLoaderContext.GameObjects[animationCurveBinding.Model]; foreach (var animationCurve in animationCurves) { var keyFrames = animationCurve.KeyFrames; var unityAnimationCurve = new AnimationCurve(keyFrames); var gameObjectPath = assetLoaderContext.GameObjectPaths[gameObject]; var propertyName = animationCurve.Property; var propertyType = animationCurve.Property.StartsWith("blendShape.") ? typeof(SkinnedMeshRenderer) : typeof(Transform); //todo: refactoring if (assetLoaderContext.Options.AnimationType == AnimationType.Generic) { TryToRemapGenericCurve(rootModel, animationCurve, animationCurveBinding, ref gameObjectPath, ref propertyName, ref propertyType); } animationClip.SetCurve(gameObjectPath, propertyType, propertyName, unityAnimationCurve); } } animationClip.EnsureQuaternionContinuity(); return animationClip; } /// <summary>Tries to convert a legacy Animation Curve path into a generic Animation path.</summary> /// <param name="rootBone">The root bone Model.</param> /// <param name="animationCurve">The Animation Curve Map to remap.</param> /// <param name="animationCurveBinding">The Animation Curve Binding to remap.</param> /// <param name="gameObjectPath">The GameObject containing the Curve path.</param> /// <param name="propertyName">The remapped Property name.</param> /// <param name="propertyType">The remapped Property type.</param> private static void TryToRemapGenericCurve(IModel rootBone, IAnimationCurve animationCurve, IAnimationCurveBinding animationCurveBinding, ref string gameObjectPath, ref string propertyName, ref Type propertyType) { if (animationCurveBinding.Model == rootBone) { var remap = false; switch (animationCurve.Property) { case Constants.LocalPositionXProperty: propertyName = Constants.RootPositionXProperty; remap = true; break; case Constants.LocalPositionYProperty: propertyName = Constants.RootPositionYProperty; remap = true; break; case Constants.LocalPositionZProperty: propertyName = Constants.RootPositionZProperty; remap = true; break; case Constants.LocalRotationXProperty: propertyName = Constants.RootRotationXProperty; remap = true; break; case Constants.LocalRotationYProperty: propertyName = Constants.RootRotationYProperty; remap = true; break; case Constants.LocalRotationZProperty: propertyName = Constants.RootRotationZProperty; remap = true; break; case Constants.LocalRotationWProperty: propertyName = Constants.RootRotationWProperty; remap = true; break; } if (remap) { gameObjectPath = ""; propertyType = typeof(Animator); } } } /// <summary>Converts the given Geometry Group into a Mesh.</summary> /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param> /// <param name="meshGameObject">The Game Object where the Mesh belongs.</param> /// <param name="meshModel">The Model used to generate the Game Object.</param> private static void ParseGeometry(AssetLoaderContext assetLoaderContext, GameObject meshGameObject, IModel meshModel) { var geometryGroup = meshModel.GeometryGroup; var geometries = geometryGroup.Geometries; var mesh = new Mesh { name = geometryGroup.Name, subMeshCount = geometries?.Count ?? 0, indexFormat = assetLoaderContext.Options.IndexFormat }; assetLoaderContext.Allocations.Add(mesh); if (geometries != null) { if (assetLoaderContext.Options.ReadAndWriteEnabled) { mesh.MarkDynamic(); } if (assetLoaderContext.Options.LipSyncMappers != null) { foreach (var lipSyncMapper in assetLoaderContext.Options.LipSyncMappers) { if (lipSyncMapper == null) { continue; } if (lipSyncMapper.Map(assetLoaderContext, geometryGroup, out var visemeToBlendTargets)) { var lipSyncMapping = meshGameObject.AddComponent<LipSyncMapping>(); lipSyncMapping.VisemeToBlendTargets = visemeToBlendTargets; break; } } } geometries = mesh.CombineGeometries(geometryGroup, meshModel.BindPoses, assetLoaderContext); if (assetLoaderContext.Options.GenerateColliders) { if (assetLoaderContext.RootModel.AllAnimations != null && assetLoaderContext.RootModel.AllAnimations.Count > 0) { if (assetLoaderContext.Options.ShowLoadingWarnings) { Debug.LogWarning("Trying to add a MeshCollider to an animated object."); } } else { var meshCollider = meshGameObject.AddComponent<MeshCollider>(); meshCollider.sharedMesh = mesh; meshCollider.convex = assetLoaderContext.Options.ConvexColliders; } } var allMaterials = new IMaterial[geometries.Count]; var modelMaterials = meshModel.Materials; if (modelMaterials != null) { for (var i = 0; i < geometries.Count; i++) { var geometry = geometries[i]; allMaterials[i] = modelMaterials[Mathf.Clamp(geometry.MaterialIndex, 0, meshModel.Materials.Count - 1)]; } } Renderer renderer = null; if (assetLoaderContext.Options.AnimationType != AnimationType.None || assetLoaderContext.Options.ImportBlendShapes) { var bones = meshModel.Bones; var geometryGroupBlendShapeGeometryBindings = geometryGroup.BlendShapeGeometryBindings; if (bones != null && bones.Count > 0 || geometryGroupBlendShapeGeometryBindings != null && geometryGroupBlendShapeGeometryBindings.Count > 0) { var skinnedMeshRenderer = meshGameObject.AddComponent<SkinnedMeshRenderer>(); skinnedMeshRenderer.sharedMesh = mesh; skinnedMeshRenderer.enabled = !assetLoaderContext.Options.ImportVisibility || meshModel.Visibility; renderer = skinnedMeshRenderer; } } if (renderer == null) { var meshFilter = meshGameObject.AddComponent<MeshFilter>(); meshFilter.sharedMesh = mesh; var meshRenderer = meshGameObject.AddComponent<MeshRenderer>(); meshRenderer.enabled = !assetLoaderContext.Options.ImportVisibility || meshModel.Visibility; renderer = meshRenderer; } var materials = new Material[allMaterials.Length]; Material loadingMaterial = null; foreach (var mapper in assetLoaderContext.Options.MaterialMappers) { if (mapper != null && mapper.IsCompatible(null)) { loadingMaterial = mapper.LoadingMaterial; break; } } if (loadingMaterial == null) { if (assetLoaderContext.Options.ShowLoadingWarnings) { Debug.LogWarning("Could not find a suitable loading Material"); } } else { for (var i = 0; i < materials.Length; i++) { materials[i] = loadingMaterial; } } renderer.sharedMaterials = materials; for (var i = 0; i < allMaterials.Length; i++) { var sourceMaterial = allMaterials[i]; if (sourceMaterial == null) { continue; } var materialRenderersContext = new MaterialRendererContext { Context = assetLoaderContext, Renderer = renderer, MaterialIndex = i, Material = sourceMaterial }; if (assetLoaderContext.MaterialRenderers.TryGetValue(sourceMaterial, out var materialRendererContextList)) { materialRendererContextList.Add(materialRenderersContext); } else { assetLoaderContext.MaterialRenderers.Add(sourceMaterial, new List<MaterialRendererContext> { materialRenderersContext }); } } } } /// <summary>Loads the root Model.</summary> /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param> private static void LoadModel(AssetLoaderContext assetLoaderContext) { if (assetLoaderContext.Options.MaterialMappers != null) { Array.Sort(assetLoaderContext.Options.MaterialMappers, (a, b) => a.CheckingOrder > b.CheckingOrder ? -1 : 1); } else if (assetLoaderContext.Options.ShowLoadingWarnings) { Debug.LogWarning("Your AssetLoaderOptions instance has no MaterialMappers. TriLib can't process materials without them."); } #if TRILIB_DRACO GltfReader.DracoDecompressorCallback = DracoMeshLoader.DracoDecompressorCallback; #endif var fileExtension = assetLoaderContext.FileExtension ?? FileUtils.GetFileExtension(assetLoaderContext.Filename, false).ToLowerInvariant(); if (assetLoaderContext.Stream == null) { var fileStream = new FileStream(assetLoaderContext.Filename, FileMode.Open); assetLoaderContext.Stream = fileStream; var reader = Readers.FindReaderForExtension(fileExtension); if (reader != null) { assetLoaderContext.RootModel = reader.ReadStream(fileStream, assetLoaderContext, assetLoaderContext.Filename, assetLoaderContext.OnProgress); } } else { var reader = Readers.FindReaderForExtension(fileExtension); if (reader != null) { assetLoaderContext.RootModel = reader.ReadStream(assetLoaderContext.Stream, assetLoaderContext, null, assetLoaderContext.OnProgress); } } } /// <summary>Processes the root Model.</summary> /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param> private static void ProcessRootModel(AssetLoaderContext assetLoaderContext) { ProcessModel(assetLoaderContext); if (assetLoaderContext.Async) { ThreadUtils.RunThread(assetLoaderContext, ref assetLoaderContext.CancellationToken, ProcessTextures, null, assetLoaderContext.HandleError ?? assetLoaderContext.OnError, assetLoaderContext.Options.Timeout); } else { ProcessTextures(assetLoaderContext); } } private static void TryProcessMaterials(AssetLoaderContext assetLoaderContext) { var allMaterialsLoaded = assetLoaderContext.RootModel?.AllTextures == null || assetLoaderContext.LoadedTexturesCount == assetLoaderContext.RootModel.AllTextures.Count; if (!assetLoaderContext.MaterialsProcessed && allMaterialsLoaded) { assetLoaderContext.MaterialsProcessed = true; if (assetLoaderContext.RootModel?.AllMaterials != null) { ProcessMaterials(assetLoaderContext); } if (assetLoaderContext.Options.AddAssetUnloader && assetLoaderContext.RootGameObject != null || assetLoaderContext.WrapperGameObject != null) { var gameObject = assetLoaderContext.RootGameObject ?? assetLoaderContext.WrapperGameObject; var assetUnloader = gameObject.AddComponent<AssetUnloader>(); assetUnloader.Id = AssetUnloader.GetNextId(); assetUnloader.Allocations = assetLoaderContext.Allocations; } assetLoaderContext.OnMaterialsLoad?.Invoke(assetLoaderContext); TryToCloseStream(assetLoaderContext); } } private static void ProcessTextures(AssetLoaderContext assetLoaderContext) { if (assetLoaderContext.RootModel?.AllTextures != null) { for (var i = 0; i < assetLoaderContext.RootModel.AllTextures.Count; i++) { var texture = assetLoaderContext.RootModel.AllTextures[i]; TextureLoadingContext textureLoadingContext = null; if (assetLoaderContext.Options.TextureMapper != null) { textureLoadingContext = assetLoaderContext.Options.TextureMapper.Map(assetLoaderContext, texture); } if (textureLoadingContext == null) { textureLoadingContext = new TextureLoadingContext { Context = assetLoaderContext, Texture = texture }; } StbImage.LoadTexture(textureLoadingContext); assetLoaderContext.Reader.UpdateLoadingPercentage((float)i / assetLoaderContext.RootModel.AllTextures.Count, 1); } } assetLoaderContext.Reader.UpdateLoadingPercentage(1f, 1); if (assetLoaderContext.Async) { Dispatcher.InvokeAsync(new ContextualizedAction<AssetLoaderContext>(TryProcessMaterials, assetLoaderContext)); } else { TryProcessMaterials(assetLoaderContext); } } private static void ProcessMaterials(AssetLoaderContext assetLoaderContext) { if (assetLoaderContext.Options.MaterialMappers != null) { foreach (var material in assetLoaderContext.RootModel.AllMaterials) { MaterialMapper usedMaterialMapper = null; var materialMapperContext = new MaterialMapperContext { Context = assetLoaderContext, Material = material }; foreach (var materialMapper in assetLoaderContext.Options.MaterialMappers) { if (materialMapper == null || !materialMapper.IsCompatible(materialMapperContext)) { continue; } materialMapper.Map(materialMapperContext); usedMaterialMapper = materialMapper; break; } if (usedMaterialMapper != null) { if (assetLoaderContext.MaterialRenderers.TryGetValue(material, out var materialRendererList)) { foreach (var materialRendererContext in materialRendererList) { usedMaterialMapper.ApplyMaterialToRenderer(materialRendererContext, materialMapperContext); } } } } } else if (assetLoaderContext.Options.ShowLoadingWarnings) { Debug.LogWarning("The given AssetLoaderOptions contains no MaterialMapper. Materials will not be created."); } } /// <summary>Handles all Model loading errors, unloads the partially loaded Model (if suitable), and calls the error callback (if existing).</summary> /// <param name="error">The Contextualized Error that has occurred.</param> private static void HandleError(IContextualizedError error) { var exception = error.GetInnerException(); if (error.GetContext() is IAssetLoaderContext iassetLoaderContext) { var assetLoaderContext = iassetLoaderContext.Context; if (assetLoaderContext != null) { TryToCloseStream(assetLoaderContext); if (assetLoaderContext.Options.DestroyOnError && assetLoaderContext.RootGameObject != null) { #if UNITY_EDITOR Object.DestroyImmediate(assetLoaderContext.RootGameObject); #else Object.Destroy(assetLoaderContext.RootGameObject); #endif assetLoaderContext.RootGameObject = null; } if (assetLoaderContext.Async) { Dispatcher.InvokeAsync(new ContextualizedAction<IContextualizedError>(assetLoaderContext.OnError, error)); } else if (assetLoaderContext.OnError != null) { assetLoaderContext.OnError(error); } } } else { var contextualizedAction = new ContextualizedAction<ContextualizedError<object>>(Rethrow, new ContextualizedError<object>(exception, null)); Dispatcher.InvokeAsync(contextualizedAction); } } private static void TryToCloseStream(AssetLoaderContext assetLoaderContext) { if (assetLoaderContext.Stream != null && assetLoaderContext.Options.CloseStreamAutomatically) { try { assetLoaderContext.Stream.Dispose(); } catch (Exception e) { } } } /// <summary>Throws the given Contextualized Error on the main Thread.</summary> /// <typeparam name="T"></typeparam> /// <param name="contextualizedError">The Contextualized Error to throw.</param> private static void Rethrow<T>(ContextualizedError<T> contextualizedError) { throw contextualizedError; } } }
54.224759
435
0.587513
[ "Apache-2.0" ]
PavelGem-13g/City-scene-editor
City-scene-editor/Assets/TriLib/TriLibCore/Scripts/AssetLoader.cs
61,764
C#
using Item.Enum; using Item.Model; using Item.View; using Item.View.Modules; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Item.Control { public class ItemTipManager { private static ItemTipManager inst; public static ItemTipManager Inst() { if (inst == null) { inst = new ItemTipManager(); } return inst; } #region Regist private Dictionary<string, ItemTipType> registedTipTypes = new Dictionary<string, ItemTipType>(); private Dictionary<ItemTipType, int[]> registedTipModules = new Dictionary<ItemTipType, int[]>(); private static Dictionary<int, int[]> moduleListDict = new Dictionary<int, int[]>(); private (BaseItemData it1, BaseItemData it2, BaseItemData it3) itemDatas; public ItemTipManager() { RegistTipTypes(); CreateDefaultModuleList(); RegistTipModules(); } private void RegistTipTypes() { RegistType("NORMAL", ItemTipType.Item); RegistType("EQUIP", ItemTipType.Equip); RegistType("SKILLBOOK", ItemTipType.Skill); RegistType("MOUNT", ItemTipType.Mount); RegistType("TREASUREBOX", ItemTipType.Box); RegistType("CURRENCY", ItemTipType.Currency); } private void RegistType(string itemType, ItemTipType tipType) { registedTipTypes.Add(itemType, tipType); } private void CreateDefaultModuleList() { var list = new int[] { ItemTipModuleType.Header, ItemTipModuleType.BaseInfo, ItemTipModuleType.Demand, ItemTipModuleType.Effect, ItemTipModuleType.Desc, ItemTipModuleType.Price, ItemTipModuleType.Button }; moduleListDict.Add(1, list); list = new int[] { ItemTipModuleType.Header, ItemTipModuleType.BaseInfo, ItemTipModuleType.Demand, ItemTipModuleType.Attr + ItemTipModuleType.AttrModuleType.Base, ItemTipModuleType.Attr + ItemTipModuleType.AttrModuleType.Addition, ItemTipModuleType.Desc, ItemTipModuleType.Price, ItemTipModuleType.Button, ItemTipModuleType.RightButton, ItemTipModuleType.Display }; moduleListDict.Add(2, list); list = new int[] { ItemTipModuleType.Header, ItemTipModuleType.BaseInfo, ItemTipModuleType.Demand, ItemTipModuleType.Skill, ItemTipModuleType.Effect, ItemTipModuleType.Desc, ItemTipModuleType.Price, ItemTipModuleType.Button, ItemTipModuleType.RightButton, ItemTipModuleType.Display }; moduleListDict.Add(3, list); list = new int[] { ItemTipModuleType.Header, ItemTipModuleType.BaseInfo, ItemTipModuleType.Demand, ItemTipModuleType.Effect, ItemTipModuleType.Desc, ItemTipModuleType.Price, ItemTipModuleType.Button, ItemTipModuleType.RightButton, ItemTipModuleType.Display }; moduleListDict.Add(4, list); list = new int[] { ItemTipModuleType.Header, ItemTipModuleType.BaseInfo, ItemTipModuleType.Demand, ItemTipModuleType.Item + ItemTipModuleType.ItemModuleType.Preview, ItemTipModuleType.Item + ItemTipModuleType.ItemModuleType.Selectable, ItemTipModuleType.Effect, ItemTipModuleType.Desc, ItemTipModuleType.Price, ItemTipModuleType.Button }; moduleListDict.Add(5, list); list = new int[] { ItemTipModuleType.Header, ItemTipModuleType.BaseInfo, ItemTipModuleType.Effect, ItemTipModuleType.Desc, ItemTipModuleType.Button }; moduleListDict.Add(6, list); } private void RegistTipModules() { RegistModules(ItemTipType.Item, 1); RegistModules(ItemTipType.Equip, 2); RegistModules(ItemTipType.Skill, 3); RegistModules(ItemTipType.Mount, 4); RegistModules(ItemTipType.Box, 5); RegistModules(ItemTipType.Currency, 6); } private void RegistModules(ItemTipType tipType, int dictIndex) { registedTipModules.Add(tipType, moduleListDict[dictIndex]); } #endregion public void OpenTipView((BaseItemData it1, BaseItemData it2, BaseItemData it3) itemDatas) { this.itemDatas = itemDatas; OpenTipView(itemDatas.it1, itemDatas.it2, itemDatas.it3); } public void OpenTipView(BaseItemData itemData1, BaseItemData itemData2 = null, BaseItemData itemData3 = null) { itemData1.tipData.additionalPartIndex = 0; if (itemData2 != null) { itemData2.tipData.additionalPartIndex = 1; //附加tip以原始tip坐标做偏移 itemData2.tipData.pos = itemData1.tipData.pos; itemData2.tipData.anchor = itemData1.tipData.anchor; itemData2.tipData.pivot = itemData1.tipData.pivot; //以多参打开tip的方式,附加tip不另外添加遮罩 itemData2.tipData.showMask = false; } if (itemData3 != null) { itemData3.tipData.additionalPartIndex = 2; //附加tip放在同一侧 itemData3.tipData.isAdditionalLeftPart = itemData2.tipData.isAdditionalLeftPart; //附加tip以原始tip坐标做偏移 itemData3.tipData.pos = itemData1.tipData.pos; itemData3.tipData.anchor = itemData1.tipData.anchor; itemData3.tipData.pivot = itemData1.tipData.pivot; //以多参打开tip的方式,附加tip不另外添加遮罩 itemData3.tipData.showMask = false; } OpenTipView(itemData1); OpenTipView(itemData2); OpenTipView(itemData3); } public void OpenTipView(BaseItemData itemData) { if (itemData == null) { return; } if (!itemData.tipData.isAdditionalPart) { ItemTipPool.Inst().RecycleAllUsingTips(); } else { ItemTipPool.Inst().RecycleUsingTipsFromIndex(itemData.tipData.additionalPartIndex); } bool full = ItemTipPool.Inst().IsTipsUsingFullUp(); if (full) { Debug.LogError("已经显示最大数量的tips"); return; } ItemTipType tipType = GetTipType(itemData); ItemTipView tipView = ItemTipPool.Inst().PopTip(); int[] modules; if (registedTipModules.TryGetValue(tipType, out modules)) { for (int i = 0; i < modules.Length; i++) { int moduleType = modules[i]; int subModuleType = moduleType % 100; int baseModuleType = moduleType - subModuleType; ItemTipModule module = ItemTipPool.Inst().PopModule(baseModuleType); module.subModuleType = subModuleType; tipView.AddModule(module); } } tipView.SetData(itemData); } public void CloseTipView(int index = 0) { ItemTipPool.Inst().RecycleUsingTipsFromIndex(index); } private ItemTipType GetTipType(BaseItemData itemData) { string tipTypeStr = itemData.itemRes.type; ItemTipType tipType; if (registedTipTypes.TryGetValue(tipTypeStr, out tipType)) { return tipType; } return ItemTipType.Item; } } }
33.987952
117
0.54626
[ "MIT" ]
taixihuase/Game-Tips-Design
Assets/Scripts/Item/Control/ItemTipManager.cs
8,609
C#
// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information. using System; namespace CommandLine { /// <summary> /// Models an value specification, or better how to handle values not bound to options. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class ValueAttribute : BaseAttribute { private readonly int index; private string metaName; /// <summary> /// Initializes a new instance of the <see cref="CommandLine.ValueAttribute"/> class. /// </summary> public ValueAttribute(int index) : base() { this.index = index; this.metaName = string.Empty; } /// <summary> /// Gets the position this option has on the command line. /// </summary> public int Index { get { return index; } } /// <summary> /// Gets or sets name of this positional value specification. /// </summary> public string MetaName { get { return metaName; } set { if (value == null) throw new ArgumentNullException("value"); metaName = value; } } } }
29.276596
143
0.566134
[ "MIT" ]
BitIndex/CashDB
extern/src/commandline/ValueAttribute.cs
1,378
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. using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Text; using Microsoft.Toolkit.HighPerformance.Extensions; #if !NETSTANDARD1_4 using Microsoft.Toolkit.HighPerformance.Helpers; #endif using BitOperations = Microsoft.Toolkit.HighPerformance.Helpers.Internals.BitOperations; #nullable enable namespace Microsoft.Toolkit.HighPerformance.Buffers { /// <summary> /// A configurable pool for <see cref="string"/> instances. This can be used to minimize allocations /// when creating multiple <see cref="string"/> instances from buffers of <see cref="char"/> values. /// The <see cref="GetOrAdd(ReadOnlySpan{char})"/> method provides a best-effort alternative to just creating /// a new <see cref="string"/> instance every time, in order to minimize the number of duplicated instances. /// The <see cref="StringPool"/> type will internally manage a highly efficient priority queue for the /// cached <see cref="string"/> instances, so that when the full capacity is reached, the least frequently /// used values will be automatically discarded to leave room for new values to cache. /// </summary> public sealed class StringPool { /// <summary> /// The size used by default by the parameterless constructor. /// </summary> private const int DefaultSize = 2048; /// <summary> /// The minimum size for <see cref="StringPool"/> instances. /// </summary> private const int MinimumSize = 32; /// <summary> /// The current array of <see cref="FixedSizePriorityMap"/> instances in use. /// </summary> private readonly FixedSizePriorityMap[] maps; /// <summary> /// The total number of maps in use. /// </summary> private readonly int numberOfMaps; /// <summary> /// Initializes a new instance of the <see cref="StringPool"/> class. /// </summary> public StringPool() : this(DefaultSize) { } /// <summary> /// Initializes a new instance of the <see cref="StringPool"/> class. /// </summary> /// <param name="minimumSize">The minimum size for the pool to create.</param> public StringPool(int minimumSize) { if (minimumSize <= 0) { ThrowArgumentOutOfRangeException(); } // Set the minimum size minimumSize = Math.Max(minimumSize, MinimumSize); // Calculates the rounded up factors for a specific size/factor pair static void FindFactors(int size, int factor, out int x, out int y) { double a = Math.Sqrt((double)size / factor), b = factor * a; x = BitOperations.RoundUpPowerOfTwo((int)a); y = BitOperations.RoundUpPowerOfTwo((int)b); } // We want to find two powers of 2 factors that produce a number // that is at least equal to the requested size. In order to find the // combination producing the optimal factors (with the product being as // close as possible to the requested size), we test a number of ratios // that we consider acceptable, and pick the best results produced. // The ratio between maps influences the number of objects being allocated, // as well as the multithreading performance when locking on maps. // We still want to contraint this number to avoid situations where we // have a way too high number of maps compared to total size. FindFactors(minimumSize, 2, out int x2, out int y2); FindFactors(minimumSize, 3, out int x3, out int y3); FindFactors(minimumSize, 4, out int x4, out int y4); int p2 = x2 * y2, p3 = x3 * y3, p4 = x4 * y4; if (p3 < p2) { p2 = p3; x2 = x3; y2 = y3; } if (p4 < p2) { p2 = p4; x2 = x4; y2 = y4; } Span<FixedSizePriorityMap> span = this.maps = new FixedSizePriorityMap[x2]; // We preallocate the maps in advance, since each bucket only contains the // array field, which is not preinitialized, so the allocations are minimal. // This lets us lock on each individual maps when retrieving a string instance. foreach (ref FixedSizePriorityMap map in span) { map = new FixedSizePriorityMap(y2); } this.numberOfMaps = x2; Size = p2; } /// <summary> /// Gets the shared <see cref="StringPool"/> instance. /// </summary> /// <remarks> /// The shared pool provides a singleton, reusable <see cref="StringPool"/> instance that /// can be accessed directly, and that pools <see cref="string"/> instances for the entire /// process. Since <see cref="StringPool"/> is thread-safe, the shared instance can be used /// concurrently by multiple threads without the need for manual synchronization. /// </remarks> public static StringPool Shared { get; } = new(); /// <summary> /// Gets the total number of <see cref="string"/> that can be stored in the current instance. /// </summary> public int Size { get; } /// <summary> /// Stores a <see cref="string"/> instance in the internal cache. /// </summary> /// <param name="value">The input <see cref="string"/> instance to cache.</param> public void Add(string value) { if (value.Length == 0) { return; } int hashcode = GetHashCode(value.AsSpan()), bucketIndex = hashcode & (this.numberOfMaps - 1); ref FixedSizePriorityMap map = ref this.maps.DangerousGetReferenceAt(bucketIndex); lock (map.SyncRoot) { map.Add(value, hashcode); } } /// <summary> /// Gets a cached <see cref="string"/> instance matching the input content, or stores the input one. /// </summary> /// <param name="value">The input <see cref="string"/> instance with the contents to use.</param> /// <returns>A <see cref="string"/> instance with the contents of <paramref name="value"/>, cached if possible.</returns> public string GetOrAdd(string value) { if (value.Length == 0) { return string.Empty; } int hashcode = GetHashCode(value.AsSpan()), bucketIndex = hashcode & (this.numberOfMaps - 1); ref FixedSizePriorityMap map = ref this.maps.DangerousGetReferenceAt(bucketIndex); lock (map.SyncRoot) { return map.GetOrAdd(value, hashcode); } } /// <summary> /// Gets a cached <see cref="string"/> instance matching the input content, or creates a new one. /// </summary> /// <param name="span">The input <see cref="ReadOnlySpan{T}"/> with the contents to use.</param> /// <returns>A <see cref="string"/> instance with the contents of <paramref name="span"/>, cached if possible.</returns> public string GetOrAdd(ReadOnlySpan<char> span) { if (span.IsEmpty) { return string.Empty; } int hashcode = GetHashCode(span), bucketIndex = hashcode & (this.numberOfMaps - 1); ref FixedSizePriorityMap map = ref this.maps.DangerousGetReferenceAt(bucketIndex); lock (map.SyncRoot) { return map.GetOrAdd(span, hashcode); } } /// <summary> /// Gets a cached <see cref="string"/> instance matching the input content (converted to Unicode), or creates a new one. /// </summary> /// <param name="span">The input <see cref="ReadOnlySpan{T}"/> with the contents to use, in a specified encoding.</param> /// <param name="encoding">The <see cref="Encoding"/> instance to use to decode the contents of <paramref name="span"/>.</param> /// <returns>A <see cref="string"/> instance with the contents of <paramref name="span"/>, cached if possible.</returns> public unsafe string GetOrAdd(ReadOnlySpan<byte> span, Encoding encoding) { if (span.IsEmpty) { return string.Empty; } int maxLength = encoding.GetMaxCharCount(span.Length); using SpanOwner<char> buffer = SpanOwner<char>.Allocate(maxLength); fixed (byte* source = span) fixed (char* destination = &buffer.DangerousGetReference()) { int effectiveLength = encoding.GetChars(source, span.Length, destination, maxLength); return GetOrAdd(new ReadOnlySpan<char>(destination, effectiveLength)); } } /// <summary> /// Tries to get a cached <see cref="string"/> instance matching the input content, if present. /// </summary> /// <param name="span">The input <see cref="ReadOnlySpan{T}"/> with the contents to use.</param> /// <param name="value">The resulting cached <see cref="string"/> instance, if present</param> /// <returns>Whether or not the target <see cref="string"/> instance was found.</returns> public bool TryGet(ReadOnlySpan<char> span, [NotNullWhen(true)] out string? value) { if (span.IsEmpty) { value = string.Empty; return true; } int hashcode = GetHashCode(span), bucketIndex = hashcode & (this.numberOfMaps - 1); ref FixedSizePriorityMap map = ref this.maps.DangerousGetReferenceAt(bucketIndex); lock (map.SyncRoot) { return map.TryGet(span, hashcode, out value); } } /// <summary> /// Resets the current instance and its associated maps. /// </summary> public void Reset() { foreach (ref FixedSizePriorityMap map in this.maps.AsSpan()) { lock (map.SyncRoot) { map.Reset(); } } } /// <summary> /// A configurable map containing a group of cached <see cref="string"/> instances. /// </summary> /// <remarks> /// Instances of this type are stored in an array within <see cref="StringPool"/> and they are /// always accessed by reference - essentially as if this type had been a class. The type is /// also private, so there's no risk for users to directly access it and accidentally copy an /// instance, which would lead to bugs due to values becoming out of sync with the internal state /// (that is, because instances would be copied by value, so primitive fields would not be shared). /// The reason why we're using a struct here is to remove an indirection level and improve cache /// locality when accessing individual buckets from the methods in the <see cref="StringPool"/> type. /// </remarks> private struct FixedSizePriorityMap { /// <summary> /// The index representing the end of a given list. /// </summary> private const int EndOfList = -1; /// <summary> /// The array of 1-based indices for the <see cref="MapEntry"/> items stored in <see cref="mapEntries"/>. /// </summary> private readonly int[] buckets; /// <summary> /// The array of currently cached entries (ie. the lists for each hash group). /// </summary> private readonly MapEntry[] mapEntries; /// <summary> /// The array of priority values associated to each item stored in <see cref="mapEntries"/>. /// </summary> private readonly HeapEntry[] heapEntries; /// <summary> /// The current number of items stored in the map. /// </summary> private int count; /// <summary> /// The current incremental timestamp for the items stored in <see cref="heapEntries"/>. /// </summary> private uint timestamp; /// <summary> /// A type representing a map entry, ie. a node in a given list. /// </summary> private struct MapEntry { /// <summary> /// The precomputed hashcode for <see cref="Value"/>. /// </summary> public int HashCode; /// <summary> /// The <see cref="string"/> instance cached in this entry. /// </summary> public string? Value; /// <summary> /// The 0-based index for the next node in the current list. /// </summary> public int NextIndex; /// <summary> /// The 0-based index for the heap entry corresponding to the current node. /// </summary> public int HeapIndex; } /// <summary> /// A type representing a heap entry, used to associate priority to each item. /// </summary> private struct HeapEntry { /// <summary> /// The timestamp for the current entry (ie. the priority for the item). /// </summary> public uint Timestamp; /// <summary> /// The 0-based index for the map entry corresponding to the current item. /// </summary> public int MapIndex; } /// <summary> /// Initializes a new instance of the <see cref="FixedSizePriorityMap"/> struct. /// </summary> /// <param name="capacity">The fixed capacity of the current map.</param> public FixedSizePriorityMap(int capacity) { this.buckets = new int[capacity]; this.mapEntries = new MapEntry[capacity]; this.heapEntries = new HeapEntry[capacity]; this.count = 0; this.timestamp = 0; } /// <summary> /// Gets an <see cref="object"/> that can be used to synchronize access to the current instance. /// </summary> public object SyncRoot { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => this.buckets; } /// <summary> /// Implements <see cref="StringPool.Add"/> for the current instance. /// </summary> /// <param name="value">The input <see cref="string"/> instance to cache.</param> /// <param name="hashcode">The precomputed hashcode for <paramref name="value"/>.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(string value, int hashcode) { ref string target = ref TryGet(value.AsSpan(), hashcode); if (Unsafe.IsNullRef(ref target)) { Insert(value, hashcode); } else { target = value; } } /// <summary> /// Implements <see cref="StringPool.GetOrAdd(string)"/> for the current instance. /// </summary> /// <param name="value">The input <see cref="string"/> instance with the contents to use.</param> /// <param name="hashcode">The precomputed hashcode for <paramref name="value"/>.</param> /// <returns>A <see cref="string"/> instance with the contents of <paramref name="value"/>.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public string GetOrAdd(string value, int hashcode) { ref string result = ref TryGet(value.AsSpan(), hashcode); if (!Unsafe.IsNullRef(ref result)) { return result; } Insert(value, hashcode); return value; } /// <summary> /// Implements <see cref="StringPool.GetOrAdd(ReadOnlySpan{char})"/> for the current instance. /// </summary> /// <param name="span">The input <see cref="ReadOnlySpan{T}"/> with the contents to use.</param> /// <param name="hashcode">The precomputed hashcode for <paramref name="span"/>.</param> /// <returns>A <see cref="string"/> instance with the contents of <paramref name="span"/>, cached if possible.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public string GetOrAdd(ReadOnlySpan<char> span, int hashcode) { ref string result = ref TryGet(span, hashcode); if (!Unsafe.IsNullRef(ref result)) { return result; } string value = span.ToString(); Insert(value, hashcode); return value; } /// <summary> /// Implements <see cref="StringPool.TryGet"/> for the current instance. /// </summary> /// <param name="span">The input <see cref="ReadOnlySpan{T}"/> with the contents to use.</param> /// <param name="hashcode">The precomputed hashcode for <paramref name="span"/>.</param> /// <param name="value">The resulting cached <see cref="string"/> instance, if present</param> /// <returns>Whether or not the target <see cref="string"/> instance was found.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGet(ReadOnlySpan<char> span, int hashcode, [NotNullWhen(true)] out string? value) { ref string result = ref TryGet(span, hashcode); if (!Unsafe.IsNullRef(ref result)) { value = result; return true; } value = null; return false; } /// <summary> /// Resets the current instance and throws away all the cached values. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Reset() { this.buckets.AsSpan().Clear(); this.mapEntries.AsSpan().Clear(); this.heapEntries.AsSpan().Clear(); this.count = 0; this.timestamp = 0; } /// <summary> /// Tries to get a target <see cref="string"/> instance, if it exists, and returns a reference to it. /// </summary> /// <param name="span">The input <see cref="ReadOnlySpan{T}"/> with the contents to use.</param> /// <param name="hashcode">The precomputed hashcode for <paramref name="span"/>.</param> /// <returns>A reference to the slot where the target <see cref="string"/> instance could be.</returns> [MethodImpl(MethodImplOptions.NoInlining)] private unsafe ref string TryGet(ReadOnlySpan<char> span, int hashcode) { ref MapEntry mapEntriesRef = ref this.mapEntries.DangerousGetReference(); ref MapEntry entry = ref Unsafe.NullRef<MapEntry>(); int length = this.buckets.Length, bucketIndex = hashcode & (length - 1); for (int i = this.buckets.DangerousGetReferenceAt(bucketIndex) - 1; (uint)i < (uint)length; i = entry.NextIndex) { entry = ref Unsafe.Add(ref mapEntriesRef, (nint)(uint)i); if (entry.HashCode == hashcode && entry.Value!.AsSpan().SequenceEqual(span)) { UpdateTimestamp(ref entry.HeapIndex); return ref entry.Value!; } } return ref Unsafe.NullRef<string>(); } /// <summary> /// Inserts a new <see cref="string"/> instance in the current map, freeing up a space if needed. /// </summary> /// <param name="value">The new <see cref="string"/> instance to store.</param> /// <param name="hashcode">The precomputed hashcode for <paramref name="value"/>.</param> [MethodImpl(MethodImplOptions.NoInlining)] private void Insert(string value, int hashcode) { ref int bucketsRef = ref this.buckets.DangerousGetReference(); ref MapEntry mapEntriesRef = ref this.mapEntries.DangerousGetReference(); ref HeapEntry heapEntriesRef = ref this.heapEntries.DangerousGetReference(); int entryIndex, heapIndex; // If the current map is full, first get the oldest value, which is // always the first item in the heap. Then, free up a slot by // removing that, and insert the new value in that empty location. if (this.count == this.mapEntries.Length) { entryIndex = heapEntriesRef.MapIndex; heapIndex = 0; ref MapEntry removedEntry = ref Unsafe.Add(ref mapEntriesRef, (nint)(uint)entryIndex); // The removal logic can be extremely optimized in this case, as we // can retrieve the precomputed hashcode for the target entry by doing // a lookup on the target map node, and we can also skip all the comparisons // while traversing the target chain since we know in advance the index of // the target node which will contain the item to remove from the map. Remove(removedEntry.HashCode, entryIndex); } else { // If the free list is not empty, get that map node and update the field entryIndex = this.count; heapIndex = this.count; } int bucketIndex = hashcode & (this.buckets.Length - 1); ref int targetBucket = ref Unsafe.Add(ref bucketsRef, (nint)(uint)bucketIndex); ref MapEntry targetMapEntry = ref Unsafe.Add(ref mapEntriesRef, (nint)(uint)entryIndex); ref HeapEntry targetHeapEntry = ref Unsafe.Add(ref heapEntriesRef, (nint)(uint)heapIndex); // Assign the values in the new map entry targetMapEntry.HashCode = hashcode; targetMapEntry.Value = value; targetMapEntry.NextIndex = targetBucket - 1; targetMapEntry.HeapIndex = heapIndex; // Update the bucket slot and the current count targetBucket = entryIndex + 1; this.count++; // Link the heap node with the current entry targetHeapEntry.MapIndex = entryIndex; // Update the timestamp and balance the heap again UpdateTimestamp(ref targetMapEntry.HeapIndex); } /// <summary> /// Removes a specified <see cref="string"/> instance from the map to free up one slot. /// </summary> /// <param name="hashcode">The precomputed hashcode of the instance to remove.</param> /// <param name="mapIndex">The index of the target map node to remove.</param> /// <remarks>The input <see cref="string"/> instance needs to already exist in the map.</remarks> [MethodImpl(MethodImplOptions.NoInlining)] private void Remove(int hashcode, int mapIndex) { ref MapEntry mapEntriesRef = ref this.mapEntries.DangerousGetReference(); int bucketIndex = hashcode & (this.buckets.Length - 1), entryIndex = this.buckets.DangerousGetReferenceAt(bucketIndex) - 1, lastIndex = EndOfList; // We can just have an undefined loop, as the input // value we're looking for is guaranteed to be present while (true) { ref MapEntry candidate = ref Unsafe.Add(ref mapEntriesRef, (nint)(uint)entryIndex); // Check the current value for a match if (entryIndex == mapIndex) { // If this was not the first list node, update the parent as well if (lastIndex != EndOfList) { ref MapEntry lastEntry = ref Unsafe.Add(ref mapEntriesRef, (nint)(uint)lastIndex); lastEntry.NextIndex = candidate.NextIndex; } else { // Otherwise, update the target index from the bucket slot this.buckets.DangerousGetReferenceAt(bucketIndex) = candidate.NextIndex + 1; } this.count--; return; } // Move to the following node in the current list lastIndex = entryIndex; entryIndex = candidate.NextIndex; } } /// <summary> /// Updates the timestamp of a heap node at the specified index (which is then synced back). /// </summary> /// <param name="heapIndex">The index of the target heap node to update.</param> [MethodImpl(MethodImplOptions.NoInlining)] private void UpdateTimestamp(ref int heapIndex) { int currentIndex = heapIndex, count = this.count; ref MapEntry mapEntriesRef = ref this.mapEntries.DangerousGetReference(); ref HeapEntry heapEntriesRef = ref this.heapEntries.DangerousGetReference(); ref HeapEntry root = ref Unsafe.Add(ref heapEntriesRef, (nint)(uint)currentIndex); uint timestamp = this.timestamp; // Check if incrementing the current timestamp for the heap node to update // would result in an overflow. If that happened, we could end up violating // the min-heap property (the value of each node has to always be <= than that // of its child nodes), eg. if we were updating a node that was not the root. // In that scenario, we could end up with a node somewhere along the heap with // a value lower than that of its parent node (as the timestamp would be 0). // To guard against this, we just check the current timestamp value, and if // the maximum value has been reached, we reinitialize the entire heap. This // is done in a non-inlined call, so we don't increase the codegen size in this // method. The reinitialization simply traverses the heap in breadth-first order // (ie. level by level), and assigns incrementing timestamps to all nodes starting // from 0. The value of the current timestamp is then just set to the current size. if (timestamp == uint.MaxValue) { // We use a goto here as this path is very rarely taken. Doing so // causes the generated asm to contain a forward jump to the fallback // path if this branch is taken, whereas the normal execution path will // not need to execute any jumps at all. This is done to reduce the overhead // introduced by this check in all the invocations where this point is not reached. goto Fallback; } Downheap: // Assign a new timestamp to the target heap node. We use a // local incremental timestamp instead of using the system timer // as this greatly reduces the overhead and the time spent in system calls. // The uint type provides a large enough range and it's unlikely users would ever // exhaust it anyway (especially considering each map has a separate counter). root.Timestamp = this.timestamp = timestamp + 1; // Once the timestamp is updated (which will cause the heap to become // unbalanced), start a sift down loop to balance the heap again. while (true) { // The heap is 0-based (so that the array length can remain the same // as the power of 2 value used for the other arrays in this type). // This means that children of each node are at positions: // - left: (2 * n) + 1 // - right: (2 * n) + 2 ref HeapEntry minimum = ref root; int left = (currentIndex * 2) + 1, right = (currentIndex * 2) + 2, targetIndex = currentIndex; // Check and update the left child, if necessary if (left < count) { ref HeapEntry child = ref Unsafe.Add(ref heapEntriesRef, (nint)(uint)left); if (child.Timestamp < minimum.Timestamp) { minimum = ref child; targetIndex = left; } } // Same check as above for the right child if (right < count) { ref HeapEntry child = ref Unsafe.Add(ref heapEntriesRef, (nint)(uint)right); if (child.Timestamp < minimum.Timestamp) { minimum = ref child; targetIndex = right; } } // If no swap is pending, we can just stop here. // Before returning, we update the target index as well. if (Unsafe.AreSame(ref root, ref minimum)) { heapIndex = targetIndex; return; } // Update the indices in the respective map entries (accounting for the swap) Unsafe.Add(ref mapEntriesRef, (nint)(uint)root.MapIndex).HeapIndex = targetIndex; Unsafe.Add(ref mapEntriesRef, (nint)(uint)minimum.MapIndex).HeapIndex = currentIndex; currentIndex = targetIndex; // Swap the parent and child (so that the minimum value bubbles up) HeapEntry temp = root; root = minimum; minimum = temp; // Update the reference to the root node root = ref Unsafe.Add(ref heapEntriesRef, (nint)(uint)currentIndex); } Fallback: UpdateAllTimestamps(); // After having updated all the timestamps, if the heap contains N items, the // node in the bottom right corner will have a value of N - 1. Since the timestamp // is incremented by 1 before starting the downheap execution, here we simply // update the local timestamp to be N - 1, so that the code above will set the // timestamp of the node currently being updated to exactly N. timestamp = (uint)(count - 1); goto Downheap; } /// <summary> /// Updates the timestamp of all the current heap nodes in incrementing order. /// The heap is always guaranteed to be complete binary tree, so when it contains /// a given number of nodes, those are all contiguous from the start of the array. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private void UpdateAllTimestamps() { int count = this.count; ref HeapEntry heapEntriesRef = ref this.heapEntries.DangerousGetReference(); for (int i = 0; i < count; i++) { Unsafe.Add(ref heapEntriesRef, (nint)(uint)i).Timestamp = (uint)i; } } } /// <summary> /// Gets the (positive) hashcode for a given <see cref="ReadOnlySpan{T}"/> instance. /// </summary> /// <param name="span">The input <see cref="ReadOnlySpan{T}"/> instance.</param> /// <returns>The hashcode for <paramref name="span"/>.</returns> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int GetHashCode(ReadOnlySpan<char> span) { #if NETSTANDARD1_4 return span.GetDjb2HashCode(); #else return HashCode<char>.Combine(span); #endif } /// <summary> /// Throws an <see cref="ArgumentException"/> when the requested size exceeds the capacity. /// </summary> private static void ThrowArgumentOutOfRangeException() { throw new ArgumentOutOfRangeException("minimumSize", "The requested size must be greater than 0"); } } }
43.51186
136
0.539437
[ "MIT" ]
deanchalk/WindowsCommunityToolk
Microsoft.Toolkit.HighPerformance/Buffers/StringPool.cs
34,853
C#
using System; namespace VBB.Model { public class ChangeLog { public int Id { get; set; } public bool? IsReviewed { get; set; } public DateTime DateChanged { get; set; } public string ChangeType { get; set; } public string ObjectType { get; set; } public int ObjectId { get; set; } public int UpdatedById { get; set; } public virtual Person UpdatedBy { get; set; } } }
18.12
53
0.576159
[ "MIT" ]
mkvster/vobabu
VBB.Model/ChangeLog.cs
453
C#
using System; using System.Diagnostics.CodeAnalysis; namespace FritzBot.Functions { /// <summary> /// Stellt eine Cache Klasse da, die den Cache selbstständig erneuert /// </summary> /// <typeparam name="T">Der Typ der gekapselt werden soll</typeparam> public class DataCache<T> { [AllowNull] private T Item = default; private readonly Func<T, T> ValueFactory; private readonly TimeSpan Expires; public DateTime Renewed { get; protected set; } public Exception? LastUpdateFail { get; protected set; } public bool IsUpToDate => Expires == TimeSpan.Zero || Renewed + Expires >= DateTime.Now; /// <summary> /// Initialisiert eine neue Cache Instanz /// </summary> /// <param name="valueFactory">Die Methode mit der der gekapselte Typ bei Ablauf erneuert werden kann. Erhält als Parameter die gecachten Daten</param> /// <param name="expiresIn">Die Zeit bis der Cache erneuert werden muss oder TimeSpan.Zero wenn er nicht automatisch erneuert werden soll</param> public DataCache(Func<T, T> valueFactory, TimeSpan expiresIn) { ValueFactory = valueFactory; Renewed = DateTime.MinValue; Expires = expiresIn; LastUpdateFail = null; } /// <summary> /// Erneuert den Cache unabhängig davon, ob er bereits abgelaufen ist /// </summary> public void ForceRefresh(bool ignoreUpdateFail) { LastUpdateFail = null; try { T tmp = ValueFactory(Item); if (tmp != null && !tmp.Equals(Item)) { Item = tmp; Renewed = DateTime.Now; } } catch (Exception ex) { LastUpdateFail = ex; if (!ignoreUpdateFail) { throw new RenewalFailedException("Erneuern des Caches fehlgeschlagen", ex); } } } /// <summary> /// Holt den gekapselten Typen aus dem Cache und erneuert ihn wenn er abgelaufen ist /// </summary> public T GetItem(bool ignoreUpdateFail) { if (!IsUpToDate) { ForceRefresh(ignoreUpdateFail); } return Item; } public static implicit operator T(DataCache<T> cache) { return cache.GetItem(true); } } public class RenewalFailedException : Exception { public RenewalFailedException() : base() { } public RenewalFailedException(string message) : base(message) { } public RenewalFailedException(string message, Exception innerException) : base(message, innerException) { } } }
35.148148
159
0.568318
[ "MIT" ]
Suchiman/FritzBot
freetzbot/Functions/DataCache.cs
2,852
C#
using System; using LinkShrink; using Xunit; namespace Tests { public class HashingShrinkerTests { private readonly char[] _saferCharacters = "0123456789ABCDEFGHIJKLMNPQRSTUVWXYZ".ToCharArray(); [Fact] public void UriMatchesAlsoMatchPath() { var uri1 = new Uri("http://google.com"); var uri2 = new Uri("http://google.com"); var shrinkStrategy = new HashingShrinkStrategy(_saferCharacters, 6); var short1 = shrinkStrategy.GetShortPath(uri1); var short2 = shrinkStrategy.GetShortPath(uri2); Assert.Equal(short1, short2); } [Fact] public void DifferingDoesNotMatch() { var uri1 = new Uri("http://google.com"); var uri2 = new Uri("http://bing.com"); var shrinkStrategy = new HashingShrinkStrategy(_saferCharacters, 6); var short1 = shrinkStrategy.GetShortPath(uri1); var short2 = shrinkStrategy.GetShortPath(uri2); Assert.NotEqual(short1, short2); } [Fact] public void SecureAndUnsecureDoesNotMatch() { var uri1 = new Uri("http://google.com"); var uri2 = new Uri("https://google.com"); var shrinkStrategy = new HashingShrinkStrategy(_saferCharacters, 6); var short1 = shrinkStrategy.GetShortPath(uri1); var short2 = shrinkStrategy.GetShortPath(uri2); Assert.NotEqual(short1, short2); } } }
30.56
103
0.598822
[ "MIT" ]
joshbannon/simple-url-shortener
UrlShortener/Tests/HashingShrinkerTests.cs
1,530
C#
using SportscardSystem.DTO.Contracts; using System.Collections.Generic; using System.Linq; using SportscardSystem.Data.Contracts; using System; using SportscardSystem.DTO; using SportscardSystem.Models; namespace SportscardSystem.Logic.Services.Contracts { public interface IClientService { /// <summary> /// Gets all clients registered in the database /// </summary> /// <returns></returns> IEnumerable<IClientDto> GetAllClients(); /// <summary> /// Adds a new client to the database /// </summary> /// <param name="client"></param> void AddClient(IClientDto clientDto); /// <summary> /// Deletes a specified client from the database /// </summary> /// <param name="client"></param> void DeleteClient(string firstName, string lastName, int? age); /// <summary> /// Gets the client/s with the most visits /// </summary> /// <returns></returns> IClientDto GetMostActiveClient(); //IQueryable<IClientDto> GetMostActiveClient(); Guid GetCompanyGuidByName(string companyName); } }
27.465116
71
0.619814
[ "MIT" ]
the-hushed-cobras/Sportscard-Project
SportscardSystem.Logic/Services/Contracts/IClientService.cs
1,183
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using TButt; namespace TButt.Services { public class TBServiceBase : MonoBehaviour { protected string _username = "null"; protected bool _ready; /// <summary> /// Establishes connections, checks entitlements, and populates user IDs with the service. /// </summary> public virtual void Initialize() { CheckEntitlement(); PopulateUserData(); } protected virtual void CheckEntitlement() { throw new System.NotImplementedException(); } protected virtual void PopulateUserData() { throw new System.NotImplementedException(); } protected void SetReady(bool on) { _ready = on; if(on) TBLogging.LogMessage("Service is ready! Local instances populated."); } protected virtual void EvalEntitlement(bool passed) { if (passed) { Debug.Log("Verified entitlement check for " + TBServiceManager.GetActiveService()); TBServiceManager.OnEntitlementCheckComplete(); } else { Debug.LogError("Failed entitlement check for " + TBServiceManager.GetActiveService()); if (TBServiceManager.Events.OnEntitlementCheckComplete != null) TBServiceManager.Events.OnEntitlementCheckComplete(false); else Application.Quit(); } } public virtual string GetUsername() { return _username; } public virtual bool IsReady() { return _ready; } /// <summary> /// Tells a service to unlock an achievement. /// </summary> /// <param name="token"></param> public virtual void UnlockAchievement(string token) { throw new System.NotImplementedException(); } /// <summary> /// Gets the full dictionary of achievement names and their unlock status from the service. /// </summary> /// <returns></returns> public virtual Dictionary<string, bool> GetAchievementDictionary() { throw new System.NotImplementedException(); } } }
28.209302
102
0.559357
[ "MIT" ]
jeff-chamberlain/tbutt-vr
Source/Assets/TButt/Services/TBServiceBase.cs
2,428
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace SkyBlueBlue { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
24.28
76
0.693575
[ "MIT" ]
15093015999/Kalearn
Program.cs
609
C#
//using AutoMapper.Configuration; using Microsoft.Extensions.Configuration; using AutoMapper.QueryableExtensions; using Microsoft.EntityFrameworkCore; using Nsiclass.Data; using Nsiclass.Data.Models; using Nsiclass.Services.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Nsiclass.Services.Implementations { public class AdminVersionService : IAdminVersionService { private readonly ClassDbContext db; public AdminVersionService(ClassDbContext db, IConfiguration configuration) { this.db = db; this.Configuration = configuration; } public IConfiguration Configuration { get; } public async Task<IEnumerable<string>> GetVersionNamesByClassAsync(string classCode) { var names = await this.db.ClassVersions.Where(c => c.isDeleted == false & c.Classif == classCode).Select(c => c.Version).ToListAsync(); return names; } public async Task<string> DeleteClassVersionAsync(string classCode, string versionCode) { if (await this.IsClassVersionExistAsync(classCode, versionCode) == false) { return $"Грешка!!! Няма версия с код: {classCode} {versionCode}"; } if (await this.IsClassVersionDeletedAsync(classCode, versionCode)) { return $"Информация!!! Версия с код: {classCode} {versionCode} вече е била маркирана като изтрита успешно"; } await this.db.Database.BeginTransactionAsync(); try { this.db.ClassRelations.Where(r => (r.SrcClassif == classCode && r.SrcVer == versionCode) || (r.DestClassif == classCode && r.DestVer == versionCode)).ToList().ForEach(r => r.IsDeleted = true); await this.db.SaveChangesAsync(); this.db.ClassRelationsTypes.Where(r => (r.SrcClassifId == classCode && r.SrcVersionId == versionCode) || (r.DestClassifId == classCode && r.DestVersionId == versionCode)).ToList() .ForEach(r => r.IsDeleted = true); await this.db.SaveChangesAsync(); this.db.ClassItems.Where(i => i.Classif == classCode && i.Version == versionCode).ToList().ForEach(r => r.IsDeleted = true); await this.db.SaveChangesAsync(); this.db.ClassVersions.Where(i => i.Classif == classCode && i.Version == versionCode).ToList().ForEach(r => r.isDeleted = true); await this.db.SaveChangesAsync(); } catch (Exception) { this.db.Database.RollbackTransaction(); return $"Грешка!!! Възникна проблем при изтриването на версията."; } this.db.Database.CommitTransaction(); return $"Версия с код: {classCode} {versionCode} беше изтрита успешно"; } public async Task<string> RestoreClassVersionAsync(string classCode, string versionCode) { if (await this.IsClassVersionExistAsync(classCode, versionCode) == false) { return $"Грешка!!! Няма версия с код: {classCode} {versionCode}"; } if (!await this.IsClassVersionDeletedAsync(classCode, versionCode)) { return $"Информация!!! Версия с код: {classCode} {versionCode} е активна"; } await this.db.Database.BeginTransactionAsync(); try { this.db.ClassVersions.Where(i => i.Classif == classCode && i.Version == versionCode).ToList().ForEach(r => r.isDeleted = false); await this.db.SaveChangesAsync(); this.db.ClassItems.Where(i => i.Classif == classCode && i.Version == versionCode).ToList().ForEach(r => r.IsDeleted = false); await this.db.SaveChangesAsync(); this.db.ClassRelationsTypes.Where(r => (r.SrcClassifId == classCode && r.SrcVersionId == versionCode) || (r.DestClassifId == classCode && r.DestVersionId == versionCode)).ToList() .ForEach(r => r.IsDeleted = false); await this.db.SaveChangesAsync(); this.db.ClassRelations.Where(r => (r.SrcClassif == classCode && r.SrcVer == versionCode) || (r.DestClassif == classCode && r.DestVer == versionCode)).ToList().ForEach(r => r.IsDeleted = false); await this.db.SaveChangesAsync(); } catch (Exception) { this.db.Database.RollbackTransaction(); return $"Грешка!!! Възникна проблем при възстановяването на версията."; } this.db.Database.CommitTransaction(); return $"Версия с код: {classCode} {versionCode} беше възстановена успешно"; } public async Task<bool> IsClassVersionDeletedAsync(string classCode, string versionCode) { var result = await this.db.ClassVersions.Where(c => c.Classif == classCode && c.Version == versionCode && c.isDeleted == true).FirstOrDefaultAsync(); if (result != null) { return true; } else { return false; } } public async Task<string> EditVersionAsync(string classif, string version, string parent, string publications, string remarks, string byLow, DateTime valid_From, DateTime? valid_To, string useAreas) { try { var currentVersion = await this.db.ClassVersions.Where(v => v.Classif == classif && v.Version == version).FirstOrDefaultAsync(); if (currentVersion == null) { return $"Няма класификационна версия {classif} {version}"; } currentVersion.Valid_From = valid_From; currentVersion.Valid_To = valid_To; currentVersion.Parent = parent; currentVersion.Publications = publications; currentVersion.Remarks = remarks; currentVersion.ByLow = byLow; currentVersion.UseAreas = useAreas; await this.db.SaveChangesAsync(); } catch (Exception) { return $"Неуспешен запис"; } return "Редакцията е успешна"; } public async Task<VersionServiceModel> GetVersionDetailsAsync(string classCode, string versionCode) { var result = await this.db.ClassVersions .Where(c => c.Classif == classCode && c.Version == versionCode) .ProjectTo<VersionServiceModel>() .FirstOrDefaultAsync(); return result; } public async Task<bool> IsClassVersionExistAsync(string classCode, string versionCode) { var currentVersion = await this.db.ClassVersions.Where(v => v.Classif == classCode && v.Version == versionCode).FirstOrDefaultAsync(); if (currentVersion == null) { return false; } return true; } public async Task<bool> IsClassVersionActiveAsync(string classCode, string versionCode) { var currentVersion = await this.db.ClassVersions.Where(v => v.Classif == classCode && v.Version == versionCode).FirstOrDefaultAsync(); if (currentVersion.isActive) { return true; } return false; } public async Task<string> ActivateClassVersionAsync(string classCode, string versionCode) { if (await this.IsClassVersionExistAsync(classCode, versionCode) == false) { return $"Грешка!!! Няма версия с код: {classCode} {versionCode}"; } var currentVersion = await this.db.ClassVersions.Where(v => v.Classif == classCode && v.Version == versionCode).FirstOrDefaultAsync(); if (currentVersion.isActive) { return $"Информация!!! Версия с код: {classCode} {versionCode} е активна вече"; } currentVersion.isActive = true; await this.db.SaveChangesAsync(); return "Активирането е успешно"; } public async Task<string> DeactivateClassVersionAsync(string classCode, string versionCode) { if (await this.IsClassVersionExistAsync(classCode, versionCode) == false) { return $"Грешка!!! Няма версия с код: {classCode} {versionCode}"; } var currentVersion = await this.db.ClassVersions.Where(v => v.Classif == classCode && v.Version == versionCode).FirstOrDefaultAsync(); if (!currentVersion.isActive) { return $"Информация!!! Версия с код: {classCode} {versionCode} е вече деактивирана"; } currentVersion.isActive = false; await this.db.SaveChangesAsync(); return "Деактивирането е успешно"; } public async Task<string> CreateCopyVersionAsync(string classCode, string versionCode, string newVersion, string userId, bool copyRelations) { if (await this.IsClassVersionExistAsync(classCode, versionCode) == false) { return $"Грешка!!! Няма версия източник с код: {classCode} {versionCode}"; } if (await this.IsClassVersionExistAsync(classCode, newVersion) == true) { return $"Грешка!!! Вече има версия с код: {classCode} {newVersion}"; } var sourceVersion = await this.db.ClassVersions.Where(v => v.Classif == classCode && v.Version == versionCode).FirstOrDefaultAsync(); var brandNewVersion = new TC_Classif_Vers() { Classif = sourceVersion.Classif, Version = newVersion, Remarks = sourceVersion.Remarks, ByLow = sourceVersion.ByLow, Publications = sourceVersion.Publications, UseAreas = sourceVersion.UseAreas, Parent = sourceVersion.Parent, Valid_From = sourceVersion.Valid_From, Valid_To = sourceVersion.Valid_To }; var connectionString = Configuration.GetSection("ConnectionStrings:DefaultConnection").Value; SqlConnection con = new SqlConnection(connectionString); SqlCommand com = new SqlCommand("ALTER TABLE ClassItems NOCHECK CONSTRAINT FK_ClassItems_ClassItems_Classif_Version_ParentItemCode"); SqlCommand comend = new SqlCommand("ALTER TABLE ClassItems CHECK CONSTRAINT FK_ClassItems_ClassItems_Classif_Version_ParentItemCode"); com.Connection = con; comend.Connection = con; con.Open(); com.ExecuteNonQuery(); await this.db.Database.BeginTransactionAsync(); try { await this.db.ClassVersions.AddAsync(brandNewVersion); await this.db.SaveChangesAsync(); var items = await this.db.ClassItems.Where(i => i.Classif == classCode && i.Version == versionCode).ToListAsync(); foreach (var item in items) { var newItem = new TC_Classif_Items() { Classif = item.Classif, Version = brandNewVersion.Version, Description = item.Description, DescriptionShort = item.DescriptionShort, DescriptionEng = item.DescriptionEng, Includes = item.Includes, IncludesMore = item.IncludesMore, IncludesNo = item.IncludesNo, IsLeaf = item.IsLeaf, ItemCode = item.ItemCode, ItemLevel = item.ItemLevel, EntryTime = DateTime.Now, IsDeleted = item.IsDeleted, OrderNo = item.OrderNo, OtherCode = item.OtherCode, ParentItemCode = item.ParentItemCode, EnteredByUserId = userId, }; await this.db.ClassItems.AddAsync(newItem); } await this.db.SaveChangesAsync(); } catch (Exception) { this.db.Database.RollbackTransaction(); comend.ExecuteNonQuery(); con.Close(); return $"Грешка!!! Възникна проблем при създаването на новата версия."; } this.db.Database.CommitTransaction(); comend.ExecuteNonQuery(); con.Close(); var result = $"Версия с код: {classCode} {newVersion} беше създадена успешно \n"; if (copyRelations) { await this.db.Database.BeginTransactionAsync(); try { var sourceRelations = await this.db.ClassRelationsTypes.Where(r => r.SrcClassifId == classCode && r.SrcVersionId == versionCode).ToListAsync(); var destRelations = await this.db.ClassRelationsTypes.Where(r => r.DestClassifId == classCode && r.DestVersionId == versionCode).ToListAsync(); foreach (var rel in sourceRelations) { var newRelationType = new TC_Classif_Rel_Types() { SrcClassifId = classCode, SrcVersionId = newVersion, DestClassifId = rel.DestClassifId, DestVersionId = rel.DestVersionId, Description = $"Копие от релация \"{rel.Description}\". Сменена версия \"{versionCode}\" с версия \"{newVersion}\"", Valid_From = rel.Valid_From, Valid_To = rel.Valid_To }; await this.db.ClassRelationsTypes.AddAsync(newRelationType); await this.db.SaveChangesAsync(); var relItemsList = await this.db.ClassRelations.Where(ri => ri.RelationTypeId == rel.Id).ToListAsync(); foreach (var relItem in relItemsList) { var newRelation = new TC_Classif_Rels() { RelationTypeId = newRelationType.Id, SrcClassif = relItem.SrcClassif, SrcVer = newRelationType.SrcVersionId, SrcItemId = relItem.SrcItemId, DestClassif = relItem.DestClassif, DestVer = relItem.DestVer, DestItemId = relItem.DestItemId, EntryTime = DateTime.Now, EnteredByUserId = userId }; await this.db.ClassRelations.AddAsync(newRelation); } await this.db.SaveChangesAsync(); } foreach (var rel in destRelations) { var newRelationType = new TC_Classif_Rel_Types() { SrcClassifId = classCode, SrcVersionId = rel.SrcVersionId, DestClassifId = rel.DestClassifId, DestVersionId = newVersion, Description = $"Копие от релация \"{rel.Description}\". Сменена версия \"{versionCode}\" с версия \"{newVersion}\"", Valid_From = rel.Valid_From, Valid_To = rel.Valid_To }; await this.db.ClassRelationsTypes.AddAsync(newRelationType); await this.db.SaveChangesAsync(); var relItemsList = await this.db.ClassRelations.Where(ri => ri.RelationTypeId == rel.Id).ToListAsync(); foreach (var relItem in relItemsList) { var newRelation = new TC_Classif_Rels() { RelationTypeId = newRelationType.Id, SrcClassif = relItem.SrcClassif, SrcVer = relItem.SrcVer, SrcItemId = relItem.SrcItemId, DestClassif = relItem.DestClassif, DestVer = newRelationType.DestVersionId, DestItemId = relItem.DestItemId, EntryTime = DateTime.Now, EnteredByUserId = userId }; await this.db.ClassRelations.AddAsync(newRelation); } await this.db.SaveChangesAsync(); } } catch (Exception) { this.db.Database.RollbackTransaction(); return result + $"Грешка!!! Възникна проблем при копирането релационните таблици."; } this.db.Database.CommitTransaction(); result = result + Environment.NewLine + $"Копирането на релационните таблици беше успешно."; } return result; } public async Task<string> TotalDeleteClassVersionAsync(string classCode, string versionCode) { if (await this.IsClassVersionExistAsync(classCode, versionCode) == false) { return $"Грешка!!! Няма версия с код: {classCode} {versionCode}"; } await this.db.Database.BeginTransactionAsync(); try { var relItems = this.db.ClassRelations.Where(r => (r.SrcClassif == classCode && r.SrcVer == versionCode) || (r.DestClassif == classCode && r.DestVer == versionCode)).ToList(); this.db.ClassRelations.RemoveRange(relItems); await this.db.SaveChangesAsync(); this.db.ClassRelationsTypes.Where(r => (r.SrcClassifId == classCode && r.SrcVersionId == versionCode) || (r.DestClassifId == classCode && r.DestVersionId == versionCode)).ToList() .ForEach(r => this.db.ClassRelationsTypes.Remove(r)); await this.db.SaveChangesAsync(); var items = this.db.ClassItems.Where(i => i.Classif == classCode && i.Version == versionCode).ToList(); this.db.ClassItems.RemoveRange(items); await this.db.SaveChangesAsync(); this.db.ClassVersions.Where(i => i.Classif == classCode && i.Version == versionCode).ToList().ForEach(r => this.db.ClassVersions.Remove(r)); await this.db.SaveChangesAsync(); } catch (Exception) { this.db.Database.RollbackTransaction(); return $"Грешка!!! Възникна проблем при изтриването на версията."; } this.db.Database.CommitTransaction(); return $"Версия с код: {classCode} {versionCode} беше тотално изтрита успешно"; } } }
46.29108
209
0.543611
[ "MIT" ]
moher4o/NSIClass
Nsiclass.Services/Implementations/AdminVersionService.cs
20,603
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.12 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace EliteQuant { public class Actual365NoLeap : DayCounter { private global::System.Runtime.InteropServices.HandleRef swigCPtr; internal Actual365NoLeap(global::System.IntPtr cPtr, bool cMemoryOwn) : base(NQuantLibcPINVOKE.Actual365NoLeap_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Actual365NoLeap obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~Actual365NoLeap() { Dispose(); } public override void Dispose() { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; NQuantLibcPINVOKE.delete_Actual365NoLeap(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } global::System.GC.SuppressFinalize(this); base.Dispose(); } } public Actual365NoLeap() : this(NQuantLibcPINVOKE.new_Actual365NoLeap(), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } } }
34.367347
144
0.648456
[ "Apache-2.0" ]
qg0/EliteQuant_Excel
SwigConversionLayer/csharp/Actual365NoLeap.cs
1,684
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace Makaretu.Dns { [TestClass] public class NSRecordTest { [TestMethod] public void Roundtrip() { var a = new NSRecord { Name = "emanon.org", Authority = "mydomain.name" }; var b = (NSRecord)new ResourceRecord().Read(a.ToByteArray()); Assert.AreEqual(a.Name, b.Name); Assert.AreEqual(a.Class, b.Class); Assert.AreEqual(a.Type, b.Type); Assert.AreEqual(a.TTL, b.TTL); Assert.AreEqual(a.Authority, b.Authority); } [TestMethod] public void Roundtrip_Master() { var a = new NSRecord { Name = "emanon.org", Authority = "mydomain.name" }; var b = (NSRecord)new ResourceRecord().Read(a.ToString()); Assert.AreEqual(a.Name, b.Name); Assert.AreEqual(a.Class, b.Class); Assert.AreEqual(a.Type, b.Type); Assert.AreEqual(a.TTL, b.TTL); Assert.AreEqual(a.Authority, b.Authority); } [TestMethod] public void Equality() { var a = new NSRecord { Name = "emanon.org", Authority = "mydomain.name" }; var b = new NSRecord { Name = "emanon.org", Authority = "mydomainx.name" }; Assert.IsTrue(a.Equals(a)); Assert.IsFalse(a.Equals(b)); Assert.IsFalse(a.Equals(null)); } } }
27.169231
73
0.492072
[ "MIT" ]
TheDuQe/net-dns
test/NSRecordTest.cs
1,768
C#
// <copyright file="IDistributionData.cs" company="OpenCensus Authors"> // Copyright 2018, OpenCensus Authors // // 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. // </copyright> namespace OpenCensus.Stats.Aggregations { using System.Collections.Generic; /// <summary> /// Data accumulated by distributed aggregation. /// </summary> public interface IDistributionData : IAggregationData { /// <summary> /// Gets the mean of values. /// </summary> double Mean { get; } /// <summary> /// Gets the number of samples. /// </summary> long Count { get; } /// <summary> /// Gets the minimum of values. /// </summary> double Min { get; } /// <summary> /// Gets the maximum of values. /// </summary> double Max { get; } /// <summary> /// Gets the sum of squares of values. /// </summary> double SumOfSquaredDeviations { get; } /// <summary> /// Gets the counts in buckets. /// </summary> IReadOnlyList<long> BucketCounts { get; } } }
29.087719
75
0.607358
[ "Apache-2.0" ]
PriceSpider-NeuIntel/opencensus-csharp
src/OpenCensus.Abstractions/Stats/Aggregations/IDistributionData.cs
1,660
C#
using AkkoCore.Commands.Abstractions; using AkkoCore.Commands.Modules.Utilities.Services; using AkkoCore.Common; using AkkoCore.Extensions; using AkkoCore.Models.Serializable; using AkkoCore.Services.Caching.Abstractions; using AkkoCore.Services.Database.Entities; using AkkoCore.Services.Timers.Abstractions; using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using Kotz.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AkkoCore.Commands.Modules.Utilities; [Group("repeat")] [Description("cmd_repeat")] [RequireUserPermissions(Permissions.ManageMessages)] public sealed class Repeaters : AkkoCommandModule { private readonly IAkkoCache _akkoCache; private readonly RepeaterService _service; public Repeaters(IAkkoCache akkoCache, RepeaterService service) { _akkoCache = akkoCache; _service = service; } [Command("here")] [Description("cmd_repeat_here")] public async Task AddDailyRepeaterAsync(CommandContext context, [Description("arg_time_of_day")] TimeOfDay timeOfDay, [RemainingText, Description("arg_repeat_message")] string message) { var success = await _service.AddRepeaterAsync(context, context.Channel, timeOfDay.Interval, message, timeOfDay); await context.Message.CreateReactionAsync((success) ? AkkoStatics.SuccessEmoji : AkkoStatics.FailureEmoji); } [Command("here")] public async Task AddRepeaterAsync(CommandContext context, [Description("arg_repeat_time")] TimeSpan time, [RemainingText, Description("arg_repeat_message")] string message) { var success = await _service.AddRepeaterAsync(context, context.Channel, time, message); await context.Message.CreateReactionAsync((success) ? AkkoStatics.SuccessEmoji : AkkoStatics.FailureEmoji); } [GroupCommand, Command("channel")] public async Task AddDailyChannelRepeaterAsync(CommandContext context, [Description("arg_discord_channel")] DiscordChannel channel, [Description("arg_time_of_day")] TimeOfDay timeOfDay, [RemainingText, Description("arg_repeat_message")] string message) { var success = await _service.AddRepeaterAsync(context, channel, timeOfDay.Interval, message, timeOfDay); await context.Message.CreateReactionAsync((success) ? AkkoStatics.SuccessEmoji : AkkoStatics.FailureEmoji); } [GroupCommand, Command("channel")] [Description("cmd_repeat_channel")] public async Task AddChannelRepeaterAsync(CommandContext context, [Description("arg_discord_channel")] DiscordChannel channel, [Description("arg_repeat_time")] TimeSpan time, [RemainingText, Description("arg_repeat_message")] string message) { var success = await _service.AddRepeaterAsync(context, channel, time, message); await context.Message.CreateReactionAsync((success) ? AkkoStatics.SuccessEmoji : AkkoStatics.FailureEmoji); } [Command("remove"), Aliases("rm")] [Description("cmd_repeat_remove")] public async Task RemoveRepeaterAsync(CommandContext context, [Description("arg_uint")] int id) { var success = await _service.RemoveRepeaterAsync(context.Guild, id); await context.Message.CreateReactionAsync((success) ? AkkoStatics.SuccessEmoji : AkkoStatics.FailureEmoji); } [Command("clear")] [Description("cmd_repeat_clear")] public async Task ClearRepeatersAsync(CommandContext context) { var success = await _service.ClearRepeatersAsync(context.Guild); await context.Message.CreateReactionAsync((success) ? AkkoStatics.SuccessEmoji : AkkoStatics.FailureEmoji); } [Command("info")] [Description("cmd_repeat_info")] public async Task RepeaterInfoAsync(CommandContext context, [Description("arg_uint")] int id) { var embed = new SerializableDiscordEmbed(); var repeaters = _service.GetRepeaters(context.Guild, x => x.Id == id); var isEmpty = repeaters is null or { Count: 0 }; if (isEmpty) embed.WithDescription(context.FormatLocalized("repeater_not_found", id)); else { var repeater = repeaters![0]; _akkoCache.Timers.TryGetValue(repeater.TimerIdFK, out var timer); var member = await context.Guild.GetMemberSafelyAsync(repeater.AuthorId); var (dbTimer, dbUser) = await _service.GetRepeaterExtraInfoAsync(timer, repeater, member); embed.WithTitle(context.FormatLocalized("repeater") + $" #{repeater.Id}") .WithDescription(Formatter.BlockCode(repeater.Content, "yaml")) .AddField("interval", repeater.Interval.ToString(@"%d\d\ %h\h\ %m\m\ %s\s"), true) .AddField("triggers_on", (timer?.ElapseAt ?? dbTimer!.ElapseAt).ToOffset(context.GetTimeZone().BaseUtcOffset).ToDiscordTimestamp(), true) .AddField("triggers_in", DateTimeOffset.Now.Add(timer?.ElapseIn ?? dbTimer!.ElapseIn).ToDiscordTimestamp(TimestampFormat.RelativeTime), true) .AddField("author", member?.GetFullname() ?? dbUser!.FullName, true) .AddField("channel", $"<#{repeater.ChannelId}>", true); } await context.RespondLocalizedAsync(embed, isEmpty, isEmpty); } [Command("list"), Aliases("show")] [Description("cmd_repeat_list")] public async Task ListRepeatersAsync(CommandContext context) { var repeaters = _service.GetRepeaters( context.Guild, null, x => new RepeaterEntity() { Id = x.Id, TimerIdFK = x.TimerIdFK, Content = x.Content, ChannelId = x.ChannelId } ); var embed = new SerializableDiscordEmbed(); if (repeaters.Count is 0) { embed.WithDescription("repeat_list_empty"); await context.RespondLocalizedAsync(embed, isError: true); } else { var timers = new List<IAkkoTimer?>(repeaters.Count); foreach (var repeater in repeaters) { timers.Add( (_akkoCache.Timers.TryGetValue(repeater.TimerIdFK, out var timer)) ? timer : default ); } embed.WithTitle("repeater_list_title") .AddField("message", string.Join("\n", repeaters.Select(x => (Formatter.Bold($"{x.Id}. ") + x.Content).MaxLength(50, AkkoConstants.EllipsisTerminator))), true) .AddField("channel", string.Join("\n", repeaters.Select(x => $"<#{x.ChannelId}>")), true) .AddField("triggers_in", string.Join("\n", timers.Select(x => (x is null) ? context.FormatLocalized("repeat_over_24h") : DateTimeOffset.Now.Add(x.ElapseIn).ToDiscordTimestamp(TimestampFormat.RelativeTime))), true); await context.RespondLocalizedAsync(embed); } } }
44.11875
230
0.678566
[ "Apache-2.0" ]
Akko-Bot/AkkoBot
AkkoCore/Commands/Modules/Utilities/Repeaters.cs
7,059
C#
using MasterDevs.ChromeDevTools; using Newtonsoft.Json; using System; using System.Collections.Generic; namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Overlay { /// <summary> /// Enters the 'inspect' mode. In this mode, elements that user is hovering over are highlighted. Backend then generates 'inspectNodeRequested' event upon element selection. /// </summary> [Command(ProtocolName.Overlay.SetInspectMode)] [SupportedBy("Chrome")] public class SetInspectModeCommand: ICommand<SetInspectModeCommandResponse> { /// <summary> /// Gets or sets Set an inspection mode. /// </summary> public string Mode { get; set; } /// <summary> /// Gets or sets A descriptor for the highlight appearance of hovered-over nodes. May be omitted if <code>enabled == false</code>. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public HighlightConfig HighlightConfig { get; set; } } }
35.615385
174
0.7473
[ "MIT" ]
Digitalbil/ChromeDevTools
source/ChromeDevTools/Protocol/Chrome/Overlay/SetInspectModeCommand.cs
926
C#
using System; using MessagePack; namespace Lykke.Job.ForwardWithdrawalResolver.Sagas.Commands { [MessagePackObject(true)] public class ProcessPaymentCommand { public string Id { set; get; } public string ClientId { set; get; } public string AssetId { set; get; } public double Amount { set; get; } public Guid NewCashinId { get; set; } public string CashinId { get; set; } } }
27.625
60
0.640271
[ "MIT" ]
LykkeCity/Lykke.Job.ForwardWithdrawalResolver
src/Lykke.Job.ForwardWithdrawalResolver/Sagas/Commands/ProcessPaymentCommand.cs
444
C#
namespace UnityModManagerNet.Installer { partial class UnityModManagerForm { /// <summary> /// Обязательная переменная конструктора. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Освободить все используемые ресурсы. /// </summary> /// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Код, автоматически созданный конструктором форм Windows /// <summary> /// Требуемый метод для поддержки конструктора — не изменяйте /// содержимое этого метода с помощью редактора кода. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UnityModManagerForm)); this.panelMain = new System.Windows.Forms.Panel(); this.splitContainerMain = new System.Windows.Forms.SplitContainer(); this.tabControl = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.btnRestore = new System.Windows.Forms.Button(); this.btnDownloadUpdate = new System.Windows.Forms.Button(); this.btnRemove = new System.Windows.Forms.Button(); this.btnOpenFolder = new System.Windows.Forms.Button(); this.gameList = new System.Windows.Forms.ComboBox(); this.btnInstall = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.currentVersion = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.installedVersion = new System.Windows.Forms.Label(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.splitContainerMods = new System.Windows.Forms.SplitContainer(); this.listMods = new System.Windows.Forms.ListView(); this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.ModcontextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.installToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.updateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.revertToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.uninstallToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.wwwToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.splitContainerModsInstall = new System.Windows.Forms.SplitContainer(); this.btnModInstall = new System.Windows.Forms.Button(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.inputLog = new System.Windows.Forms.TextBox(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.statusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog(); this.modInstallFileDialog = new System.Windows.Forms.OpenFileDialog(); this.panelMain.SuspendLayout(); this.splitContainerMain.Panel1.SuspendLayout(); this.splitContainerMain.Panel2.SuspendLayout(); this.splitContainerMain.SuspendLayout(); this.tabControl.SuspendLayout(); this.tabPage1.SuspendLayout(); this.tabPage2.SuspendLayout(); this.splitContainerMods.Panel1.SuspendLayout(); this.splitContainerMods.Panel2.SuspendLayout(); this.splitContainerMods.SuspendLayout(); this.ModcontextMenuStrip1.SuspendLayout(); this.splitContainerModsInstall.Panel1.SuspendLayout(); this.splitContainerModsInstall.SuspendLayout(); this.tabPage3.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.SuspendLayout(); // // panelMain // this.panelMain.Controls.Add(this.splitContainerMain); this.panelMain.Dock = System.Windows.Forms.DockStyle.Fill; this.panelMain.Location = new System.Drawing.Point(0, 0); this.panelMain.Name = "panelMain"; this.panelMain.Size = new System.Drawing.Size(326, 398); this.panelMain.TabIndex = 3; // // splitContainerMain // this.splitContainerMain.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainerMain.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; this.splitContainerMain.IsSplitterFixed = true; this.splitContainerMain.Location = new System.Drawing.Point(0, 0); this.splitContainerMain.Margin = new System.Windows.Forms.Padding(0); this.splitContainerMain.Name = "splitContainerMain"; this.splitContainerMain.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainerMain.Panel1 // this.splitContainerMain.Panel1.Controls.Add(this.tabControl); // // splitContainerMain.Panel2 // this.splitContainerMain.Panel2.Controls.Add(this.statusStrip1); this.splitContainerMain.Panel2MinSize = 20; this.splitContainerMain.Size = new System.Drawing.Size(326, 398); this.splitContainerMain.SplitterDistance = 374; this.splitContainerMain.TabIndex = 11; // // tabControl // this.tabControl.Controls.Add(this.tabPage1); this.tabControl.Controls.Add(this.tabPage2); this.tabControl.Controls.Add(this.tabPage3); this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.tabControl.Location = new System.Drawing.Point(0, 0); this.tabControl.Margin = new System.Windows.Forms.Padding(0); this.tabControl.Name = "tabControl"; this.tabControl.Padding = new System.Drawing.Point(0, 4); this.tabControl.SelectedIndex = 0; this.tabControl.Size = new System.Drawing.Size(326, 374); this.tabControl.SizeMode = System.Windows.Forms.TabSizeMode.Fixed; this.tabControl.TabIndex = 10; this.tabControl.SelectedIndexChanged += new System.EventHandler(this.tabs_Changed); // // tabPage1 // this.tabPage1.BackColor = System.Drawing.Color.WhiteSmoke; this.tabPage1.Controls.Add(this.btnRestore); this.tabPage1.Controls.Add(this.btnDownloadUpdate); this.tabPage1.Controls.Add(this.btnRemove); this.tabPage1.Controls.Add(this.btnOpenFolder); this.tabPage1.Controls.Add(this.gameList); this.tabPage1.Controls.Add(this.btnInstall); this.tabPage1.Controls.Add(this.label3); this.tabPage1.Controls.Add(this.currentVersion); this.tabPage1.Controls.Add(this.label2); this.tabPage1.Controls.Add(this.installedVersion); this.tabPage1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.tabPage1.Location = new System.Drawing.Point(4, 28); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(318, 342); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Install"; // // btnRestore // this.btnRestore.AutoSize = true; this.btnRestore.Dock = System.Windows.Forms.DockStyle.Top; this.btnRestore.Enabled = false; this.btnRestore.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.btnRestore.Location = new System.Drawing.Point(3, 93); this.btnRestore.Name = "btnRestore"; this.btnRestore.Size = new System.Drawing.Size(312, 45); this.btnRestore.TabIndex = 13; this.btnRestore.Text = "Restore original files"; this.btnRestore.UseMnemonic = false; this.btnRestore.UseVisualStyleBackColor = true; this.btnRestore.Click += new System.EventHandler(this.btnRestore_Click); // // btnDownloadUpdate // this.btnDownloadUpdate.AutoSize = true; this.btnDownloadUpdate.BackColor = System.Drawing.Color.PaleGreen; this.btnDownloadUpdate.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.btnDownloadUpdate.Location = new System.Drawing.Point(190, 178); this.btnDownloadUpdate.Name = "btnDownloadUpdate"; this.btnDownloadUpdate.Size = new System.Drawing.Size(122, 26); this.btnDownloadUpdate.TabIndex = 12; this.btnDownloadUpdate.Text = "Download update"; this.btnDownloadUpdate.UseMnemonic = false; this.btnDownloadUpdate.UseVisualStyleBackColor = false; this.btnDownloadUpdate.Visible = false; this.btnDownloadUpdate.Click += new System.EventHandler(this.btnDownloadUpdate_Click); // // btnRemove // this.btnRemove.AutoSize = true; this.btnRemove.Dock = System.Windows.Forms.DockStyle.Top; this.btnRemove.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.btnRemove.Location = new System.Drawing.Point(3, 48); this.btnRemove.Name = "btnRemove"; this.btnRemove.Size = new System.Drawing.Size(312, 45); this.btnRemove.TabIndex = 2; this.btnRemove.Text = "Uninstall"; this.btnRemove.UseMnemonic = false; this.btnRemove.UseVisualStyleBackColor = true; this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); // // btnOpenFolder // this.btnOpenFolder.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.btnOpenFolder.Location = new System.Drawing.Point(5, 178); this.btnOpenFolder.Name = "btnOpenFolder"; this.btnOpenFolder.Size = new System.Drawing.Size(171, 26); this.btnOpenFolder.TabIndex = 9; this.btnOpenFolder.Text = "Select Game Folder"; this.btnOpenFolder.UseVisualStyleBackColor = true; this.btnOpenFolder.Click += new System.EventHandler(this.btnOpenFolder_Click); // // gameList // this.gameList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.gameList.FormattingEnabled = true; this.gameList.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.gameList.Location = new System.Drawing.Point(6, 147); this.gameList.Name = "gameList"; this.gameList.Size = new System.Drawing.Size(169, 21); this.gameList.Sorted = true; this.gameList.TabIndex = 8; this.gameList.SelectedIndexChanged += new System.EventHandler(this.gameList_Changed); // // btnInstall // this.btnInstall.AutoSize = true; this.btnInstall.Dock = System.Windows.Forms.DockStyle.Top; this.btnInstall.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.btnInstall.Location = new System.Drawing.Point(3, 3); this.btnInstall.Margin = new System.Windows.Forms.Padding(5); this.btnInstall.Name = "btnInstall"; this.btnInstall.Size = new System.Drawing.Size(312, 45); this.btnInstall.TabIndex = 1; this.btnInstall.Text = "Install"; this.btnInstall.UseMnemonic = false; this.btnInstall.UseVisualStyleBackColor = true; this.btnInstall.Click += new System.EventHandler(this.btnInstall_Click); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(187, 160); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(87, 13); this.label3.TabIndex = 7; this.label3.Text = "Installed Version:"; // // currentVersion // this.currentVersion.AutoSize = true; this.currentVersion.Location = new System.Drawing.Point(266, 144); this.currentVersion.Name = "currentVersion"; this.currentVersion.Size = new System.Drawing.Size(31, 13); this.currentVersion.TabIndex = 4; this.currentVersion.Text = "1.0.0"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(187, 144); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(82, 13); this.label2.TabIndex = 6; this.label2.Text = "Current Version:"; // // installedVersion // this.installedVersion.AutoSize = true; this.installedVersion.Location = new System.Drawing.Point(271, 160); this.installedVersion.Name = "installedVersion"; this.installedVersion.Size = new System.Drawing.Size(10, 13); this.installedVersion.TabIndex = 5; this.installedVersion.Text = "-"; // // tabPage2 // this.tabPage2.BackColor = System.Drawing.Color.WhiteSmoke; this.tabPage2.Controls.Add(this.splitContainerMods); this.tabPage2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.tabPage2.Location = new System.Drawing.Point(4, 28); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(318, 342); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Mods"; // // splitContainerMods // this.splitContainerMods.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainerMods.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; this.splitContainerMods.IsSplitterFixed = true; this.splitContainerMods.Location = new System.Drawing.Point(3, 3); this.splitContainerMods.Margin = new System.Windows.Forms.Padding(0); this.splitContainerMods.Name = "splitContainerMods"; this.splitContainerMods.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainerMods.Panel1 // this.splitContainerMods.Panel1.Controls.Add(this.listMods); // // splitContainerMods.Panel2 // this.splitContainerMods.Panel2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.splitContainerMods.Panel2.Controls.Add(this.splitContainerModsInstall); this.splitContainerMods.Size = new System.Drawing.Size(312, 336); this.splitContainerMods.SplitterDistance = 190; this.splitContainerMods.TabIndex = 0; // // listMods // this.listMods.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3, this.columnHeader4}); this.listMods.ContextMenuStrip = this.ModcontextMenuStrip1; this.listMods.Dock = System.Windows.Forms.DockStyle.Fill; this.listMods.FullRowSelect = true; this.listMods.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.listMods.Location = new System.Drawing.Point(0, 0); this.listMods.MultiSelect = false; this.listMods.Name = "listMods"; this.listMods.Size = new System.Drawing.Size(312, 190); this.listMods.TabIndex = 0; this.listMods.UseCompatibleStateImageBehavior = false; this.listMods.View = System.Windows.Forms.View.Details; // // columnHeader1 // this.columnHeader1.Text = "Name"; this.columnHeader1.Width = 116; // // columnHeader2 // this.columnHeader2.Text = "Version"; this.columnHeader2.Width = 50; // // columnHeader3 // this.columnHeader3.Text = "Manager Version"; this.columnHeader3.Width = 50; // // columnHeader4 // this.columnHeader4.Text = "Status"; this.columnHeader4.Width = 90; // // ModcontextMenuStrip1 // this.ModcontextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.installToolStripMenuItem, this.updateToolStripMenuItem, this.revertToolStripMenuItem, this.uninstallToolStripMenuItem, this.wwwToolStripMenuItem1}); this.ModcontextMenuStrip1.Name = "ModcontextMenuStrip1"; this.ModcontextMenuStrip1.Size = new System.Drawing.Size(137, 114); this.ModcontextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.ModcontextMenuStrip1_Opening); // // installToolStripMenuItem // this.installToolStripMenuItem.Name = "installToolStripMenuItem"; this.installToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.installToolStripMenuItem.Text = "Install"; this.installToolStripMenuItem.Click += new System.EventHandler(this.installToolStripMenuItem_Click); // // updateToolStripMenuItem // this.updateToolStripMenuItem.Name = "updateToolStripMenuItem"; this.updateToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.updateToolStripMenuItem.Text = "Update"; this.updateToolStripMenuItem.Click += new System.EventHandler(this.updateToolStripMenuItem_Click); // // revertToolStripMenuItem // this.revertToolStripMenuItem.Name = "revertToolStripMenuItem"; this.revertToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.revertToolStripMenuItem.Text = "Revert"; this.revertToolStripMenuItem.Click += new System.EventHandler(this.revertToolStripMenuItem_Click); // // uninstallToolStripMenuItem // this.uninstallToolStripMenuItem.Name = "uninstallToolStripMenuItem"; this.uninstallToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.uninstallToolStripMenuItem.Text = "Uninstall"; this.uninstallToolStripMenuItem.Click += new System.EventHandler(this.uninstallToolStripMenuItem_Click); // // wwwToolStripMenuItem1 // this.wwwToolStripMenuItem1.Name = "wwwToolStripMenuItem1"; this.wwwToolStripMenuItem1.Size = new System.Drawing.Size(136, 22); this.wwwToolStripMenuItem1.Text = "Home Page"; this.wwwToolStripMenuItem1.Click += new System.EventHandler(this.wwwToolStripMenuItem1_Click); // // splitContainerModsInstall // this.splitContainerModsInstall.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainerModsInstall.Location = new System.Drawing.Point(0, 0); this.splitContainerModsInstall.Name = "splitContainerModsInstall"; this.splitContainerModsInstall.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainerModsInstall.Panel1 // this.splitContainerModsInstall.Panel1.Controls.Add(this.btnModInstall); // // splitContainerModsInstall.Panel2 // this.splitContainerModsInstall.Panel2.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("splitContainerModsInstall.Panel2.BackgroundImage"))); this.splitContainerModsInstall.Panel2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.splitContainerModsInstall.Size = new System.Drawing.Size(312, 142); this.splitContainerModsInstall.SplitterDistance = 45; this.splitContainerModsInstall.TabIndex = 0; // // btnModInstall // this.btnModInstall.Dock = System.Windows.Forms.DockStyle.Fill; this.btnModInstall.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.25F); this.btnModInstall.Location = new System.Drawing.Point(0, 0); this.btnModInstall.Name = "btnModInstall"; this.btnModInstall.Size = new System.Drawing.Size(312, 45); this.btnModInstall.TabIndex = 0; this.btnModInstall.Text = "Install Mod"; this.btnModInstall.UseVisualStyleBackColor = true; this.btnModInstall.Click += new System.EventHandler(this.btnModInstall_Click); // // tabPage3 // this.tabPage3.BackColor = System.Drawing.Color.WhiteSmoke; this.tabPage3.Controls.Add(this.inputLog); this.tabPage3.Location = new System.Drawing.Point(4, 28); this.tabPage3.Name = "tabPage3"; this.tabPage3.Padding = new System.Windows.Forms.Padding(3); this.tabPage3.Size = new System.Drawing.Size(318, 342); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Log"; // // inputLog // this.inputLog.Dock = System.Windows.Forms.DockStyle.Fill; this.inputLog.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.25F); this.inputLog.Location = new System.Drawing.Point(3, 3); this.inputLog.Multiline = true; this.inputLog.Name = "inputLog"; this.inputLog.ReadOnly = true; this.inputLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.inputLog.Size = new System.Drawing.Size(312, 336); this.inputLog.TabIndex = 10; // // statusStrip1 // this.statusStrip1.AutoSize = false; this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.statusLabel}); this.statusStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Flow; this.statusStrip1.Location = new System.Drawing.Point(0, -2); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.ShowItemToolTips = true; this.statusStrip1.Size = new System.Drawing.Size(326, 22); this.statusStrip1.TabIndex = 0; this.statusStrip1.Text = "statusStrip1"; // // statusLabel // this.statusLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 2); this.statusLabel.MergeAction = System.Windows.Forms.MergeAction.Replace; this.statusLabel.Name = "statusLabel"; this.statusLabel.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never; this.statusLabel.Size = new System.Drawing.Size(39, 15); this.statusLabel.Text = "Ready"; this.statusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // folderBrowserDialog // this.folderBrowserDialog.RootFolder = System.Environment.SpecialFolder.MyComputer; this.folderBrowserDialog.HelpRequest += new System.EventHandler(this.folderBrowserDialog_HelpRequest); // // modInstallFileDialog // this.modInstallFileDialog.Filter = "ZIP|*.zip"; this.modInstallFileDialog.Multiselect = true; // // UnityModManagerForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(326, 398); this.Controls.Add(this.panelMain); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "UnityModManagerForm"; this.ShowIcon = false; this.Text = "UnityModManager Installer"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.UnityModLoaderForm_FormClosing); this.panelMain.ResumeLayout(false); this.splitContainerMain.Panel1.ResumeLayout(false); this.splitContainerMain.Panel2.ResumeLayout(false); this.splitContainerMain.ResumeLayout(false); this.tabControl.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage1.PerformLayout(); this.tabPage2.ResumeLayout(false); this.splitContainerMods.Panel1.ResumeLayout(false); this.splitContainerMods.Panel2.ResumeLayout(false); this.splitContainerMods.ResumeLayout(false); this.ModcontextMenuStrip1.ResumeLayout(false); this.splitContainerModsInstall.Panel1.ResumeLayout(false); this.splitContainerModsInstall.ResumeLayout(false); this.tabPage3.ResumeLayout(false); this.tabPage3.PerformLayout(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel panelMain; private System.Windows.Forms.Label currentVersion; private System.Windows.Forms.Label installedVersion; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox gameList; private System.Windows.Forms.Button btnOpenFolder; private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog; private System.Windows.Forms.TabControl tabControl; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.Button btnRemove; private System.Windows.Forms.Button btnInstall; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.SplitContainer splitContainerMods; private System.Windows.Forms.ListView listMods; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.SplitContainer splitContainerMain; private System.Windows.Forms.TabPage tabPage3; public System.Windows.Forms.TextBox inputLog; public System.Windows.Forms.ToolStripStatusLabel statusLabel; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ColumnHeader columnHeader3; private System.Windows.Forms.ColumnHeader columnHeader4; private System.Windows.Forms.ContextMenuStrip ModcontextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem updateToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem installToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem uninstallToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem revertToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem wwwToolStripMenuItem1; private System.Windows.Forms.SplitContainer splitContainerModsInstall; private System.Windows.Forms.Button btnModInstall; private System.Windows.Forms.OpenFileDialog modInstallFileDialog; private System.Windows.Forms.Button btnDownloadUpdate; private System.Windows.Forms.Button btnRestore; } }
54.22604
181
0.632808
[ "MIT" ]
zaxcs/unity-mod-manager
UnityModManager/Form.Designer.cs
30,244
C#
using OpenTK; using System; namespace HedgeEdit { [Serializable] public class VPObjectInstance { // Variables/Constants public Quaternion Rotation { get => rot; set { rot = value; UpdateMatrix(); } } public Vector3 Position { get => pos; set { pos = value; UpdateMatrix(); } } public Vector3 Scale { get => scale; set { scale = value; UpdateMatrix(); } } public Matrix4 Matrix => matrix; public object CustomData = null; protected Matrix4 matrix = Matrix4.Identity; protected Quaternion rot = Quaternion.Identity; protected Vector3 pos = Vector3.Zero, scale = Vector3.One; // Constructors /// <summary> /// Creates an instance with default position (0,0,0), /// rotation (0,0,0,1), and scale (1,1,1). /// </summary> /// <param name="customData">Any custom data you wish to store for later use.</param> public VPObjectInstance(object customData = null) { CustomData = customData; } /// <summary> /// Creates an instance with specified transform. /// Quite slow as it has to extract rotation from the matrix. /// Please call this version of the constructor sparingly!! /// </summary> /// <param name="matrix">A 4x4 matrix representing the transform of this object.</param> /// <param name="customData">Any custom data you wish to store for later use.</param> public VPObjectInstance(Matrix4 matrix, object customData = null) { this.matrix = matrix; CustomData = customData; pos = matrix.ExtractTranslation(); rot = matrix.ExtractRotation(); scale = matrix.ExtractScale(); } /// <summary> /// Creates an instance at the specified position with the position/rotation/scale /// values present in the given QD composed matrix. /// </summary> /// <param name="matrix">4x4 Matrix composed of an orthogonal /// rotation, diagonal scale, and position.</param> /// <param name="customData">Any custom data you wish to store for later use.</param> public VPObjectInstance(float[,] matrix, object customData = null) { var rotMatrix = new float[3, 3]; MatrixQDDecomposition(matrix, rotMatrix, out scale); pos = new Vector3(matrix[0, 3], matrix[1, 3], matrix[2, 3]); rot = Quaternion.FromMatrix(new Matrix3( rotMatrix[0, 0], rotMatrix[0, 1], rotMatrix[0, 2], rotMatrix[1, 0], rotMatrix[1, 1], rotMatrix[1, 2], rotMatrix[2, 0], rotMatrix[2, 1], rotMatrix[2, 2])); CustomData = customData; UpdateMatrix(); } /// <summary> /// Creates an instance at the specified position with default /// rotation (0,0,0,1) and scale (1,1,1). /// </summary> /// <param name="pos">Position of the object in world-space.</param> /// <param name="customData">Any custom data you wish to store for later use.</param> public VPObjectInstance(Vector3 pos, object customData = null) { this.pos = pos; CustomData = customData; UpdateMatrix(); } /// <summary> /// Creates an instance at the specified position with the /// specified rotation and default scale (1,1,1). /// </summary> /// <param name="pos">Position of the object in world-space.</param> /// <param name="rot">Rotation of the object in world-space.</param> /// <param name="customData">Any custom data you wish to store for later use.</param> public VPObjectInstance(Vector3 pos, Quaternion rot, object customData = null) { this.pos = pos; this.rot = rot; CustomData = customData; UpdateMatrix(); } /// <summary> /// Creates an instance at the specified position with the specified scale. /// </summary> /// <param name="pos">Position of the object in world-space.</param> /// <param name="scale">Scale of the object in world-space.</param> /// <param name="customData">Any custom data you wish to store for later use.</param> public VPObjectInstance(Vector3 pos, Vector3 scale, object customData = null) { this.pos = pos; this.scale = scale; CustomData = customData; UpdateMatrix(); } /// <summary> /// Creates an instance at the specified position with the specified rotation/scale. /// </summary> /// <param name="pos">Position of the object in world-space.</param> /// <param name="rot">Rotation of the object in world-space.</param> /// <param name="scale">Scale of the object in world-space.</param> /// <param name="customData">Any custom data you wish to store for later use.</param> public VPObjectInstance(Vector3 pos, Quaternion rot, Vector3 scale, object customData = null) { this.pos = pos; this.rot = rot; this.scale = scale; CustomData = customData; UpdateMatrix(); } // Methods protected void UpdateMatrix() { matrix = Matrix4.CreateScale(scale) * Matrix4.CreateFromQuaternion(rot) * Matrix4.CreateTranslation(pos); } // The following 2 methods were taken from OGRE (for now) with some light modifications // because try as I might I can't seem to understand how this decomposition works // and can't find any information about it online. protected float RSQ(float r) { return (1 / (float)System.Math.Sqrt(r)); } protected void MatrixQDDecomposition(float[,] m, float[,] q, out Vector3 d) { float fInvLength = m[0, 0] * m[0, 0] + m[1, 0] * m[1, 0] + m[2, 0] * m[2, 0]; if (fInvLength != 0) fInvLength = RSQ(fInvLength); q[0, 0] = m[0, 0] * fInvLength; q[1, 0] = m[1, 0] * fInvLength; q[2, 0] = m[2, 0] * fInvLength; float fDot = q[0, 0] * m[0, 1] + q[1, 0] * m[1, 1] + q[2, 0] * m[2, 1]; q[0, 1] = m[0, 1] - fDot * q[0, 0]; q[1, 1] = m[1, 1] - fDot * q[1, 0]; q[2, 1] = m[2, 1] - fDot * q[2, 0]; fInvLength = q[0, 1] * q[0, 1] + q[1, 1] * q[1, 1] + q[2, 1] * q[2, 1]; if (fInvLength != 0) fInvLength = RSQ(fInvLength); q[0, 1] *= fInvLength; q[1, 1] *= fInvLength; q[2, 1] *= fInvLength; fDot = q[0, 0] * m[0, 2] + q[1, 0] * m[1, 2] + q[2, 0] * m[2, 2]; q[0, 2] = m[0, 2] - fDot * q[0, 0]; q[1, 2] = m[1, 2] - fDot * q[1, 0]; q[2, 2] = m[2, 2] - fDot * q[2, 0]; fDot = q[0, 1] * m[0, 2] + q[1, 1] * m[1, 2] + q[2, 1] * m[2, 2]; q[0, 2] -= fDot * q[0, 1]; q[1, 2] -= fDot * q[1, 1]; q[2, 2] -= fDot * q[2, 1]; fInvLength = q[0, 2] * q[0, 2] + q[1, 2] * q[1, 2] + q[2, 2] * q[2, 2]; if (fInvLength != 0) fInvLength = RSQ(fInvLength); q[0, 2] *= fInvLength; q[1, 2] *= fInvLength; q[2, 2] *= fInvLength; float fDet = q[0, 0] * q[1, 1] * q[2, 2] + q[0, 1] * q[1, 2] * q[2, 0] + q[0, 2] * q[1, 0] * q[2, 1] - q[0, 2] * q[1, 1] * q[2, 0] - q[0, 1] * q[1, 0] * q[2, 2] - q[0, 0] * q[1, 2] * q[2, 1]; if (fDet < 0.0) { // Negate all values in the matrix for (int iRow = 0; iRow < 3; ++iRow) { for (int iCol = 0; iCol < 3; ++iCol) { q[iRow, iCol] = -q[iRow, iCol]; } } } // Get Diagonal d = new Vector3() { X = q[0, 0] * m[0, 0] + q[1, 0] * m[1, 0] + q[2, 0] * m[2, 0], Y = q[0, 1] * m[0, 1] + q[1, 1] * m[1, 1] + q[2, 1] * m[2, 1], Z = q[0, 2] * m[0, 2] + q[1, 2] * m[1, 2] + q[2, 2] * m[2, 2] }; } } }
36.214876
96
0.482999
[ "MIT" ]
Jovana222/idk
HedgeEdit/VPObjectInstance.cs
8,766
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was auto-generated by com.unity.inputsystem:InputActionCodeGenerator // version 1.2.0 // from Assets/Scripts/Input/Mashrooms_Screen_input.inputactions // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Generic; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Utilities; public partial class @Mashrooms_Screen_input : IInputActionCollection2, IDisposable { public InputActionAsset asset { get; } public @Mashrooms_Screen_input() { asset = InputActionAsset.FromJson(@"{ ""name"": ""Mashrooms_Screen_input"", ""maps"": [ { ""name"": ""Player"", ""id"": ""3aabccfc-1963-4490-9e85-cc845f975726"", ""actions"": [ { ""name"": ""Move"", ""type"": ""Value"", ""id"": ""5e2f1a14-24d6-47ae-a5de-a181eb7ef227"", ""expectedControlType"": ""Vector2"", ""processors"": """", ""interactions"": """", ""initialStateCheck"": true }, { ""name"": ""Look"", ""type"": ""Value"", ""id"": ""969be9bd-fa0d-4452-87d2-de0bc89455b9"", ""expectedControlType"": ""Vector2"", ""processors"": """", ""interactions"": """", ""initialStateCheck"": true }, { ""name"": ""Fire"", ""type"": ""Button"", ""id"": ""5e3baa84-56f3-483a-b8a1-302dbbe6d902"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": """", ""initialStateCheck"": false }, { ""name"": ""Btn1"", ""type"": ""Button"", ""id"": ""0df6d308-f4ef-4e5f-a115-15c27612f1bf"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"", ""initialStateCheck"": false }, { ""name"": ""Btn2"", ""type"": ""Button"", ""id"": ""9f10a749-40db-457f-a178-9efe64fcc87d"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"", ""initialStateCheck"": false }, { ""name"": ""Btn3"", ""type"": ""Button"", ""id"": ""9816e4fb-75a0-45e0-af38-876e10b421f6"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"", ""initialStateCheck"": false }, { ""name"": ""Btn4"", ""type"": ""Button"", ""id"": ""f68e0a0f-1e21-4c04-8959-e6b71f059f13"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"", ""initialStateCheck"": false }, { ""name"": ""Btn5"", ""type"": ""Button"", ""id"": ""5c853f9a-da5a-4bbc-bbb7-a6fed8061c41"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"", ""initialStateCheck"": false }, { ""name"": ""Btn6"", ""type"": ""Button"", ""id"": ""29c83562-b814-4521-90a4-bf23d5d0a724"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"", ""initialStateCheck"": false }, { ""name"": ""Btn7"", ""type"": ""Button"", ""id"": ""74491db9-d615-44b9-a0b8-5db14ebf87b8"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"", ""initialStateCheck"": false }, { ""name"": ""Btn8"", ""type"": ""Button"", ""id"": ""d70543d4-6fa4-4ab9-bd02-97fbde8076b0"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"", ""initialStateCheck"": false }, { ""name"": ""Btn9"", ""type"": ""Button"", ""id"": ""081267a8-0306-4e09-bd2e-ebe8da3470f8"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": ""Press"", ""initialStateCheck"": false } ], ""bindings"": [ { ""name"": """", ""id"": ""978bfe49-cc26-4a3d-ab7b-7d7a29327403"", ""path"": ""<Gamepad>/leftStick"", ""interactions"": """", ""processors"": """", ""groups"": "";Gamepad"", ""action"": ""Move"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": ""WASD"", ""id"": ""00ca640b-d935-4593-8157-c05846ea39b3"", ""path"": ""Dpad"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Move"", ""isComposite"": true, ""isPartOfComposite"": false }, { ""name"": ""up"", ""id"": ""e2062cb9-1b15-46a2-838c-2f8d72a0bdd9"", ""path"": ""<Keyboard>/w"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse"", ""action"": ""Move"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""up"", ""id"": ""8180e8bd-4097-4f4e-ab88-4523101a6ce9"", ""path"": ""<Keyboard>/upArrow"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse"", ""action"": ""Move"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""down"", ""id"": ""320bffee-a40b-4347-ac70-c210eb8bc73a"", ""path"": ""<Keyboard>/s"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse"", ""action"": ""Move"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""down"", ""id"": ""1c5327b5-f71c-4f60-99c7-4e737386f1d1"", ""path"": ""<Keyboard>/downArrow"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse"", ""action"": ""Move"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""left"", ""id"": ""d2581a9b-1d11-4566-b27d-b92aff5fabbc"", ""path"": ""<Keyboard>/a"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse"", ""action"": ""Move"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""left"", ""id"": ""2e46982e-44cc-431b-9f0b-c11910bf467a"", ""path"": ""<Keyboard>/leftArrow"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse"", ""action"": ""Move"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""right"", ""id"": ""fcfe95b8-67b9-4526-84b5-5d0bc98d6400"", ""path"": ""<Keyboard>/d"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse"", ""action"": ""Move"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""right"", ""id"": ""77bff152-3580-4b21-b6de-dcd0c7e41164"", ""path"": ""<Keyboard>/rightArrow"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse"", ""action"": ""Move"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": """", ""id"": ""1635d3fe-58b6-4ba9-a4e2-f4b964f6b5c8"", ""path"": ""<XRController>/{Primary2DAxis}"", ""interactions"": """", ""processors"": """", ""groups"": ""XR"", ""action"": ""Move"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""3ea4d645-4504-4529-b061-ab81934c3752"", ""path"": ""<Joystick>/stick"", ""interactions"": """", ""processors"": """", ""groups"": ""Joystick"", ""action"": ""Move"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""c1f7a91b-d0fd-4a62-997e-7fb9b69bf235"", ""path"": ""<Gamepad>/rightStick"", ""interactions"": """", ""processors"": """", ""groups"": "";Gamepad"", ""action"": ""Look"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""8c8e490b-c610-4785-884f-f04217b23ca4"", ""path"": ""<Pointer>/delta"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse;Touch"", ""action"": ""Look"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""3e5f5442-8668-4b27-a940-df99bad7e831"", ""path"": ""<Joystick>/{Hatswitch}"", ""interactions"": """", ""processors"": """", ""groups"": ""Joystick"", ""action"": ""Look"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""143bb1cd-cc10-4eca-a2f0-a3664166fe91"", ""path"": ""<Gamepad>/rightTrigger"", ""interactions"": """", ""processors"": """", ""groups"": "";Gamepad"", ""action"": ""Fire"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""05f6913d-c316-48b2-a6bb-e225f14c7960"", ""path"": ""<Mouse>/leftButton"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse"", ""action"": ""Fire"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""886e731e-7071-4ae4-95c0-e61739dad6fd"", ""path"": ""<Touchscreen>/primaryTouch/tap"", ""interactions"": """", ""processors"": """", ""groups"": "";Touch"", ""action"": ""Fire"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""ee3d0cd2-254e-47a7-a8cb-bc94d9658c54"", ""path"": ""<Joystick>/trigger"", ""interactions"": """", ""processors"": """", ""groups"": ""Joystick"", ""action"": ""Fire"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""8255d333-5683-4943-a58a-ccb207ff1dce"", ""path"": ""<XRController>/{PrimaryAction}"", ""interactions"": """", ""processors"": """", ""groups"": ""XR"", ""action"": ""Fire"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""ae354f98-2249-413d-8bd9-05f79254fdb2"", ""path"": ""<Keyboard>/1"", ""interactions"": """", ""processors"": """", ""groups"": ""Touch;Keyboard&Mouse"", ""action"": ""Btn1"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""0aa7ce22-5b37-43fe-b9b9-38cd211ae990"", ""path"": ""<Keyboard>/2"", ""interactions"": """", ""processors"": """", ""groups"": ""Touch;Keyboard&Mouse"", ""action"": ""Btn2"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""deed0181-621d-4d5c-ab17-00b0efcdec74"", ""path"": ""<Keyboard>/3"", ""interactions"": """", ""processors"": """", ""groups"": ""Touch;Keyboard&Mouse"", ""action"": ""Btn3"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""bc5249bd-2384-4aa1-a34f-b7610dd5d5e8"", ""path"": ""<Keyboard>/4"", ""interactions"": """", ""processors"": """", ""groups"": ""Touch;Keyboard&Mouse"", ""action"": ""Btn4"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""f887c7cc-18cf-4de2-9c24-213c16227171"", ""path"": ""<Keyboard>/5"", ""interactions"": """", ""processors"": """", ""groups"": ""Touch;Keyboard&Mouse"", ""action"": ""Btn5"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""51de3014-6253-4508-bd4a-2062fa28ce36"", ""path"": ""<Keyboard>/6"", ""interactions"": """", ""processors"": """", ""groups"": ""Touch;Keyboard&Mouse"", ""action"": ""Btn6"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""39cdee4d-0dbd-4e2a-8458-1efa1a0a991e"", ""path"": ""<Keyboard>/7"", ""interactions"": """", ""processors"": """", ""groups"": ""Touch;Keyboard&Mouse"", ""action"": ""Btn7"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""ebf2b5d2-91d4-4c1b-9b8e-42d976c8c10e"", ""path"": ""<Keyboard>/8"", ""interactions"": """", ""processors"": """", ""groups"": ""Touch;Keyboard&Mouse"", ""action"": ""Btn8"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""d30b1938-4801-429a-ad24-36ac31271beb"", ""path"": ""<Keyboard>/9"", ""interactions"": """", ""processors"": """", ""groups"": ""Touch;Keyboard&Mouse"", ""action"": ""Btn9"", ""isComposite"": false, ""isPartOfComposite"": false } ] }, { ""name"": ""UI"", ""id"": ""fe7c1a67-9165-4f46-9f1e-e49ded79c08a"", ""actions"": [ { ""name"": ""Navigate"", ""type"": ""Value"", ""id"": ""5b72bdd0-bf32-4f59-8e66-1de114d85acc"", ""expectedControlType"": ""Vector2"", ""processors"": """", ""interactions"": """", ""initialStateCheck"": true }, { ""name"": ""Submit"", ""type"": ""Button"", ""id"": ""31ce4598-ba47-4ff1-b0a1-a6d4d431672b"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": """", ""initialStateCheck"": false }, { ""name"": ""Cancel"", ""type"": ""Button"", ""id"": ""bcb06544-221f-455f-9b0f-4d9871060980"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": """", ""initialStateCheck"": false }, { ""name"": ""Point"", ""type"": ""PassThrough"", ""id"": ""d0e757a4-0b9e-48b3-bf3b-2f148439ef39"", ""expectedControlType"": ""Vector2"", ""processors"": """", ""interactions"": """", ""initialStateCheck"": false }, { ""name"": ""Click"", ""type"": ""PassThrough"", ""id"": ""d823febf-7972-4048-b70d-206607a2cfab"", ""expectedControlType"": ""Button"", ""processors"": """", ""interactions"": """", ""initialStateCheck"": false }, { ""name"": ""ScrollWheel"", ""type"": ""PassThrough"", ""id"": ""54e6b0b8-e9ec-4921-9fb1-13c24b126634"", ""expectedControlType"": ""Vector2"", ""processors"": """", ""interactions"": """", ""initialStateCheck"": false }, { ""name"": ""MiddleClick"", ""type"": ""PassThrough"", ""id"": ""7a670ab8-0cd0-42df-9970-77959d70dbf5"", ""expectedControlType"": """", ""processors"": """", ""interactions"": """", ""initialStateCheck"": false }, { ""name"": ""RightClick"", ""type"": ""PassThrough"", ""id"": ""6bc28b6a-a2a6-4776-a5c0-9f55c0e11b3e"", ""expectedControlType"": """", ""processors"": """", ""interactions"": """", ""initialStateCheck"": false }, { ""name"": ""TrackedDevicePosition"", ""type"": ""PassThrough"", ""id"": ""6072c393-8ba5-4945-af0e-97625c1e97b3"", ""expectedControlType"": ""Vector3"", ""processors"": """", ""interactions"": """", ""initialStateCheck"": false }, { ""name"": ""TrackedDeviceOrientation"", ""type"": ""PassThrough"", ""id"": ""0b67e6f8-ae42-4edf-ace4-d9645551fe08"", ""expectedControlType"": ""Quaternion"", ""processors"": """", ""interactions"": """", ""initialStateCheck"": false } ], ""bindings"": [ { ""name"": ""Gamepad"", ""id"": ""809f371f-c5e2-4e7a-83a1-d867598f40dd"", ""path"": ""2DVector"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Navigate"", ""isComposite"": true, ""isPartOfComposite"": false }, { ""name"": ""up"", ""id"": ""14a5d6e8-4aaf-4119-a9ef-34b8c2c548bf"", ""path"": ""<Gamepad>/leftStick/up"", ""interactions"": """", ""processors"": """", ""groups"": "";Gamepad"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""up"", ""id"": ""9144cbe6-05e1-4687-a6d7-24f99d23dd81"", ""path"": ""<Gamepad>/rightStick/up"", ""interactions"": """", ""processors"": """", ""groups"": "";Gamepad"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""down"", ""id"": ""2db08d65-c5fb-421b-983f-c71163608d67"", ""path"": ""<Gamepad>/leftStick/down"", ""interactions"": """", ""processors"": """", ""groups"": "";Gamepad"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""down"", ""id"": ""58748904-2ea9-4a80-8579-b500e6a76df8"", ""path"": ""<Gamepad>/rightStick/down"", ""interactions"": """", ""processors"": """", ""groups"": "";Gamepad"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""left"", ""id"": ""8ba04515-75aa-45de-966d-393d9bbd1c14"", ""path"": ""<Gamepad>/leftStick/left"", ""interactions"": """", ""processors"": """", ""groups"": "";Gamepad"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""left"", ""id"": ""712e721c-bdfb-4b23-a86c-a0d9fcfea921"", ""path"": ""<Gamepad>/rightStick/left"", ""interactions"": """", ""processors"": """", ""groups"": "";Gamepad"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""right"", ""id"": ""fcd248ae-a788-4676-a12e-f4d81205600b"", ""path"": ""<Gamepad>/leftStick/right"", ""interactions"": """", ""processors"": """", ""groups"": "";Gamepad"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""right"", ""id"": ""1f04d9bc-c50b-41a1-bfcc-afb75475ec20"", ""path"": ""<Gamepad>/rightStick/right"", ""interactions"": """", ""processors"": """", ""groups"": "";Gamepad"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": """", ""id"": ""fb8277d4-c5cd-4663-9dc7-ee3f0b506d90"", ""path"": ""<Gamepad>/dpad"", ""interactions"": """", ""processors"": """", ""groups"": "";Gamepad"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": ""Joystick"", ""id"": ""e25d9774-381c-4a61-b47c-7b6b299ad9f9"", ""path"": ""2DVector"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Navigate"", ""isComposite"": true, ""isPartOfComposite"": false }, { ""name"": ""up"", ""id"": ""3db53b26-6601-41be-9887-63ac74e79d19"", ""path"": ""<Joystick>/stick/up"", ""interactions"": """", ""processors"": """", ""groups"": ""Joystick"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""down"", ""id"": ""0cb3e13e-3d90-4178-8ae6-d9c5501d653f"", ""path"": ""<Joystick>/stick/down"", ""interactions"": """", ""processors"": """", ""groups"": ""Joystick"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""left"", ""id"": ""0392d399-f6dd-4c82-8062-c1e9c0d34835"", ""path"": ""<Joystick>/stick/left"", ""interactions"": """", ""processors"": """", ""groups"": ""Joystick"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""right"", ""id"": ""942a66d9-d42f-43d6-8d70-ecb4ba5363bc"", ""path"": ""<Joystick>/stick/right"", ""interactions"": """", ""processors"": """", ""groups"": ""Joystick"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""Keyboard"", ""id"": ""ff527021-f211-4c02-933e-5976594c46ed"", ""path"": ""2DVector"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Navigate"", ""isComposite"": true, ""isPartOfComposite"": false }, { ""name"": ""up"", ""id"": ""563fbfdd-0f09-408d-aa75-8642c4f08ef0"", ""path"": ""<Keyboard>/w"", ""interactions"": """", ""processors"": """", ""groups"": ""Keyboard&Mouse"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""up"", ""id"": ""eb480147-c587-4a33-85ed-eb0ab9942c43"", ""path"": ""<Keyboard>/upArrow"", ""interactions"": """", ""processors"": """", ""groups"": ""Keyboard&Mouse"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""down"", ""id"": ""2bf42165-60bc-42ca-8072-8c13ab40239b"", ""path"": ""<Keyboard>/s"", ""interactions"": """", ""processors"": """", ""groups"": ""Keyboard&Mouse"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""down"", ""id"": ""85d264ad-e0a0-4565-b7ff-1a37edde51ac"", ""path"": ""<Keyboard>/downArrow"", ""interactions"": """", ""processors"": """", ""groups"": ""Keyboard&Mouse"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""left"", ""id"": ""74214943-c580-44e4-98eb-ad7eebe17902"", ""path"": ""<Keyboard>/a"", ""interactions"": """", ""processors"": """", ""groups"": ""Keyboard&Mouse"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""left"", ""id"": ""cea9b045-a000-445b-95b8-0c171af70a3b"", ""path"": ""<Keyboard>/leftArrow"", ""interactions"": """", ""processors"": """", ""groups"": ""Keyboard&Mouse"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""right"", ""id"": ""8607c725-d935-4808-84b1-8354e29bab63"", ""path"": ""<Keyboard>/d"", ""interactions"": """", ""processors"": """", ""groups"": ""Keyboard&Mouse"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": ""right"", ""id"": ""4cda81dc-9edd-4e03-9d7c-a71a14345d0b"", ""path"": ""<Keyboard>/rightArrow"", ""interactions"": """", ""processors"": """", ""groups"": ""Keyboard&Mouse"", ""action"": ""Navigate"", ""isComposite"": false, ""isPartOfComposite"": true }, { ""name"": """", ""id"": ""9e92bb26-7e3b-4ec4-b06b-3c8f8e498ddc"", ""path"": ""*/{Submit}"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Submit"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""82627dcc-3b13-4ba9-841d-e4b746d6553e"", ""path"": ""*/{Cancel}"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Cancel"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""c52c8e0b-8179-41d3-b8a1-d149033bbe86"", ""path"": ""<Mouse>/position"", ""interactions"": """", ""processors"": """", ""groups"": ""Keyboard&Mouse"", ""action"": ""Point"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""e1394cbc-336e-44ce-9ea8-6007ed6193f7"", ""path"": ""<Pen>/position"", ""interactions"": """", ""processors"": """", ""groups"": ""Keyboard&Mouse"", ""action"": ""Point"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""5693e57a-238a-46ed-b5ae-e64e6e574302"", ""path"": ""<Touchscreen>/touch*/position"", ""interactions"": """", ""processors"": """", ""groups"": ""Touch"", ""action"": ""Point"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""4faf7dc9-b979-4210-aa8c-e808e1ef89f5"", ""path"": ""<Mouse>/leftButton"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse"", ""action"": ""Click"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""8d66d5ba-88d7-48e6-b1cd-198bbfef7ace"", ""path"": ""<Pen>/tip"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse"", ""action"": ""Click"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""47c2a644-3ebc-4dae-a106-589b7ca75b59"", ""path"": ""<Touchscreen>/touch*/press"", ""interactions"": """", ""processors"": """", ""groups"": ""Touch"", ""action"": ""Click"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""bb9e6b34-44bf-4381-ac63-5aa15d19f677"", ""path"": ""<XRController>/trigger"", ""interactions"": """", ""processors"": """", ""groups"": ""XR"", ""action"": ""Click"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""38c99815-14ea-4617-8627-164d27641299"", ""path"": ""<Mouse>/scroll"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse"", ""action"": ""ScrollWheel"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""24066f69-da47-44f3-a07e-0015fb02eb2e"", ""path"": ""<Mouse>/middleButton"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse"", ""action"": ""MiddleClick"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""4c191405-5738-4d4b-a523-c6a301dbf754"", ""path"": ""<Mouse>/rightButton"", ""interactions"": """", ""processors"": """", ""groups"": "";Keyboard&Mouse"", ""action"": ""RightClick"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""7236c0d9-6ca3-47cf-a6ee-a97f5b59ea77"", ""path"": ""<XRController>/devicePosition"", ""interactions"": """", ""processors"": """", ""groups"": ""XR"", ""action"": ""TrackedDevicePosition"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""23e01e3a-f935-4948-8d8b-9bcac77714fb"", ""path"": ""<XRController>/deviceRotation"", ""interactions"": """", ""processors"": """", ""groups"": ""XR"", ""action"": ""TrackedDeviceOrientation"", ""isComposite"": false, ""isPartOfComposite"": false } ] } ], ""controlSchemes"": [ { ""name"": ""Keyboard&Mouse"", ""bindingGroup"": ""Keyboard&Mouse"", ""devices"": [ { ""devicePath"": ""<Keyboard>"", ""isOptional"": false, ""isOR"": false }, { ""devicePath"": ""<Mouse>"", ""isOptional"": false, ""isOR"": false } ] }, { ""name"": ""Gamepad"", ""bindingGroup"": ""Gamepad"", ""devices"": [ { ""devicePath"": ""<Gamepad>"", ""isOptional"": false, ""isOR"": false } ] }, { ""name"": ""Touch"", ""bindingGroup"": ""Touch"", ""devices"": [ { ""devicePath"": ""<Touchscreen>"", ""isOptional"": false, ""isOR"": false } ] }, { ""name"": ""Joystick"", ""bindingGroup"": ""Joystick"", ""devices"": [ { ""devicePath"": ""<Joystick>"", ""isOptional"": false, ""isOR"": false } ] }, { ""name"": ""XR"", ""bindingGroup"": ""XR"", ""devices"": [ { ""devicePath"": ""<XRController>"", ""isOptional"": false, ""isOR"": false } ] } ] }"); // Player m_Player = asset.FindActionMap("Player", throwIfNotFound: true); m_Player_Move = m_Player.FindAction("Move", throwIfNotFound: true); m_Player_Look = m_Player.FindAction("Look", throwIfNotFound: true); m_Player_Fire = m_Player.FindAction("Fire", throwIfNotFound: true); m_Player_Btn1 = m_Player.FindAction("Btn1", throwIfNotFound: true); m_Player_Btn2 = m_Player.FindAction("Btn2", throwIfNotFound: true); m_Player_Btn3 = m_Player.FindAction("Btn3", throwIfNotFound: true); m_Player_Btn4 = m_Player.FindAction("Btn4", throwIfNotFound: true); m_Player_Btn5 = m_Player.FindAction("Btn5", throwIfNotFound: true); m_Player_Btn6 = m_Player.FindAction("Btn6", throwIfNotFound: true); m_Player_Btn7 = m_Player.FindAction("Btn7", throwIfNotFound: true); m_Player_Btn8 = m_Player.FindAction("Btn8", throwIfNotFound: true); m_Player_Btn9 = m_Player.FindAction("Btn9", throwIfNotFound: true); // UI m_UI = asset.FindActionMap("UI", throwIfNotFound: true); m_UI_Navigate = m_UI.FindAction("Navigate", throwIfNotFound: true); m_UI_Submit = m_UI.FindAction("Submit", throwIfNotFound: true); m_UI_Cancel = m_UI.FindAction("Cancel", throwIfNotFound: true); m_UI_Point = m_UI.FindAction("Point", throwIfNotFound: true); m_UI_Click = m_UI.FindAction("Click", throwIfNotFound: true); m_UI_ScrollWheel = m_UI.FindAction("ScrollWheel", throwIfNotFound: true); m_UI_MiddleClick = m_UI.FindAction("MiddleClick", throwIfNotFound: true); m_UI_RightClick = m_UI.FindAction("RightClick", throwIfNotFound: true); m_UI_TrackedDevicePosition = m_UI.FindAction("TrackedDevicePosition", throwIfNotFound: true); m_UI_TrackedDeviceOrientation = m_UI.FindAction("TrackedDeviceOrientation", throwIfNotFound: true); } public void Dispose() { UnityEngine.Object.Destroy(asset); } public InputBinding? bindingMask { get => asset.bindingMask; set => asset.bindingMask = value; } public ReadOnlyArray<InputDevice>? devices { get => asset.devices; set => asset.devices = value; } public ReadOnlyArray<InputControlScheme> controlSchemes => asset.controlSchemes; public bool Contains(InputAction action) { return asset.Contains(action); } public IEnumerator<InputAction> GetEnumerator() { return asset.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Enable() { asset.Enable(); } public void Disable() { asset.Disable(); } public IEnumerable<InputBinding> bindings => asset.bindings; public InputAction FindAction(string actionNameOrId, bool throwIfNotFound = false) { return asset.FindAction(actionNameOrId, throwIfNotFound); } public int FindBinding(InputBinding bindingMask, out InputAction action) { return asset.FindBinding(bindingMask, out action); } // Player private readonly InputActionMap m_Player; private IPlayerActions m_PlayerActionsCallbackInterface; private readonly InputAction m_Player_Move; private readonly InputAction m_Player_Look; private readonly InputAction m_Player_Fire; private readonly InputAction m_Player_Btn1; private readonly InputAction m_Player_Btn2; private readonly InputAction m_Player_Btn3; private readonly InputAction m_Player_Btn4; private readonly InputAction m_Player_Btn5; private readonly InputAction m_Player_Btn6; private readonly InputAction m_Player_Btn7; private readonly InputAction m_Player_Btn8; private readonly InputAction m_Player_Btn9; public struct PlayerActions { private @Mashrooms_Screen_input m_Wrapper; public PlayerActions(@Mashrooms_Screen_input wrapper) { m_Wrapper = wrapper; } public InputAction @Move => m_Wrapper.m_Player_Move; public InputAction @Look => m_Wrapper.m_Player_Look; public InputAction @Fire => m_Wrapper.m_Player_Fire; public InputAction @Btn1 => m_Wrapper.m_Player_Btn1; public InputAction @Btn2 => m_Wrapper.m_Player_Btn2; public InputAction @Btn3 => m_Wrapper.m_Player_Btn3; public InputAction @Btn4 => m_Wrapper.m_Player_Btn4; public InputAction @Btn5 => m_Wrapper.m_Player_Btn5; public InputAction @Btn6 => m_Wrapper.m_Player_Btn6; public InputAction @Btn7 => m_Wrapper.m_Player_Btn7; public InputAction @Btn8 => m_Wrapper.m_Player_Btn8; public InputAction @Btn9 => m_Wrapper.m_Player_Btn9; public InputActionMap Get() { return m_Wrapper.m_Player; } public void Enable() { Get().Enable(); } public void Disable() { Get().Disable(); } public bool enabled => Get().enabled; public static implicit operator InputActionMap(PlayerActions set) { return set.Get(); } public void SetCallbacks(IPlayerActions instance) { if (m_Wrapper.m_PlayerActionsCallbackInterface != null) { @Move.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnMove; @Move.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnMove; @Move.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnMove; @Look.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnLook; @Look.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnLook; @Look.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnLook; @Fire.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnFire; @Fire.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnFire; @Fire.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnFire; @Btn1.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn1; @Btn1.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn1; @Btn1.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn1; @Btn2.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn2; @Btn2.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn2; @Btn2.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn2; @Btn3.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn3; @Btn3.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn3; @Btn3.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn3; @Btn4.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn4; @Btn4.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn4; @Btn4.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn4; @Btn5.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn5; @Btn5.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn5; @Btn5.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn5; @Btn6.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn6; @Btn6.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn6; @Btn6.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn6; @Btn7.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn7; @Btn7.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn7; @Btn7.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn7; @Btn8.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn8; @Btn8.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn8; @Btn8.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn8; @Btn9.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn9; @Btn9.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn9; @Btn9.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnBtn9; } m_Wrapper.m_PlayerActionsCallbackInterface = instance; if (instance != null) { @Move.started += instance.OnMove; @Move.performed += instance.OnMove; @Move.canceled += instance.OnMove; @Look.started += instance.OnLook; @Look.performed += instance.OnLook; @Look.canceled += instance.OnLook; @Fire.started += instance.OnFire; @Fire.performed += instance.OnFire; @Fire.canceled += instance.OnFire; @Btn1.started += instance.OnBtn1; @Btn1.performed += instance.OnBtn1; @Btn1.canceled += instance.OnBtn1; @Btn2.started += instance.OnBtn2; @Btn2.performed += instance.OnBtn2; @Btn2.canceled += instance.OnBtn2; @Btn3.started += instance.OnBtn3; @Btn3.performed += instance.OnBtn3; @Btn3.canceled += instance.OnBtn3; @Btn4.started += instance.OnBtn4; @Btn4.performed += instance.OnBtn4; @Btn4.canceled += instance.OnBtn4; @Btn5.started += instance.OnBtn5; @Btn5.performed += instance.OnBtn5; @Btn5.canceled += instance.OnBtn5; @Btn6.started += instance.OnBtn6; @Btn6.performed += instance.OnBtn6; @Btn6.canceled += instance.OnBtn6; @Btn7.started += instance.OnBtn7; @Btn7.performed += instance.OnBtn7; @Btn7.canceled += instance.OnBtn7; @Btn8.started += instance.OnBtn8; @Btn8.performed += instance.OnBtn8; @Btn8.canceled += instance.OnBtn8; @Btn9.started += instance.OnBtn9; @Btn9.performed += instance.OnBtn9; @Btn9.canceled += instance.OnBtn9; } } } public PlayerActions @Player => new PlayerActions(this); // UI private readonly InputActionMap m_UI; private IUIActions m_UIActionsCallbackInterface; private readonly InputAction m_UI_Navigate; private readonly InputAction m_UI_Submit; private readonly InputAction m_UI_Cancel; private readonly InputAction m_UI_Point; private readonly InputAction m_UI_Click; private readonly InputAction m_UI_ScrollWheel; private readonly InputAction m_UI_MiddleClick; private readonly InputAction m_UI_RightClick; private readonly InputAction m_UI_TrackedDevicePosition; private readonly InputAction m_UI_TrackedDeviceOrientation; public struct UIActions { private @Mashrooms_Screen_input m_Wrapper; public UIActions(@Mashrooms_Screen_input wrapper) { m_Wrapper = wrapper; } public InputAction @Navigate => m_Wrapper.m_UI_Navigate; public InputAction @Submit => m_Wrapper.m_UI_Submit; public InputAction @Cancel => m_Wrapper.m_UI_Cancel; public InputAction @Point => m_Wrapper.m_UI_Point; public InputAction @Click => m_Wrapper.m_UI_Click; public InputAction @ScrollWheel => m_Wrapper.m_UI_ScrollWheel; public InputAction @MiddleClick => m_Wrapper.m_UI_MiddleClick; public InputAction @RightClick => m_Wrapper.m_UI_RightClick; public InputAction @TrackedDevicePosition => m_Wrapper.m_UI_TrackedDevicePosition; public InputAction @TrackedDeviceOrientation => m_Wrapper.m_UI_TrackedDeviceOrientation; public InputActionMap Get() { return m_Wrapper.m_UI; } public void Enable() { Get().Enable(); } public void Disable() { Get().Disable(); } public bool enabled => Get().enabled; public static implicit operator InputActionMap(UIActions set) { return set.Get(); } public void SetCallbacks(IUIActions instance) { if (m_Wrapper.m_UIActionsCallbackInterface != null) { @Navigate.started -= m_Wrapper.m_UIActionsCallbackInterface.OnNavigate; @Navigate.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnNavigate; @Navigate.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnNavigate; @Submit.started -= m_Wrapper.m_UIActionsCallbackInterface.OnSubmit; @Submit.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnSubmit; @Submit.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnSubmit; @Cancel.started -= m_Wrapper.m_UIActionsCallbackInterface.OnCancel; @Cancel.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnCancel; @Cancel.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnCancel; @Point.started -= m_Wrapper.m_UIActionsCallbackInterface.OnPoint; @Point.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnPoint; @Point.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnPoint; @Click.started -= m_Wrapper.m_UIActionsCallbackInterface.OnClick; @Click.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnClick; @Click.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnClick; @ScrollWheel.started -= m_Wrapper.m_UIActionsCallbackInterface.OnScrollWheel; @ScrollWheel.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnScrollWheel; @ScrollWheel.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnScrollWheel; @MiddleClick.started -= m_Wrapper.m_UIActionsCallbackInterface.OnMiddleClick; @MiddleClick.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnMiddleClick; @MiddleClick.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnMiddleClick; @RightClick.started -= m_Wrapper.m_UIActionsCallbackInterface.OnRightClick; @RightClick.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnRightClick; @RightClick.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnRightClick; @TrackedDevicePosition.started -= m_Wrapper.m_UIActionsCallbackInterface.OnTrackedDevicePosition; @TrackedDevicePosition.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnTrackedDevicePosition; @TrackedDevicePosition.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnTrackedDevicePosition; @TrackedDeviceOrientation.started -= m_Wrapper.m_UIActionsCallbackInterface.OnTrackedDeviceOrientation; @TrackedDeviceOrientation.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnTrackedDeviceOrientation; @TrackedDeviceOrientation.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnTrackedDeviceOrientation; } m_Wrapper.m_UIActionsCallbackInterface = instance; if (instance != null) { @Navigate.started += instance.OnNavigate; @Navigate.performed += instance.OnNavigate; @Navigate.canceled += instance.OnNavigate; @Submit.started += instance.OnSubmit; @Submit.performed += instance.OnSubmit; @Submit.canceled += instance.OnSubmit; @Cancel.started += instance.OnCancel; @Cancel.performed += instance.OnCancel; @Cancel.canceled += instance.OnCancel; @Point.started += instance.OnPoint; @Point.performed += instance.OnPoint; @Point.canceled += instance.OnPoint; @Click.started += instance.OnClick; @Click.performed += instance.OnClick; @Click.canceled += instance.OnClick; @ScrollWheel.started += instance.OnScrollWheel; @ScrollWheel.performed += instance.OnScrollWheel; @ScrollWheel.canceled += instance.OnScrollWheel; @MiddleClick.started += instance.OnMiddleClick; @MiddleClick.performed += instance.OnMiddleClick; @MiddleClick.canceled += instance.OnMiddleClick; @RightClick.started += instance.OnRightClick; @RightClick.performed += instance.OnRightClick; @RightClick.canceled += instance.OnRightClick; @TrackedDevicePosition.started += instance.OnTrackedDevicePosition; @TrackedDevicePosition.performed += instance.OnTrackedDevicePosition; @TrackedDevicePosition.canceled += instance.OnTrackedDevicePosition; @TrackedDeviceOrientation.started += instance.OnTrackedDeviceOrientation; @TrackedDeviceOrientation.performed += instance.OnTrackedDeviceOrientation; @TrackedDeviceOrientation.canceled += instance.OnTrackedDeviceOrientation; } } } public UIActions @UI => new UIActions(this); private int m_KeyboardMouseSchemeIndex = -1; public InputControlScheme KeyboardMouseScheme { get { if (m_KeyboardMouseSchemeIndex == -1) m_KeyboardMouseSchemeIndex = asset.FindControlSchemeIndex("Keyboard&Mouse"); return asset.controlSchemes[m_KeyboardMouseSchemeIndex]; } } private int m_GamepadSchemeIndex = -1; public InputControlScheme GamepadScheme { get { if (m_GamepadSchemeIndex == -1) m_GamepadSchemeIndex = asset.FindControlSchemeIndex("Gamepad"); return asset.controlSchemes[m_GamepadSchemeIndex]; } } private int m_TouchSchemeIndex = -1; public InputControlScheme TouchScheme { get { if (m_TouchSchemeIndex == -1) m_TouchSchemeIndex = asset.FindControlSchemeIndex("Touch"); return asset.controlSchemes[m_TouchSchemeIndex]; } } private int m_JoystickSchemeIndex = -1; public InputControlScheme JoystickScheme { get { if (m_JoystickSchemeIndex == -1) m_JoystickSchemeIndex = asset.FindControlSchemeIndex("Joystick"); return asset.controlSchemes[m_JoystickSchemeIndex]; } } private int m_XRSchemeIndex = -1; public InputControlScheme XRScheme { get { if (m_XRSchemeIndex == -1) m_XRSchemeIndex = asset.FindControlSchemeIndex("XR"); return asset.controlSchemes[m_XRSchemeIndex]; } } public interface IPlayerActions { void OnMove(InputAction.CallbackContext context); void OnLook(InputAction.CallbackContext context); void OnFire(InputAction.CallbackContext context); void OnBtn1(InputAction.CallbackContext context); void OnBtn2(InputAction.CallbackContext context); void OnBtn3(InputAction.CallbackContext context); void OnBtn4(InputAction.CallbackContext context); void OnBtn5(InputAction.CallbackContext context); void OnBtn6(InputAction.CallbackContext context); void OnBtn7(InputAction.CallbackContext context); void OnBtn8(InputAction.CallbackContext context); void OnBtn9(InputAction.CallbackContext context); } public interface IUIActions { void OnNavigate(InputAction.CallbackContext context); void OnSubmit(InputAction.CallbackContext context); void OnCancel(InputAction.CallbackContext context); void OnPoint(InputAction.CallbackContext context); void OnClick(InputAction.CallbackContext context); void OnScrollWheel(InputAction.CallbackContext context); void OnMiddleClick(InputAction.CallbackContext context); void OnRightClick(InputAction.CallbackContext context); void OnTrackedDevicePosition(InputAction.CallbackContext context); void OnTrackedDeviceOrientation(InputAction.CallbackContext context); } }
44.4782
126
0.431097
[ "Unlicense" ]
holypony/TapMushrooms
Assets/Scripts/Input/Mashrooms_Screen_input.cs
63,248
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("InfiniteBox")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("InfiniteBox")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("81613f31-00e8-46c5-b847-9a29b61fde1c")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 //通过使用 "*",如下所示: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.324324
56
0.716115
[ "Apache-2.0" ]
crecheng/DSPMod
InfiniteBox/Properties/AssemblyInfo.cs
1,278
C#
using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Autofac; using NUnit.Framework; using Orchard.Environment; namespace Orchard.Tests.Environment { [TestFixture] public class OrchardStarterTests { [Test] public void DefaultOrchardHostInstanceReturnedByCreateHost() { var host = OrchardStarter.CreateHost(b => b.RegisterInstance(new ControllerBuilder())); Assert.That(host, Is.TypeOf<DefaultOrchardHost>()); } [Test] public void ContainerResolvesServicesInSameOrderTheyAreRegistered() { var container = OrchardStarter.CreateHostContainer(builder => { builder.RegisterType<Component1>().As<IServiceA>(); builder.RegisterType<Component2>().As<IServiceA>(); }); var services = container.Resolve<IEnumerable<IServiceA>>(); Assert.That(services.Count(), Is.EqualTo(2)); Assert.That(services.First(), Is.TypeOf<Component1>()); Assert.That(services.Last(), Is.TypeOf<Component2>()); } [Test] public void MostRecentlyRegisteredServiceReturnsFromSingularResolve() { var container = OrchardStarter.CreateHostContainer(builder => { builder.RegisterType<Component1>().As<IServiceA>(); builder.RegisterType<Component2>().As<IServiceA>(); }); var service = container.Resolve<IServiceA>(); Assert.That(service, Is.Not.Null); Assert.That(service, Is.TypeOf<Component2>()); } public interface IServiceA {} public class Component1 : IServiceA {} public class Component2 : IServiceA {} } }
37.695652
99
0.633218
[ "BSD-3-Clause" ]
1996dylanriley/Orchard
src/Orchard.Tests/Environment/OrchardStarterTests.cs
1,736
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using CitizenFX.Core; using CitizenFX.Core.UI; using static CitizenFX.Core.Native.API; using Magicallity.Client.Helpers; using Magicallity.Client.Player.Controls; using Magicallity.Client.UI.Classes; using Magicallity.Shared; using Magicallity.Shared.Attributes; using Magicallity.Shared.Enums; using Magicallity.Shared.Helpers; using Magicallity.Shared.Loader; using Font = CitizenFX.Core.UI.Font; namespace Magicallity.Client.Jobs.EmergencyServices.Police { public class Radar : JobClass { private bool radarEnabled = false; private bool radarFrozen = false; private ScreenText frontVehText = new ScreenText("", 828, 963, 0.4f, null, Color.FromArgb(255, 255, 255), Font.ChaletLondon, Alignment.Center); private ScreenText backVehText = new ScreenText("", 828, 1006, 0.4f, null, Color.FromArgb(255, 255, 255), Font.ChaletLondon, Alignment.Center); public Radar() { Client.RegisterEventHandler("Police.ToggleRadar", new Action(ToggleRadar)); CommandRegister.RegisterCommand("radar", cmd => { ToggleRadar(); }); } public void ToggleRadar() { radarEnabled = !radarEnabled; Log.ToChat("[Police]", $"Radar {(radarEnabled ? "enabled" : "disabled")}", ConstantColours.Police); } private Vehicle getRadarVehicle(float distance) { var playerVeh = Game.PlayerPed.CurrentVehicle; var baseOffset = GetOffsetFromEntityInWorldCoords(playerVeh.Handle, 0.0f, 1.0f, 1.0f); var captureOffset = GetOffsetFromEntityInWorldCoords(playerVeh.Handle, 0.0f, distance, 0.0f); /*var rayHandle = StartShapeTestCapsule(baseOffset.Z, baseOffset.Y, baseOffset.Z, captureOffset.X, captureOffset.Y, captureOffset.Z, 3.0f, 10, playerVeh.Handle, 7); bool hitEntity = false; Vector3 endCoords = Vector3.Zero; Vector3 surfaceNormal = Vector3.Zero; int entityHit = 0; var rayResult = GetShapeTestResult(rayHandle, ref hitEntity, ref endCoords, ref surfaceNormal, ref entityHit);*/ var data = World.RaycastCapsule(baseOffset, captureOffset, 3.0f, (IntersectOptions)10, playerVeh); return data.DitHitEntity ? data.HitEntity as Vehicle : null; } [DynamicTick(TickUsage.InVehicle)] private async Task RadarTick() { if (Cache.PlayerPed.CurrentVehicle.ClassType != VehicleClass.Emergency || !JobHandler.OnDutyAsJob(JobType.Police)) return; var frontVeh = getRadarVehicle(105.0f); var backVeh = getRadarVehicle(-105.0f); if(radarEnabled) { if (frontVeh != null && !radarFrozen) { frontVehText.Caption = $"F: {frontVeh.LocalizedName} | {frontVeh.Mods.LicensePlate} | {Math.Round(frontVeh.Speed * 2.23694f)} MPH"; } if (backVeh != null && !radarFrozen) { backVehText.Caption = $"B: {backVeh.LocalizedName} | {backVeh.Mods.LicensePlate} | {Math.Round(backVeh.Speed * 2.23694f)} MPH"; } if (Input.IsControlJustPressed(Control.FrontendRdown)) { radarFrozen = !radarFrozen; frontVehText.Color = radarFrozen ? ConstantColours.Green : Color.FromArgb(255, 255, 255); backVehText.Color = radarFrozen ? ConstantColours.Green : Color.FromArgb(255, 255, 255); } frontVehText.DrawTick(); backVehText.DrawTick(); } if (Input.IsControlJustPressed(Control.Detonate)) { if (frontVeh != null) { ExecuteCommand($"runplate {frontVeh.Mods.LicensePlate}"); } } } } }
39.173077
176
0.616102
[ "MIT" ]
Jazzuh/Magicallity-public-source
src/Magicallity.Client/Jobs/EmergencyServices/Police/Radar.cs
4,076
C#
using System; public static partial class Extensions { /// <summary> /// A DateTime extension method that return a DateTime of the last day of the year with the time set to /// "23:59:59:999". The last moment of the last day of the year. Use "DateTime2" column type in sql to keep the /// precision. /// </summary> /// <param name="this">The @this to act on.</param> /// <returns>A DateTime of the last day of the year with the time set to "23:59:59:999".</returns> public static DateTime EndOfYear(this DateTime @this) { return new DateTime(@this.Year, 1, 1).AddYears(1).Subtract(new TimeSpan(0, 0, 0, 0, 1)); } }
43.25
121
0.625723
[ "MIT" ]
edwardmeng/FluentMethods
src/Core/System.DateTime/EndOfYear.cs
694
C#
#nullable enable using System; using Robust.Shared.Serialization; namespace Content.Shared.GameObjects.Components.Singularity { [NetSerializable, Serializable] public enum RadiationCollectorVisuals { VisualState } [NetSerializable, Serializable] public enum RadiationCollectorVisualState { Active, Activating, Deactivating, Deactive } }
18.727273
59
0.68932
[ "MIT" ]
BingoJohnson/space-station-14
Content.Shared/GameObjects/Components/Singularity/SharedRadiationCollectorComponent.cs
414
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BusinessLayer.BadExceptions { public class Operations { public void SaveCustomerAndOrder(CustomerDto customer, OrderDto order) { try { // Load the customer, update it and save it // Load the order, update it and save it } catch (CustomerOperationException ex) { switch (ex.Error) { case CustomerOperationException.CustomerOperationError.SaveCustomrError: throw new BusinessLayerException(ErrorReason.SaveCustomerError); case CustomerOperationException.CustomerOperationError.LoadCustomerError: throw new BusinessLayerException(ErrorReason.LoadCustomerError); default: throw; } } catch (OrderOperationException ex) { switch (ex.Error) { case OrderOperationException.OrderOperationError.SaveOrderError: throw new BusinessLayerException(ErrorReason.SaveOrderError); case OrderOperationException.OrderOperationError.LoadOrderError: throw new BusinessLayerException(ErrorReason.LoadOrderError); default: throw; } } } } }
35.111111
93
0.552532
[ "MIT" ]
claq2/Exceptions
BusinessLayer/BadExceptions/Operations.cs
1,582
C#
using System.Threading.Tasks; namespace Marketplace.Framework { public interface IApplicationService { Task HandleAsync(object command); } }
16.3
41
0.711656
[ "MIT" ]
MHacker9404/Sandbox
Marketplace.Framework/IApplicationService.cs
165
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. // </auto-generated> //------------------------------------------------------------------------------ namespace MemoEngine.Account { public partial class ManageLogins { /// <summary> /// successMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder successMessage; } }
31.32
84
0.478927
[ "MIT" ]
VisualAcademy/EntityFrameworkCore
DotNetNote/MemoEngine/Account/ManageLogins.aspx.designer.cs
785
C#
#region Using directives #endregion namespace Blazorise { public class ThemeProgressOptions : BasicOptions { public string PageProgressDefaultColor { get; set; } = "#ffffff"; } }
18.272727
73
0.691542
[ "MIT" ]
CPlusPlus17/Blazorise
Source/Blazorise/Themes/Models/ThemeProgressOptions.cs
203
C#
#if !NETSTANDARD13 /* * 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 sagemaker-2017-07-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; namespace Amazon.SageMaker.Model { /// <summary> /// Base class for ListPipelines paginators. /// </summary> internal sealed partial class ListPipelinesPaginator : IPaginator<ListPipelinesResponse>, IListPipelinesPaginator { private readonly IAmazonSageMaker _client; private readonly ListPipelinesRequest _request; private int _isPaginatorInUse = 0; /// <summary> /// Enumerable containing all full responses for the operation /// </summary> public IPaginatedEnumerable<ListPipelinesResponse> Responses => new PaginatedResponse<ListPipelinesResponse>(this); /// <summary> /// Enumerable containing all of the PipelineSummaries /// </summary> public IPaginatedEnumerable<PipelineSummary> PipelineSummaries => new PaginatedResultKeyResponse<ListPipelinesResponse, PipelineSummary>(this, (i) => i.PipelineSummaries); internal ListPipelinesPaginator(IAmazonSageMaker client, ListPipelinesRequest request) { this._client = client; this._request = request; } #if BCL IEnumerable<ListPipelinesResponse> IPaginator<ListPipelinesResponse>.Paginate() { if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0) { throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance."); } PaginatorUtils.SetUserAgentAdditionOnRequest(_request); var nextToken = _request.NextToken; ListPipelinesResponse response; do { _request.NextToken = nextToken; response = _client.ListPipelines(_request); nextToken = response.NextToken; yield return response; } while (!string.IsNullOrEmpty(nextToken)); } #endif #if AWS_ASYNC_ENUMERABLES_API async IAsyncEnumerable<ListPipelinesResponse> IPaginator<ListPipelinesResponse>.PaginateAsync(CancellationToken cancellationToken = default) { if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0) { throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance."); } PaginatorUtils.SetUserAgentAdditionOnRequest(_request); var nextToken = _request.NextToken; ListPipelinesResponse response; do { _request.NextToken = nextToken; response = await _client.ListPipelinesAsync(_request, cancellationToken).ConfigureAwait(false); nextToken = response.NextToken; cancellationToken.ThrowIfCancellationRequested(); yield return response; } while (!string.IsNullOrEmpty(nextToken)); } #endif } } #endif
40.040404
150
0.65111
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/_bcl45+netstandard/ListPipelinesPaginator.cs
3,964
C#
using FlubuCore.Context; using FlubuCore.Context.FluentInterface; using FlubuCore.Context.FluentInterface.Interfaces; using FlubuCore.Infrastructure; using FlubuCore.Scripting; using FlubuCore.Targeting; using FlubuCore.Tasks; using FlubuCore.Tests.TestData.BuildScripts.ForCreateTargetWithAttributes; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Moq; using Xunit; namespace FlubuCore.Tests { public class TargetCreatorTests { private readonly ITaskSession _taskSession; public TargetCreatorTests() { var sp = new ServiceCollection().AddTransient<ITarget, TargetFluentInterface>() .AddTransient<ICoreTaskFluentInterface, CoreTaskFluentInterface>() .AddTransient<ITaskFluentInterface, TaskFluentInterface>() .AddTransient<ILinuxTaskFluentInterface, LinuxTaskFluentInterface>() .AddTransient<IIisTaskFluentInterface, IisTaskFluentInterface>() .AddTransient<IWebApiFluentInterface, WebApiFluentInterface>() .AddTransient<IGitFluentInterface, GitFluentInterface>() .AddTransient<IDockerFluentInterface, DockerFluentInterface>() .AddTransient<IToolsFluentInterface, ToolsFluentInterface>() .AddSingleton<IHttpClientFactory, HttpClientFactory>() .BuildServiceProvider(); _taskSession = new TaskSession(new Mock<ILogger<TaskSession>>().Object, new TargetTree(null, null), new CommandArguments(), new Mock<ITaskFactory>().Object, new FluentInterfaceFactory(sp), null, null); } [Fact] public void CreateTargetFromMethodAttributes_AddsTargets_Sucesfull() { TargetCreator.CreateTargetFromMethodAttributes(new BuildScriptWithTargetsFromAttribute(), _taskSession); Assert.Equal(5, _taskSession.TargetTree.TargetCount); Assert.True(_taskSession.TargetTree.HasTarget("Target1")); Assert.True(_taskSession.TargetTree.HasTarget("Target2")); Assert.True(_taskSession.TargetTree.HasTarget("Target3")); } [Fact] public void CreateTargetFromMethodAttributes_NoTargets_Succesfull() { TargetCreator.CreateTargetFromMethodAttributes(new BuildScriptNoTargetsWithAttribute(), _taskSession); Assert.Equal(2, _taskSession.TargetTree.TargetCount); } [Fact] public void CreateTargetFromMethodAttributes_MethodHasNoParameters_ThrowsScriptException() { var ex = Assert.Throws<ScriptException>(() => TargetCreator.CreateTargetFromMethodAttributes(new BuildScriptMethodHasNoParameters(), _taskSession)); Assert.Equal("Failed to create target 'Test'. Method 'TestTarget' must have atleast one parameter which must be of type 'ITarget'", ex.Message); } [Fact] public void CreateTargetFromMethodAttributes_MethodAndAttributeParameterCountDoNotMatch_ThrowsScriptException() { var ex = Assert.Throws<ScriptException>(() => TargetCreator.CreateTargetFromMethodAttributes(new BuildScriptParameterCountNotMatch(), _taskSession)); Assert.Equal("Failed to create target 'Test'. Method parameters TestTarget do not match count of attribute parametrs.", ex.Message); } ////[Fact] ////public void CreateTargetFromMethodAttributes_MethodAndAttributeParameterTypeMismatch_ThrowsScriptException() ////{ //// var ex = Assert.Throws<ScriptException>(() => TargetCreator.CreateTargetFromMethodAttributes(new BuildScriptParameterTypeMismatch(), _taskSession)); //// Assert.Equal("Failed to create target 'Test'. Attribute parameter 21 does not match 'TestTarget' method parameter 21. Expected System.String Actual: System.Int32", ex.Message); ////} } }
51.893333
213
0.71814
[ "BSD-2-Clause" ]
issafram/flubu.core
FlubuCore.Tests/TargetCreatorTests.cs
3,894
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using Microsoft.Win32; namespace RegEditor.Usercontol { public partial class RegistryValuesControl : UserControl { private readonly IEnumerable<string> _typesKind = Enum.GetNames(typeof (RegistryValueKind)); public RegistryValue RegistryValue { get; private set; } public bool DialogResult { get; private set; } public RegistryValuesControl() { InitializeComponent(); cbKeyType.ItemsSource = _typesKind; cbKeyType.SelectedIndex = 0; } public RegistryValuesControl(RegistryValue? value) { InitializeComponent(); tbKeyName.Text = value.Value.Name; cbKeyType.ItemsSource = _typesKind; cbKeyType.SelectedValue = value.Value.Type.ToString(); tbKeyValue.Text = value.Value.Value.ToString(); } private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { if(!tbKeyValue.Text.Any() || !tbKeyName.Text.Any())return; var type = (RegistryValueKind)Enum.Parse(typeof(RegistryValueKind), cbKeyType.SelectedValue.ToString()); RegistryValue = new RegistryValue { Name = tbKeyName.Text ,Value = tbKeyValue.Text ,Type = type }; DialogResult = true; WindowOperator.Cancel_Click(this); } } }
32.125
116
0.620623
[ "CC0-1.0" ]
23S163PR/system-programming
Novak.Andriy/All_Projects/RegEditor/Usercontol/RegistryValuesControl.xaml.cs
1,544
C#
using System.ComponentModel.DataAnnotations; namespace SPID.AspNetCore.IdentityServerSample.IdentityServer.Controllers { public class LoginInputModel { [Required] public string Username { get; set; } [Required] public string Password { get; set; } public bool RememberLogin { get; set; } public string ReturnUrl { get; set; } } }
27.857143
73
0.661538
[ "MIT" ]
AndreaPetrelli/spid-aspnetcore
samples/2_IdentityServer/SPID.AspNetCore.IdentityServerSample.IdentityServer/Controllers/Account/LoginInputModel.cs
390
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; namespace NRoles.Engine.Test.Support.AbstractMembers { public abstract class Base { public abstract int Method(); } [CompositionTest( Description = "Abstract method in a base class should be 'superceded' by abstract role method", RoleType = typeof(Role_With_Abstract_Method), TestType = typeof(Child_Test))] public abstract class Derived : Base, Does<Role_With_Abstract_Method> { } public class Child : Derived { public override int Method() { return 1; } } public abstract class Role_With_Abstract_Method : Role { public abstract int Method(); public virtual int Answer { get { return Method() + 41; } } } public class Child_Test : DynamicTestFixture { public override void Test() { //var r = new Child().As<Role_With_Abstract_Method>(); // mono got confused with the extension method here var r = NRoles.Roles.As<Role_With_Abstract_Method>(new Child()); Assert.AreEqual(42, r.Answer); } } }
27.428571
113
0.669271
[ "MIT" ]
xingh/nroles
src/NRoles.Engine.Test.Acceptance/Support/AbstractMembers.cs
1,154
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Sample.Shared; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Sample.Server.Controllers; [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } }
25.125
110
0.700498
[ "Unlicense" ]
ScriptBox99/blazor-state
Samples/Tutorial/Sample/Server/Controllers/WeatherForecastController.cs
1,005
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace forca { public partial class FrmJogar : Form { public FrmJogar() { InitializeComponent(); } private void FrmJogar_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { this.Hide(); FrmForca frm = new FrmForca(); frm.Show(); } private void FrmJogar_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } } }
19.589744
78
0.600785
[ "CC0-1.0" ]
leomonteiro/incubadora
forca/forca/FrmJogar.cs
766
C#
using NUnit.Framework; using ToDoList.Api.Services.Providers; namespace ToDoList.Api.Services.Tests.Providers { [TestFixture] public class ConnectionConfigurationServiceTests { [Test] public void ConnectionString() { // Act var service = new ConnectionConfiguration(); // Assert Assert.That(service.ConnectionString, Is.EqualTo("http://test.url/todolist"), "Connection string is not correctly retrieved"); } } }
26.15
138
0.623327
[ "MIT" ]
vaclavm/kentico-onboarding-cs
ToDoList/test/ToDoList.Api.Services.Tests/Providers/ConnectionConfigurationTests.cs
525
C#
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2020 Jiang Yin. All rights reserved. // Homepage: https://GameFramework.cn/ // Feedback: mailto:ellan@GameFramework.cn //------------------------------------------------------------ namespace GX.Entity { /// <summary> /// 实体接口。 /// </summary> public interface IEntity { /// <summary> /// 获取实体编号。 /// </summary> int Id { get; } /// <summary> /// 获取实体资源名称。 /// </summary> string EntityAssetName { get; } /// <summary> /// 获取实体实例。 /// </summary> object Handle { get; } /// <summary> /// 获取实体所属的实体组。 /// </summary> IEntityGroup EntityGroup { get; } /// <summary> /// 实体初始化。 /// </summary> /// <param name="entityId">实体编号。</param> /// <param name="entityAssetName">实体资源名称。</param> /// <param name="entityGroup">实体所属的实体组。</param> /// <param name="isNewInstance">是否是新实例。</param> /// <param name="userData">用户自定义数据。</param> void OnInit(int entityId, string entityAssetName, IEntityGroup entityGroup, bool isNewInstance, object userData); /// <summary> /// 实体回收。 /// </summary> void OnRecycle(); /// <summary> /// 实体显示。 /// </summary> /// <param name="userData">用户自定义数据。</param> void OnShow(object userData); /// <summary> /// 实体隐藏。 /// </summary> /// <param name="isShutdown">是否是关闭实体管理器时触发。</param> /// <param name="userData">用户自定义数据。</param> void OnHide(bool isShutdown, object userData); /// <summary> /// 实体附加子实体。 /// </summary> /// <param name="childEntity">附加的子实体。</param> /// <param name="userData">用户自定义数据。</param> void OnAttached(IEntity childEntity, object userData); /// <summary> /// 实体解除子实体。 /// </summary> /// <param name="childEntity">解除的子实体。</param> /// <param name="userData">用户自定义数据。</param> void OnDetached(IEntity childEntity, object userData); /// <summary> /// 实体附加子实体。 /// </summary> /// <param name="parentEntity">被附加的父实体。</param> /// <param name="userData">用户自定义数据。</param> void OnAttachTo(IEntity parentEntity, object userData); /// <summary> /// 实体解除子实体。 /// </summary> /// <param name="parentEntity">被解除的父实体。</param> /// <param name="userData">用户自定义数据。</param> void OnDetachFrom(IEntity parentEntity, object userData); /// <summary> /// 实体轮询。 /// </summary> /// <param name="elapseSeconds">逻辑流逝时间,以秒为单位。</param> /// <param name="realElapseSeconds">真实流逝时间,以秒为单位。</param> void OnUpdate(float elapseSeconds, float realElapseSeconds); } }
28.603604
122
0.470551
[ "MIT" ]
modi00012/GameFramework
GameFramework/Entity/IEntity.cs
3,680
C#
using System; using System.Linq.Expressions; namespace Super.Model.Selection { public class Compile<TIn, TOut> : Select<TIn, TOut> { public Compile(Expression<Func<TIn, TOut>> select) : base(select.Compile()) {} } }
22.2
80
0.720721
[ "MIT" ]
SuperDotNet/Super.NET
Super/Model/Selection/Compile.cs
224
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 macie2-2020-01-01.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.Macie2.Model { /// <summary> /// Provides information about the category, types, and occurrences of sensitive data /// that produced a sensitive data finding. /// </summary> public partial class SensitiveDataItem { private SensitiveDataItemCategory _category; private List<DefaultDetection> _detections = new List<DefaultDetection>(); private long? _totalCount; /// <summary> /// Gets and sets the property Category. /// <para> /// The category of sensitive data that was detected. For example: CREDENTIALS, for credentials /// data such as private keys or AWS secret keys; FINANCIAL_INFORMATION, for financial /// data such as credit card numbers; or, PERSONAL_INFORMATION, for personal health information, /// such as health insurance identification numbers, or personally identifiable information, /// such as driver's license identification numbers. /// </para> /// </summary> public SensitiveDataItemCategory Category { get { return this._category; } set { this._category = value; } } // Check to see if Category property is set internal bool IsSetCategory() { return this._category != null; } /// <summary> /// Gets and sets the property Detections. /// <para> /// An array of objects, one for each type of sensitive data that was detected. Each object /// reports the number of occurrences of a specific type of sensitive data that was detected, /// and the location of up to 15 of those occurrences. /// </para> /// </summary> public List<DefaultDetection> Detections { get { return this._detections; } set { this._detections = value; } } // Check to see if Detections property is set internal bool IsSetDetections() { return this._detections != null && this._detections.Count > 0; } /// <summary> /// Gets and sets the property TotalCount. /// <para> /// The total number of occurrences of the sensitive data that was detected. /// </para> /// </summary> public long TotalCount { get { return this._totalCount.GetValueOrDefault(); } set { this._totalCount = value; } } // Check to see if TotalCount property is set internal bool IsSetTotalCount() { return this._totalCount.HasValue; } } }
35.558824
105
0.614557
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Macie2/Generated/Model/SensitiveDataItem.cs
3,627
C#
namespace LibSignal.Protocol.Net.State { public interface PreKeyStore { // Throws InvalidKeyIdException public PreKeyRecord loadPreKey(int preKeyId); public void storePreKey(int preKeyId, PreKeyRecord record); public bool containsPreKey(int preKeyId); public void removePreKey(int preKeyId); } }
20.764706
67
0.691218
[ "MIT" ]
SeppPenner/LibSignal.Protocol.Net
src/LibSignal.Protocol.Net/State/PreKeyStore.cs
353
C#
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /* * * Marshaler code for OpenWire format for ActiveMQBytesMessage * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the Java Classes * in the nms-activemq-openwire-generator module * */ using System; using System.IO; using Apache.NMS.ActiveMQ.Commands; namespace Apache.NMS.ActiveMQ.OpenWire.V8 { /// <summary> /// Marshalling code for Open Wire Format for ActiveMQBytesMessage /// </summary> class ActiveMQBytesMessageMarshaller : ActiveMQMessageMarshaller { /// <summery> /// Creates an instance of the Object that this marshaller handles. /// </summery> public override DataStructure CreateObject() { return new ActiveMQBytesMessage(); } /// <summery> /// Returns the type code for the Object that this Marshaller handles.. /// </summery> public override byte GetDataStructureType() { return ActiveMQBytesMessage.ID_ACTIVEMQBYTESMESSAGE; } // // Un-marshal an object instance from the data input stream // public override void TightUnmarshal(OpenWireFormat wireFormat, Object o, BinaryReader dataIn, BooleanStream bs) { base.TightUnmarshal(wireFormat, o, dataIn, bs); } // // Write the booleans that this object uses to a BooleanStream // public override int TightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) { int rc = base.TightMarshal1(wireFormat, o, bs); return rc + 0; } // // Write a object instance to data output stream // public override void TightMarshal2(OpenWireFormat wireFormat, Object o, BinaryWriter dataOut, BooleanStream bs) { base.TightMarshal2(wireFormat, o, dataOut, bs); } // // Un-marshal an object instance from the data input stream // public override void LooseUnmarshal(OpenWireFormat wireFormat, Object o, BinaryReader dataIn) { base.LooseUnmarshal(wireFormat, o, dataIn); } // // Write a object instance to data output stream // public override void LooseMarshal(OpenWireFormat wireFormat, Object o, BinaryWriter dataOut) { base.LooseMarshal(wireFormat, o, dataOut); } } }
32.475248
120
0.64878
[ "Apache-2.0" ]
BigYellowHammer/activemq-nms-openwire
src/main/csharp/OpenWire/V8/ActiveMQBytesMessageMarshaller.cs
3,280
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UXI.Common { public class DisposableBase : IDisposable { private bool _disposed; public void Dispose() { Dispose(true); GC.SuppressFinalize(true); } protected virtual void Dispose(bool disposing) { if (_disposed) { return; } _disposed = true; } ~DisposableBase() { Dispose(false); } } }
17.742857
54
0.507246
[ "MIT" ]
martinkonopka/UXI.Libs
src/UXI.Common/DisposableBase.cs
621
C#
using System; using System.Collections.Generic; using System.Text; namespace Ui.MauiX.Test.Models { public class Person { #region Properties public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } #endregion } }
19.625
45
0.617834
[ "MIT" ]
ihvrooman/Ui.MauiX
Ui.MauiX.Test/Models/Person.cs
316
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 26.11.2020. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Multiply.Complete.Int32.NUMERIC_2_1{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Int32; using T_DATA2 =System.Decimal; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields public static class TestSet_001__fields { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_INTEGER"; private const string c_NameOf__COL_DATA2 ="COL2_NUM_2_1"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1)] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2, TypeName="NUMERIC(2,1)")] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1 c_value1=7; const T_DATA2 c_value2=4; System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); Assert.AreEqual (11, c_value1+c_value2); var recs=db.testTable.Where(r => (string)(object)(r.COL_DATA1*r.COL_DATA2)=="28.0" && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").PUSH().N("t",c_NameOf__COL_DATA1).T(" * ").N("t",c_NameOf__COL_DATA2).W_BRKTS().W_CastAsVCH(32).POP().T(" = _utf8 '28.0') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_A001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1 c_value1=7; const T_DATA2 c_value2=4; System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); Assert.AreEqual (11, c_value1+c_value2); var recs=db.testTable.Where(r => (string)(object)(r.COL_DATA1*r.COL_DATA2*1)=="28.0" && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").PUSH().N("t",c_NameOf__COL_DATA1).T(" * ").N("t",c_NameOf__COL_DATA2).W_BRKTS().T(" * 1").W_BRKTS().W_CastAsVCH(32).POP().T(" = _utf8 '28.0') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_A001 //Helper methdods ------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Multiply.Complete.Int32.NUMERIC_2_1
28.146119
225
0.55743
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_002__AS_STR/Multiply/Complete/Int32/NUMERIC_2_1/TestSet_001__fields.cs
6,166
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace PLMPackModel { using System; using System.Collections.Generic; public partial class Group { public Group() { this.CardboardFormats = new HashSet<CardboardFormat>(); this.CardboardProfiles = new HashSet<CardboardProfile>(); this.Documents = new HashSet<Document>(); this.TreeNodeGroupShares = new HashSet<TreeNodeGroupShare>(); this.TreeNodes = new HashSet<TreeNode>(); this.AspNetUsers = new HashSet<AspNetUser>(); this.AspNetUsers1 = new HashSet<AspNetUser>(); this.ParamDefaultComponents = new HashSet<ParamDefaultComponent>(); } public string Id { get; set; } public string GroupName { get; set; } public string GroupDesc { get; set; } public System.DateTime DateCreated { get; set; } public string UserId { get; set; } public virtual AspNetUser AspNetUser { get; set; } public virtual ICollection<CardboardFormat> CardboardFormats { get; set; } public virtual ICollection<CardboardProfile> CardboardProfiles { get; set; } public virtual ICollection<Document> Documents { get; set; } public virtual ICollection<TreeNodeGroupShare> TreeNodeGroupShares { get; set; } public virtual ICollection<TreeNode> TreeNodes { get; set; } public virtual ICollection<AspNetUser> AspNetUsers { get; set; } public virtual ICollection<AspNetUser> AspNetUsers1 { get; set; } public virtual ICollection<ParamDefaultComponent> ParamDefaultComponents { get; set; } } }
44.608696
94
0.609162
[ "MIT" ]
minrogi/PLMPack
Sources/PLMPackModel/Group.cs
2,052
C#
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Website: https://www.blazor.zone or https://argozhang.github.io/ using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Localization; namespace BootstrapBlazor.Components; /// <summary> /// /// </summary> public sealed partial class GoTop { private ElementReference GoTopElement { get; set; } /// <summary> /// 获得/设置 滚动条所在组件 /// </summary> [Parameter] public string? Target { get; set; } /// <summary> /// 获得/设置 鼠标悬停提示文字信息 /// </summary> [Parameter] [NotNull] public string? TooltipText { get; set; } [Inject] [NotNull] private IStringLocalizer<GoTop>? Localizer { get; set; } /// <summary> /// OnInitialized 方法 /// </summary> protected override void OnInitialized() { base.OnInitialized(); TooltipText ??= Localizer[nameof(TooltipText)]; } /// <summary> /// OnAfterRenderAsync 方法 /// </summary> /// <param name="firstRender"></param> /// <returns></returns> protected override async Task OnAfterRenderAsync(bool firstRender) { await base.OnAfterRenderAsync(firstRender); if (firstRender) await JSRuntime.InvokeVoidAsync(GoTopElement, "bb_gotop", Target ?? ""); } }
25.303571
111
0.644319
[ "Apache-2.0" ]
Ashhhhhh520/BootstrapBlazor
src/BootstrapBlazor/Components/Gotop/GoTop.razor.cs
1,477
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. using System.Collections.Generic; using System.Linq; namespace System.Net.NetworkInformation { internal class OsxNetworkInterface : UnixNetworkInterface { private readonly OsxIpInterfaceProperties _ipProperties; private readonly long _speed; protected unsafe OsxNetworkInterface(string name) : base(name) { Interop.Sys.NativeIPInterfaceStatistics nativeStats; if (Interop.Sys.GetNativeIPInterfaceStatistics(name, out nativeStats) == -1) { throw new NetworkInformationException(SR.net_PInvokeError); } _speed = (long)nativeStats.Speed; _ipProperties = new OsxIpInterfaceProperties(this, (int)nativeStats.Mtu); } public unsafe static NetworkInterface[] GetOsxNetworkInterfaces() { Dictionary<string, OsxNetworkInterface> interfacesByName = new Dictionary<string, OsxNetworkInterface>(); List<Exception> exceptions = null; const int MaxTries = 3; for (int attempt = 0; attempt < MaxTries; attempt++) { // Because these callbacks are executed in a reverse-PInvoke, we do not want any exceptions // to propogate out, because they will not be catchable. Instead, we track all the exceptions // that are thrown in these callbacks, and aggregate them at the end. int result = Interop.Sys.EnumerateInterfaceAddresses( (name, ipAddr, maskAddr) => { try { OsxNetworkInterface oni = GetOrCreate(interfacesByName, name); oni.ProcessIpv4Address(ipAddr, maskAddr); } catch (Exception e) { if (exceptions == null) { exceptions = new List<Exception>(); } exceptions.Add(e); } }, (name, ipAddr, scopeId) => { try { OsxNetworkInterface oni = GetOrCreate(interfacesByName, name); oni.ProcessIpv6Address(ipAddr, *scopeId); } catch (Exception e) { if (exceptions == null) { exceptions = new List<Exception>(); } exceptions.Add(e); } }, (name, llAddr) => { try { OsxNetworkInterface oni = GetOrCreate(interfacesByName, name); oni.ProcessLinkLayerAddress(llAddr); } catch (Exception e) { if (exceptions == null) { exceptions = new List<Exception>(); } exceptions.Add(e); } }); if (exceptions != null) { throw new NetworkInformationException(SR.net_PInvokeError, new AggregateException(exceptions)); } else if (result == 0) { return interfacesByName.Values.ToArray(); } else { interfacesByName.Clear(); } } throw new NetworkInformationException(SR.net_PInvokeError); } /// <summary> /// Gets or creates an OsxNetworkInterface, based on whether it already exists in the given Dictionary. /// If created, it is added to the Dictionary. /// </summary> /// <param name="interfaces">The Dictionary of existing interfaces.</param> /// <param name="name">The name of the interface.</param> /// <returns>The cached or new OsxNetworkInterface with the given name.</returns> private static OsxNetworkInterface GetOrCreate(Dictionary<string, OsxNetworkInterface> interfaces, string name) { OsxNetworkInterface oni; if (!interfaces.TryGetValue(name, out oni)) { oni = new OsxNetworkInterface(name); interfaces.Add(name, oni); } return oni; } public override IPInterfaceProperties GetIPProperties() { return _ipProperties; } public override IPInterfaceStatistics GetIPStatistics() { return new OsxIpInterfaceStatistics(Name); } public override IPv4InterfaceStatistics GetIPv4Statistics() { return new OsxIPv4InterfaceStatistics(Name); } public override OperationalStatus OperationalStatus { get { // This is a crude approximation, but does allow us to determine // whether an interface is operational or not. The OS exposes more information // (see ifconfig and the "Status" label), but it's unclear how closely // that information maps to the OperationalStatus enum we expose here. return Addresses.Count > 0 ? OperationalStatus.Up : OperationalStatus.Unknown; } } public override long Speed { get { return _speed; } } public override bool SupportsMulticast { get { return _ipProperties.MulticastAddresses.Count > 0; } } public override bool IsReceiveOnly { get { throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); } } } }
40.429487
136
0.507848
[ "MIT" ]
Roibal/corefx
src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/OsxNetworkInterface.cs
6,307
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DataFactory.Latest.Inputs { /// <summary> /// A copy activity Azure Databricks Delta Lake sink. /// </summary> public sealed class AzureDatabricksDeltaLakeSinkArgs : Pulumi.ResourceArgs { /// <summary> /// Azure Databricks Delta Lake import settings. /// </summary> [Input("importSettings")] public Input<Inputs.AzureDatabricksDeltaLakeImportCommandArgs>? ImportSettings { get; set; } /// <summary> /// The maximum concurrent connection count for the sink data store. Type: integer (or Expression with resultType integer). /// </summary> [Input("maxConcurrentConnections")] public Input<object>? MaxConcurrentConnections { get; set; } /// <summary> /// SQL pre-copy script. Type: string (or Expression with resultType string). /// </summary> [Input("preCopyScript")] public Input<object>? PreCopyScript { get; set; } /// <summary> /// Sink retry count. Type: integer (or Expression with resultType integer). /// </summary> [Input("sinkRetryCount")] public Input<object>? SinkRetryCount { get; set; } /// <summary> /// Sink retry wait. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). /// </summary> [Input("sinkRetryWait")] public Input<object>? SinkRetryWait { get; set; } /// <summary> /// Copy sink type. /// Expected value is 'AzureDatabricksDeltaLakeSink'. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; /// <summary> /// Write batch size. Type: integer (or Expression with resultType integer), minimum: 0. /// </summary> [Input("writeBatchSize")] public Input<object>? WriteBatchSize { get; set; } /// <summary> /// Write batch timeout. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). /// </summary> [Input("writeBatchTimeout")] public Input<object>? WriteBatchTimeout { get; set; } public AzureDatabricksDeltaLakeSinkArgs() { } } }
36.611111
148
0.60091
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/DataFactory/Latest/Inputs/AzureDatabricksDeltaLakeSinkArgs.cs
2,636
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* IrbisBuffer.cs -- helper class for interop with Irbis DLL * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System; using System.Runtime.InteropServices; using JetBrains.Annotations; using MoonSharp.Interpreter; #endregion namespace OfficialWrapper { /// <summary> /// /// </summary> [PublicAPI] [MoonSharpUserData] [StructLayout(LayoutKind.Explicit)] public sealed class IrbisBuffer { #region Properties /// <summary> /// Size. /// </summary> [FieldOffset(0)] public int Size; /// <summary> /// Capacity. /// </summary> [FieldOffset(4)] public int Capacity; /// <summary> /// Pointer. /// </summary> [FieldOffset(8)] public IntPtr Pointer; /// <summary> /// Data. /// </summary> public byte[] Data { get { byte[] result = new byte[Size]; Marshal.Copy(Pointer, result, 0, Size); return result; } } #endregion } }
20.764706
84
0.506374
[ "MIT" ]
amironov73/ManagedClient.45
Source/Classic/Libs/OfficialWrapper/Source/IrbisBuffer.cs
1,414
C#
using System; using System.Linq; namespace _08.CustomComparator { public class CustomComparator { public static Predicate<int> predicate = n => n % 2 == 0; public static void Main() { var input = Console.ReadLine().Split().Select(int.Parse).ToArray(); Array.Sort(input, (x1, x2) => { if (!predicate(x1) && predicate(x2)) { return 1; } if (predicate(x1) && !predicate(x2)) { return -1; } return x1.CompareTo(x2); }); Console.WriteLine(string.Join(" ", input)); } } }
23.451613
79
0.436039
[ "MIT" ]
mdamyanova/C-Sharp-Web-Development
08.C# Fundamentals/08.01.C# Advanced/13.Functional Programming - Exercise/08.CustomComparator/CustomComparator.cs
729
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using AntDesign; using AntDesign.TableModels; using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Logging; using Sitko.Core.App.Blazor.Components; using Sitko.Core.Repository; namespace Sitko.Core.Blazor.AntDesignComponents.Components { public abstract partial class BaseAntListComponent<TItem> where TItem : class { private bool isTableInitialized; private QueryModel? lastQueryModel; private Task<(TItem[] items, int itemsCount)>? loadTask; private MethodInfo? sortMethod; protected IEnumerable<TItem> Items { get; private set; } = Array.Empty<TItem>(); public int Count { get; protected set; } protected Table<TItem>? Table { get; set; } [Parameter] public int PageSize { get; set; } = 50; [Parameter] public int PageIndex { get; set; } = 1; [Parameter] public Func<Task>? OnDataLoaded { get; set; } [Parameter] public RenderFragment<TItem>? ChildContent { get; set; } [Parameter] public RenderFragment<TItem>? RowTemplate { get; set; } [Parameter] public RenderFragment<RowData<TItem>>? ExpandTemplate { get; set; } [Parameter] public Func<RowData<TItem>, bool> RowExpandable { get; set; } = _ => true; [Parameter] public Func<TItem, IEnumerable<TItem>> TreeChildren { get; set; } = _ => Enumerable.Empty<TItem>(); [Parameter] public Func<RowData<TItem>, Dictionary<string, object>> OnRow { get; set; } = _ => new Dictionary<string, object>(); [Parameter] public Func<Dictionary<string, object>> OnHeaderRow { get; set; } = () => new Dictionary<string, object>(); [Parameter] public string? Title { get; set; } [Parameter] public RenderFragment? TitleTemplate { get; set; } [Parameter] public string? Footer { get; set; } [Parameter] public RenderFragment? FooterTemplate { get; set; } [Parameter] public TableSize? Size { get; set; } [Parameter] public TableLocale Locale { get; set; } = LocaleProvider.CurrentLocale.Table; [Parameter] public bool Bordered { get; set; } [Parameter] public string? ScrollX { get; set; } [Parameter] public string? ScrollY { get; set; } [Parameter] public int ScrollBarWidth { get; set; } = 17; [Parameter] public int IndentSize { get; set; } = 15; [Parameter] public int ExpandIconColumnIndex { get; set; } [Parameter] public Func<RowData<TItem>, string> RowClassName { get; set; } = _ => ""; [Parameter] public Func<RowData<TItem>, string> ExpandedRowClassName { get; set; } = _ => ""; [Parameter] public EventCallback<RowData<TItem>> OnExpand { get; set; } [Parameter] public SortDirection[] SortDirections { get; set; } = SortDirection.Preset.Default; [Parameter] public string TableLayout { get; set; } = ""; [Parameter] public EventCallback<RowData<TItem>> OnRowClick { get; set; } [Parameter] public bool HidePagination { get; set; } [Parameter] public string PaginationPosition { get; set; } = "bottomRight"; [Parameter] public EventCallback<int> TotalChanged { get; set; } [Parameter] public EventCallback<PaginationEventArgs> OnPageIndexChange { get; set; } [Parameter] public EventCallback<PaginationEventArgs> OnPageSizeChange { get; set; } [Parameter] public IEnumerable<TItem>? SelectedRows { get; set; } [Parameter] public EventCallback<IEnumerable<TItem>> SelectedRowsChanged { get; set; } public override ScopeType ScopeType { get; set; } = ScopeType.Isolated; protected LoadRequest<TItem>? LastRequest { get; set; } protected override void Initialize() { base.Initialize(); var method = typeof(ITableSortModel).GetMethod("SortList", BindingFlags.NonPublic | BindingFlags.Instance); if (method is null) { throw new MissingMethodException("Method SortList not found"); } sortMethod = method.MakeGenericMethod(typeof(TItem)); Logger.LogDebug("Sort method stored"); } public Task InitializeTableAsync(QueryModel queryModel) { Logger.LogDebug("Try to initialize table"); if (!isTableInitialized) { Logger.LogDebug("Table is not initialized. Proceed"); isTableInitialized = true; return OnChangeAsync(queryModel); } else { Logger.LogDebug("Table already initialized, skip"); } return Task.CompletedTask; } protected async Task OnChangeAsync(QueryModel? queryModel) { Logger.LogDebug("Table model changed. Need to load data"); if (!isTableInitialized) { Logger.LogDebug("Table is not initialized. Skip"); return; } await StartLoadingAsync(); List<FilterOperation<TItem>> filters = new(); List<SortOperation<TItem>> sorts = new(); Logger.LogDebug("Parse query model"); if (queryModel is not null) { if (sortMethod is not null) { foreach (var sortEntry in queryModel.SortModel.Where(s => s.Sort is not null)) { sorts.Add(new SortOperation<TItem>(items => { var sortResult = sortMethod.Invoke(sortEntry, new object?[] { items }); if (sortResult is IOrderedQueryable<TItem> orderedQueryable) { return orderedQueryable; } throw new InvalidOperationException("Error sorting model"); }, sortEntry.FieldName, sortEntry.Sort == SortDirection.Descending.ToString())); } } foreach (var filterModel in queryModel.FilterModel) { var values = new List<FilterOperationValue>(); foreach (var modelFilter in filterModel.Filters) { QueryContextOperator? compareOperator = modelFilter.FilterCompareOperator switch { TableFilterCompareOperator.Equals => QueryContextOperator.Equal, TableFilterCompareOperator.Contains => QueryContextOperator.Contains, TableFilterCompareOperator.StartsWith => QueryContextOperator.StartsWith, TableFilterCompareOperator.EndsWith => QueryContextOperator.EndsWith, TableFilterCompareOperator.GreaterThan => QueryContextOperator.Greater, TableFilterCompareOperator.LessThan => QueryContextOperator.Less, TableFilterCompareOperator.GreaterThanOrEquals => QueryContextOperator.GreaterOrEqual, TableFilterCompareOperator.LessThanOrEquals => QueryContextOperator.LessOrEqual, TableFilterCompareOperator.NotEquals => QueryContextOperator.NotEqual, TableFilterCompareOperator.IsNull => QueryContextOperator.IsNull, TableFilterCompareOperator.IsNotNull => QueryContextOperator.NotNull, TableFilterCompareOperator.NotContains => QueryContextOperator.NotContains, _ => null }; if (compareOperator is not null) { values.Add(new FilterOperationValue(modelFilter.Value, compareOperator.Value)); } else { Logger.LogWarning("Unsupported filter operator: {Operator}", modelFilter.FilterCompareOperator); } } filters.Add(new FilterOperation<TItem>(items => filterModel.FilterList(items), filterModel.FieldName, values.ToArray())); } } var page = queryModel?.PageIndex ?? PageIndex; var request = new LoadRequest<TItem>(page, filters, sorts); Logger.LogDebug("LoadRequest: {@LoadRequest}", request); lastQueryModel = queryModel; try { Logger.LogDebug("Run load data task"); loadTask = GetDataAsync(request); var (items, itemsCount) = await loadTask; Logger.LogDebug("Data loaded. Count: {Count}", itemsCount); Items = items; Count = itemsCount; LastRequest = request; if (OnDataLoaded is not null) { Logger.LogDebug("Execute OnDataLoaded"); await OnDataLoaded(); } } catch (Exception e) { Logger.LogError(e, "Error loading list data: {ErrorText}", e.ToString()); } Logger.LogDebug("Data load is complete"); await StopLoadingAsync(); } public async Task RefreshAsync(int? page = null) { if (page is not null) { PageIndex = page.Value; } await OnChangeAsync(lastQueryModel); } protected abstract Task<(TItem[] items, int itemsCount)> GetDataAsync(LoadRequest<TItem> request, CancellationToken cancellationToken = default); protected override async Task DisposeAsync(bool disposing) { await base.DisposeAsync(disposing); if (loadTask is not null) { await loadTask; } } } public class LoadRequest<TItem> where TItem : class { public LoadRequest(int page, List<FilterOperation<TItem>> filters, List<SortOperation<TItem>> sort) { Page = page; Filters = filters; Sort = sort; } public int Page { get; } public List<FilterOperation<TItem>> Filters { get; } public List<SortOperation<TItem>> Sort { get; } } public class FilterOperation<TItem> where TItem : class { public Func<IQueryable<TItem>, IQueryable<TItem>> Operation { get; } public string Property { get; } public FilterOperation(Func<IQueryable<TItem>, IQueryable<TItem>> operation, string property, FilterOperationValue[] values) { Operation = operation; Property = property; } } public class FilterOperationValue { public object Value { get; } public QueryContextOperator Operator { get; } public FilterOperationValue(object value, QueryContextOperator @operator) { Value = value; Operator = @operator; } } public class SortOperation<TItem> where TItem : class { public Func<IQueryable<TItem>, IOrderedQueryable<TItem>> Operation { get; } public string Property { get; } public bool IsDescending { get; } public SortOperation(Func<IQueryable<TItem>, IOrderedQueryable<TItem>> operation, string property, bool isDescending) { Operation = operation; Property = property; IsDescending = isDescending; } } }
39.078431
119
0.571835
[ "MIT" ]
IgorAlymov/Sitko.Core
src/Sitko.Core.Blazor.AntDesign/Components/BaseAntListComponent.razor.cs
11,960
C#
using System.Collections.Generic; using Improbable.Worker.CInterop; namespace Improbable.Gdk.Core { /// <summary> /// Represents an object which can initialize the connection parameters. /// </summary> public interface IConnectionParameterInitializer { /// <summary> /// Initializes the connection parameters. /// </summary> /// <param name="connectionParameters">The <see cref="ConnectionParameters"/> object to initialize.</param> void Initialize(ConnectionParameters connectionParameters); } public class CommandLineConnectionParameterInitializer : IConnectionParameterInitializer { private readonly CommandLineArgs commandLineArgs; public CommandLineConnectionParameterInitializer() { commandLineArgs = CommandLineArgs.FromCommandLine(); } internal CommandLineConnectionParameterInitializer(Dictionary<string, string> args) { commandLineArgs = CommandLineArgs.From(args); } public void Initialize(ConnectionParameters connectionParameters) { commandLineArgs.TryGetCommandLineValue(RuntimeConfigNames.LinkProtocol, ref connectionParameters.Network.ConnectionType); } } }
33.205128
115
0.688031
[ "MIT" ]
DenDrummer/TI-conf_19-20_groep-1
POC/SpatialOS Maze/gdk-for-unity/workers/unity/Packages/io.improbable.gdk.core/Worker/ConnectionHandlers/ConnectionParameterInitializers.cs
1,295
C#
// THIS FILE IS AUTO-GENERATED using System.Collections.Generic; namespace dotlox { public interface IVisitor<R> { R VisitBinaryExpr(Binary expr); R VisitUnaryExpr(Unary expr); R VisitGroupingExpr(Grouping expr); R VisitLiteralExpr(Literal expr); } public abstract class Expr { public abstract R Accept<R>(IVisitor<R> visitor); } public class Binary : Expr { public Binary(Expr left, Token oper, Expr right) { Left = left; Oper = oper; Right = right; } public override R Accept<R>(IVisitor<R> visitor) { return visitor.VisitBinaryExpr(this); } public Expr Left { get; } public Token Oper { get; } public Expr Right { get; } } public class Unary : Expr { public Unary(Token oper, Expr right) { Oper = oper; Right = right; } public override R Accept<R>(IVisitor<R> visitor) { return visitor.VisitUnaryExpr(this); } public Token Oper { get; } public Expr Right { get; } } public class Grouping : Expr { public Grouping(Expr expression) { Expression = expression; } public override R Accept<R>(IVisitor<R> visitor) { return visitor.VisitGroupingExpr(this); } public Expr Expression { get; } } public class Literal : Expr { public Literal(object value) { Value = value; } public override R Accept<R>(IVisitor<R> visitor) { return visitor.VisitLiteralExpr(this); } public object Value { get; } } }
23.777778
58
0.556659
[ "MIT" ]
martind/dotlox
dotlox/Expr.cs
1,712
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.Emr.Model.V20160408 { public class CreateFlowProjectClusterSettingResponse : AcsResponse { private string requestId; private bool? data; public string RequestId { get { return requestId; } set { requestId = value; } } public bool? Data { get { return data; } set { data = value; } } } }
22.526316
68
0.686916
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-emr/Emr/Model/V20160408/CreateFlowProjectClusterSettingResponse.cs
1,284
C#
using System; using System.Net; using Microsoft.VisualStudio.TestTools.UnitTesting; using RestFluencing; using RestFluencing.Assertion; namespace RestFluencing.Sample.GitHub { [TestClass] public class GitHubGetRequests { [TestInitialize] public void FixTsl() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; } [TestMethod] public void SimpleGetRequest() { Rest.GetFromUrl("https://api.github.com/users/defunkt") .WithHeader("User-Agent", "RestFluencing Sample") .Response() .ReturnsStatus(HttpStatusCode.OK) .Assert(); } [TestMethod] public void SimpleGetRequestNotFound() { Rest.GetFromUrl("https://api.github.com/XXusers/XXXXXXdefunkt") .WithHeader("User-Agent", "RestFluencing Sample") .Response() .ReturnsStatus(HttpStatusCode.NotFound) .Assert(); } [TestMethod] public void GetTheModelToPassItOn() { GitHubUserModel user = null; Rest.GetFromUrl("https://api.github.com/users/defunkt") .WithHeader("User-Agent", "RestFluencing Sample") .Response() .ReturnsModel<GitHubUserModel>(model => { user = model; return true; }, string.Empty) .Assert(); Assert.IsNotNull(user); } } }
21.508772
69
0.700653
[ "MIT" ]
djmnz/RestFluencing
samples/RestFluencing.Sample.GitHub/GitHubGetRequests.cs
1,228
C#
using System; using System.Collections.Generic; namespace WiremockUI.Data { public class Settings { public Guid Id { get; set; } public Dictionary<string, string> Languages { get; set; } = new Dictionary<string, string>(); public string DefaultLanguage { get; set; } public string TrustStoreDefault { get; set; } public string TrustStorePwdDefault { get; set; } } }
28
101
0.652381
[ "MIT" ]
juniorgasparotto/WiremockUI
src/WiremockUI/Data/Settings.cs
422
C#
using System.Collections; using System.Collections.Generic; namespace DataCloner.Core.Framework { public class StructuralEqualityComparer<T> : IEqualityComparer<T> { private static StructuralEqualityComparer<T> _defaultComparer; public bool Equals(T x, T y) { return StructuralComparisons.StructuralEqualityComparer.Equals(x, y); } public int GetHashCode(T obj) { return StructuralComparisons.StructuralEqualityComparer.GetHashCode(obj); } public static StructuralEqualityComparer<T> Default { get { return _defaultComparer ?? (_defaultComparer = new StructuralEqualityComparer<T>()); } } } }
27.923077
104
0.666667
[ "MIT" ]
naster01/DataCloner
archive/DataCloner.Core.Net/Framework/Helpers.cs
728
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using WebSocketManager; namespace Gis.WsServer { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddSingleton<ConnectionManager>(); services.AddSingleton<WebSocketHandler>(); services.AddControllers(); services.Configure<ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Common.WsServer.Api", Version = "v1" }); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { var serviceScopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>(); var serviceProvider = serviceScopeFactory.CreateScope().ServiceProvider; app.UseRouting(); app.UseForwardedHeaders(); app.UseWebSockets(); app.UseStaticFiles(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Gis.WsServer.Api")); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.Map("/ws", app => app.UseMiddleware<WebSocketManagerMiddleware>(serviceProvider.GetService<WebSocketHandler>())); } } }
31.967742
129
0.631685
[ "Apache-2.0" ]
maksim83/InsideTest
Common.WsServer/Startup.cs
1,982
C#
namespace MyLisp { public enum SyntaxKind { PlusToken, MinusToken, StarToken, SlashToken, BadToken, EndOfFileToken, OpenParenthesisToken, CloseParenthesisToken, IntegerNumberToken, FloatingPointNumberToken, IdentifierToken, StringToken, PercentToken, QuoteToken, OnePlusToken, OneMinusToken, } }
19
33
0.574371
[ "MIT" ]
DavidBetteridge/Lisp
MyLisp/01. Lexer/SyntaxKind.cs
439
C#
using System; using UnityEngine; [Serializable] public class MazeRoomSettings { public Material FloorMaterial; public Material wallMaterial; }
15.3
34
0.777778
[ "MIT" ]
mayxen/Maze-Game
Assets/Proyect/Scripts/MazeRoomSettings.cs
155
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from /usr/include/x86_64-linux-gnu/sys/types.h and corresponding dependencies of Ubuntu 20.04 // Original source is Copyright © Free Software Foundation, Inc. Licensed under the GNU Lesser General Public License v2.1 or later. // For the purposes of LGPL v3.0 this is a "Combined Work" where the "Application" (TerraFX.Interop.LibC) makes use of the "Library" (LibC) // by dynamically linking to the "Library". The object code from of the "Application" incoroprates material from the source header files // that are provided as part of the "Library" and is limited to numerical parameters, data structure layouts and accessors, small macros, // and inline functions and templates (ten or fewer lines in length). using System; namespace TerraFX.Interop.LibC; public unsafe partial struct pthread_t : IComparable, IComparable<pthread_t>, IEquatable<pthread_t>, IFormattable { [NativeTypeName("unsigned long int")] public readonly nuint Value; public pthread_t(nuint value) { Value = value; } public static bool operator ==(pthread_t left, pthread_t right) => left.Value == right.Value; public static bool operator !=(pthread_t left, pthread_t right) => left.Value != right.Value; public static bool operator <(pthread_t left, pthread_t right) => left.Value < right.Value; public static bool operator <=(pthread_t left, pthread_t right) => left.Value <= right.Value; public static bool operator >(pthread_t left, pthread_t right) => left.Value > right.Value; public static bool operator >=(pthread_t left, pthread_t right) => left.Value >= right.Value; public static implicit operator pthread_t(byte value) => new pthread_t(value); public static explicit operator byte(pthread_t value) => (byte)(value.Value); public static explicit operator pthread_t(short value) => new pthread_t((nuint)(value)); public static explicit operator short(pthread_t value) => (short)(value.Value); public static explicit operator pthread_t(int value) => new pthread_t((nuint)(value)); public static explicit operator int(pthread_t value) => (int)(value.Value); public static explicit operator pthread_t(long value) => new pthread_t((nuint)(value)); public static explicit operator long(pthread_t value) => (long)(value.Value); public static explicit operator pthread_t(nint value) => new pthread_t((nuint)(value)); public static explicit operator nint(pthread_t value) => (nint)(value.Value); public static explicit operator pthread_t(sbyte value) => new pthread_t((nuint)(value)); public static explicit operator sbyte(pthread_t value) => (sbyte)(value.Value); public static implicit operator pthread_t(ushort value) => new pthread_t(value); public static explicit operator ushort(pthread_t value) => (ushort)(value.Value); public static implicit operator pthread_t(uint value) => new pthread_t(value); public static explicit operator uint(pthread_t value) => (uint)(value.Value); public static explicit operator pthread_t(ulong value) => new pthread_t((nuint)(value)); public static implicit operator ulong(pthread_t value) => value.Value; public static implicit operator pthread_t(nuint value) => new pthread_t(value); public static implicit operator nuint(pthread_t value) => value.Value; public int CompareTo(object? obj) { if (obj is pthread_t other) { return CompareTo(other); } return (obj is null) ? 1 : throw new ArgumentException("obj is not an instance of pthread_t."); } public int CompareTo(pthread_t other) => Value.CompareTo(other.Value); public override bool Equals(object? obj) => (obj is pthread_t other) && Equals(other); public bool Equals(pthread_t other) => Value.Equals(other.Value); public override int GetHashCode() => Value.GetHashCode(); public override string ToString() => Value.ToString(); public string ToString(string? format, IFormatProvider? formatProvider) => Value.ToString(format, formatProvider); }
42.666667
145
0.727036
[ "MIT" ]
tannergooding/terrafx.interop.libc
sources/Interop/Libc/Posix/sys/types/pthread_t.cs
4,226
C#
// The MIT License (MIT) // Copyright (c) 2015 Ben Abelshausen // 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 System; using System.Linq; using System.Collections.Generic; namespace GTFS.Entities.Collections { /// <summary> /// A collection of GTFS-entities that can be identified by an ID based on a list. /// </summary> public class UniqueEntityListCollection<T> : IUniqueEntityCollection<T> where T : GTFSEntity { /// <summary> /// Holds the list containing all stops. /// </summary> private List<T> _entities; /// <summary> /// Holds the function to match ID's. /// </summary> private Func<T, string, bool> _hasId; /// <summary> /// Creates a unique entity collection based on a list. /// </summary> /// <param name="entities"></param> /// <param name="hasId"></param> public UniqueEntityListCollection(List<T> entities, Func<T, string, bool> hasId) { _entities = entities; _hasId = hasId; } /// <summary> /// Adds an entity. /// </summary> /// <param name="entity"></param> public void Add(T entity) { _entities.Add(entity); } /// <summary> /// Gets the entity with the given id. /// </summary> /// <param name="entityId"></param> /// <returns></returns> public T Get(string entityId) { foreach(var entity in _entities) { if(_hasId(entity, entityId)) { return entity; } } return default(T); } /// <summary> /// Gets the entity at the given index. /// </summary> /// <param name="idx"></param> /// <returns></returns> public T Get(int idx) { return _entities[idx]; } /// <summary> /// Removes the entity with the given id. /// </summary> /// <param name="entityId"></param> /// <returns></returns> public bool Remove(string entityId) { for (int idx = 0; idx < _entities.Count; idx++) { var stop = _entities[idx]; if (_hasId(stop, entityId)) { _entities.RemoveAt(idx); return true; } } return false; } /// <summary> /// Returns all entities. /// </summary> /// <returns></returns> public IEnumerable<T> Get() { return _entities; } public IEnumerable<string> GetIds() { throw new NotImplementedException(); } /// <summary> /// Returns the number of entities. /// </summary> public int Count { get { return _entities.Count; } } /// <summary> /// Returns an enumerator that iterates through the entities. /// </summary> /// <returns></returns> public IEnumerator<T> GetEnumerator() { return _entities.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the entities. /// </summary> /// <returns></returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _entities.GetEnumerator(); } /// <summary> /// This is just a placeholder /// </summary> /// <returns></returns> public bool Update(string entityId, T newEntity) { throw new NotImplementedException(); } /// <summary> /// This is just a placeholder /// </summary> /// <returns></returns> public void AddRange(IUniqueEntityCollection<T> entities) { _entities.AddRange(entities); } /// <summary> /// This is just a placeholder /// </summary> /// <returns></returns> public void RemoveRange(IEnumerable<string> entityIds) { throw new NotImplementedException(); } /// <summary> /// Replaces the internal list of entities with a new, empty list. /// </summary> /// <returns></returns> public void RemoveAll() { _entities = new List<T>(); } } }
29.951872
88
0.542403
[ "MIT" ]
timminata/GTFS
GTFS/Entities/Collections/UniqueEntityListCollection.cs
5,603
C#
using System.Globalization; using SixLabors.ImageSharp.PixelFormats; namespace WizBot.Services { /// <summary> /// Custom setting value parsers for types which don't have them by default /// </summary> public static class ConfigParsers { /// <summary> /// Default string parser. Passes input to output and returns true. /// </summary> public static bool String(string input, out string output) { output = input; return true; } public static bool Culture(string input, out CultureInfo output) { try { output = new CultureInfo(input); return true; } catch { output = null; return false; } } } public static class ConfigPrinters { public static string ToString<TAny>(TAny input) => input.ToString(); public static string Culture(CultureInfo culture) => culture.Name; public static string Color(Rgba32 color) => ((uint) (color.B << 0 | color.G << 8 | color.R << 16)).ToString("X6"); } }
26.434783
85
0.53125
[ "MIT" ]
Wizkiller96/WizBot
src/WizBot/Services/Settings/ConfigParsers.cs
1,218
C#
using System; namespace ProtoBuf.Meta { public delegate void TypeFormatEventHandler(object sender, TypeFormatEventArgs args); }
18.571429
86
0.823077
[ "MIT" ]
corefan/tianqi_src
src/ProtoBuf.Meta/TypeFormatEventHandler.cs
130
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using OrchardCore.ContentManagement.Metadata.Models; using OrchardCore.ContentManagement.Utilities; namespace OrchardCore.ContentManagement.Metadata.Builders { public class ContentTypeDefinitionBuilder { private string _name; private string _displayName; private readonly IList<ContentTypePartDefinition> _parts; private readonly JObject _settings; public ContentTypeDefinition Current { get; private set; } public ContentTypeDefinitionBuilder() : this(new ContentTypeDefinition(null, null)) { } public ContentTypeDefinitionBuilder(ContentTypeDefinition existing) { Current = existing; if (existing == null) { _parts = new List<ContentTypePartDefinition>(); _settings = new JObject(); } else { _name = existing.Name; _displayName = existing.DisplayName; _parts = existing.Parts.ToList(); _settings = new JObject(existing.Settings); } } public ContentTypeDefinition Build() { if (!_name[0].IsLetter()) { throw new ArgumentException("Content type name must start with a letter", "name"); } if (!String.Equals(_name, _name.ToSafeName(), StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("Content type name contains invalid characters", "name"); } if (_name.IsReservedContentName()) { throw new ArgumentException("Content type name is reserved for internal use", "name"); } return new ContentTypeDefinition(_name, _displayName, _parts, _settings); } public ContentTypeDefinitionBuilder Named(string name) { _name = name; return this; } public ContentTypeDefinitionBuilder DisplayedAs(string displayName) { _displayName = displayName; return this; } [Obsolete("Use WithSettings<T>. This will be removed in a future version.")] public ContentTypeDefinitionBuilder WithSetting(string name, object value) { _settings[name] = JToken.FromObject(value); return this; } public ContentTypeDefinitionBuilder MergeSettings(JObject settings) { _settings.Merge(settings, ContentBuilderSettings.JsonMergeSettings); return this; } public ContentTypeDefinitionBuilder MergeSettings<T>(Action<T> setting) where T : class, new() { var existingJObject = _settings[typeof(T).Name] as JObject; // If existing settings do not exist, create. if (existingJObject == null) { existingJObject = JObject.FromObject(new T(), ContentBuilderSettings.IgnoreDefaultValuesSerializer); _settings[typeof(T).Name] = existingJObject; } var settingsToMerge = existingJObject.ToObject<T>(); setting(settingsToMerge); _settings[typeof(T).Name] = JObject.FromObject(settingsToMerge, ContentBuilderSettings.IgnoreDefaultValuesSerializer); return this; } public ContentTypeDefinitionBuilder WithSettings<T>(T settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var jObject = JObject.FromObject(settings, ContentBuilderSettings.IgnoreDefaultValuesSerializer); _settings[typeof(T).Name] = jObject; return this; } public ContentTypeDefinitionBuilder RemovePart(string partName) { var existingPart = _parts.SingleOrDefault(x => x.Name == partName); if (existingPart != null) { _parts.Remove(existingPart); } return this; } public ContentTypeDefinitionBuilder WithPart(string partName) { return WithPart(partName, configuration => { }); } public ContentTypeDefinitionBuilder WithPart(string name, string partName) { return WithPart(name, new ContentPartDefinition(partName), configuration => { }); } public ContentTypeDefinitionBuilder WithPart(string name, string partName, Action<ContentTypePartDefinitionBuilder> configuration) { return WithPart(name, new ContentPartDefinition(partName), configuration); } public ContentTypeDefinitionBuilder WithPart(string partName, Action<ContentTypePartDefinitionBuilder> configuration) { return WithPart(partName, new ContentPartDefinition(partName), configuration); } public ContentTypeDefinitionBuilder WithPart(string name, ContentPartDefinition partDefinition, Action<ContentTypePartDefinitionBuilder> configuration) { var existingPart = _parts.FirstOrDefault(x => x.Name == name); if (existingPart != null) { _parts.Remove(existingPart); } else { existingPart = new ContentTypePartDefinition(name, partDefinition, new JObject()); existingPart.ContentTypeDefinition = Current; } var configurer = new PartConfigurerImpl(existingPart); configuration(configurer); _parts.Add(configurer.Build()); return this; } public Task<ContentTypeDefinitionBuilder> WithPartAsync(string name, string partName, Func<ContentTypePartDefinitionBuilder, Task> configurationAsync) { return WithPartAsync(name, new ContentPartDefinition(partName), configurationAsync); } public Task<ContentTypeDefinitionBuilder> WithPartAsync(string partName, Func<ContentTypePartDefinitionBuilder, Task> configurationAsync) { return WithPartAsync(partName, new ContentPartDefinition(partName), configurationAsync); } public async Task<ContentTypeDefinitionBuilder> WithPartAsync(string name, ContentPartDefinition partDefinition, Func<ContentTypePartDefinitionBuilder, Task> configurationAsync) { var existingPart = _parts.FirstOrDefault(x => x.Name == name); if (existingPart != null) { _parts.Remove(existingPart); } else { existingPart = new ContentTypePartDefinition(name, partDefinition, new JObject()); existingPart.ContentTypeDefinition = Current; } var configurer = new PartConfigurerImpl(existingPart); await configurationAsync(configurer); _parts.Add(configurer.Build()); return this; } private class PartConfigurerImpl : ContentTypePartDefinitionBuilder { private readonly ContentPartDefinition _partDefinition; public PartConfigurerImpl(ContentTypePartDefinition part) : base(part) { Current = part; _partDefinition = part.PartDefinition; } public override ContentTypePartDefinition Build() { if (!Current.Name[0].IsLetter()) { throw new ArgumentException("Content part name must start with a letter", "name"); } if (!String.Equals(Current.Name, Current.Name.ToSafeName(), StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("Content part name contains invalid characters", "name"); } return new ContentTypePartDefinition(Current.Name, _partDefinition, _settings) { ContentTypeDefinition = Current.ContentTypeDefinition, }; } } } }
36.440529
185
0.608559
[ "BSD-3-Clause" ]
1051324354/OrchardCore
src/OrchardCore/OrchardCore.ContentManagement.Abstractions/Metadata/Builders/ContentTypeDefinitionBuilder.cs
8,272
C#
namespace BNQ.Core.Extensions { public static class PotExtensions { public static double GetHalfPot(this double pot) { return pot / 2; } } }
18.181818
57
0.535
[ "MIT" ]
YouJinTou/BNQ
BNQ/BNQ.Core/Extensions/PotExtensions.cs
202
C#
namespace More.Windows.Input { using System; using System.Diagnostics.Contracts; using System.Threading.Tasks; /// <summary> /// Represents an asynchronous, named command<seealso cref="NamedCommand{T}"/>. /// </summary> /// <typeparam name="T">The <see cref="Type">type</see> of parameter associated with the command.</typeparam> public class AsyncNamedCommand<T> : AsyncCommand<T>, INamedCommand { string id; string name; string desc = string.Empty; /// <summary> /// Initializes a new instance of the <see cref="AsyncNamedCommand{T}"/> class. /// </summary> /// <param name="name">The command name.</param> /// <param name="executeAsyncMethod">The <see cref="Func{T,TResult}"/> representing the asynchronous execute method.</param> public AsyncNamedCommand( string name, Func<T, Task> executeAsyncMethod ) : this( null, name, executeAsyncMethod, DefaultFunc.CanExecute ) { } /// <summary> /// Initializes a new instance of the <see cref="AsyncNamedCommand{T}"/> class. /// </summary> /// <param name="id">The command identifier.</param> /// <param name="name">The command name.</param> /// <param name="executeAsyncMethod">The <see cref="Func{T,TResult}"/> representing the asynchronous execute method.</param> public AsyncNamedCommand( string id, string name, Func<T, Task> executeAsyncMethod ) : this( id, name, executeAsyncMethod, DefaultFunc.CanExecute ) { } /// <summary> /// Initializes a new instance of the <see cref="AsyncNamedCommand{T}"/> class. /// </summary> /// <param name="name">The command name.</param> /// <param name="executeAsyncMethod">The <see cref="Func{T,TResult}"/> representing the asynchronous execute method.</param> /// <param name="canExecuteMethod">The <see cref="Func{T1,T2}"/> representing the can execute method.</param> public AsyncNamedCommand( string name, Func<T, Task> executeAsyncMethod, Func<T, bool> canExecuteMethod ) : this( null, name, executeAsyncMethod, canExecuteMethod ) { } /// <summary> /// Initializes a new instance of the <see cref="AsyncNamedCommand{T}"/> class. /// </summary> /// <param name="id">The command identifier.</param> /// <param name="name">The command name.</param> /// <param name="executeAsyncMethod">The <see cref="Func{T,TResult}"/> representing the asynchronous execute method.</param> /// <param name="canExecuteMethod">The <see cref="Func{T1,T2}"/> representing the can execute method.</param> public AsyncNamedCommand( string id, string name, Func<T, Task> executeAsyncMethod, Func<T, bool> canExecuteMethod ) : base( executeAsyncMethod, canExecuteMethod ) { Arg.NotNullOrEmpty( name, nameof( name ) ); this.id = id; this.name = name; } /// <summary> /// Gets or sets the command name. /// </summary> /// <value>The command name.</value> public string Name { get { Contract.Ensures( !string.IsNullOrEmpty( name ) ); return name; } set { Arg.NotNullOrEmpty( value, nameof( value ) ); SetProperty( ref name, value ); } } /// <summary> /// Gets or sets the command description. /// </summary> /// <value>The command description.</value> public virtual string Description { get { Contract.Ensures( desc != null ); return desc; } set { Arg.NotNull( value, nameof( value ) ); SetProperty( ref desc, value ); } } /// <summary> /// Gets or sets the identifier associated with the command. /// </summary> /// <value>The command identifier. If this property is unset, the default /// value is the <see cref="Name">name</see> of the command.</value> public string Id { get { Contract.Ensures( !string.IsNullOrEmpty( Contract.Result<string>() ) ); return string.IsNullOrEmpty( id ) ? Name : id; } set { Arg.NotNullOrEmpty( value, nameof( value ) ); SetProperty( ref id, value ); } } } }
40.666667
132
0.562338
[ "MIT" ]
JTOne123/More
src/More.UI/Windows.Input/AsyncNamedCommand{T}.cs
4,638
C#
using OOPsIDidItAgain._05.MakeUseOfTypeSafety.Web.Shared; namespace OOPsIDidItAgain._05.MakeUseOfTypeSafety.Web.Domain { public interface IItemRepository { Item? Get(ItemId itemId); } }
22.888889
60
0.752427
[ "MIT" ]
joaofbantunes/OOPsIDidItAgain
src/OOPsIDidItAgain.05.MakeUseOfTypeSafety.Web/Domain/IItemRepository.cs
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 glacier-2012-06-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Glacier.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Glacier.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DescribeJob operation /// </summary> public class DescribeJobResponseUnmarshaller : JsonResponseUnmarshaller { public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DescribeJobResponse response = new DescribeJobResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Action", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Action = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ArchiveId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.ArchiveId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ArchiveSHA256TreeHash", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.ArchiveSHA256TreeHash = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ArchiveSizeInBytes", targetDepth)) { var unmarshaller = LongUnmarshaller.Instance; response.ArchiveSizeInBytes = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Completed", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; response.Completed = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("CompletionDate", targetDepth)) { var unmarshaller = Amazon.Runtime.Internal.Transform.DateTimeUnmarshaller.Instance; response.CompletionDate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("CreationDate", targetDepth)) { var unmarshaller = Amazon.Runtime.Internal.Transform.DateTimeUnmarshaller.Instance; response.CreationDate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("InventoryRetrievalParameters", targetDepth)) { var unmarshaller = InventoryRetrievalJobDescriptionUnmarshaller.Instance; response.InventoryRetrievalParameters = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("InventorySizeInBytes", targetDepth)) { var unmarshaller = LongUnmarshaller.Instance; response.InventorySizeInBytes = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("JobDescription", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.JobDescription = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("JobId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.JobId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("RetrievalByteRange", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.RetrievalByteRange = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SHA256TreeHash", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.SHA256TreeHash = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SNSTopic", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.SNSTopic = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("StatusCode", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.StatusCode = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("StatusMessage", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.StatusMessage = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("VaultARN", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.VaultARN = unmarshaller.Unmarshall(context); continue; } } return response; } public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterValueException")) { return new InvalidParameterValueException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("MissingParameterValueException")) { return new MissingParameterValueException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return new ResourceNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException")) { return new ServiceUnavailableException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonGlacierException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static DescribeJobResponseUnmarshaller _instance = new DescribeJobResponseUnmarshaller(); internal static DescribeJobResponseUnmarshaller GetInstance() { return _instance; } public static DescribeJobResponseUnmarshaller Instance { get { return _instance; } } } }
45.227979
174
0.595372
[ "Apache-2.0" ]
ermshiperete/aws-sdk-net
AWSSDK_DotNet35/Amazon.Glacier/Model/Internal/MarshallTransformations/DescribeJobResponseUnmarshaller.cs
8,729
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace LaserControl.HardwareAPI { public class Camera { public virtual string Name { get { return "Hardware API Camera"; } } public virtual string Path { get; set; } public virtual bool IsConnected { get; protected set; } public Camera(string path) { //tada Path = path; IsConnected = false; } public virtual void SetDisplayingImageType(int type) { } public virtual void SetOverlay(bool threshold, bool fixedCross, bool detectedCross) { } public virtual void SetProcessing(bool doprocessing) { } public virtual void SetThreshold(int newThreshold) { } public virtual void SetInvertThreshold(bool inv) { } public virtual Bitmap GetImage() { return new Bitmap(1,1); } public virtual void DisplayCurrentImage() { } public virtual double GetXPercent() { return 0; } public virtual double GetYPercent() { return 0; } } }
17.166667
91
0.493065
[ "MIT" ]
Lowhuhn/LaserControl
LaserControl/LaserControl.HardwareAPI/Camera.cs
1,444
C#
using Foundatio.Parsers.ElasticQueries.Extensions; using Foundatio.Parsers.LuceneQueries.Nodes; using Foundatio.Parsers.LuceneQueries.Visitors; using Nest; namespace Exceptionless.Core.Repositories.Queries; public class StackDateFixedQueryVisitor : ChainableQueryVisitor { private readonly string _dateFixedFieldName; public StackDateFixedQueryVisitor(string dateFixedFieldName) { if (String.IsNullOrEmpty(dateFixedFieldName)) throw new ArgumentNullException(nameof(dateFixedFieldName)); _dateFixedFieldName = dateFixedFieldName; } public override Task<IQueryNode> VisitAsync(TermNode node, IQueryVisitorContext context) { if (!String.Equals(node.Field, "fixed", StringComparison.OrdinalIgnoreCase)) return Task.FromResult<IQueryNode>(node); if (!Boolean.TryParse(node.Term, out bool isFixed)) return Task.FromResult<IQueryNode>(node); var query = new ExistsQuery { Field = _dateFixedFieldName }; node.SetQuery(isFixed ? query : !query); return Task.FromResult<IQueryNode>(node); } }
36.8
94
0.740036
[ "Apache-2.0" ]
491134648/Exceptionless
src/Exceptionless.Core/Repositories/Queries/Visitors/StackDateFixedQueryVisitor.cs
1,106
C#
using Microsoft.Extensions.Logging; using NLog; using NLog.Config; using NLog.Targets; using NLog.Layouts; using NLog.Extensions.Logging; namespace LoggingBenchmarks { #pragma warning disable CA2000 // Dispose objects before losing scope public static class NLogProvider { public static (ILoggerProvider LogggerProvider, LogFactory LogFactory) CreateNLogProvider() { LoggingConfiguration Config = new LoggingConfiguration(); JsonLayout Layout = new JsonLayout { IncludeAllProperties = true }; Layout.Attributes.Add(new JsonAttribute("time", "${longdate}")); Layout.Attributes.Add(new JsonAttribute("threadId", "${threadid}")); Layout.Attributes.Add(new JsonAttribute("level", "${level:upperCase=true}")); Layout.Attributes.Add(new JsonAttribute("message", "${message}")); Target Target = new ConsoleTarget("Console") { Layout = Layout, AutoFlush = true, // Matches Serilog Buffered }; Config.AddTarget("Console", Target); Config.AddRuleForAllLevels(Target, "*", true); LogFactory LogFactory = new LogFactory(Config); NLogLoggerProvider Provider = new NLogLoggerProvider( new NLogProviderOptions { ShutdownOnDispose = true }, LogFactory); return (Provider, LogFactory); } } #pragma warning restore CA2000 // Dispose objects before losing scope }
26.057692
93
0.721033
[ "MIT" ]
0xced/core
ClassLibraries/Macross.Logging.StandardOutput/Benchmarks/NLogProvider.cs
1,357
C#
using GraphQL.Types; namespace P7.BlogStore.Core.GraphQL { public class BlogMutationInput : InputObjectGraphType { public BlogMutationInput() { Name = "blogMutationInput"; Field<NonNullGraphType<StringGraphType>>("id"); Field<NonNullGraphType<MetaDataInput>>("metaData"); Field<NonNullGraphType<BlogInput>>("document"); } } public class BlogInput : InputObjectGraphType { public BlogInput() { Name = "blogInput"; Field<NonNullGraphType<StringGraphType>>("data"); Field<NonNullGraphType<DateGraphType>>("timeStamp"); Field<NonNullGraphType<StringGraphType>>("title"); Field<NonNullGraphType<StringGraphType>>("summary"); Field<ListGraphType<StringGraphType>>("tags"); Field<ListGraphType<StringGraphType>>("categories"); } } }
33.25
64
0.615467
[ "Apache-2.0" ]
ghstahl/P7
src/P7.BlogStore.Core/GraphQL/BlogMutationInput.cs
933
C#
using System.Reflection; using System.Runtime.InteropServices; // Общие сведения об этой сборке предоставляются следующим набором // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, // связанные со сборкой. [assembly: AssemblyTitle("MT.SharedComponents")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("MT.SharedComponents")] [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми // для компонентов COM. Если необходимо обратиться к типу в этой сборке через // COM, задайте атрибуту ComVisible значение TRUE для этого типа. [assembly: ComVisible(false)] // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM [assembly: Guid("7fbde973-6216-4d95-adce-eb1ef97e1c42")] // Сведения о версии сборки состоят из следующих четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер сборки // Редакция // // Можно задать все значения или принять номер сборки и номер редакции по умолчанию. // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.444444
99
0.764789
[ "MIT" ]
Sivolday/MT
MT.SharedComponents/Properties/AssemblyInfo.cs
2,000
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using ProjName = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicLineCommit : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicLineCommit(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicLineCommit)) { } [Fact, Trait(Traits.Feature, Traits.Features.LineCommit)] void CaseCorrection() { VisualStudio.Editor.SetText(@"Module Goo Sub M() Dim x = Sub() End Sub End Module"); VisualStudio.Editor.PlaceCaret("Sub()", charsOffset: 1); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.Verify.CaretPosition(48); } [Fact, Trait(Traits.Feature, Traits.Features.LineCommit)] void UndoWithEndConstruct() { VisualStudio.Editor.SetText(@"Module Module1 Sub Main() End Sub REM End Module"); VisualStudio.Editor.PlaceCaret(" REM"); VisualStudio.Editor.SendKeys("sub", VirtualKey.Escape, " goo()", VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@"Sub goo() End Sub"); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Undo); VisualStudio.Editor.Verify.CaretPosition(54); } [Fact, Trait(Traits.Feature, Traits.Features.LineCommit)] void UndoWithoutEndConstruct() { VisualStudio.Editor.SetText(@"Module Module1 ''' <summary></summary> Sub Main() End Sub End Module"); VisualStudio.Editor.PlaceCaret("Module1"); VisualStudio.Editor.SendKeys(VirtualKey.Down, VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@"Module Module1 ''' <summary></summary> Sub Main() End Sub End Module"); VisualStudio.Editor.Verify.CaretPosition(18); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Undo); VisualStudio.Editor.Verify.CaretPosition(16); } [Fact, Trait(Traits.Feature, Traits.Features.LineCommit)] void CommitOnSave() { VisualStudio.Editor.SetText(@"Module Module1 Sub Main() End Sub End Module "); VisualStudio.Editor.PlaceCaret("(", charsOffset: 1); VisualStudio.Editor.SendKeys("x as integer", VirtualKey.Tab); VisualStudio.ExecuteCommand("File.SaveSelectedItems"); VisualStudio.Editor.Verify.TextContains(@"Sub Main(x As Integer)"); VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Undo); VisualStudio.Editor.Verify.TextContains(@"Sub Main(x As Integer)"); VisualStudio.Editor.Verify.CaretPosition(45); } [Fact, Trait(Traits.Feature, Traits.Features.LineCommit)] void CommitOnFocusLost() { VisualStudio.Editor.SetText(@"Module M Sub M() End Sub End Module"); VisualStudio.Editor.PlaceCaret("End Sub", charsOffset: -1); VisualStudio.Editor.SendKeys(" "); VisualStudio.SolutionExplorer.AddFile(new ProjName(ProjectName), "TestZ.vb", open: true); // Cause focus lost VisualStudio.SolutionExplorer.OpenFile(new ProjName(ProjectName), "TestZ.vb"); // Work around https://github.com/dotnet/roslyn/issues/18488 VisualStudio.Editor.SendKeys(" "); VisualStudio.SolutionExplorer.CloseFile(new ProjName(ProjectName), "TestZ.vb", saveFile: false); VisualStudio.Editor.Verify.TextContains(@" Sub M() End Sub "); } [Fact, Trait(Traits.Feature, Traits.Features.LineCommit)] void CommitOnFocusLostDoesNotFormatWithPrettyListingOff() { try { VisualStudio.Workspace.SetPerLanguageOption("PrettyListing", "FeatureOnOffOptions", LanguageNames.VisualBasic, false); VisualStudio.Editor.SetText(@"Module M Sub M() End Sub End Module"); VisualStudio.Editor.PlaceCaret("End Sub", charsOffset: -1); VisualStudio.Editor.SendKeys(" "); VisualStudio.SolutionExplorer.AddFile(new ProjName(ProjectName), "TestZ.vb", open: true); // Cause focus lost VisualStudio.SolutionExplorer.OpenFile(new ProjName(ProjectName), "TestZ.vb"); // Work around https://github.com/dotnet/roslyn/issues/18488 VisualStudio.Editor.SendKeys(" "); VisualStudio.SolutionExplorer.CloseFile(new ProjName(ProjectName), "TestZ.vb", saveFile: false); VisualStudio.Editor.Verify.TextContains(@" Sub M() End Sub "); } finally { VisualStudio.Workspace.SetPerLanguageOption("PrettyListing", "FeatureOnOffOptions", LanguageNames.VisualBasic, true); } } } }
37.606897
161
0.647717
[ "Apache-2.0" ]
ElanHasson/roslyn
src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicLineCommit.cs
5,455
C#
/** * (C) Copyright IBM Corp. 2017, 2019. * * 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.Collections.Generic; using Newtonsoft.Json; namespace IBM.Watson.PersonalityInsights.v3.Model { /// <summary> /// The consumption preferences that the service inferred from the input content. /// </summary> public class ConsumptionPreferencesCategory { /// <summary> /// The unique, non-localized identifier of the consumption preferences category to which the results pertain. /// IDs have the form `consumption_preferences_{category}`. /// </summary> [JsonProperty("consumption_preference_category_id", NullValueHandling = NullValueHandling.Ignore)] public string ConsumptionPreferenceCategoryId { get; set; } /// <summary> /// The user-visible name of the consumption preferences category. /// </summary> [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)] public string Name { get; set; } /// <summary> /// Detailed results inferred from the input text for the individual preferences of the category. /// </summary> [JsonProperty("consumption_preferences", NullValueHandling = NullValueHandling.Ignore)] public List<ConsumptionPreferences> ConsumptionPreferences { get; set; } } }
39.659574
118
0.703863
[ "Apache-2.0" ]
AndreiLuis/dotnet-standard-sdk
src/IBM.Watson.PersonalityInsights.v3/Model/ConsumptionPreferencesCategory.cs
1,864
C#
namespace Examples { using System; using Bond; using Bond.Protocols; using Bond.IO.Unsafe; using examples.schema_view; static class Program { static void Main() { var example = new Example { num = 42, str = "test", items = { 3.14, 0 } }; var output = new OutputBuffer(); var writer = new CompactBinaryWriter<OutputBuffer>(output); Marshal.To(writer, example); var input = new InputBuffer(output.Data); ExampleView view = Unmarshal<ExampleView>.From(input); ThrowIfFalse(example.num == view.num); ThrowIfFalse(example.str.Equals(view.str, StringComparison.Ordinal)); } static void ThrowIfFalse(bool b) { if (!b) throw new Exception("Assertion failed"); } } }
23.74359
81
0.528078
[ "MIT" ]
1lann/bond
examples/cs/core/schema_view/program.cs
928
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Thismaker.Horus.IO; namespace Thismaker.Aretha { class HorusFile : HorusSoul, ISoulServant { private List<string> GenCommands=new List<string>() { "encrypt", "decrypt" }; private List<string> Args = new List<string>() { "key", "input", "output" }; public async Task OnSession(string args = null) { while (true) { var resp = Ask(null, false, true); if (resp.ToLower() == "back") { return; } var valid = false; foreach(var command in GenCommands) { if(resp.ToLower().StartsWith($"{command} ")) { string key=null, input=null, output = null; var part = resp.Remove(0, command.Length + 1); foreach(var arg in Args) { if (!part.ToLower().StartsWith($"-{arg} "))continue; part = part[(arg.Length + 2)..]; var split = part.Split('"',StringSplitOptions.RemoveEmptyEntries); if (nameof(key) == arg) key = split[0]; if (nameof(input) == arg) input = split[0]; if (nameof(output) == arg) output = split[0]; part = part[(split[0].Length+2)..].Trim(); } if(string.IsNullOrEmpty(key)|| string.IsNullOrEmpty(input)|| string.IsNullOrEmpty(output)) { break; } bool encrypt = command == "encrypt"; using var cryptoStream = encrypt? File.OpenWrite(output):File.OpenRead(input); using var plainStream = encrypt? File.OpenRead(input):File.OpenWrite(output); using var file = new CryptoFile(cryptoStream, key); if (encrypt) await file.WriteAsync(plainStream, Aretha.WriteProgress()); else await file.ReadAsync(plainStream, Aretha.WriteProgress()); valid = true; break; } if (!valid) Speak("Not a valid command"); } } } } }
29.645161
103
0.424012
[ "Apache-2.0" ]
Phystro/LiquidSnow
src/Aretha/Souls/HorusSoul/HorusFile.cs
2,759
C#
using System; using Android.Webkit; using Java.Interop; namespace TLExtension.Droid { public class JSBridge : Java.Lang.Object { readonly WeakReference<TLExtensionWebViewRenderer> renderer; public JSBridge(TLExtensionWebViewRenderer inputRenderer) { renderer = new WeakReference<TLExtensionWebViewRenderer>(inputRenderer); } [JavascriptInterface] [Export("invokeAction")] public void InvokeAction(string data) { TLExtensionWebViewRenderer instanceRenderer; if (renderer != null && renderer.TryGetTarget(out instanceRenderer)) { ((TLExtensionWebView)instanceRenderer.Element).InvokeAction(data); } } } }
26.482759
84
0.644531
[ "MIT" ]
HexagramNM/TLExtension
TLExtension.Android/JSBridge.cs
770
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { #pragma warning disable CS8618 [JsiiByValue(fqn: "aws.Wafv2RuleGroupRuleStatementOrStatementStatementOrStatementStatementByteMatchStatement")] public class Wafv2RuleGroupRuleStatementOrStatementStatementOrStatementStatementByteMatchStatement : aws.IWafv2RuleGroupRuleStatementOrStatementStatementOrStatementStatementByteMatchStatement { [JsiiProperty(name: "positionalConstraint", typeJson: "{\"primitive\":\"string\"}", isOverride: true)] public string PositionalConstraint { get; set; } [JsiiProperty(name: "searchString", typeJson: "{\"primitive\":\"string\"}", isOverride: true)] public string SearchString { get; set; } /// <summary>text_transformation block.</summary> [JsiiProperty(name: "textTransformation", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2RuleGroupRuleStatementOrStatementStatementOrStatementStatementByteMatchStatementTextTransformation\"},\"kind\":\"array\"}}", isOverride: true)] public aws.IWafv2RuleGroupRuleStatementOrStatementStatementOrStatementStatementByteMatchStatementTextTransformation[] TextTransformation { get; set; } /// <summary>field_to_match block.</summary> [JsiiOptional] [JsiiProperty(name: "fieldToMatch", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2RuleGroupRuleStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatch\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)] public aws.IWafv2RuleGroupRuleStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatch[]? FieldToMatch { get; set; } } }
43.295455
263
0.700262
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/Wafv2RuleGroupRuleStatementOrStatementStatementOrStatementStatementByteMatchStatement.cs
1,905
C#
/* Copyright (C) 2012-2014 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. */ using System.Collections.Generic; namespace dnlib.DotNet.Writer { /// <summary> /// Interface to get and set raw heap data. Implemented by the offset heaps: #Strings, /// #GUID, #Blob, and #US. /// </summary> /// <typeparam name="TValue">Type of cooked data</typeparam> public interface IOffsetHeap<TValue> { /// <summary> /// Gets the size of the data as raw data when written to the heap /// </summary> /// <param name="data">The data</param> /// <returns>Size of the data as raw data when written to the heap</returns> int GetRawDataSize(TValue data); /// <summary> /// Overrides what value should be written to the heap. /// </summary> /// <param name="offset">Offset of value. Must match an offset returned by /// <see cref="GetAllRawData()"/></param> /// <param name="rawData">The new raw data. The size must match the raw size exactly.</param> void SetRawData(uint offset, byte[] rawData); /// <summary> /// Gets all inserted raw data and their offsets. The returned <see cref="byte"/> array /// is owned by the caller. /// </summary> /// <returns>An enumerable of all raw data and their offsets</returns> IEnumerable<KeyValuePair<uint, byte[]>> GetAllRawData(); } }
42.196429
95
0.71223
[ "MIT" ]
Georgeto/dnlib
src/DotNet/Writer/IOffsetHeap.cs
2,365
C#
using System.Linq; using System.Runtime.CompilerServices; using System; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using GameplayAbilitySystem.ExtensionMethods; using GameplayAbilitySystem.Abilities; using GameplayAbilitySystem.Events; using GameplayAbilitySystem.GameplayEffects; using GameplayAbilitySystem.Interfaces; using UnityEngine; using GameplayAbilitySystem.Attributes; using UnityEngine.Events; using GameplayAbilitySystem.Enums; using GameplayAbilitySystem.GameplayCues; namespace GameplayAbilitySystem { /// <inheritdoc /> [AddComponentMenu("Gameplay Ability System/Ability System")] public class AbilitySystemComponent : MonoBehaviour, IGameplayAbilitySystem { public Transform TargettingLocation; [SerializeField] private GenericAbilityEvent _onGameplayAbilityActivated = new GenericAbilityEvent(); /// <inheritdoc /> public GenericAbilityEvent OnGameplayAbilityActivated => _onGameplayAbilityActivated; [SerializeField] private GenericAbilityEvent _onGameplayAbilityEnded = new GenericAbilityEvent(); /// <inheritdoc /> public GenericAbilityEvent OnGameplayAbilityEnded => _onGameplayAbilityEnded; [SerializeField] private GameplayEvent _onGameplayEvent = new GameplayEvent(); /// <inheritdoc /> public GameplayEvent OnGameplayEvent => _onGameplayEvent; [SerializeField] protected ActiveGameplayEffectsContainer _activeGameplayEffectsContainer; /// <inheritdoc /> public ActiveGameplayEffectsContainer ActiveGameplayEffectsContainer => _activeGameplayEffectsContainer; [SerializeField] protected List<IGameplayAbility> _runningAbilities = new List<IGameplayAbility>(); /// <inheritdoc /> public List<IGameplayAbility> RunningAbilities => _runningAbilities; [SerializeField] protected GenericGameplayEffectEvent _onEffectAdded = new GenericGameplayEffectEvent(); /// <inheritdoc /> public GenericGameplayEffectEvent OnEffectAdded => _onEffectAdded; [SerializeField] protected GenericGameplayEffectEvent _onEffectRemoved = new GenericGameplayEffectEvent(); /// <inheritdoc /> public GenericGameplayEffectEvent OnEffectRemoved => _onEffectRemoved; [SerializeField] private GenericAbilityEvent _onGameplayAbilityCommitted = new GenericAbilityEvent(); /// <inheritdoc /> public GenericAbilityEvent OnGameplayAbilityCommitted => _onGameplayAbilityCommitted; public void Awake() { this._activeGameplayEffectsContainer = new ActiveGameplayEffectsContainer(this); } /// <inheritdoc /> public Transform GetActor() { return this.transform; } void Update() { } /// <inheritdoc /> public void HandleGameplayEvent(GameplayTag EventTag, GameplayEventData Payload) { /** * TODO: Handle triggered abilities * Search component for all abilities that are automatically triggered from a gameplay event */ OnGameplayEvent.Invoke(EventTag, Payload); } /// <inheritdoc /> public void NotifyAbilityEnded(GameplayAbility ability) { _runningAbilities.Remove(ability); } /// <inheritdoc /> public bool TryActivateAbility(GameplayAbility Ability) { if (!this.CanActivateAbility(Ability)) return false; if (!Ability.IsAbilityActivatable(this)) return false; _runningAbilities.Add(Ability); Ability.CommitAbility(this); return true; } /// <inheritdoc /> public bool CanActivateAbility(GameplayAbility Ability) { // Check if an ability is already active on this ASC if (_runningAbilities.Count > 0) { return false; } return true; } public async void ApplyBatchGameplayEffects(IEnumerable<(GameplayEffect Effect, IGameplayAbilitySystem Target, float Level)> BatchedGameplayEffects) { var instantEffects = BatchedGameplayEffects.Where(x => x.Effect.GameplayEffectPolicy.DurationPolicy == Enums.EDurationPolicy.Instant); var durationalEffects = BatchedGameplayEffects.Where( x => x.Effect.GameplayEffectPolicy.DurationPolicy == Enums.EDurationPolicy.HasDuration || x.Effect.GameplayEffectPolicy.DurationPolicy == Enums.EDurationPolicy.Infinite ); // Apply instant effects foreach (var item in instantEffects) { if (await ApplyGameEffectToTarget(item.Effect, item.Target)) { // item.Target.AddGameplayEffectToActiveList(Effect); } } // Apply durational effects foreach (var effect in durationalEffects) { if (await ApplyGameEffectToTarget(effect.Effect, effect.Target)) { } } } /// <inheritdoc /> public Task<GameplayEffect> ApplyGameEffectToTarget(GameplayEffect Effect, IGameplayAbilitySystem Target, float Level = 0) { // TODO: Check to make sure all the attributes being modified by this gameplay effect exist on the target // TODO: Get list of tags owned by target // TODO: Check for immunity tags, and don't apply gameplay effect if target is immune (and also add Immunity Tags container to IGameplayEffect) // TODO: Check to make sure Application Tag Requirements are met (i.e. target has the required tags, if any) // If this is a non-instant gameplay effect (i.e. it will modify the current value, not the base value) // If this is an instant gameplay effect (i.e. it will modify the base value) // Handling Instant effects is different to handling HasDuration and Infinite effects if (Effect.GameplayEffectPolicy.DurationPolicy == Enums.EDurationPolicy.Instant) { Effect.ApplyInstantEffect(Target); } else { // Durational effects require attention to many more things than instant effects // Such as stacking and effect durations var EffectData = new ActiveGameplayEffectData(Effect, this, Target); _ = Target.ActiveGameplayEffectsContainer.ApplyGameEffect(EffectData); } var gameplayCues = Effect.GameplayCues; // Execute gameplay cue for (var i = 0; i < gameplayCues.Count; i++) { var cue = gameplayCues[i]; cue.HandleGameplayCue(Target.GetActor().gameObject,new GameplayCueParameters(null, null, null), EGameplayCueEvent.OnActive); } return Task.FromResult(Effect); } /// <inheritdoc /> public float GetNumericAttributeBase(AttributeType AttributeType) { var attributeSet = this.GetComponent<AttributeSet>(); var attribute = attributeSet.Attributes.FirstOrDefault(x => x.AttributeType == AttributeType); if (attribute == null) return 0; return attribute.BaseValue; } /// <inheritdoc /> public float GetNumericAttributeCurrent(AttributeType AttributeType) { var attributeSet = this.GetComponent<AttributeSet>(); return attributeSet.Attributes.FirstOrDefault(x => x.AttributeType == AttributeType).CurrentValue; } public void SetNumericAttributeBase(AttributeType AttributeType, float modifier) { var attributeSet = this.GetComponent<AttributeSet>(); var attribute = attributeSet.Attributes.FirstOrDefault(x => x.AttributeType == AttributeType); var newValue = modifier; attribute.SetAttributeBaseValue(attributeSet, ref newValue); } public void SetNumericAttributeCurrent(AttributeType AttributeType, float NewValue) { var attributeSet = this.GetComponent<AttributeSet>(); var attribute = attributeSet.Attributes.FirstOrDefault(x => x.AttributeType == AttributeType); attribute.SetAttributeCurrentValue(attributeSet, ref NewValue); } } }
41.029268
158
0.665914
[ "MIT" ]
renBuWen/UnityGameplayAbilitySystem
Assets/Plugins/GameplayAbilitySystem/AbilitySystemComponent.cs
8,413
C#
using System; using System.Xml.Serialization; using Newtonsoft.Json; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// KoubeiRetailWmsSupplierreportQueryModel Data Structure. /// </summary> [Serializable] public class KoubeiRetailWmsSupplierreportQueryModel : AlipayObject { /// <summary> /// 下单时间上区间 /// </summary> [JsonProperty("end_time")] [XmlElement("end_time")] public string EndTime { get; set; } /// <summary> /// 页码 /// </summary> [JsonProperty("page_no")] [XmlElement("page_no")] public long PageNo { get; set; } /// <summary> /// 每页数量 /// </summary> [JsonProperty("page_size")] [XmlElement("page_size")] public long PageSize { get; set; } /// <summary> /// 下单时间下区间 /// </summary> [JsonProperty("start_time")] [XmlElement("start_time")] public string StartTime { get; set; } /// <summary> /// 状态,INT:单据未完成,FINISHED:单据已完成 /// </summary> [JsonProperty("state")] [XmlElement("state")] public string State { get; set; } /// <summary> /// 供货商盘点单id /// </summary> [JsonProperty("supplier_report_id")] [XmlElement("supplier_report_id")] public string SupplierReportId { get; set; } /// <summary> /// 仓库编码 /// </summary> [JsonProperty("warehouse_code")] [XmlElement("warehouse_code")] public string WarehouseCode { get; set; } } }
25.825397
71
0.540258
[ "MIT" ]
AkonCoder/Payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/KoubeiRetailWmsSupplierreportQueryModel.cs
1,715
C#
/** * MIT License * * Copyright (c) 2016 Derek Goslin < http://corememorydump.blogspot.ie/ > * * 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 DDPAIDash.Core.Types; namespace DDPAIDash.Converter { internal class ImageQualityEnumMatchToBoolConverter : EnumMatchToBoolConverter<ImageQuality> { } }
40.212121
96
0.771665
[ "MIT" ]
DerekGn/DDAPIDash
DDPAIDash/Converter/ImageQualityEnumMatchToBoolConverter.cs
1,329
C#
// Copyright © 2012-2020 Vaughn Vernon. All rights reserved. // // This Source Code Form is subject to the terms of the // Mozilla Public License, v. 2.0. If a copy of the MPL // was not distributed with this file, You can obtain // one at https://mozilla.org/MPL/2.0/. using System.Collections.Generic; using System.Linq; using Vlingo.Actors.TestKit; using Vlingo.Common; using Vlingo.Symbio.Store; using Vlingo.Symbio.Store.Journal; namespace Vlingo.Symbio.Tests.Store.Journal.InMemory { public class MockAppendResultInterest<TEntry, TState> : IAppendResultInterest { private AccessSafely _access; private List<JournalData<TEntry, TState>> _entries = new List<JournalData<TEntry, TState>>(); public void AppendResultedIn<TSource, TSnapshotState>(IOutcome<StorageException, Result> outcome, string streamName, int streamVersion, TSource source, Optional<TSnapshotState> snapshot, object @object) where TSource : Source { outcome.AndThen(result => { _access.WriteUsing("appendResultedIn", new JournalData<TSource, TSnapshotState>(streamName, streamVersion, null, result, new List<TSource> { source }, snapshot)); return result; }).Otherwise(cause => { _access.WriteUsing("appendResultedIn", new JournalData<TSource, TSnapshotState>(streamName, streamVersion, cause, Result.Error, new List<TSource> { source }, snapshot)); return cause.Result; }); } public void AppendResultedIn<TSource, TSnapshotState>(IOutcome<StorageException, Result> outcome, string streamName, int streamVersion, TSource source, Metadata metadata, Optional<TSnapshotState> snapshot, object @object) where TSource : Source { outcome.AndThen(result => { _access.WriteUsing("appendResultedIn", new JournalData<TSource, TSnapshotState>(streamName, streamVersion, null, result, new List<TSource> { source }, snapshot)); return result; }).Otherwise(cause => { _access.WriteUsing("appendResultedIn", new JournalData<TSource, TSnapshotState>(streamName, streamVersion, cause, Result.Error, new List<TSource> { source }, snapshot)); return cause.Result; }); } public void AppendAllResultedIn<TSource, TSnapshotState>(IOutcome<StorageException, Result> outcome, string streamName, int streamVersion, IEnumerable<TSource> sources, Optional<TSnapshotState> snapshot, object @object) where TSource : Source { outcome.AndThen(result => { _access.WriteUsing("appendResultedIn", new JournalData<TSource, TSnapshotState>(streamName, streamVersion, null, result, sources.ToList(), snapshot)); return result; }).Otherwise(cause => { _access.WriteUsing("appendResultedIn", new JournalData<TSource, TSnapshotState>(streamName, streamVersion, cause, Result.Error, sources.ToList(), snapshot)); return cause.Result; }); } public void AppendAllResultedIn<TSource, TSnapshotState>(IOutcome<StorageException, Result> outcome, string streamName, int streamVersion, IEnumerable<TSource> sources, Metadata metadata, Optional<TSnapshotState> snapshot, object @object) where TSource : Source { outcome.AndThen(result => { _access.WriteUsing("appendResultedIn", new JournalData<TSource, TSnapshotState>(streamName, streamVersion, null, result, sources.ToList(), snapshot)); return result; }).Otherwise(cause => { _access.WriteUsing("appendResultedIn", new JournalData<TSource, TSnapshotState>(streamName, streamVersion, cause, Result.Error, sources.ToList(), snapshot)); return cause.Result; }); } public AccessSafely AfterCompleting(int times) { _access = AccessSafely.AfterCompleting(times) .WritingWith<JournalData<TEntry, TState>>("appendResultedIn", j => _entries.Add(j)) .ReadingWith("appendResultedIn", () => _entries) .ReadingWith("size", () => _entries.Count); return _access; } public int ReceivedAppendsSize => _access.ReadFrom<int>("size"); public IEnumerable<JournalData<TEntry, TState>> Entries => _access.ReadFrom<List<JournalData<TEntry, TState>>>("appendResultedIn"); } }
52.931818
269
0.646629
[ "MPL-2.0" ]
Johnny-Bee/vlingo-net-symbio
src/Vlingo.Symbio.Tests/Store/Journal/InMemory/MockAppendResultInterest.cs
4,659
C#
using System; namespace JollyQuotes { /// <inheritdoc cref="IQuoteGenerator"/> /// <typeparam name="T">Type of <see cref="IQuote"/> this class can generate.</typeparam> public abstract partial class QuoteGenerator<T> : IQuoteGenerator where T : class, IQuote { /// <inheritdoc/> public abstract string ApiName { get; } /// <summary> /// Source of the quotes, e.g. a link, file name or raw text. /// </summary> public string Source { get; } /// <summary> /// Initializes a new instance of the <see cref="QuoteGenerator{T}"/> class with a <paramref name="source"/> specified. /// </summary> /// <param name="source">Source of the quotes, e.g. a link, file name or raw text.</param> /// <exception cref="ArgumentException"><paramref name="source"/> is <see langword="null"/> or empty.</exception> protected QuoteGenerator(string source) { if (string.IsNullOrWhiteSpace(source)) { throw Error.NullOrEmpty(nameof(source)); } Source = source; } /// <inheritdoc cref="IQuoteGenerator.GetRandomQuote()"/> public abstract T GetRandomQuote(); /// <inheritdoc cref="IQuoteGenerator.GetRandomQuote(string)"/> public abstract T? GetRandomQuote(string tag); /// <inheritdoc cref="IQuoteGenerator.GetRandomQuote(string[])"/> public abstract T? GetRandomQuote(params string[]? tags); IQuote IQuoteGenerator.GetRandomQuote() { return GetRandomQuote(); } IQuote? IQuoteGenerator.GetRandomQuote(string tag) { return GetRandomQuote(tag); } IQuote? IQuoteGenerator.GetRandomQuote(params string[]? tags) { return GetRandomQuote(tags); } } }
28.385965
121
0.68974
[ "MIT" ]
piotrstenke/JollyQuotes
src/JollyQuotes.Core/QuoteGenerator.cs
1,620
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("Naegi-bot")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Naegi-bot")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("2dec03c1-4274-49c7-83cb-52da09fc131c")] // 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")]
37.459459
84
0.74531
[ "Apache-2.0" ]
anonymousculprit/MakotoNaegi_DiscordBot
Naegi-bot/Naegi-bot/Naegi-bot/Properties/AssemblyInfo.cs
1,389
C#
using System.Threading; using System.Threading.Tasks; using AppKit; using Xamarin.Forms; using Xamarin.Forms.Platform.MacOS; using SkiaSharp.Views.Mac; [assembly: ExportImageSourceHandler(typeof(SkiaSharp.Views.Forms.SKImageImageSource), typeof(SkiaSharp.Views.Forms.SKImageSourceHandler))] [assembly: ExportImageSourceHandler(typeof(SkiaSharp.Views.Forms.SKBitmapImageSource), typeof(SkiaSharp.Views.Forms.SKImageSourceHandler))] [assembly: ExportImageSourceHandler(typeof(SkiaSharp.Views.Forms.SKPixmapImageSource), typeof(SkiaSharp.Views.Forms.SKImageSourceHandler))] [assembly: ExportImageSourceHandler(typeof(SkiaSharp.Views.Forms.SKPictureImageSource), typeof(SkiaSharp.Views.Forms.SKImageSourceHandler))] namespace SkiaSharp.Views.Forms { public sealed class SKImageSourceHandler : IImageSourceHandler { public Task<NSImage> LoadImageAsync(ImageSource imagesource, CancellationToken cancelationToken = default(CancellationToken), float scale = 1f) { NSImage image = null; var imageImageSource = imagesource as SKImageImageSource; if (imageImageSource != null) { image = imageImageSource.Image?.ToNSImage(); } var bitmapImageSource = imagesource as SKBitmapImageSource; if (bitmapImageSource != null) { image = bitmapImageSource.Bitmap?.ToNSImage(); } var pixmapImageSource = imagesource as SKPixmapImageSource; if (pixmapImageSource != null) { image = pixmapImageSource.Pixmap?.ToNSImage(); } var pictureImageSource = imagesource as SKPictureImageSource; if (pictureImageSource != null) { image = pictureImageSource.Picture?.ToNSImage(pictureImageSource.Dimensions); } return Task.FromResult(image); } } }
34.24
145
0.778037
[ "MIT" ]
jsuarezruiz/SkiaSharp
source/SkiaSharp.Views.Forms/SkiaSharp.Views.Forms.Mac/SKImageSourceHandler.cs
1,712
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net.Http.Headers; using System.Web.Http.Description; using AuthorizationDemos.Areas.HelpPage.ModelDescriptions; namespace AuthorizationDemos.Areas.HelpPage.Models { /// <summary> /// The model that represents an API displayed on the help page. /// </summary> public class HelpPageApiModel { /// <summary> /// Initializes a new instance of the <see cref="HelpPageApiModel"/> class. /// </summary> public HelpPageApiModel() { UriParameters = new Collection<ParameterDescription>(); SampleRequests = new Dictionary<MediaTypeHeaderValue, object>(); SampleResponses = new Dictionary<MediaTypeHeaderValue, object>(); ErrorMessages = new Collection<string>(); } /// <summary> /// Gets or sets the <see cref="ApiDescription"/> that describes the API. /// </summary> public ApiDescription ApiDescription { get; set; } /// <summary> /// Gets or sets the <see cref="ParameterDescription"/> collection that describes the URI parameters for the API. /// </summary> public Collection<ParameterDescription> UriParameters { get; private set; } /// <summary> /// Gets or sets the documentation for the request. /// </summary> public string RequestDocumentation { get; set; } /// <summary> /// Gets or sets the <see cref="ModelDescription"/> that describes the request body. /// </summary> public ModelDescription RequestModelDescription { get; set; } /// <summary> /// Gets the request body parameter descriptions. /// </summary> public IList<ParameterDescription> RequestBodyParameters { get { return GetParameterDescriptions(RequestModelDescription); } } /// <summary> /// Gets or sets the <see cref="ModelDescription"/> that describes the resource. /// </summary> public ModelDescription ResourceDescription { get; set; } /// <summary> /// Gets the resource property descriptions. /// </summary> public IList<ParameterDescription> ResourceProperties { get { return GetParameterDescriptions(ResourceDescription); } } /// <summary> /// Gets the sample requests associated with the API. /// </summary> public IDictionary<MediaTypeHeaderValue, object> SampleRequests { get; private set; } /// <summary> /// Gets the sample responses associated with the API. /// </summary> public IDictionary<MediaTypeHeaderValue, object> SampleResponses { get; private set; } /// <summary> /// Gets the error messages associated with this model. /// </summary> public Collection<string> ErrorMessages { get; private set; } private static IList<ParameterDescription> GetParameterDescriptions(ModelDescription modelDescription) { ComplexTypeModelDescription complexTypeModelDescription = modelDescription as ComplexTypeModelDescription; if (complexTypeModelDescription != null) { return complexTypeModelDescription.Properties; } CollectionModelDescription collectionModelDescription = modelDescription as CollectionModelDescription; if (collectionModelDescription != null) { complexTypeModelDescription = collectionModelDescription.ElementDescription as ComplexTypeModelDescription; if (complexTypeModelDescription != null) { return complexTypeModelDescription.Properties; } } return null; } } }
36.722222
123
0.616238
[ "MIT" ]
garrettwong/AuthorizationDemos
AuthorizationDemos/Areas/HelpPage/Models/HelpPageApiModel.cs
3,966
C#
using System; namespace TeamPicker.Classes { [Serializable] public class SettingsData { public decimal Version { get; set; } public int NumberOfTeams { get; set; } public int MaximumRating { get; set; } public bool BalanceTeams { get; set; } public string OrderBy { get; set; } public bool TrafficLightRatings { get; set; } public bool HighAccuracy { get; set; } public bool DisplayNotes { get; set; } } }
20.541667
53
0.604462
[ "MIT" ]
LynxMagnus/team-picker
TeamPicker/Classes/SettingsData.cs
493
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace SaveAndLoad { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new SimpleForm()); } } }
22.391304
65
0.615534
[ "MIT" ]
rohansen/Code-Examples
SerialPorts & IO/SaveAndLoadFromHDD/SaveAndLoad/Program.cs
517
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace DEX { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Menu", id = UrlParameter.Optional } ); } } }
23.75
98
0.580702
[ "Apache-2.0" ]
ADukeLabs/DEX
DEX/DEX/App_Start/RouteConfig.cs
572
C#
using System; using System.Collections.Generic; using System.Linq; using BattleLogic.Card.CardsCore; using UnityEngine; namespace Data.Static.Data.Battle.Cards.CardsGenerate { [CreateAssetMenu(menuName = "Data/Battle/Cards/CardsGenerate/CardsTypeChance", fileName = "CardsTypeChanceGenerate")] public class CardsTypeChanceGenerate : StaticDataItem { [Serializable] public class Item { public CardType Type; [Range(1, 100)] public int Chance; [Range(-100, 100)] public int[] Shift; } public Dictionary<CardType, GenerateChanceData> TypeWithPercentage => Data.ToDictionary(x => x.Type, x => new GenerateChanceData(x.Chance, x.Shift)); public Item[] Data; } }
27.846154
85
0.714088
[ "MIT" ]
NeoremFf/Wizard-Fighter
WizardFighter/Assets/Scripts/Data/Static/Data/Battle/Cards/CardsGenerate/CardsTypeChanceGenerate.cs
726
C#
using SlackNet.Interaction; namespace SlackNet.Blocks { public class PlainTextInput : BlockElement, IInputBlockElement { public PlainTextInput() : base("plain_text_input") { } /// <summary> /// An identifier for the input value when the parent modal is submitted. /// You can use this when you receive a <see cref="ViewSubmission"/> payload to identify the value of the input element. /// Should be unique among all other <see cref="IActionElement.ActionId"/>s used elsewhere by your app. /// </summary> public string ActionId { get; set; } /// <summary> /// A plain text object that defines the placeholder text shown in the plain-text input. /// </summary> public PlainText Placeholder { get; set; } /// <summary> /// The initial value in the plain-text input when it is loaded. /// </summary> public string InitialValue { get; set; } /// <summary> /// Indicates whether the input will be a single line (False) or a larger textarea (True). /// </summary> public bool Multiline { get; set; } /// <summary> /// The minimum length of input that the user must provide. If the user provides less, they will receive an error. /// </summary> public int? MinLength { get; set; } /// <summary> /// The maximum length of input that the user can provide. If the user provides more, they will receive an error. /// </summary> public int? MaxLength { get; set; } } [SlackType("plain_text_input")] public class PlainTextInputValue : ElementValue { public string Value { get; set; } } }
36.914894
128
0.61268
[ "MIT" ]
eFloh/SlackNet
SlackNet/Blocks/PlainTextInput.cs
1,735
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerModel { public PlayerModel(){} public float GetDamage(){ float dmg = 0; if (Input.GetKeyDown (KeyCode.Alpha1)) { dmg += 10; } else if (Input.GetKeyDown (KeyCode.Alpha2)) { dmg += 5; } else if (Input.GetKeyDown(KeyCode.Alpha3)){ dmg += 1; } return dmg; } }
15.44
49
0.660622
[ "MIT" ]
Kolefn/ECW
ExampleProject/Assets/MVC/Scripts/PlayerModel.cs
388
C#
namespace RepairsApi.V2.Filtering { public static class FilterSectionConstants { public const string Status = "Status"; public const string Priority = "Priority"; public const string Trades = "Trades"; public const string Contractors = "Contractors"; } public static class FilterConstants { public const string WorkOrder = "WorkOrder"; } }
25.3125
56
0.65679
[ "MIT" ]
LBHackney-IT/repairs-api-dotnet
RepairsApi/V2/Filtering/FilterSectionConstants.cs
405
C#
using System; using System.Linq; using Eventualize.Interfaces.BaseTypes; namespace Eventualize.Interfaces.Domain { public interface IEventConverter { IEventData DeserializeEventData(BoundedContextName boundedContextName, EventTypeName eventTypeName, Guid id, byte[] data); byte[] SerializeEventData(IEventData eventData); } }
25.428571
130
0.769663
[ "MIT" ]
Useurmind/Eventualize
Eventualize.Interfaces/Domain/IEventConverter.cs
356
C#
//------------------------------------------------------------------------------ // <copyright file="TransferCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.Azure.Storage.DataMovement { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Globalization; using System.Runtime.Serialization; using TransferKey = System.Tuple<TransferLocation, TransferLocation>; /// <summary> /// A collection of transfers. /// </summary> #if BINARY_SERIALIZATION [Serializable] #else [DataContract] [KnownType(typeof(DirectoryTransfer))] [KnownType(typeof(SingleObjectTransfer))] #endif // BINARY_SERIALIZATION internal class TransferCollection<T> #if BINARY_SERIALIZATION : ISerializable where T : Transfer #endif // BINARY_SERIALIZATION { /// <summary> /// Serialization field name for single object transfers. /// </summary> private const string SingleObjectTransfersName = "SingleObjectTransfers"; /// <summary> /// Serialization field name for directory transfers. /// </summary> private const string DirectoryTransfersName = "DirectoryTransfers"; /// <summary> /// All transfers in the collection. /// </summary> private ConcurrentDictionary<TransferKey, Transfer> transfers = new ConcurrentDictionary<TransferKey, Transfer>(); /// <summary> /// Overall transfer progress tracker. /// </summary> private TransferProgressTracker overallProgressTracker = new TransferProgressTracker(); #if BINARY_SERIALIZATION /// <summary> /// Initializes a new instance of the <see cref="TransferCollection{T}"/> class. /// </summary> internal TransferCollection() { } /// <summary> /// Initializes a new instance of the <see cref="TransferCollection{T}"/> class. /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> protected TransferCollection(SerializationInfo info, StreamingContext context) { if (info == null) { throw new System.ArgumentNullException("info"); } int transferCount = info.GetInt32(SingleObjectTransfersName); for (int i = 0; i < transferCount; ++i) { this.AddTransfer((T)info.GetValue(string.Format(CultureInfo.InvariantCulture, "{0}{1}", SingleObjectTransfersName, i), typeof(SingleObjectTransfer))); } transferCount = info.GetInt32(DirectoryTransfersName); for (int i = 0; i < transferCount; ++i) { this.AddTransfer((T)info.GetValue(string.Format(CultureInfo.InvariantCulture, "{0}{1}", DirectoryTransfersName, i), typeof(DirectoryTransfer))); } foreach (Transfer transfer in this.transfers.Values) { this.OverallProgressTracker.AddProgress(transfer.ProgressTracker); } } #endif // BINARY_SERIALIZATION #region Serialization helpers #if !BINARY_SERIALIZATION [DataMember] private Transfer[] serializedTransfers; /// <summary> /// Initializes a deserialized TransferCollection (by rebuilding the the transfer /// dictionary and progress tracker) /// </summary> /// <param name="context"></param> [OnDeserialized] private void OnDeserializedCallback(StreamingContext context) { // DCS doesn't invoke ctors, so all initialization must be done here transfers = new ConcurrentDictionary<TransferKey, Transfer>(); overallProgressTracker = new TransferProgressTracker(); foreach (Transfer t in serializedTransfers) { this.AddTransfer(t); } foreach (Transfer transfer in this.transfers.Values) { this.OverallProgressTracker.AddProgress(transfer.ProgressTracker); } } /// <summary> /// Serializes the object by storing the trasnfers in a more DCS-friendly format /// </summary> /// <param name="context"></param> [OnSerializing] private void OnSerializingCallback(StreamingContext context) { serializedTransfers = this.transfers.Select(kv => kv.Value).Where(t => t != null).ToArray(); } #endif //!BINARY_SERIALIZATION #endregion // Serialization helpers /// <summary> /// Gets the number of transfers currently in the collection. /// </summary> public int Count { get { return this.transfers.Count; } } /// <summary> /// Gets the overall transfer progress. /// </summary> public TransferProgressTracker OverallProgressTracker { get { return this.overallProgressTracker; } } #if BINARY_SERIALIZATION /// <summary> /// Serializes the checkpoint. /// </summary> /// <param name="info">Serialization info object.</param> /// <param name="context">Streaming context.</param> public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } List<SingleObjectTransfer> singleObjectTransfers = new List<SingleObjectTransfer>(); List<DirectoryTransfer> directoryTransfers = new List<DirectoryTransfer>(); foreach (var kv in this.transfers) { SingleObjectTransfer transfer = kv.Value as SingleObjectTransfer; if (transfer != null) { singleObjectTransfers.Add(transfer); continue; } DirectoryTransfer transfer2 = kv.Value as DirectoryTransfer; if (transfer2 != null) { directoryTransfers.Add(transfer2); continue; } } info.AddValue(SingleObjectTransfersName, singleObjectTransfers.Count); for (int i = 0; i < singleObjectTransfers.Count; ++i) { info.AddValue(string.Format(CultureInfo.InvariantCulture, "{0}{1}", SingleObjectTransfersName, i), singleObjectTransfers[i], typeof(SingleObjectTransfer)); } info.AddValue(DirectoryTransfersName, directoryTransfers.Count); for (int i = 0; i < directoryTransfers.Count; ++i) { info.AddValue(string.Format(CultureInfo.InvariantCulture, "{0}{1}", DirectoryTransfersName, i), directoryTransfers[i], typeof(DirectoryTransfer)); } } #endif // BINARY_SERIALIZATION /// <summary> /// Adds a transfer. /// </summary> /// <param name="transfer">The transfer to be added.</param> /// <param name="updateProgress">Whether or not to update collection's progress with the subtransfer's.</param> #if DOTNET5_4 public void AddTransfer(Transfer transfer, bool updateProgress = true) #else public void AddTransfer(T transfer, bool updateProgress = true) #endif { transfer.ProgressTracker.Parent = this.OverallProgressTracker; if (updateProgress) { this.overallProgressTracker.AddProgress(transfer.ProgressTracker); } bool unused = this.transfers.TryAdd(new TransferKey(transfer.Source, transfer.Destination), transfer); Debug.Assert(unused, "Transfer with the same source and destination already exists"); } /// <summary> /// Remove a transfer. /// </summary> /// <param name="transfer">Transfer to be removed</param> /// <returns>True if the transfer is removed successfully, false otherwise.</returns> public bool RemoveTransfer(Transfer transfer) { Transfer unused = null; if (this.transfers.TryRemove(new TransferKey(transfer.Source, transfer.Destination), out unused)) { transfer.ProgressTracker.Parent = null; return true; } return false; } /// <summary> /// Gets a transfer with the specified source location, destination location and transfer method. /// </summary> /// <param name="sourceLocation">Source location of the transfer.</param> /// <param name="destLocation">Destination location of the transfer.</param> /// <param name="transferMethod">Transfer method.</param> /// <returns>A transfer that matches the specified source location, destination location and transfer method; Or null if no matches.</returns> public Transfer GetTransfer(TransferLocation sourceLocation, TransferLocation destLocation, TransferMethod transferMethod) { Transfer transfer = null; if (this.transfers.TryGetValue(new TransferKey(sourceLocation, destLocation), out transfer)) { if (transfer.TransferMethod == transferMethod) { return transfer; } } return null; } /// <summary> /// Get an enumerable object for all tansfers in this TransferCollection. /// </summary> /// <returns>An enumerable object for all tansfers in this TransferCollection.</returns> public IEnumerable<Transfer> GetEnumerator() { return this.transfers.Values; } /// <summary> /// Gets a static snapshot of this transfer checkpoint /// </summary> /// <returns>A snapshot of current transfer checkpoint</returns> #if DOTNET5_4 public TransferCollection<T> Copy() { TransferCollection<T> copyObj = new TransferCollection<T>(); foreach (var kv in this.transfers) { Transfer transfer = kv.Value as Transfer; copyObj.AddTransfer((Transfer)transfer.Copy()); } return copyObj; } #else public TransferCollection<T> Copy() { TransferCollection<T> copyObj = new TransferCollection<T>(); foreach (var kv in this.transfers) { var transfer = kv.Value; copyObj.AddTransfer((T)transfer.Copy()); } return copyObj; } #endif } }
36.2
171
0.585817
[ "MIT" ]
Azure/azure-storage-net-data-movement
lib/TransferCollection.cs
11,041
C#
/******************************************/ /* */ /* Copyright (c) 2020 monitor1394 */ /* https://github.com/monitor1394 */ /* */ /******************************************/ using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace XUGL { /// <summary> /// UGUI Graphics Library. /// UGUI 图形库 /// </summary> public static class UGL { private static readonly Color32 s_ClearColor32 = new Color32(0, 0, 0, 0); private static readonly Vector2 s_ZeroVector2 = Vector2.zero; private static UIVertex[] s_Vertex = new UIVertex[4]; private static List<Vector3> s_CurvesPosList = new List<Vector3>(); /// <summary> /// Draw a arrow. 画箭头 /// </summary> /// <param name="vh"></param> /// <param name="startPoint">起始位置</param> /// <param name="arrowPoint">箭头位置</param> /// <param name="width">箭头宽</param> /// <param name="height">箭头长</param> /// <param name="offset">相对箭头位置的偏移</param> /// <param name="dent">箭头凹度</param> /// <param name="color">颜色</param> public static void DrawArrow(VertexHelper vh, Vector3 startPoint, Vector3 arrowPoint, float width, float height, float offset, float dent, Color32 color) { var dir = (arrowPoint - startPoint).normalized; var sharpPos = arrowPoint + (offset + height / 4) * dir; var middle = sharpPos + (dent - height) * dir; var diff = Vector3.Cross(dir, Vector3.forward).normalized * width / 2; var left = sharpPos - height * dir + diff; var right = sharpPos - height * dir - diff; DrawTriangle(vh, middle, sharpPos, left, color); DrawTriangle(vh, middle, sharpPos, right, color); } /// <summary> /// Draw a line. 画直线 /// </summary> /// <param name="vh"></param> /// <param name="startPoint">起点</param> /// <param name="endPoint">终点</param> /// <param name="width">线宽</param> /// <param name="color">颜色</param> public static void DrawLine(VertexHelper vh, Vector3 startPoint, Vector3 endPoint, float width, Color32 color) { DrawLine(vh, startPoint, endPoint, width, color, color); } /// <summary> /// Draw a line. 画直线 /// </summary> /// <param name="vh"></param> /// <param name="startPoint">起点</param> /// <param name="endPoint">终点</param> /// <param name="width">线宽</param> /// <param name="color">颜色</param> /// <param name="toColor">渐变颜色</param> public static void DrawLine(VertexHelper vh, Vector3 startPoint, Vector3 endPoint, float width, Color32 color, Color32 toColor) { if (startPoint == endPoint) return; Vector3 v = Vector3.Cross(endPoint - startPoint, Vector3.forward).normalized * width; s_Vertex[0].position = startPoint - v; s_Vertex[1].position = endPoint - v; s_Vertex[2].position = endPoint + v; s_Vertex[3].position = startPoint + v; for (int j = 0; j < 4; j++) { s_Vertex[j].color = j == 0 || j == 3 ? color : toColor; s_Vertex[j].uv0 = s_ZeroVector2; } vh.AddUIVertexQuad(s_Vertex); } /// <summary> /// Draw a line defined by three points. 画一条由3个点确定的折线 /// </summary> /// <param name="vh"></param> /// <param name="startPoint">起始点</param> /// <param name="middlePoint">中间转折点</param> /// <param name="endPoint">终点</param> /// <param name="width">线宽</param> /// <param name="color">颜色</param> public static void DrawLine(VertexHelper vh, Vector3 startPoint, Vector3 middlePoint, Vector3 endPoint, float width, Color32 color) { var dir1 = (middlePoint - startPoint).normalized; var dir2 = (endPoint - middlePoint).normalized; var dir1v = Vector3.Cross(dir1, Vector3.forward).normalized; var dir2v = Vector3.Cross(dir2, Vector3.forward).normalized; var dir3 = (dir1 + dir2).normalized; var isDown = Vector3.Cross(dir1, dir2).z <= 0; var angle = (180 - Vector3.Angle(dir1, dir2)) * Mathf.Deg2Rad / 2; var diff = width / Mathf.Sin(angle); var dirDp = Vector3.Cross(dir3, Vector3.forward).normalized; var dnPos = middlePoint + (isDown ? dirDp : -dirDp) * diff; var upPos1 = middlePoint + (isDown ? -dir1v : dir1v) * width; var upPos2 = middlePoint + (isDown ? -dir2v : dir2v) * width; var startUp = startPoint - dir1v * width; var startDn = startPoint + dir1v * width; var endUp = endPoint - dir2v * width; var endDn = endPoint + dir2v * width; if (isDown) { DrawQuadrilateral(vh, startDn, startUp, upPos1, dnPos, color); DrawQuadrilateral(vh, dnPos, upPos2, endUp, endDn, color); DrawTriangle(vh, dnPos, upPos1, upPos2, color); } else { DrawQuadrilateral(vh, startDn, startUp, dnPos, upPos1, color); DrawQuadrilateral(vh, upPos2, dnPos, endUp, endDn, color); DrawTriangle(vh, dnPos, upPos1, upPos2, color); } } /// <summary> /// Draw a dash line. 画虚线 /// </summary> /// <param name="vh"></param> /// <param name="startPoint">起始点</param> /// <param name="endPoint">结束点</param> /// <param name="width">线宽</param> /// <param name="color">起始颜色</param> /// <param name="toColor">结束颜色</param> /// <param name="lineLength">实线部分长度,默认为线宽的12倍</param> /// <param name="gapLength">间隙部分长度,默认为线宽的3倍</param> /// <param name="posList">可选,输出的关键点</param> public static void DrawDashLine(VertexHelper vh, Vector3 startPoint, Vector3 endPoint, float width, Color32 color, Color32 toColor, float lineLength = 0f, float gapLength = 0f, List<Vector3> posList = null) { float dist = Vector3.Distance(startPoint, endPoint); if (dist < 0.1f) return; if (lineLength == 0) lineLength = 12 * width; if (gapLength == 0) gapLength = 3 * width; int segment = Mathf.CeilToInt(dist / (lineLength + gapLength)); Vector3 dir = (endPoint - startPoint).normalized; Vector3 sp = startPoint, np; var isGradient = !color.Equals(toColor); if (posList != null) posList.Clear(); for (int i = 1; i <= segment; i++) { if (posList != null) posList.Add(sp); np = startPoint + dir * dist * i / segment; var dashep = np - dir * gapLength; DrawLine(vh, sp, dashep, width, isGradient ? Color32.Lerp(color, toColor, i * 1.0f / segment) : color); sp = np; } if (posList != null) posList.Add(endPoint); DrawLine(vh, sp, endPoint, width, toColor); } /// <summary> /// Draw a dot line. 画点线 /// </summary> /// <param name="vh"></param> /// <param name="startPoint">起始点</param> /// <param name="endPoint">结束点</param> /// <param name="width">线宽</param> /// <param name="color">起始颜色</param> /// <param name="toColor">结束颜色</param> /// <param name="lineLength">实线部分长度,默认为线宽的3倍</param> /// <param name="gapLength">间隙部分长度,默认为线宽的3倍</param> /// <param name="posList">可选,输出的关键点</param> public static void DrawDotLine(VertexHelper vh, Vector3 startPoint, Vector3 endPoint, float width, Color32 color, Color32 toColor, float lineLength = 0f, float gapLength = 0f, List<Vector3> posList = null) { var dist = Vector3.Distance(startPoint, endPoint); if (dist < 0.1f) return; if (lineLength == 0) lineLength = 3 * width; if (gapLength == 0) gapLength = 3 * width; var segment = Mathf.CeilToInt(dist / (lineLength + gapLength)); var dir = (endPoint - startPoint).normalized; var sp = startPoint; var np = Vector3.zero; var isGradient = !color.Equals(toColor); if (posList != null) posList.Clear(); for (int i = 1; i <= segment; i++) { if (posList != null) posList.Add(sp); np = startPoint + dir * dist * i / segment; var dashep = np - dir * gapLength; DrawLine(vh, sp, dashep, width, isGradient ? Color32.Lerp(color, toColor, i * 1.0f / segment) : color); sp = np; } if (posList != null) posList.Add(endPoint); DrawLine(vh, sp, endPoint, width, toColor); } /// <summary> /// Draw a dash-dot line. 画点划线 /// </summary> /// <param name="vh"></param> /// <param name="startPoint">起始点</param> /// <param name="endPoint">结束点</param> /// <param name="width">线宽</param> /// <param name="color">颜色</param> /// <param name="dashLength">划线长,默认15倍线宽</param> /// <param name="dotLength">点线长,默认3倍线宽</param> /// <param name="gapLength">间隙长,默认5倍线宽</param> /// <param name="posList">可选,输出的关键点</param> public static void DrawDashDotLine(VertexHelper vh, Vector3 startPoint, Vector3 endPoint, float width, Color32 color, float dashLength = 0f, float dotLength = 0, float gapLength = 0f, List<Vector3> posList = null) { float dist = Vector3.Distance(startPoint, endPoint); if (dist < 0.1f) return; if (dashLength == 0) dashLength = 15 * width; if (dotLength == 0) dotLength = 3 * width; if (gapLength == 0) gapLength = 5 * width; int segment = Mathf.CeilToInt(dist / (dashLength + 2 * gapLength + dotLength)); Vector3 dir = (endPoint - startPoint).normalized; Vector3 sp = startPoint, np; if (posList != null) posList.Clear(); for (int i = 1; i <= segment; i++) { if (posList != null) posList.Add(sp); np = startPoint + dir * dist * i / segment; var dashep = np - dir * (2 * gapLength + dotLength); DrawLine(vh, sp, dashep, width, color); if (posList != null) posList.Add(dashep); var dotsp = dashep + gapLength * dir; var dotep = dotsp + dotLength * dir; DrawLine(vh, dotsp, dotep, width, color); if (posList != null) posList.Add(dotsp); sp = np; } if (posList != null) posList.Add(endPoint); DrawLine(vh, sp, endPoint, width, color); } /// <summary> /// Draw a dash-dot-dot line. 画双点划线 /// </summary> /// <param name="vh"></param> /// <param name="startPoint">起始点</param> /// <param name="endPoint">结束点</param> /// <param name="width">线宽</param> /// <param name="color">颜色</param> /// <param name="dashLength">折线长,默认15倍线宽</param> /// <param name="dotLength">点线长,默认3倍线宽</param> /// <param name="gapLength">间隙长,默认5倍线宽</param> /// <param name="posList">可选,输出的关键点</param> public static void DrawDashDotDotLine(VertexHelper vh, Vector3 startPoint, Vector3 endPoint, float width, Color32 color, float dashLength = 0f, float dotLength = 0f, float gapLength = 0f, List<Vector3> posList = null) { float dist = Vector3.Distance(startPoint, endPoint); if (dist < 0.1f) return; if (dashLength == 0) dashLength = 15 * width; if (dotLength == 0) dotLength = 3 * width; if (gapLength == 0) gapLength = 5 * width; int segment = Mathf.CeilToInt(dist / (dashLength + 3 * gapLength + 2 * dotLength)); Vector3 dir = (endPoint - startPoint).normalized; Vector3 sp = startPoint, np; if (posList != null) posList.Clear(); for (int i = 1; i <= segment; i++) { if (posList != null) posList.Add(sp); np = startPoint + dir * dist * i / segment; var dashep = np - dir * (3 * gapLength + 2 * dotLength); DrawLine(vh, sp, dashep, width, color); if (posList != null) posList.Add(dashep); var dotsp = dashep + gapLength * dir; var dotep = dotsp + dotLength * dir; DrawLine(vh, dotsp, dotep, width, color); if (posList != null) posList.Add(dotep); var dotsp2 = dotep + gapLength * dir; var dotep2 = dotsp2 + dotLength * dir; DrawLine(vh, dotsp2, dotep2, width, color); if (posList != null) posList.Add(dotep2); sp = np; } if (posList != null) posList.Add(endPoint); DrawLine(vh, sp, endPoint, width, color); } /// <summary> /// Draw a zebar-line. 画斑马线 /// </summary> /// <param name="vh"></param> /// <param name="startPoint">起始点</param> /// <param name="endPoint">结束点</param> /// <param name="width">线宽</param> /// <param name="zebraWidth">斑马条纹宽</param> /// <param name="zebraGap">间隙宽</param> /// <param name="color">起始颜色</param> /// <param name="toColor">结束颜色</param> public static void DrawZebraLine(VertexHelper vh, Vector3 startPoint, Vector3 endPoint, float width, float zebraWidth, float zebraGap, Color32 color, Color32 toColor) { DrawDotLine(vh, startPoint, endPoint, width, color, toColor, zebraWidth, zebraGap); } /// <summary> /// Draw a diamond. 画菱形(钻石形状) /// </summary> /// <param name="vh"></param> /// <param name="center">中心点</param> /// <param name="size">尺寸</param> /// <param name="color">颜色</param> public static void DrawDiamond(VertexHelper vh, Vector3 center, float size, Color32 color) { DrawDiamond(vh, center, size, color, color); } /// <summary> /// Draw a diamond. 画菱形(钻石形状) /// </summary> /// <param name="vh"></param> /// <param name="center">中心点</param> /// <param name="size">尺寸</param> /// <param name="color">渐变色1</param> /// <param name="toColor">渐变色2</param> public static void DrawDiamond(VertexHelper vh, Vector3 center, float size, Color32 color, Color32 toColor) { var p1 = new Vector2(center.x - size, center.y); var p2 = new Vector2(center.x, center.y + size); var p3 = new Vector2(center.x + size, center.y); var p4 = new Vector2(center.x, center.y - size); DrawTriangle(vh, p4, p1, p2, color, color, toColor); DrawTriangle(vh, p3, p4, p2, color, color, toColor); } /// <summary> /// Draw a square. 画正方形 /// </summary> /// <param name="center">中心点</param> /// <param name="radius">半径</param> /// <param name="color">颜色</param> public static void DrawSquare(VertexHelper vh, Vector3 center, float radius, Color32 color) { DrawSquare(vh, center, radius, color, color, true); } /// <summary> /// Draw a square. 画带渐变的正方形 /// </summary> /// <param name="vh"></param> /// <param name="center">中心点</param> /// <param name="radius">半径</param> /// <param name="color">渐变色1</param> /// <param name="toColor">渐变色2</param> /// <param name="vertical">渐变是否为垂直方向</param> public static void DrawSquare(VertexHelper vh, Vector3 center, float radius, Color32 color, Color32 toColor, bool vertical = true) { Vector3 p1, p2, p3, p4; if (vertical) { p1 = new Vector3(center.x + radius, center.y - radius); p2 = new Vector3(center.x - radius, center.y - radius); p3 = new Vector3(center.x - radius, center.y + radius); p4 = new Vector3(center.x + radius, center.y + radius); } else { p1 = new Vector3(center.x - radius, center.y - radius); p2 = new Vector3(center.x - radius, center.y + radius); p3 = new Vector3(center.x + radius, center.y + radius); p4 = new Vector3(center.x + radius, center.y - radius); } DrawQuadrilateral(vh, p1, p2, p3, p4, color, toColor); } /// <summary> /// Draw a rectangle. 画带长方形 /// </summary> /// <param name="p1">起始点</param> /// <param name="p2">结束点</param> /// <param name="radius">半径</param> /// <param name="color">颜色</param> public static void DrawRectangle(VertexHelper vh, Vector3 p1, Vector3 p2, float radius, Color32 color) { DrawRectangle(vh, p1, p2, radius, color, color); } /// <summary> /// Draw a rectangle. 画带渐变的长方形 /// </summary> /// <param name="vh"></param> /// <param name="p1">起始点</param> /// <param name="p2">结束点</param> /// <param name="radius">半径</param> /// <param name="color">渐变色1</param> /// <param name="toColor">渐变色2</param> public static void DrawRectangle(VertexHelper vh, Vector3 p1, Vector3 p2, float radius, Color32 color, Color32 toColor) { var dir = (p2 - p1).normalized; var dirv = Vector3.Cross(dir, Vector3.forward).normalized; var p3 = p1 + dirv * radius; var p4 = p1 - dirv * radius; var p5 = p2 - dirv * radius; var p6 = p2 + dirv * radius; DrawQuadrilateral(vh, p3, p4, p5, p6, color, toColor); } /// <summary> /// Draw a rectangle. 画长方形 /// </summary> /// <param name="vh"></param> /// <param name="p">中心点</param> /// <param name="xRadius">x宽</param> /// <param name="yRadius">y宽</param> /// <param name="color">颜色</param> /// <param name="vertical">是否垂直方向</param> public static void DrawRectangle(VertexHelper vh, Vector3 p, float xRadius, float yRadius, Color32 color, bool vertical = true) { DrawRectangle(vh, p, xRadius, yRadius, color, color, vertical); } /// <summary> /// Draw a rectangle. 画带渐变的长方形 /// </summary> /// <param name="vh"></param> /// <param name="p">中心点</param> /// <param name="xRadius">x宽</param> /// <param name="yRadius">y宽</param> /// <param name="color">渐变色1</param> /// <param name="toColor">渐变色2</param> /// <param name="vertical">是否垂直方向</param> public static void DrawRectangle(VertexHelper vh, Vector3 p, float xRadius, float yRadius, Color32 color, Color32 toColor, bool vertical = true) { Vector3 p1, p2, p3, p4; if (vertical) { p1 = new Vector3(p.x + xRadius, p.y - yRadius); p2 = new Vector3(p.x - xRadius, p.y - yRadius); p3 = new Vector3(p.x - xRadius, p.y + yRadius); p4 = new Vector3(p.x + xRadius, p.y + yRadius); } else { p1 = new Vector3(p.x - xRadius, p.y - yRadius); p2 = new Vector3(p.x - xRadius, p.y + yRadius); p3 = new Vector3(p.x + xRadius, p.y + yRadius); p4 = new Vector3(p.x + xRadius, p.y - yRadius); } DrawQuadrilateral(vh, p1, p2, p3, p4, color, toColor); } /// <summary> /// Draw a quadrilateral. 画任意的四边形 /// </summary> /// <param name="vh"></param> /// <param name="p1"></param> /// <param name="p2"></param> /// <param name="p3"></param> /// <param name="p4"></param> /// <param name="color"></param> public static void DrawQuadrilateral(VertexHelper vh, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4, Color32 color) { DrawQuadrilateral(vh, p1, p2, p3, p4, color, color); } /// <summary> /// Draw a quadrilateral. 画任意带渐变的四边形 /// </summary> /// <param name="vh"></param> /// <param name="p1"></param> /// <param name="p2"></param> /// <param name="p3"></param> /// <param name="p4"></param> /// <param name="startColor"></param> /// <param name="toColor"></param> public static void DrawQuadrilateral(VertexHelper vh, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4, Color32 startColor, Color32 toColor) { s_Vertex[0].position = p1; s_Vertex[1].position = p2; s_Vertex[2].position = p3; s_Vertex[3].position = p4; for (int j = 0; j < 4; j++) { s_Vertex[j].color = j >= 2 ? toColor : startColor; s_Vertex[j].uv0 = s_ZeroVector2; } vh.AddUIVertexQuad(s_Vertex); } private static void InitCornerRadius(float[] cornerRadius, float width, float height, bool horizontal, bool invert, ref float brLt, ref float brRt, ref float brRb, ref float brLb, ref bool needRound) { if (cornerRadius == null) return; if (invert) { if (horizontal) { brLt = cornerRadius.Length > 0 ? cornerRadius[1] : 0; brRt = cornerRadius.Length > 1 ? cornerRadius[0] : 0; brRb = cornerRadius.Length > 2 ? cornerRadius[3] : 0; brLb = cornerRadius.Length > 3 ? cornerRadius[2] : 0; } else { brLt = cornerRadius.Length > 0 ? cornerRadius[3] : 0; brRt = cornerRadius.Length > 1 ? cornerRadius[2] : 0; brRb = cornerRadius.Length > 2 ? cornerRadius[1] : 0; brLb = cornerRadius.Length > 3 ? cornerRadius[0] : 0; } } else { brLt = cornerRadius.Length > 0 ? cornerRadius[0] : 0; brRt = cornerRadius.Length > 1 ? cornerRadius[1] : 0; brRb = cornerRadius.Length > 2 ? cornerRadius[2] : 0; brLb = cornerRadius.Length > 3 ? cornerRadius[3] : 0; } needRound = brLb != 0 || brRt != 0 || brRb != 0 || brLb != 0; if (needRound) { var min = Mathf.Min(width, height); if (brLt == 1 && brRt == 1 && brRb == 1 && brLb == 1) { brLt = brRt = brRb = brLb = min / 2; return; } if (brLt > 0 && brLt <= 1) brLt = brLt * min; if (brRt > 0 && brRt <= 1) brRt = brRt * min; if (brRb > 0 && brRb <= 1) brRb = brRb * min; if (brLb > 0 && brLb <= 1) brLb = brLb * min; if (horizontal) { if (brLb + brLt >= height) { var total = brLb + brLt; brLb = height * (brLb / total); brLt = height * (brLt / total); } if (brRt + brRb >= height) { var total = brRt + brRb; brRt = height * (brRt / total); brRb = height * (brRb / total); } if (brLt + brRt >= width) { var total = brLt + brRt; brLt = width * (brLt / total); brRt = width * (brRt / total); } if (brRb + brLb >= width) { var total = brRb + brLb; brRb = width * (brRb / total); brLb = width * (brLb / total); } } else { if (brLt + brRt >= width) { var total = brLt + brRt; brLt = width * (brLt / total); brRt = width * (brRt / total); } if (brRb + brLb >= width) { var total = brRb + brLb; brRb = width * (brRb / total); brLb = width * (brLb / total); } if (brLb + brLt >= height) { var total = brLb + brLt; brLb = height * (brLb / total); brLt = height * (brLt / total); } if (brRt + brRb >= height) { var total = brRt + brRb; brRt = height * (brRt / total); brRb = height * (brRb / total); } } } } /// <summary> /// 绘制圆角矩形 /// </summary> /// <param name="vh"></param> /// <param name="center"></param> /// <param name="rectWidth"></param> /// <param name="rectHeight"></param> /// <param name="color"></param> /// <param name="toColor"></param> /// <param name="rotate"></param> /// <param name="cornerRadius"></param> /// <param name="isYAxis"></param> /// <param name="smoothness"></param> /// <param name="invertCorner"></param> public static void DrawRoundRectangle(VertexHelper vh, Vector3 center, float rectWidth, float rectHeight, Color32 color, Color32 toColor, float rotate = 0, float[] cornerRadius = null, bool isYAxis = false, float smoothness = 2, bool invertCorner = false) { var isGradient = !UGLHelper.IsValueEqualsColor(color, toColor); var halfWid = rectWidth / 2; var halfHig = rectHeight / 2; float brLt = 0, brRt = 0, brRb = 0, brLb = 0; bool needRound = false; InitCornerRadius(cornerRadius, rectWidth, rectHeight, isYAxis, invertCorner, ref brLt, ref brRt, ref brRb, ref brLb, ref needRound); var tempCenter = Vector3.zero; var lbIn = new Vector3(center.x - halfWid, center.y - halfHig); var ltIn = new Vector3(center.x - halfWid, center.y + halfHig); var rtIn = new Vector3(center.x + halfWid, center.y + halfHig); var rbIn = new Vector3(center.x + halfWid, center.y - halfHig); if (needRound) { var lbIn2 = lbIn; var ltIn2 = ltIn; var rtIn2 = rtIn; var rbIn2 = rbIn; var roundLb = lbIn; var roundLt = ltIn; var roundRt = rtIn; var roundRb = rbIn; if (brLt > 0) { roundLt = new Vector3(center.x - halfWid + brLt, center.y + halfHig - brLt); ltIn = roundLt + brLt * Vector3.left; ltIn2 = roundLt + brLt * Vector3.up; } if (brRt > 0) { roundRt = new Vector3(center.x + halfWid - brRt, center.y + halfHig - brRt); rtIn = roundRt + brRt * Vector3.up; rtIn2 = roundRt + brRt * Vector3.right; } if (brRb > 0) { roundRb = new Vector3(center.x + halfWid - brRb, center.y - halfHig + brRb); rbIn = roundRb + brRb * Vector3.right; rbIn2 = roundRb + brRb * Vector3.down; } if (brLb > 0) { roundLb = new Vector3(center.x - halfWid + brLb, center.y - halfHig + brLb); lbIn = roundLb + brLb * Vector3.left; lbIn2 = roundLb + brLb * Vector3.down; } if (isYAxis) { var maxLeft = Mathf.Max(brLt, brLb); var maxRight = Mathf.Max(brRt, brRb); var ltInRight = ltIn + maxLeft * Vector3.right; var lbInRight = lbIn + maxLeft * Vector3.right; var rtIn2Left = rtIn2 + maxRight * Vector3.left; var rbInLeft = rbIn + maxRight * Vector3.left; var roundLbRight = roundLb + (maxLeft - brLb) * Vector3.right; var lbIn2Right = lbIn2 + (maxLeft - brLb) * Vector3.right; if (roundLbRight.x > roundRb.x) roundLbRight.x = roundRb.x; if (lbIn2Right.x > roundRb.x) lbIn2Right.x = roundRb.x; var ltIn2Right = ltIn2 + (maxLeft - brLt) * Vector3.right; var roundLtRight = roundLt + (maxLeft - brLt) * Vector3.right; if (ltIn2Right.x > roundRt.x) ltIn2Right.x = roundRt.x; if (roundLtRight.x > roundRt.x) roundLtRight.x = roundRt.x; var roundRtLeft = roundRt + (maxRight - brRt) * Vector3.left; var rtInLeft = rtIn + (maxRight - brRt) * Vector3.left; if (roundRtLeft.x < roundLt.x) roundRtLeft.x = roundLt.x; if (rtInLeft.x < roundLt.x) rtInLeft.x = roundLt.x; var rbIn2Left = rbIn2 + (maxRight - brRb) * Vector3.left; var roundRbLeft = roundRb + (maxRight - brRb) * Vector3.left; if (rbIn2Left.x < roundLb.x) rbIn2Left.x = roundLb.x; if (roundRbLeft.x < roundLb.x) roundRbLeft.x = roundLb.x; if (!isGradient) { DrawSector(vh, roundLt, brLt, color, color, 270, 360, 1, isYAxis, smoothness); DrawSector(vh, roundRt, brRt, toColor, toColor, 0, 90, 1, isYAxis, smoothness); DrawSector(vh, roundRb, brRb, toColor, toColor, 90, 180, 1, isYAxis, smoothness); DrawSector(vh, roundLb, brLb, color, color, 180, 270, 1, isYAxis, smoothness); DrawQuadrilateral(vh, ltIn, ltInRight, lbInRight, lbIn, color, color); DrawQuadrilateral(vh, lbIn2, roundLb, roundLbRight, lbIn2Right, color, color); DrawQuadrilateral(vh, roundLt, ltIn2, ltIn2Right, roundLtRight, color, color); DrawQuadrilateral(vh, rbInLeft, rtIn2Left, rtIn2, rbIn, toColor, toColor); DrawQuadrilateral(vh, roundRtLeft, rtInLeft, rtIn, roundRt, toColor, toColor); DrawQuadrilateral(vh, rbIn2Left, roundRbLeft, roundRb, rbIn2, toColor, toColor); var clt = new Vector3(center.x - halfWid + maxLeft, center.y + halfHig); var crt = new Vector3(center.x + halfWid - maxRight, center.y + halfHig); var crb = new Vector3(center.x + halfWid - maxRight, center.y - halfHig); var clb = new Vector3(center.x - halfWid + maxLeft, center.y - halfHig); if (crt.x > clt.x) { DrawQuadrilateral(vh, clb, clt, crt, crb, color, toColor); } } else { var tempLeftColor = Color32.Lerp(color, toColor, maxLeft / rectWidth); var upLeftColor = Color32.Lerp(color, tempLeftColor, brLt / maxLeft); var downLeftColor = Color32.Lerp(color, tempLeftColor, brLb / maxLeft); var tempRightColor = Color32.Lerp(color, toColor, (rectWidth - maxRight) / rectWidth); var upRightColor = Color32.Lerp(tempRightColor, toColor, (maxRight - brRt) / maxRight); var downRightColor = Color32.Lerp(tempRightColor, toColor, (maxRight - brRb) / maxRight); DrawSector(vh, roundLt, brLt, color, upLeftColor, 270, 360, 1, isYAxis, smoothness); DrawSector(vh, roundRt, brRt, upRightColor, toColor, 0, 90, 1, isYAxis, smoothness); DrawSector(vh, roundRb, brRb, downRightColor, toColor, 90, 180, 1, isYAxis, smoothness); DrawSector(vh, roundLb, brLb, color, downLeftColor, 180, 270, 1, isYAxis, smoothness); DrawQuadrilateral(vh, lbIn, ltIn, ltInRight, lbInRight, color, tempLeftColor); DrawQuadrilateral(vh, lbIn2, roundLb, roundLbRight, lbIn2Right, downLeftColor, roundLbRight.x == roundRb.x ? downRightColor : tempLeftColor); DrawQuadrilateral(vh, roundLt, ltIn2, ltIn2Right, roundLtRight, upLeftColor, ltIn2Right.x == roundRt.x ? upRightColor : tempLeftColor); DrawQuadrilateral(vh, rbInLeft, rtIn2Left, rtIn2, rbIn, tempRightColor, toColor); DrawQuadrilateral(vh, roundRtLeft, rtInLeft, rtIn, roundRt, roundRtLeft.x == roundLt.x ? upLeftColor : tempRightColor, upRightColor); DrawQuadrilateral(vh, rbIn2Left, roundRbLeft, roundRb, rbIn2, rbIn2Left.x == roundLb.x ? downLeftColor : tempRightColor, downRightColor); var clt = new Vector3(center.x - halfWid + maxLeft, center.y + halfHig); var crt = new Vector3(center.x + halfWid - maxRight, center.y + halfHig); var crb = new Vector3(center.x + halfWid - maxRight, center.y - halfHig); var clb = new Vector3(center.x - halfWid + maxLeft, center.y - halfHig); if (crt.x > clt.x) { DrawQuadrilateral(vh, clb, clt, crt, crb, tempLeftColor, tempRightColor); } } } else { var maxup = Mathf.Max(brLt, brRt); var maxdown = Mathf.Max(brLb, brRb); var clt = new Vector3(center.x - halfWid, center.y + halfHig - maxup); var crt = new Vector3(center.x + halfWid, center.y + halfHig - maxup); var crb = new Vector3(center.x + halfWid, center.y - halfHig + maxdown); var clb = new Vector3(center.x - halfWid, center.y - halfHig + maxdown); var lbIn2Up = lbIn2 + maxdown * Vector3.up; var rbIn2Up = rbIn2 + maxdown * Vector3.up; var rtInDown = rtIn + maxup * Vector3.down; var ltIn2Down = ltIn2 + maxup * Vector3.down; var roundLtDown = roundLt + (maxup - brLt) * Vector3.down; var ltInDown = ltIn + (maxup - brLt) * Vector3.down; if (roundLtDown.y < roundLb.y) roundLtDown.y = roundLb.y; if (ltInDown.y < roundLb.y) ltInDown.y = roundLb.y; var rtIn2Down = rtIn2 + (maxup - brRt) * Vector3.down; var roundRtDown = roundRt + (maxup - brRt) * Vector3.down; if (rtIn2Down.y < roundRb.y) rtIn2Down.y = roundRb.y; if (roundRtDown.y < roundRb.y) roundRtDown.y = roundRb.y; var lbInUp = lbIn + (maxdown - brLb) * Vector3.up; var roundLbUp = roundLb + (maxdown - brLb) * Vector3.up; if (lbInUp.y > roundLt.y) lbInUp.y = roundLt.y; if (roundLbUp.y > roundLt.y) roundLbUp.y = roundLt.y; var roundRbUp = roundRb + (maxdown - brRb) * Vector3.up; var rbInUp = rbIn + (maxdown - brRb) * Vector3.up; if (roundRbUp.y > roundRt.y) roundRbUp.y = roundRt.y; if (rbInUp.y > roundRt.y) rbInUp.y = roundRt.y; if (!isGradient) { DrawSector(vh, roundLt, brLt, toColor, toColor, 270, 360, 1, isYAxis, smoothness); DrawSector(vh, roundRt, brRt, toColor, toColor, 0, 90, 1, isYAxis, smoothness); DrawSector(vh, roundRb, brRb, color, color, 90, 180, 1, isYAxis, smoothness); DrawSector(vh, roundLb, brLb, color, color, 180, 270, 1, isYAxis, smoothness); DrawQuadrilateral(vh, ltIn2, rtIn, rtInDown, ltIn2Down, toColor, toColor); DrawQuadrilateral(vh, ltIn, roundLt, roundLtDown, ltInDown, toColor, toColor); DrawQuadrilateral(vh, roundRt, rtIn2, rtIn2Down, roundRtDown, toColor, toColor); DrawQuadrilateral(vh, lbIn2, lbIn2Up, rbIn2Up, rbIn2, color, color); DrawQuadrilateral(vh, lbIn, lbInUp, roundLbUp, roundLb, color, color); DrawQuadrilateral(vh, roundRb, roundRbUp, rbInUp, rbIn, color, color); if (clt.y > clb.y) { DrawQuadrilateral(vh, clt, crt, crb, clb, toColor, color); } } else { var tempUpColor = Color32.Lerp(color, toColor, (rectHeight - maxup) / rectHeight); var leftUpColor = Color32.Lerp(tempUpColor, toColor, (maxup - brLt) / maxup); var rightUpColor = Color32.Lerp(tempUpColor, toColor, (maxup - brRt) / maxup); var tempDownColor = Color32.Lerp(color, toColor, maxdown / rectHeight); var leftDownColor = Color32.Lerp(color, tempDownColor, brLb / maxdown); var rightDownColor = Color32.Lerp(color, tempDownColor, brRb / maxdown); DrawSector(vh, roundLt, brLt, leftUpColor, toColor, 270, 360, 1, isYAxis, smoothness); DrawSector(vh, roundRt, brRt, rightUpColor, toColor, 0, 90, 1, isYAxis, smoothness); DrawSector(vh, roundRb, brRb, rightDownColor, color, 90, 180, 1, isYAxis, smoothness); DrawSector(vh, roundLb, brLb, leftDownColor, color, 180, 270, 1, isYAxis, smoothness); DrawQuadrilateral(vh, ltIn2, rtIn, rtInDown, ltIn2Down, toColor, tempUpColor); DrawQuadrilateral(vh, ltIn, roundLt, roundLtDown, ltInDown, leftUpColor, roundLtDown.y == roundLb.y ? leftDownColor : tempUpColor); DrawQuadrilateral(vh, roundRt, rtIn2, rtIn2Down, roundRtDown, rightUpColor, rtIn2Down.y == roundRb.y ? rightDownColor : tempUpColor); DrawQuadrilateral(vh, rbIn2, lbIn2, lbIn2Up, rbIn2Up, color, tempDownColor); DrawQuadrilateral(vh, roundLb, lbIn, lbInUp, roundLbUp, leftDownColor, lbInUp.y == roundLt.y ? leftUpColor : tempDownColor); DrawQuadrilateral(vh, rbIn, roundRb, roundRbUp, rbInUp, rightDownColor, roundRbUp.y == roundRt.y ? rightUpColor : tempDownColor); if (clt.y > clb.y) { DrawQuadrilateral(vh, clt, crt, crb, clb, tempUpColor, tempDownColor); } } } } else { DrawQuadrilateral(vh, lbIn, ltIn, rtIn, rbIn, toColor, color); } } /// <summary> /// 绘制(圆角)边框 /// </summary> /// <param name="vh"></param> /// <param name="center"></param> /// <param name="rectWidth"></param> /// <param name="rectHeight"></param> /// <param name="borderWidth"></param> /// <param name="color"></param> /// <param name="rotate"></param> /// <param name="cornerRadius"></param> /// <param name="invertCorner"></param> public static void DrawBorder(VertexHelper vh, Vector3 center, float rectWidth, float rectHeight, float borderWidth, Color32 color, float rotate = 0, float[] cornerRadius = null, bool horizontal = false, float smoothness = 1f, bool invertCorner = false) { DrawBorder(vh, center, rectWidth, rectHeight, borderWidth, color, s_ClearColor32, rotate, cornerRadius, horizontal, smoothness, invertCorner); } /// <summary> /// 绘制(圆角)边框 /// </summary> /// <param name="vh"></param> /// <param name="center"></param> /// <param name="rectWidth"></param> /// <param name="rectHeight"></param> /// <param name="borderWidth"></param> /// <param name="color"></param> /// <param name="toColor"></param> /// <param name="rotate"></param> /// <param name="cornerRadius"></param> /// <param name="horizontal"></param> /// <param name="smoothness"></param> /// <param name="invertCorner"></param> public static void DrawBorder(VertexHelper vh, Vector3 center, float rectWidth, float rectHeight, float borderWidth, Color32 color, Color32 toColor, float rotate = 0, float[] cornerRadius = null, bool horizontal = false, float smoothness = 1f, bool invertCorner = false) { if (borderWidth == 0 || UGLHelper.IsClearColor(color)) return; var halfWid = rectWidth / 2; var halfHig = rectHeight / 2; var lbIn = new Vector3(center.x - halfWid, center.y - halfHig); var lbOt = new Vector3(center.x - halfWid - borderWidth, center.y - halfHig - borderWidth); var ltIn = new Vector3(center.x - halfWid, center.y + halfHig); var ltOt = new Vector3(center.x - halfWid - borderWidth, center.y + halfHig + borderWidth); var rtIn = new Vector3(center.x + halfWid, center.y + halfHig); var rtOt = new Vector3(center.x + halfWid + borderWidth, center.y + halfHig + borderWidth); var rbIn = new Vector3(center.x + halfWid, center.y - halfHig); var rbOt = new Vector3(center.x + halfWid + borderWidth, center.y - halfHig - borderWidth); float brLt = 0, brRt = 0, brRb = 0, brLb = 0; bool needRound = false; InitCornerRadius(cornerRadius, rectWidth, rectHeight, horizontal, invertCorner, ref brLt, ref brRt, ref brRb, ref brLb, ref needRound); var tempCenter = Vector3.zero; if (UGLHelper.IsClearColor(toColor)) { toColor = color; } if (needRound) { var lbIn2 = lbIn; var lbOt2 = lbOt; var ltIn2 = ltIn; var ltOt2 = ltOt; var rtIn2 = rtIn; var rtOt2 = rtOt; var rbIn2 = rbIn; var rbOt2 = rbOt; if (brLt > 0) { tempCenter = new Vector3(center.x - halfWid + brLt, center.y + halfHig - brLt); DrawDoughnut(vh, tempCenter, brLt, brLt + borderWidth, horizontal ? color : toColor, s_ClearColor32, 270, 360, smoothness); ltIn = tempCenter + brLt * Vector3.left; ltOt = tempCenter + (brLt + borderWidth) * Vector3.left; ltIn2 = tempCenter + brLt * Vector3.up; ltOt2 = tempCenter + (brLt + borderWidth) * Vector3.up; } if (brRt > 0) { tempCenter = new Vector3(center.x + halfWid - brRt, center.y + halfHig - brRt); DrawDoughnut(vh, tempCenter, brRt, brRt + borderWidth, toColor, s_ClearColor32, 0, 90, smoothness); rtIn = tempCenter + brRt * Vector3.up; rtOt = tempCenter + (brRt + borderWidth) * Vector3.up; rtIn2 = tempCenter + brRt * Vector3.right; rtOt2 = tempCenter + (brRt + borderWidth) * Vector3.right; } if (brRb > 0) { tempCenter = new Vector3(center.x + halfWid - brRb, center.y - halfHig + brRb); DrawDoughnut(vh, tempCenter, brRb, brRb + borderWidth, horizontal ? toColor : color, s_ClearColor32, 90, 180, smoothness); rbIn = tempCenter + brRb * Vector3.right; rbOt = tempCenter + (brRb + borderWidth) * Vector3.right; rbIn2 = tempCenter + brRb * Vector3.down; rbOt2 = tempCenter + (brRb + borderWidth) * Vector3.down; } if (brLb > 0) { tempCenter = new Vector3(center.x - halfWid + brLb, center.y - halfHig + brLb); DrawDoughnut(vh, tempCenter, brLb, brLb + borderWidth, color, s_ClearColor32, 180, 270, smoothness); lbIn = tempCenter + brLb * Vector3.left; lbOt = tempCenter + (brLb + borderWidth) * Vector3.left; lbIn2 = tempCenter + brLb * Vector3.down; lbOt2 = tempCenter + (brLb + borderWidth) * Vector3.down; } if (horizontal) { DrawQuadrilateral(vh, lbIn, lbOt, ltOt, ltIn, color, color); DrawQuadrilateral(vh, ltIn2, ltOt2, rtOt, rtIn, color, toColor); DrawQuadrilateral(vh, rtIn2, rtOt2, rbOt, rbIn, toColor, toColor); DrawQuadrilateral(vh, rbIn2, rbOt2, lbOt2, lbIn2, toColor, color); } else { DrawQuadrilateral(vh, lbIn, lbOt, ltOt, ltIn, color, toColor); DrawQuadrilateral(vh, ltIn2, ltOt2, rtOt, rtIn, toColor, toColor); DrawQuadrilateral(vh, rtIn2, rtOt2, rbOt, rbIn, toColor, color); DrawQuadrilateral(vh, rbIn2, rbOt2, lbOt2, lbIn2, color, color); } } else { if (rotate > 0) { lbIn = UGLHelper.RotateRound(lbIn, center, Vector3.forward, rotate); lbOt = UGLHelper.RotateRound(lbOt, center, Vector3.forward, rotate); ltIn = UGLHelper.RotateRound(ltIn, center, Vector3.forward, rotate); ltOt = UGLHelper.RotateRound(ltOt, center, Vector3.forward, rotate); rtIn = UGLHelper.RotateRound(rtIn, center, Vector3.forward, rotate); rtOt = UGLHelper.RotateRound(rtOt, center, Vector3.forward, rotate); rbIn = UGLHelper.RotateRound(rbIn, center, Vector3.forward, rotate); rbOt = UGLHelper.RotateRound(rbOt, center, Vector3.forward, rotate); } if (horizontal) { DrawQuadrilateral(vh, lbIn, lbOt, ltOt, ltIn, color, color); DrawQuadrilateral(vh, ltIn, ltOt, rtOt, rtIn, color, toColor); DrawQuadrilateral(vh, rtIn, rtOt, rbOt, rbIn, toColor, toColor); DrawQuadrilateral(vh, rbIn, rbOt, lbOt, lbIn, toColor, color); } else { DrawQuadrilateral(vh, lbIn, lbOt, ltOt, ltIn, color, toColor); DrawQuadrilateral(vh, ltIn, ltOt, rtOt, rtIn, toColor, toColor); DrawQuadrilateral(vh, rtIn, rtOt, rbOt, rbIn, toColor, color); DrawQuadrilateral(vh, rbIn, rbOt, lbOt, lbIn, color, color); } } } public static void DrawTriangle(VertexHelper vh, Vector3 p1, Vector3 p2, Vector3 p3, Color32 color) { DrawTriangle(vh, p1, p2, p3, color, color, color); } public static void DrawTriangle(VertexHelper vh, Vector3 pos, float size, Color32 color) { DrawTriangle(vh, pos, size, color, color); } public static void DrawTriangle(VertexHelper vh, Vector3 pos, float size, Color32 color, Color32 toColor) { var x = size * Mathf.Cos(30 * Mathf.PI / 180); var y = size * Mathf.Sin(30 * Mathf.PI / 180); var p1 = new Vector2(pos.x - x, pos.y - y); var p2 = new Vector2(pos.x, pos.y + size); var p3 = new Vector2(pos.x + x, pos.y - y); DrawTriangle(vh, p1, p2, p3, color, toColor, color); } public static void DrawTriangle(VertexHelper vh, Vector3 p1, Vector3 p2, Vector3 p3, Color32 color, Color32 color2, Color32 color3) { UIVertex v1 = new UIVertex(); v1.position = p1; v1.color = color; v1.uv0 = s_ZeroVector2; UIVertex v2 = new UIVertex(); v2.position = p2; v2.color = color2; v2.uv0 = s_ZeroVector2; UIVertex v3 = new UIVertex(); v3.position = p3; v3.color = color3; v3.uv0 = s_ZeroVector2; int startIndex = vh.currentVertCount; vh.AddVert(v1); vh.AddVert(v2); vh.AddVert(v3); vh.AddTriangle(startIndex, startIndex + 1, startIndex + 2); } public static void DrawCricle(VertexHelper vh, Vector3 center, float radius, Color32 color, float smoothness = 2f) { DrawCricle(vh, center, radius, color, color, 0, s_ClearColor32, smoothness); } public static void DrawCricle(VertexHelper vh, Vector3 center, float radius, Color32 color, Color32 toColor, float smoothness = 2f) { DrawSector(vh, center, radius, color, toColor, 0, 360, 0, s_ClearColor32, smoothness); } public static void DrawCricle(VertexHelper vh, Vector3 center, float radius, Color32 color, Color32 toColor, float borderWidth, Color32 borderColor, float smoothness = 2f) { DrawSector(vh, center, radius, color, toColor, 0, 360, borderWidth, borderColor, smoothness); } public static void DrawCricle(VertexHelper vh, Vector3 center, float radius, Color32 color, float borderWidth, Color32 borderColor, float smoothness = 2f) { DrawCricle(vh, center, radius, color, color, borderWidth, borderColor, smoothness); } public static void DrawEmptyCricle(VertexHelper vh, Vector3 center, float radius, float tickness, Color32 color, Color32 emptyColor, float smoothness = 2f) { DrawDoughnut(vh, center, radius - tickness, radius, color, color, emptyColor, 0, 360, 0, s_ClearColor32, 0, smoothness); } public static void DrawEmptyCricle(VertexHelper vh, Vector3 center, float radius, float tickness, Color32 color, Color32 emptyColor, float borderWidth, Color32 borderColor, float smoothness = 2f) { DrawDoughnut(vh, center, radius - tickness, radius, color, color, emptyColor, 0, 360, borderWidth, borderColor, 0, smoothness); } public static void DrawEmptyCricle(VertexHelper vh, Vector3 center, float radius, float tickness, Color32 color, Color32 toColor, Color32 emptyColor, float smoothness = 2f) { DrawDoughnut(vh, center, radius - tickness, radius, color, toColor, emptyColor, 0, 360, 0, s_ClearColor32, 0, smoothness); } public static void DrawEmptyCricle(VertexHelper vh, Vector3 center, float radius, float tickness, Color32 color, Color32 toColor, Color32 emptyColor, float borderWidth, Color32 borderColor, float smoothness = 2f) { DrawDoughnut(vh, center, radius - tickness, radius, color, toColor, emptyColor, 0, 360, borderWidth, borderColor, 0, smoothness); } public static void DrawSector(VertexHelper vh, Vector3 center, float radius, Color32 color, float startDegree, float toDegree, float smoothness = 2f) { DrawSector(vh, center, radius, color, color, startDegree, toDegree, 0, s_ClearColor32, smoothness); } public static void DrawSector(VertexHelper vh, Vector3 center, float radius, Color32 color, Color32 toColor, float startDegree, float toDegree, int gradientType = 0, bool isYAxis = false, float smoothness = 2f) { DrawSector(vh, center, radius, color, toColor, startDegree, toDegree, 0, s_ClearColor32, 0, smoothness, gradientType, isYAxis); } public static void DrawSector(VertexHelper vh, Vector3 center, float radius, Color32 color, float startDegree, float toDegree, float borderWidth, Color32 borderColor, float smoothness = 2f) { DrawSector(vh, center, radius, color, color, startDegree, toDegree, borderWidth, borderColor, smoothness); } public static void DrawSector(VertexHelper vh, Vector3 center, float radius, Color32 color, Color32 toColor, float startDegree, float toDegree, float borderWidth, Color32 borderColor, float smoothness = 2f) { DrawSector(vh, center, radius, color, toColor, startDegree, toDegree, borderWidth, borderColor, 0, smoothness); } /// <summary> /// 绘制扇形(可带边框、有空白边距、3种类型渐变) /// </summary> /// <param name="vh"></param> /// <param name="center">中心点</param> /// <param name="radius">半径</param> /// <param name="color">颜色</param> /// <param name="toColor">渐变颜色</param> /// <param name="startDegree">开始角度</param> /// <param name="toDegree">结束角度</param> /// <param name="borderWidth">边框宽度</param> /// <param name="borderColor">边框颜色</param> /// <param name="space">边距</param> /// <param name="smoothness">光滑度</param> /// <param name="gradientType">渐变类型,0:向圆形渐变,1:水平或垂直渐变,2:开始角度向结束角度渐变</param> /// <param name="isYAxis">水平渐变还是垂直渐变,gradientType为1时生效</param> public static void DrawSector(VertexHelper vh, Vector3 center, float radius, Color32 color, Color32 toColor, float startDegree, float toDegree, float borderWidth, Color32 borderColor, float space, float smoothness, int gradientType = 0, bool isYAxis = false) { if (radius == 0) return; if (space > 0 && Mathf.Abs(toDegree - startDegree) >= 360) space = 0; radius -= borderWidth; smoothness = (smoothness < 0 ? 2f : smoothness); int segments = (int)((2 * Mathf.PI * radius) * (Mathf.Abs(toDegree - startDegree) / 360) / smoothness); if (segments < 1) segments = 1; float startAngle = startDegree * Mathf.Deg2Rad; float toAngle = toDegree * Mathf.Deg2Rad; float realStartAngle = startAngle; float realToAngle = toAngle; float halfAngle = (toAngle - startAngle) / 2; float borderAngle = 0; float spaceAngle = 0; var p2 = center + radius * UGLHelper.GetDire(startAngle); var p3 = Vector3.zero; var p4 = Vector3.zero; var spaceCenter = center; var realCenter = center; var lastP4 = center; var lastColor = color; var needBorder = borderWidth != 0; var needSpace = space != 0; var borderLineWidth = needSpace ? borderWidth : borderWidth / 2; var lastPos = Vector3.zero; var middleDire = UGLHelper.GetDire(startAngle + halfAngle); if (needBorder || needSpace) { float spaceDiff = 0f; float borderDiff = 0f; if (needSpace) { spaceDiff = space / Mathf.Sin(halfAngle); spaceCenter = center + spaceDiff * middleDire; realCenter = spaceCenter; spaceAngle = 2 * Mathf.Asin(space / (2 * radius)); realStartAngle = startAngle + spaceAngle; realToAngle = toAngle - spaceAngle; if (realToAngle < realStartAngle) realToAngle = realStartAngle; p2 = UGLHelper.GetPos(center, radius, realStartAngle); } if (needBorder) { borderDiff = borderLineWidth / Mathf.Sin(halfAngle); realCenter += borderDiff * middleDire; borderAngle = 2 * Mathf.Asin(borderLineWidth / (2 * radius)); realStartAngle = realStartAngle + borderAngle; realToAngle = realToAngle - borderAngle; if (realToAngle < realStartAngle) { realToAngle = realStartAngle; p2 = UGLHelper.GetPos(center, radius, realStartAngle); } else { var borderX1 = UGLHelper.GetPos(center, radius, realStartAngle); DrawQuadrilateral(vh, realCenter, spaceCenter, p2, borderX1, borderColor); p2 = borderX1; var borderX2 = UGLHelper.GetPos(center, radius, realToAngle); var pEnd = UGLHelper.GetPos(center, radius, toAngle - spaceAngle); DrawQuadrilateral(vh, realCenter, borderX2, pEnd, spaceCenter, borderColor); } } } float segmentAngle = (realToAngle - realStartAngle) / segments; bool isLeft = startDegree >= 180; for (int i = 0; i <= segments; i++) { float currAngle = realStartAngle + i * segmentAngle; p3 = center + radius * UGLHelper.GetDire(currAngle); if (gradientType == 1) { if (isYAxis) { p4 = new Vector3(p3.x, realCenter.y); var dist = p4.x - realCenter.x; var tcolor = Color32.Lerp(color, toColor, dist >= 0 ? dist / radius : Mathf.Min(radius + dist, radius) / radius); if (isLeft && (i == segments || i == 0)) tcolor = toColor; DrawQuadrilateral(vh, lastP4, p2, p3, p4, lastColor, tcolor); lastP4 = p4; lastColor = tcolor; } else { p4 = new Vector3(realCenter.x, p3.y); var tcolor = Color32.Lerp(color, toColor, Mathf.Abs(p4.y - realCenter.y) / radius); DrawQuadrilateral(vh, lastP4, p2, p3, p4, lastColor, tcolor); lastP4 = p4; lastColor = tcolor; } } else if (gradientType == 2) { var tcolor = Color32.Lerp(color, toColor, i / segments); DrawQuadrilateral(vh, realCenter, p2, p3, realCenter, lastColor, tcolor); lastColor = tcolor; } else { DrawTriangle(vh, realCenter, p2, p3, toColor, color, color); } p2 = p3; } if (needBorder || needSpace) { if (realToAngle > realStartAngle) { var borderX2 = center + radius * UGLHelper.GetDire(realToAngle); DrawTriangle(vh, realCenter, p2, borderX2, toColor, color, color); if (needBorder) { var realStartDegree = (realStartAngle - borderAngle) * Mathf.Rad2Deg; var realToDegree = (realToAngle + borderAngle) * Mathf.Rad2Deg; DrawDoughnut(vh, center, radius, radius + borderWidth, borderColor, s_ClearColor32, realStartDegree, realToDegree, smoothness); } } } } public static void DrawRoundCap(VertexHelper vh, Vector3 center, float width, float radius, float angle, bool clockwise, Color32 color, bool end) { var px = Mathf.Sin(angle * Mathf.Deg2Rad) * radius; var py = Mathf.Cos(angle * Mathf.Deg2Rad) * radius; var pos = new Vector3(px, py) + center; if (end) { if (clockwise) DrawSector(vh, pos, width, color, angle, angle + 180, 0, s_ClearColor32); else DrawSector(vh, pos, width, color, angle, angle - 180, 0, s_ClearColor32); } else { if (clockwise) DrawSector(vh, pos, width, color, angle + 180, angle + 360, 0, s_ClearColor32); else DrawSector(vh, pos, width, color, angle - 180, angle - 360, 0, s_ClearColor32); } } public static void DrawDoughnut(VertexHelper vh, Vector3 center, float insideRadius, float outsideRadius, Color32 color, Color32 emptyColor, float smoothness = 2f) { DrawDoughnut(vh, center, insideRadius, outsideRadius, color, color, emptyColor, 0, 360, 0, s_ClearColor32, 0, smoothness); } public static void DrawDoughnut(VertexHelper vh, Vector3 center, float insideRadius, float outsideRadius, Color32 color, Color32 emptyColor, float startDegree, float toDegree, float smoothness = 1f) { DrawDoughnut(vh, center, insideRadius, outsideRadius, color, color, emptyColor, startDegree, toDegree, 0, s_ClearColor32, 0, smoothness); } public static void DrawDoughnut(VertexHelper vh, Vector3 center, float insideRadius, float outsideRadius, Color32 color, Color32 emptyColor, float startDegree, float toDegree, float borderWidth, Color32 borderColor, float smoothness = 2f) { DrawDoughnut(vh, center, insideRadius, outsideRadius, color, color, emptyColor, startDegree, toDegree, borderWidth, borderColor, 0, smoothness); } public static void DrawDoughnut(VertexHelper vh, Vector3 center, float insideRadius, float outsideRadius, Color32 color, Color32 toColor, Color32 emptyColor, float smoothness = 2f) { DrawDoughnut(vh, center, insideRadius, outsideRadius, color, toColor, emptyColor, 0, 360, 0, s_ClearColor32, 0, smoothness); } public static void DrawDoughnut(VertexHelper vh, Vector3 center, float insideRadius, float outsideRadius, Color32 color, Color32 toColor, Color32 emptyColor, float startDegree, float toDegree, float borderWidth, Color32 borderColor, float space, float smoothness, bool roundCap = false, bool clockwise = true) { if (toDegree - startDegree == 0) return; if (space > 0 && Mathf.Abs(toDegree - startDegree) >= 360) space = 0; if (insideRadius <= 0) { DrawSector(vh, center, outsideRadius, color, toColor, startDegree, toDegree, borderWidth, borderColor, space, smoothness); return; } outsideRadius -= borderWidth; insideRadius += borderWidth; smoothness = smoothness < 0 ? 2f : smoothness; Vector3 p1, p2, p3, p4, e1, e2; var needBorder = borderWidth != 0; var needSpace = space != 0; var diffAngle = Mathf.Abs(toDegree - startDegree) * Mathf.Deg2Rad; int segments = (int)((2 * Mathf.PI * outsideRadius) * (diffAngle * Mathf.Rad2Deg / 360) / smoothness); if (segments < 1) segments = 1; float startAngle = startDegree * Mathf.Deg2Rad; float toAngle = toDegree * Mathf.Deg2Rad; float realStartOutAngle = startAngle; float realToOutAngle = toAngle; float realStartInAngle = startAngle; float realToInAngle = toAngle; float halfAngle = (toAngle - startAngle) / 2; float borderAngle = 0, borderInAngle = 0, borderHalfAngle = 0; float spaceAngle = 0, spaceInAngle = 0, spaceHalfAngle = 0; var spaceCenter = center; var realCenter = center; var startDire = new Vector3(Mathf.Sin(startAngle), Mathf.Cos(startAngle)).normalized; var toDire = new Vector3(Mathf.Sin(toAngle), Mathf.Cos(toAngle)).normalized; var middleDire = new Vector3(Mathf.Sin(startAngle + halfAngle), Mathf.Cos(startAngle + halfAngle)).normalized; p1 = center + insideRadius * startDire; p2 = center + outsideRadius * startDire; e1 = center + insideRadius * toDire; e2 = center + outsideRadius * toDire; if (roundCap) { var roundRadius = (outsideRadius - insideRadius) / 2; var roundAngleRadius = insideRadius + roundRadius; var roundAngle = Mathf.Atan(roundRadius / roundAngleRadius); if (diffAngle < 2 * roundAngle) { roundCap = false; } } if (needBorder || needSpace) { if (needSpace) { var spaceDiff = space / Mathf.Sin(halfAngle); spaceCenter = center + Mathf.Abs(spaceDiff) * middleDire; realCenter = spaceCenter; spaceAngle = 2 * Mathf.Asin(space / (2 * outsideRadius)); spaceInAngle = 2 * Mathf.Asin(space / (2 * insideRadius)); spaceHalfAngle = 2 * Mathf.Asin(space / (2 * (insideRadius + (outsideRadius - insideRadius) / 2))); if (clockwise) { p1 = UGLHelper.GetPos(center, insideRadius, startAngle + spaceInAngle, false); e1 = UGLHelper.GetPos(center, insideRadius, toAngle - spaceInAngle, false); realStartOutAngle = startAngle + spaceAngle; realToOutAngle = toAngle - spaceAngle; realStartInAngle = startAngle + spaceInAngle; realToInAngle = toAngle - spaceInAngle; } else { p1 = UGLHelper.GetPos(center, insideRadius, startAngle - spaceInAngle, false); e1 = UGLHelper.GetPos(center, insideRadius, toAngle + spaceInAngle, false); realStartOutAngle = startAngle - spaceAngle; realToOutAngle = toAngle + spaceAngle; realStartInAngle = startAngle - spaceInAngle; realToOutAngle = toAngle + spaceInAngle; } p2 = UGLHelper.GetPos(center, outsideRadius, realStartOutAngle, false); e2 = UGLHelper.GetPos(center, outsideRadius, realToOutAngle, false); } if (needBorder) { var borderDiff = borderWidth / Mathf.Sin(halfAngle); realCenter += Mathf.Abs(borderDiff) * middleDire; borderAngle = 2 * Mathf.Asin(borderWidth / (2 * outsideRadius)); borderInAngle = 2 * Mathf.Asin(borderWidth / (2 * insideRadius)); borderHalfAngle = 2 * Mathf.Asin(borderWidth / (2 * (insideRadius + (outsideRadius - insideRadius) / 2))); if (clockwise) { realStartOutAngle = realStartOutAngle + borderAngle; realToOutAngle = realToOutAngle - borderAngle; realStartInAngle = startAngle + spaceInAngle + borderInAngle; realToInAngle = toAngle - spaceInAngle - borderInAngle; var newp1 = UGLHelper.GetPos(center, insideRadius, startAngle + spaceInAngle + borderInAngle, false); var newp2 = UGLHelper.GetPos(center, outsideRadius, realStartOutAngle, false); if (!roundCap) DrawQuadrilateral(vh, newp2, newp1, p1, p2, borderColor); p1 = newp1; p2 = newp2; if (toAngle - spaceInAngle - 2 * borderInAngle > realStartOutAngle) { var newe1 = UGLHelper.GetPos(center, insideRadius, toAngle - spaceInAngle - borderInAngle, false); var newe2 = UGLHelper.GetPos(center, outsideRadius, realToOutAngle, false); if (!roundCap) DrawQuadrilateral(vh, newe2, e2, e1, newe1, borderColor); e1 = newe1; e2 = newe2; } } else { realStartOutAngle = realStartOutAngle - borderAngle; realToOutAngle = realToOutAngle + borderAngle; realStartInAngle = startAngle - spaceInAngle - borderInAngle; realToInAngle = toAngle + spaceInAngle + borderInAngle; var newp1 = UGLHelper.GetPos(center, insideRadius, startAngle - spaceInAngle - borderInAngle, false); var newp2 = UGLHelper.GetPos(center, outsideRadius, realStartOutAngle, false); if (!roundCap) DrawQuadrilateral(vh, newp2, newp1, p1, p2, borderColor); p1 = newp1; p2 = newp2; if (toAngle + spaceInAngle + 2 * borderInAngle < realStartOutAngle) { var newe1 = UGLHelper.GetPos(center, insideRadius, toAngle + spaceInAngle + borderInAngle, false); var newe2 = UGLHelper.GetPos(center, outsideRadius, realToOutAngle, false); if (!roundCap) DrawQuadrilateral(vh, newe2, e2, e1, newe1, borderColor); e1 = newe1; e2 = newe2; } } } } if (roundCap) { var roundRadius = (outsideRadius - insideRadius) / 2; var roundAngleRadius = insideRadius + roundRadius; var roundAngle = Mathf.Atan(roundRadius / roundAngleRadius); if (clockwise) { realStartOutAngle = startAngle + 2 * spaceHalfAngle + borderHalfAngle + roundAngle; realStartInAngle = startAngle + 2 * spaceHalfAngle + borderHalfAngle + roundAngle; } else { realStartOutAngle = startAngle - 2 * spaceHalfAngle - borderHalfAngle - roundAngle; realStartInAngle = startAngle - 2 * spaceHalfAngle - borderHalfAngle - roundAngle; } var roundTotalDegree = realStartOutAngle * Mathf.Rad2Deg; var roundCenter = center + roundAngleRadius * UGLHelper.GetDire(realStartOutAngle); var sectorStartDegree = clockwise ? roundTotalDegree + 180 : roundTotalDegree; var sectorToDegree = clockwise ? roundTotalDegree + 360 : roundTotalDegree + 180; DrawSector(vh, roundCenter, roundRadius, color, sectorStartDegree, sectorToDegree, smoothness / 2); if (needBorder) { DrawDoughnut(vh, roundCenter, roundRadius, roundRadius + borderWidth, borderColor, s_ClearColor32, sectorStartDegree, sectorToDegree, smoothness / 2); } p1 = UGLHelper.GetPos(center, insideRadius, realStartOutAngle); p2 = UGLHelper.GetPos(center, outsideRadius, realStartOutAngle); if (clockwise) { realToOutAngle = toAngle - 2 * spaceHalfAngle - borderHalfAngle - roundAngle; realToInAngle = toAngle - 2 * spaceHalfAngle - borderHalfAngle - roundAngle; if (realToOutAngle < realStartOutAngle) realToOutAngle = realStartOutAngle; } else { realToOutAngle = toAngle + 2 * spaceHalfAngle + borderHalfAngle + roundAngle; realToInAngle = toAngle + 2 * spaceHalfAngle + borderHalfAngle + roundAngle; if (realToOutAngle > realStartOutAngle) realToOutAngle = realStartOutAngle; } roundTotalDegree = realToOutAngle * Mathf.Rad2Deg; roundCenter = center + roundAngleRadius * UGLHelper.GetDire(realToOutAngle); sectorStartDegree = clockwise ? roundTotalDegree : roundTotalDegree + 180; sectorToDegree = clockwise ? roundTotalDegree + 180 : roundTotalDegree + 360; DrawSector(vh, roundCenter, roundRadius, toColor, sectorStartDegree, sectorToDegree, smoothness / 2); if (needBorder) { DrawDoughnut(vh, roundCenter, roundRadius, roundRadius + borderWidth, borderColor, s_ClearColor32, sectorStartDegree, sectorToDegree, smoothness / 2); } e1 = UGLHelper.GetPos(center, insideRadius, realToOutAngle); e2 = UGLHelper.GetPos(center, outsideRadius, realToOutAngle); } var segmentAngle = (realToInAngle - realStartInAngle) / segments; var isGradient = !UGLHelper.IsValueEqualsColor(color, toColor); for (int i = 0; i <= segments; i++) { float currAngle = realStartInAngle + i * segmentAngle; p3 = new Vector3(center.x + outsideRadius * Mathf.Sin(currAngle), center.y + outsideRadius * Mathf.Cos(currAngle)); p4 = new Vector3(center.x + insideRadius * Mathf.Sin(currAngle), center.y + insideRadius * Mathf.Cos(currAngle)); if (!UGLHelper.IsClearColor(emptyColor)) DrawTriangle(vh, center, p1, p4, emptyColor); if (isGradient) { var tcolor = Color32.Lerp(color, toColor, i * 1.0f / segments); DrawQuadrilateral(vh, p2, p3, p4, p1, tcolor, tcolor); } else { DrawQuadrilateral(vh, p2, p3, p4, p1, color, color); } p1 = p4; p2 = p3; } if (needBorder || needSpace || roundCap) { if (clockwise) { var isInAngleFixed = toAngle - spaceInAngle - 2 * borderInAngle > realStartOutAngle; if (isInAngleFixed) DrawQuadrilateral(vh, p2, e2, e1, p1, color, toColor); else DrawTriangle(vh, p2, e2, p1, color, color, toColor); if (needBorder) { var realStartDegree = (realStartOutAngle - (roundCap ? 0 : borderAngle)) * Mathf.Rad2Deg; var realToDegree = (realToOutAngle + (roundCap ? 0 : borderAngle)) * Mathf.Rad2Deg; if (realToDegree < realStartOutAngle) realToDegree = realStartOutAngle; var inStartDegree = roundCap ? realStartDegree : (startAngle + spaceInAngle) * Mathf.Rad2Deg; var inToDegree = roundCap ? realToDegree : (toAngle - spaceInAngle) * Mathf.Rad2Deg; if (inToDegree < inStartDegree) inToDegree = inStartDegree; if (isInAngleFixed) DrawDoughnut(vh, center, insideRadius - borderWidth, insideRadius, borderColor, s_ClearColor32, inStartDegree, inToDegree, smoothness); DrawDoughnut(vh, center, outsideRadius, outsideRadius + borderWidth, borderColor, s_ClearColor32, realStartDegree, realToDegree, smoothness); } } else { var isInAngleFixed = toAngle + spaceInAngle + 2 * borderInAngle < realStartOutAngle; if (isInAngleFixed) DrawQuadrilateral(vh, p2, e2, e1, p1, color, toColor); else DrawTriangle(vh, p2, e2, p1, color, color, toColor); if (needBorder) { var realStartDegree = (realStartOutAngle + (roundCap ? 0 : borderAngle)) * Mathf.Rad2Deg; var realToDegree = (realToOutAngle - (roundCap ? 0 : borderAngle)) * Mathf.Rad2Deg; var inStartDegree = roundCap ? realStartDegree : (startAngle - spaceInAngle) * Mathf.Rad2Deg; var inToDegree = roundCap ? realToDegree : (toAngle + spaceInAngle) * Mathf.Rad2Deg; if (inToDegree > inStartDegree) inToDegree = inStartDegree; if (isInAngleFixed) { DrawDoughnut(vh, center, insideRadius - borderWidth, insideRadius, borderColor, s_ClearColor32, inStartDegree, inToDegree, smoothness); } DrawDoughnut(vh, center, outsideRadius, outsideRadius + borderWidth, borderColor, s_ClearColor32, realStartDegree, realToDegree, smoothness); } } } } /// <summary> /// 画贝塞尔曲线 /// </summary> /// <param name="vh"></param> /// <param name="sp">起始点</param> /// <param name="ep">结束点</param> /// <param name="cp1">控制点1</param> /// <param name="cp2">控制点2</param> /// <param name="lineWidth">曲线宽</param> /// <param name="lineColor">曲线颜色</param> public static void DrawCurves(VertexHelper vh, Vector3 sp, Vector3 ep, Vector3 cp1, Vector3 cp2, float lineWidth, Color32 lineColor, float smoothness) { var dist = Vector3.Distance(sp, ep); var segment = (int)(dist / (smoothness <= 0 ? 2f : smoothness)); UGLHelper.GetBezierList2(ref s_CurvesPosList, sp, ep, segment, cp1, cp2); if (s_CurvesPosList.Count > 1) { var start = s_CurvesPosList[0]; var to = Vector3.zero; var dir = s_CurvesPosList[1] - start; var diff = Vector3.Cross(dir, Vector3.forward).normalized * lineWidth; var startUp = start - diff; var startDn = start + diff; for (int i = 1; i < s_CurvesPosList.Count; i++) { to = s_CurvesPosList[i]; diff = Vector3.Cross(to - start, Vector3.forward).normalized * lineWidth; var toUp = to - diff; var toDn = to + diff; DrawQuadrilateral(vh, startUp, toUp, toDn, startDn, lineColor); startUp = toUp; startDn = toDn; start = to; } } } } }
50.60799
135
0.518822
[ "MIT" ]
monitor1394/XUGL
Runtime/UGL.cs
82,362
C#