text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; public class OnTheWayScript : NPCBaseFSM { Animator anim; CircleAttraction[] ca; ChildAI[] child; float IdleTime = 0; public float animDistance; public float cooldown; int maxValue; int maxValueGlobal; public bool inCircle; ScriptPOI closestPOI; bool go; void Awake() { ca = FindObjectsOfType(typeof(CircleAttraction)) as CircleAttraction[]; child = FindObjectsOfType(typeof(ChildAI)) as ChildAI[]; } // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { base.OnStateEnter(animator, stateInfo, layerIndex); anim = NPC.GetComponent<Animator>(); } // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { if(closestPOI != null){ agent.SetDestination(closestPOI.transform.position); } for (int i = 0; i < ca.Length; i++){ float distance = Vector3.Distance(agent.transform.position, ca[i].transform.position); // Check la distance entre l'IA est les cercles d'attractions. if (ca[i].repulse == true && distance <= ca[i].radius){ cooldown = 0; closestPOI = null; ScriptPOI[] globalPOI = GameObject.FindObjectsOfType<ScriptPOI>(); for (int y = 0; y < globalPOI.Length; y++) { float distanceRepulse = Vector3.Distance(ca[i].transform.position, globalPOI[y].transform.position); if (distanceRepulse >= ca[i].radius){ go = true; closestPOI = globalPOI[y]; } } } if (go == true && closestPOI != null){ agent.SetDestination(closestPOI.transform.position); } if(ca[i].valueCircle > maxValue) // Change la valeur du cercle d'attraction en cas de valeur plus grande { maxValue = ca[i].valueCircle; } if (ca[i].valueCircle == maxValue) // Quand la valeur est la plus grande et que l'ia s'est donc dirigé vers le cercle avec la plus grande valeur { if (distance <= ca[i].radius)// Si l'IA est dans un cercle d'attraction alors : { inCircle = true; // Active un booléen cooldown = 0; float distanceClosestPoint = Mathf.Infinity; for(int y = 0; y < ca[i].allPOI.Length; y++){ // Check tout les POI du cercle d'attraction float distanceToPOI = Vector3.Distance(agent.transform.position, ca[i].allPOI[y].transform.position); // Check distance entre IA et les POI if (distanceToPOI < distanceClosestPoint) // Si la distance est plus petite alors l'IA se dirige vers ce POI { distanceClosestPoint = distanceToPOI; agent.SetDestination(ca[i].allPOI[y].transform.position); Debug.DrawLine(NPC.transform.position, ca[i].allPOI[y].transform.position); animDistance = Vector3.Distance(NPC.transform.position, ca[i].allPOI[y].transform.position); anim.SetFloat("distance", Vector3.Distance(NPC.transform.position, ca[i].allPOI[y].transform.position)); } } } } else if (distance > ca[i].radius) // Si l'ia n'est pas dans un cercle d'attraction { inCircle = false; cooldown -= Time.deltaTime; //Diminue le cooldown agent.speed = 0; if (cooldown <= 0){ // Quand le cooldowon est à 0 agent.speed = 3.5f; cooldown = 0; if (inCircle == false){ for (int z = 0; z < ca.Length; z++){ if(ca[z].valueCircle > maxValueGlobal) // Change la valeur du cercle d'attraction en cas de valeur plus grande { maxValueGlobal = ca[z].valueCircle; } if (ca[z].valueCircle == maxValueGlobal) // Quand la valeur est la plus grande et que l'ia s'est donc dirigé vers le cercle avec la plus grande valeur { agent.SetDestination(ca[z].transform.position); } } } } } } /* else if (ca[i].repulse == true){ ScriptPOI closestPOI = null; ScriptPOI[] globalPOI = GameObject.FindObjectsOfType<ScriptPOI>(); for (int y = 0; y < globalPOI.Length; y++) { float distanceRepulse = Vector3.Distance(ca[i].transform.position, globalPOI[y].transform.position); if (distanceRepulse <= ca[i].radius){ agent.SetDestination(globalPOI[y].transform.position); Debug.DrawLine(NPC.transform.position, globalPOI[y].transform.position); } } } */ } }
namespace _05._ExtractEmails { using System; using System.Text.RegularExpressions; public class Startup { public static void Main() { string text = Console.ReadLine(); string pattern = @"(?<=\s)[a-z0-9]+([.-]\w*)*@[a-z]+([.-]\w*)*(\.[a-z]+)"; MatchCollection matches = Regex.Matches(text, pattern); foreach (Match match in matches) { Console.WriteLine(match); } } } }
using System; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using Types; public class DialogueManager : Singleton<DialogueManager> { private Queue<string> sentences; public TextMeshProUGUI dialogueText; public TextMeshProUGUI nameText; public bool isEnding = false; public DialogueType currentDialogueType; protected override void Awake() { base.Awake(); sentences = new Queue<string>(); } public void StartDialogue(Dialogue dialogue) { currentDialogueType = dialogue.type; nameText.text = dialogue.name; sentences.Clear(); foreach (string sentence in dialogue.sentences) { sentences.Enqueue(sentence); } DisplayNextSentence(); } public void DisplayNextSentence() { if (sentences.Count == 0) { EndDialogue(); return; } string sentence = sentences.Dequeue(); dialogueText.text = sentence; } public void EndDialogue() { if (currentDialogueType == DialogueType.Change) { SoundManager.Instance.PlayMusic(SoundManager.Instance.supriseMusic); Boss.Instance.anim.SetTrigger("Change"); Boss.Instance.StartDialog2(); } else if (currentDialogueType == DialogueType.Ending) { GameManager.Instance.Quit(); } else if(currentDialogueType == DialogueType.Start) { GameManager.Instance.LoadScene("Game"); } } }
using FluentAssertions; using NUnit.Framework; using WebDriverOnCore.PageObjects; using WebDriverOnCore.PageSteps; using WebDriverOnCore.TestsData; using WebDriverOnCore.TestUntillities; using WebDriverOnCore.WebDriver; namespace WebDriverOnCore.Tests { public class ScoreBoardTests : TestsBaseClass { #region Class fields private CommonPageSteps _commonSteps; private ScoreboardPageSteps _scoreboardPageSteps; #endregion #region Test setup and TearDown protected override void TestSetup() { base.TestSetup(); _commonSteps = new CommonPageSteps(); _scoreboardPageSteps = new ScoreboardPageSteps(); navigation.OpenWebSiteOnMainPage(); } #endregion #region Tests [Test] [Category("LongRunning")] [TestCase("Матчи и турниры", "Англия. Премьер-лига")] public void UserChoicesAPLmatches_OnlyAplFixturesAndResultsShown(string menuName, string tornament) { //Arrange _commonSteps.GetHeaderNavigationMenuWithName(menuName).Click(); Driver.CurrentBrowser.Url.Should().Be(ExpectedValues.PageNameUrlDictionary[menuName]); //Act _scoreboardPageSteps.SelectTornamentFromTornamentsDropDownList(tornament); //Assert Assert.AreEqual(tornament, _scoreboardPageSteps.GetSelectedTornamentText()); } #endregion } }
using Coldairarrow.Business.Sto_BaseInfo; using Coldairarrow.Entity.Sto_BaseInfo; using Coldairarrow.Util; using System; using System.Web.Mvc; namespace Coldairarrow.Web { public class Sto_MaterialController : BaseMvcController { Sto_MaterialBusiness _sto_MaterialBusiness = new Sto_MaterialBusiness(); static SystemCache _systemCache = new SystemCache(); #region 视图功能 public ActionResult Index() { return View(); } public ActionResult Form(string id) { var theData = id.IsNullOrEmpty() ? new Sto_Material() : _sto_MaterialBusiness.GetTheData(id); return View(theData); } #endregion #region 获取数据 /// <summary> /// 获取数据列表 /// </summary> /// <param name="condition">查询类型</param> /// <param name="keyword">关键字</param> /// <returns></returns> public ActionResult GetDataList(string condition, string keyword, Pagination pagination) { var dataList = _sto_MaterialBusiness.GetDataList(condition, keyword, pagination); return Content(pagination.BuildTableResult_DataGrid(dataList).ToJson()); } public ActionResult QueryByMatNo(string matNo) { Sto_Material _m = _sto_MaterialBusiness.QueryMaterial(matNo); return Content(_m.ToJson()); } #endregion #region 缓存数据和提取 /// <summary> /// 用于查询物料缓存id /// </summary> /// <param name="id"></param> /// <returns></returns> public ActionResult Find(string id) { Sto_Material _o = new Sto_Material() { Id = id }; return View(_o); } public ActionResult FindCacheItem(string id) { var theData = _systemCache.GetCache<Sto_Material>(id); if (theData == null) { theData = new Sto_Material(); } else { //清除缓存 _systemCache.RemoveCache(id); } return Content(theData.ToJson()); } public ActionResult CreateCacheItem(CacheMaterial theData) { if (theData.Id.IsNullOrEmpty()) { return Error("对象无效"); } else { _systemCache.SetCache(theData.Id, theData.Entity, new TimeSpan(0, 1, 0)); } return Success(); } #endregion #region 提交数据 /// <summary> /// 保存 /// </summary> /// <param name="theData">保存的数据</param> public ActionResult SaveData(Sto_Material theData) { if(theData.Id.IsNullOrEmpty()) { theData.Id = Guid.NewGuid().ToSequentialGuid(); _sto_MaterialBusiness.AddData(theData); } else { _sto_MaterialBusiness.UpdateData(theData); } return Success(); } /// <summary> /// 删除数据 /// </summary> /// <param name="theData">删除的数据</param> public ActionResult DeleteData(string ids) { _sto_MaterialBusiness.DeleteData(ids.ToList<string>()); return Success("删除成功!"); } #endregion } public class CacheMaterial { public Sto_Material Entity { get; set; } public string Id { get; set; } } }
using HotelBooking.ViewModels; using System.Security.Claims; namespace HotelBooking.ModelBuilders.Abstract { public interface IProfileModelBuilder { ProfileViewModel BuildModel(ClaimsPrincipal userLoged); } }
using ArkSavegameToolkitNet.Types; using log4net; using Newtonsoft.Json; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.MemoryMappedFiles; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArkSavegameToolkitNet { [JsonObject(MemberSerialization.OptIn)] public class ArkSavegame : IGameObjectContainer, IDisposable { private static ILog _logger = LogManager.GetLogger(typeof(ArkSavegame)); [JsonProperty] public IList<GameObject> Objects { get { return _objects; } private set { if (value == null) throw new NullReferenceException("Value cannot be null"); _objects = value; } } private IList<GameObject> _objects = new List<GameObject>(); [JsonProperty] public IList<string> DataFiles { get { return _dataFiles; } set { if (value == null) throw new NullReferenceException("Value cannot be null"); _dataFiles = value; } } private IList<string> _dataFiles = new List<string>(); [JsonProperty] public IList<EmbeddedData> EmbeddedData { get { return _embeddedData; } set { if (value == null) throw new NullReferenceException("Value cannot be null"); _embeddedData = value; } } private IList<EmbeddedData> _embeddedData = new List<EmbeddedData>(); [JsonProperty] public short SaveVersion { get; set; } [JsonProperty] public float GameTime { get; set; } //the only way to get this is by looking at the last modified date of the savegame file. this may not be correct if not read from an active save on the server [JsonProperty] public DateTime SaveTime { get; set; } public SaveState SaveState { get; set; } protected internal int binaryDataOffset; protected internal int nameTableOffset; protected internal int propertiesBlockOffset; private string _fileName; private bool _baseRead; private long _gameObjectsOffset; private ArkStringCache _arkStringCache; private ArkNameCache _arkNameCache; private readonly int? _savegameMaxDegreeOfParallelism; private ArkNameTree _exclusivePropertyNameTree; private MemoryMappedFile _mmf; private MemoryMappedViewAccessor _va; private ArkArchive _archive; public ArkSavegame(int? savegameMaxDegreeOfParallelism = null, ArkNameTree exclusivePropertyNameTree = null) { Objects = new List<GameObject>(); _arkNameCache = new ArkNameCache(); _arkStringCache = new ArkStringCache(); _savegameMaxDegreeOfParallelism = savegameMaxDegreeOfParallelism; _exclusivePropertyNameTree = exclusivePropertyNameTree; } public ArkSavegame(string fileName, ArkNameCache arkNameCache = null, int? savegameMaxDegreeOfParallelism = null, ArkNameTree exclusivePropertyNameTree = null) { _fileName = fileName; _arkNameCache = arkNameCache ?? new ArkNameCache(); _arkStringCache = new ArkStringCache(); _savegameMaxDegreeOfParallelism = savegameMaxDegreeOfParallelism; _exclusivePropertyNameTree = exclusivePropertyNameTree; var fi = new FileInfo(_fileName); var size = fi.Length; SaveTime = fi.LastWriteTimeUtc; //if (size == 0) return false; _mmf = MemoryMappedFile.CreateFromFile(_fileName, FileMode.Open, null, 0L, MemoryMappedFileAccess.Read); _va = _mmf.CreateViewAccessor(0L, 0L, MemoryMappedFileAccess.Read); _archive = new ArkArchive(_va, size, _arkNameCache, _arkStringCache, _exclusivePropertyNameTree); } /// <summary> /// Load all gameobjects, properties and other data in this savegame. /// </summary> public bool LoadEverything() { //var fi = new FileInfo(_fileName); //var size = fi.Length; //SaveTime = fi.LastWriteTimeUtc; //if (size == 0) return false; //using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(_fileName, FileMode.Open)) //{ // using (MemoryMappedViewAccessor va = mmf.CreateViewAccessor(0L, 0L, MemoryMappedFileAccess.Read)) // { // ArkArchive archive = new ArkArchive(va, size, _arkNameCache); // readBinary(archive, mmf); // } //} readBinary(_archive, _mmf); return true; } public GameObject GetObjectAtOffset(long offset, int nextPropertiesOffset) { var oldposition = _archive.Position; _archive.Position = offset; var gameObject = new GameObject(_archive, _arkNameCache); gameObject.loadProperties(_archive, null, propertiesBlockOffset, nextPropertiesOffset); _archive.Position = oldposition; return gameObject; } public IEnumerable<Tuple<GameObjectReader, GameObjectReader>> GetObjectsEnumerable() { var fi = new FileInfo(_fileName); var size = fi.Length; SaveTime = fi.LastWriteTimeUtc; if (size == 0) yield break; //using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(_fileName, FileMode.Open, null, 0L, MemoryMappedFileAccess.Read)) //{ // using (MemoryMappedViewAccessor va = mmf.CreateViewAccessor(0L, 0L, MemoryMappedFileAccess.Read)) // { // ArkArchive archive = new ArkArchive(va, size, _arkNameCache); // if (!_baseRead) readBinaryBase(archive); // else archive.Position = _gameObjectsOffset; // var count = archive.GetInt(); // for (var n = 0; n < count; n++) // { // var gameObject = new GameObjectReader(archive, _arkNameCache) { Index = n }; // archive.Position += gameObject.Size; // yield return gameObject; // } // } //} if (!_baseRead) readBinaryBase(_archive); else _archive.Position = _gameObjectsOffset; var count = _archive.GetInt(); GameObjectReader prev = null; for (var n = 0; n <= count; n++) { GameObjectReader gameObject = null; if (n < count) { gameObject = new GameObjectReader(_archive, _arkNameCache) { Index = n }; _archive.Position += gameObject.Size; } if (n > 0) yield return Tuple.Create(prev, gameObject); prev = gameObject; } } public void readBinary(ArkArchive archive, MemoryMappedFile mmf) { if (!_baseRead) readBinaryBase(archive); else archive.Position = _gameObjectsOffset; readBinaryObjects(archive); readBinaryObjectProperties(archive, mmf); } private void readBinaryBase(ArkArchive archive) { readBinaryHeader(archive); if (SaveVersion > 5) { // Name table is located after the objects block, but will be needed to read the objects block readBinaryNameTable(archive); } readBinaryDataFiles(archive); SaveState = new SaveState { GameTime = GameTime, SaveTime = SaveTime, MapName = DataFiles.FirstOrDefault() }; readBinaryEmbeddedData(archive); var unknownValue = archive.GetInt(); if (unknownValue != 0) { //if (unknownValue > 2) //{ // var msg = $"Found unexpected Value {unknownValue} at {archive.Position - 4:X}"; // _logger.Error(msg); // throw new System.NotSupportedException(msg); //} for (int n = 0; n < unknownValue; n++) { var unknownFlags = archive.GetInt(); var objectCount = archive.GetInt(); var name = archive.GetString(); } } _baseRead = true; _gameObjectsOffset = archive.Position; } protected void readBinaryHeader(ArkArchive archive) { SaveVersion = archive.GetShort(); if (SaveVersion == 5) { GameTime = archive.GetFloat(); propertiesBlockOffset = 0; } else if (SaveVersion == 6) { nameTableOffset = archive.GetInt(); propertiesBlockOffset = archive.GetInt(); GameTime = archive.GetFloat(); } else if (SaveVersion == 7 || SaveVersion == 8) { binaryDataOffset = archive.GetInt(); var unknownValue = archive.GetInt(); if (unknownValue != 0) { var msg = $"Found unexpected Value {unknownValue} at {archive.Position - 4:X}"; _logger.Error(msg); throw new System.NotSupportedException(msg); } nameTableOffset = archive.GetInt(); propertiesBlockOffset = archive.GetInt(); GameTime = archive.GetFloat(); } else if (SaveVersion == 9) { binaryDataOffset = archive.GetInt(); var unknownValue = archive.GetInt(); if (unknownValue != 0) { var msg = $"Found unexpected Value {unknownValue} at {archive.Position - 4:X}"; _logger.Error(msg); throw new System.NotSupportedException(msg); } nameTableOffset = archive.GetInt(); propertiesBlockOffset = archive.GetInt(); GameTime = archive.GetFloat(); //note: unknown integer value was added in v268.22 with SaveVersion=9 [0x25 (37) on The Island, 0x26 (38) on ragnarok/center/scorched] var unknownValue2 = archive.GetInt(); } else { var msg = $"Found unknown Version {SaveVersion}"; _logger.Error(msg); throw new System.NotSupportedException(msg); } } protected void readBinaryNameTable(ArkArchive archive) { var position = archive.Position; archive.Position = nameTableOffset; var nameCount = archive.GetInt(); var nameTable = new List<string>(nameCount); for (var n = 0; n < nameCount; n++) { nameTable.Add(archive.GetString()); } archive.NameTable = nameTable; archive.Position = position; } protected void readBinaryDataFiles(ArkArchive archive, bool dataFiles = true) { var count = archive.GetInt(); if (dataFiles) { DataFiles.Clear(); for (var n = 0; n < count; n++) { DataFiles.Add(archive.GetString()); } } else { for (var n = 0; n < count; n++) { archive.SkipString(); } } } protected void readBinaryEmbeddedData(ArkArchive archive, bool embeddedData = true) { var count = archive.GetInt(); if (embeddedData) { EmbeddedData.Clear(); for (var n = 0; n < count; n++) { EmbeddedData.Add(new EmbeddedData(archive)); } } else { for (int n = 0; n < count; n++) { Types.EmbeddedData.Skip(archive); } } } protected void readBinaryObjects(ArkArchive archive, bool gameObjects = true) { if (gameObjects) { var count = archive.GetInt(); Objects.Clear(); for (var n = 0; n < count; n++) { var gameObject = new GameObject(archive, _arkNameCache); gameObject.ObjectId = n; Objects.Add(gameObject); } } } protected void readBinaryObjectProperties(ArkArchive archive, MemoryMappedFile mmf, Func<GameObject, bool> objectFilter = null, bool gameObjects = true, bool gameObjectProperties = true) { if (gameObjects && gameObjectProperties) { var success = true; try { var cb = new ConcurrentBag<ArkArchive>(); cb.Add(archive); var indices = Enumerable.Range(0, Objects.Count); if (objectFilter != null) indices = indices.Where(x => objectFilter(Objects[x])); Parallel.ForEach(indices, _savegameMaxDegreeOfParallelism.HasValue ? new ParallelOptions { MaxDegreeOfParallelism = _savegameMaxDegreeOfParallelism.Value } : new ParallelOptions { }, () => { ArkArchive arch = null; var va = cb.TryTake(out arch) ? null : mmf.CreateViewAccessor(0L, 0L, MemoryMappedFileAccess.Read); return new { va = va, a = arch ?? new ArkArchive(archive, va) }; }, (item, loopState, taskLocals) => { readBinaryObjectPropertiesImpl(item, taskLocals.a); return taskLocals; }, (taskLocals) => { if (taskLocals?.va != null) taskLocals.va.Dispose(); } ); } catch (AggregateException ae) { success = false; ae.Handle(ex => { if (ex is IOException && ex.Message.IndexOf("Not enough storage is available to process this command.", StringComparison.OrdinalIgnoreCase) != -1) { _logger.Error($"Not enough memory available to load properties with this degree of parallelism."); return true; } return false; }); } if (!success) throw new ApplicationException("Failed to load properties for all gameobjects."); } } protected void readBinaryObjectPropertiesImpl(int n, ArkArchive archive) { Objects[n].loadProperties(archive, (n < Objects.Count - 1) ? Objects[n + 1] : null, propertiesBlockOffset); } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { _va?.Dispose(); _mmf?.Dispose(); _va = null; _mmf = null; } disposedValue = true; } } public void Dispose() { Dispose(true); } #endregion } }
using gView.Framework.Data; using gView.Framework.Geometry; using gView.Framework.Network.Algorthm; using gView.Framework.system; using gView.Framework.UI; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace gView.Framework.Network.Tracers { public abstract class TraceNextTargetNode : INetworkTracer, IProgressReporterEvent { protected abstract NetworkNodeType TargetNodeType { get; } #region INetworkTracer Member virtual public string Name { get { return "Trace Next Node"; } } public bool CanTrace(NetworkTracerInputCollection input) { if (input == null) { return false; } return input.Collect(NetworkTracerInputType.SourceNode).Count == 1 || input.Collect(NetworkTracerInputType.SoruceEdge).Count == 1; } async public Task<NetworkTracerOutputCollection> Trace(INetworkFeatureClass network, NetworkTracerInputCollection input, ICancelTracker cancelTraker) { if (network == null || !CanTrace(input)) { return null; } GraphTable gt = new GraphTable(network.GraphTableAdapter()); NetworkSourceInput sourceNode = null; NetworkSourceEdgeInput sourceEdge = null; if (input.Collect(NetworkTracerInputType.SourceNode).Count == 1) { sourceNode = input.Collect(NetworkTracerInputType.SourceNode)[0] as NetworkSourceInput; } else if (input.Collect(NetworkTracerInputType.SoruceEdge).Count == 1) { sourceEdge = input.Collect(NetworkTracerInputType.SoruceEdge)[0] as NetworkSourceEdgeInput; } else { return null; } input.Collect(NetworkTracerInputType.BarrierNodes); NetworkTracerOutputCollection outputCollection = new NetworkTracerOutputCollection(); List<int> edgeIds = new List<int>(); NetworkPathOutput pathOutput = new NetworkPathOutput(); List<int> neighborNodeFcIds = new List<int>(); Dictionary<int, string> neighborFcs = new Dictionary<int, string>(); foreach (var networkClass in await network.NetworkClasses()) { if (networkClass.GeometryType != GeometryType.Point) { continue; } int fcid = await network.NetworkClassId(networkClass.Name); neighborNodeFcIds.Add(fcid); neighborFcs.Add(fcid, networkClass.Name); } Dijkstra dijkstra = new Dijkstra(cancelTraker); dijkstra.reportProgress += this.ReportProgress; dijkstra.ApplySwitchState = input.Contains(NetworkTracerInputType.IgnoreSwitches) == false && network.HasDisabledSwitches; dijkstra.TargetNodeFcIds = neighborNodeFcIds; dijkstra.TargetNodeType = TargetNodeType; Dijkstra.ApplyInputIds(dijkstra, input); Dijkstra.Nodes dijkstraEndNodes = null; if (sourceNode != null) { dijkstra.Calculate(gt, sourceNode.NodeId); dijkstraEndNodes = dijkstra.DijkstraEndNodes; } else if (sourceEdge != null) { IGraphEdge graphEdge = gt.QueryEdge(sourceEdge.EdgeId); if (graphEdge == null) { return null; } bool n1_2_n2 = gt.QueryN1ToN2(graphEdge.N1, graphEdge.N2) != null; bool n2_2_n1 = gt.QueryN1ToN2(graphEdge.N2, graphEdge.N1) != null; if (n1_2_n2 == false && n2_2_n1 == false) { return null; } bool n1switchState = dijkstra.ApplySwitchState ? gt.SwitchState(graphEdge.N1) : true; bool n2switchState = dijkstra.ApplySwitchState ? gt.SwitchState(graphEdge.N2) : true; bool n1isNeighbor = neighborNodeFcIds.Contains(gt.GetNodeFcid(graphEdge.N1)); bool n2isNeighbor = neighborNodeFcIds.Contains(gt.GetNodeFcid(graphEdge.N2)); if (n1isNeighbor && n2isNeighbor) { dijkstraEndNodes = new Dijkstra.Nodes(); dijkstraEndNodes.Add(new Dijkstra.Node(graphEdge.N1)); dijkstraEndNodes.Add(new Dijkstra.Node(graphEdge.N2)); dijkstraEndNodes[0].EId = graphEdge.Eid; edgeIds.Add(graphEdge.Eid); pathOutput.Add(new NetworkEdgeOutput(graphEdge.Eid)); } else { if (!n1isNeighbor && n1switchState == true) { dijkstra.Calculate(gt, graphEdge.N1); dijkstraEndNodes = dijkstra.DijkstraEndNodes; if (!n1_2_n2 && n2isNeighbor) { Dijkstra.Node n1Node = new Dijkstra.Node(graphEdge.N2); n1Node.EId = graphEdge.Eid; dijkstraEndNodes.Add(n1Node); edgeIds.Add(graphEdge.Eid); pathOutput.Add(new NetworkEdgeOutput(graphEdge.Eid)); } } else if (!n2isNeighbor && n2switchState == true) { dijkstra.Calculate(gt, graphEdge.N2); dijkstraEndNodes = dijkstra.DijkstraEndNodes; if (!n2_2_n1 && n1isNeighbor) { Dijkstra.Node n1Node = new Dijkstra.Node(graphEdge.N1); n1Node.EId = graphEdge.Eid; dijkstraEndNodes.Add(n1Node); edgeIds.Add(graphEdge.Eid); pathOutput.Add(new NetworkEdgeOutput(graphEdge.Eid)); } } } } #region Create Output if (dijkstraEndNodes == null) { return null; } ProgressReport report = (ReportProgress != null ? new ProgressReport() : null); #region Collect End Nodes if (report != null) { report.Message = "Collect End Nodes..."; report.featurePos = 0; report.featureMax = dijkstraEndNodes.Count; ReportProgress(report); } int counter = 0; foreach (Dijkstra.Node endNode in dijkstraEndNodes) { int fcId = gt.GetNodeFcid(endNode.Id); if (neighborNodeFcIds.Contains(fcId) && gt.GetNodeType(endNode.Id) == this.TargetNodeType) { IFeature nodeFeature = await network.GetNodeFeature(endNode.Id); if (nodeFeature != null && nodeFeature.Shape is IPoint) { string fcName = neighborFcs.ContainsKey(fcId) ? neighborFcs[fcId] : String.Empty; //outputCollection.Add(new NetworkNodeFlagOuput(endNode.Id, nodeFeature.Shape as IPoint)); outputCollection.Add(new NetworkFlagOutput(nodeFeature.Shape as IPoint, new NetworkFlagOutput.NodeFeatureData(endNode.Id, fcId, Convert.ToInt32(nodeFeature["OID"]), fcName))); } } counter++; if (report != null && counter % 1000 == 0) { report.featurePos = counter; ReportProgress(report); } } #endregion #region Collect EdgedIds if (report != null) { report.Message = "Collect Edges..."; report.featurePos = 0; report.featureMax = dijkstra.DijkstraNodes.Count; ReportProgress(report); } counter = 0; foreach (Dijkstra.Node dijkstraEndNode in dijkstraEndNodes) { Dijkstra.NetworkPath networkPath = dijkstra.DijkstraPath(dijkstraEndNode.Id); if (networkPath == null) { continue; } foreach (Dijkstra.NetworkPathEdge pathEdge in networkPath) { int index = edgeIds.BinarySearch(pathEdge.EId); if (index >= 0) { continue; } edgeIds.Insert(~index, pathEdge.EId); pathOutput.Add(new NetworkEdgeOutput(pathEdge.EId)); counter++; if (report != null && counter % 1000 == 0) { report.featurePos = counter; ReportProgress(report); } } } if (pathOutput.Count > 0) { outputCollection.Add(pathOutput); } #endregion #endregion return outputCollection; } #endregion #region IProgressReporterEvent Member public event ProgressReporterEvent ReportProgress; #endregion } [RegisterPlugInAttribute("B2F1272A-FC0E-40BD-9219-5ED6A660304E")] public class TraceNextSources : TraceNextTargetNode { protected override NetworkNodeType TargetNodeType { get { return NetworkNodeType.Source; } } public override string Name { get { return "Trace Next Sources"; } } } [RegisterPlugInAttribute("3EBC7A9E-A386-4EC2-99F9-36653A64ECBE")] public class TraceNextSinks : TraceNextTargetNode { protected override NetworkNodeType TargetNodeType { get { return NetworkNodeType.Sink; } } public override string Name { get { return "Trace Next Sinks"; } } } [RegisterPlugInAttribute("96242C33-7221-47B1-8069-3905FEE66241")] public class TraceNextTrafficCross : TraceNextTargetNode { protected override NetworkNodeType TargetNodeType { get { return NetworkNodeType.Traffic_Cross; } } public override string Name { get { return "Trace Next Traffic Cross"; } } } [RegisterPlugInAttribute("2EAAF416-1ABE-4957-9107-77F71007442D")] public class TraceNextTrafficLight : TraceNextTargetNode { protected override NetworkNodeType TargetNodeType { get { return NetworkNodeType.Traffic_Light; } } public override string Name { get { return "Trace Next Traffic Light"; } } } [RegisterPlugInAttribute("B9670DCF-02A5-4EED-A59F-154DCF064B05")] public class TraceNextTrafficRoundabout : TraceNextTargetNode { protected override NetworkNodeType TargetNodeType { get { return NetworkNodeType.Traffic_Roundabout; } } public override string Name { get { return "Trace Next Traffic Roundabout"; } } } [RegisterPlugInAttribute("DCE2F264-F464-4AEA-B534-39201C12DF3D")] public class TraceNextTrafficStop : TraceNextTargetNode { protected override NetworkNodeType TargetNodeType { get { return NetworkNodeType.Traffic_Stop; } } public override string Name { get { return "Trace Next Traffic Stop"; } } } [RegisterPlugInAttribute("C12055D1-A981-40A1-A84D-DCB900464ACE")] public class TraceNextGasStation : TraceNextTargetNode { protected override NetworkNodeType TargetNodeType { get { return NetworkNodeType.Gas_Station; } } public override string Name { get { return "Trace Next Gas Station"; } } } [RegisterPlugInAttribute("A966A99A-FFA0-43D3-9BBB-161ADDF171C2")] public class TraceNextGasSwitch : TraceNextTargetNode { protected override NetworkNodeType TargetNodeType { get { return NetworkNodeType.Gas_Switch; } } public override string Name { get { return "Trace Next Gas Switch"; } } } [RegisterPlugInAttribute("D954E4D8-DEBC-40BC-9648-49A404E879AF")] public class TraceNextGasCustomer : TraceNextTargetNode { protected override NetworkNodeType TargetNodeType { get { return NetworkNodeType.Gas_Customer; } } public override string Name { get { return "Trace Next Gas Customer"; } } } [RegisterPlugInAttribute("09F050A2-DC30-4C42-9281-C54CC1D54469")] public class TraceNextGasStop : TraceNextTargetNode { protected override NetworkNodeType TargetNodeType { get { return NetworkNodeType.Gas_Stop; } } public override string Name { get { return "Trace Next Gas Stop"; } } } [RegisterPlugInAttribute("3CCC0592-42AD-4A14-ABE7-F3C596000C19")] public class TraceNextElectricityCustomer : TraceNextTargetNode { protected override NetworkNodeType TargetNodeType { get { return NetworkNodeType.Electricity_Customer; } } public override string Name { get { return "Trace Next Electricity Customer"; } } } [RegisterPlugInAttribute("84F9E9C7-B945-486C-BE18-AD727377AF41")] public class TraceNextElectricityJunctionBox : TraceNextTargetNode { protected override NetworkNodeType TargetNodeType { get { return NetworkNodeType.Electricity_JunctionBox; } } public override string Name { get { return "Trace Next Electricity JunctionBox"; } } } [RegisterPlugInAttribute("DA57D5E1-709B-4638-B322-44B37F1482DE")] public class TraceNextElectrictiyStation : TraceNextTargetNode { protected override NetworkNodeType TargetNodeType { get { return NetworkNodeType.Electrictiy_Station; } } public override string Name { get { return "Trace Next Electrictiy Station"; } } } }
namespace Merchello.UkFest.Web.Ditto.ValueResolvers { using Our.Umbraco.Ditto; using Umbraco.Web; /// <summary> /// The active link value resolver. /// </summary> public class ActiveLinkValueResolver : DittoValueResolver { /// <summary> /// The resolve value. /// </summary> /// <returns> /// The <see cref="object"/>. /// </returns> public override object ResolveValue() { if (Content == null) return false; return Content.Path.Contains(UmbracoContext.Current.PageId.ToString()); } } }
using CapaDiseno; using Prototipo2P.Mantenimientos.Forms; using System; using System.Drawing; using System.Windows.Forms; using Prototipo2P.Proceso.MovimientoInventario.Forms; namespace Prototipo2P { public partial class MDI_SegundoParcial : Form { private int childFormNumber = 0; string usuario; string nombreBd = "sic"; public MDI_SegundoParcial() { InitializeComponent(); } //funcion para mantenimientos private void mant(int tabla) { Frm_Mantenimiento mantenimiento = new Frm_Mantenimiento(usuario, tabla, nombreBd); mantenimiento.Show(); mantenimiento.TopLevel = false; mantenimiento.TopMost = true; panel1.Controls.Add(mantenimiento); } private void ShowNewForm(object sender, EventArgs e) { Form childForm = new Form(); childForm.MdiParent = this; childForm.Text = "Ventana " + childFormNumber++; childForm.Show(); } private void OpenFile(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); openFileDialog.Filter = "Archivos de texto (*.txt)|*.txt|Todos los archivos (*.*)|*.*"; if (openFileDialog.ShowDialog(this) == DialogResult.OK) { string FileName = openFileDialog.FileName; } } private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); saveFileDialog.Filter = "Archivos de texto (*.txt)|*.txt|Todos los archivos (*.*)|*.*"; if (saveFileDialog.ShowDialog(this) == DialogResult.OK) { string FileName = saveFileDialog.FileName; } } private void ExitToolsStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void CutToolStripMenuItem_Click(object sender, EventArgs e) { } private void CopyToolStripMenuItem_Click(object sender, EventArgs e) { } private void PasteToolStripMenuItem_Click(object sender, EventArgs e) { } private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e) { } private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e) { } private void CascadeToolStripMenuItem_Click(object sender, EventArgs e) { LayoutMdi(MdiLayout.Cascade); } private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e) { LayoutMdi(MdiLayout.TileVertical); } private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e) { LayoutMdi(MdiLayout.TileHorizontal); } private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e) { LayoutMdi(MdiLayout.ArrangeIcons); } private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e) { foreach (Form childForm in MdiChildren) { childForm.Close(); } } private void seguridadToolStripMenuItem_Click(object sender, EventArgs e) { } private void MDI_SegundoParcial_Load(object sender, EventArgs e) { frm_login login = new frm_login(); login.ShowDialog(); Lbl_usuario.Text = login.obtenerNombreUsuario(); usuario = Lbl_usuario.Text; } private void seguridadToolStripMenuItem1_Click(object sender, EventArgs e) { MDI_Seguridad seguridad = new MDI_Seguridad(Lbl_usuario.Text); seguridad.lbl_nombreUsuario.Text = Lbl_usuario.Text; seguridad.ShowDialog(); } private void productosToolStripMenuItem_Click(object sender, EventArgs e) { mant(1); } private void clientesToolStripMenuItem_Click(object sender, EventArgs e) { mant(2); } private void proveedoresToolStripMenuItem_Click(object sender, EventArgs e) { mant(3); } private void lineasToolStripMenuItem_Click(object sender, EventArgs e) { mant(4); } private void marcasToolStripMenuItem_Click(object sender, EventArgs e) { mant(5); } private void vendedoresToolStripMenuItem_Click(object sender, EventArgs e) { mant(6); } private void movimientoDeInventarioToolStripMenuItem_Click(object sender, EventArgs e) { ListaMovimientos lista = new ListaMovimientos(); lista.Show(); lista.TopLevel = false; lista.TopMost = true; panel1.Controls.Add(lista); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; using Item_Subtracter.DataModel; using Item_Subtracter.Helpers; using Microsoft.Office.Interop.Excel; namespace Item_Subtracter { public partial class Form1 : Form { //List<IGrouping<string,MPN_List>> __mpn_ime = new List<IGrouping<string, MPN_List>>(); List<string> mpn_ime = new List<string>(); List<string> MPN_Listesi = new List<string>(); IMEEntities db; string _tempMPN; int removedWordCount = 0; int matchingItemCount = 0; List<Color> ColorList = new List<Color>(); string LogString = "MPN Listesi Hazır Değil"; private Random rnd = new Random(); public Form1() { CheckForIllegalCrossThreadCalls = false; InitializeComponent(); typeof(DataGridView).InvokeMember("DoubleBuffered", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty, null, dgItems, new object[] { true }); db = new IMEEntities(); ColorList.Add(Color.FromArgb(244, 176, 132)); ColorList.Add(Color.FromArgb(180, 198, 231)); ColorList.Add(Color.FromArgb(183, 240, 154)); ColorList.Add(Color.FromArgb(246, 180, 92)); ColorList.Add(Color.FromArgb(211, 163, 251)); ColorList.Add(Color.FromArgb(191, 246, 253)); ColorList.Add(Color.FromArgb(255, 171, 171)); ColorList.Add(Color.FromArgb(247, 255, 93)); ColorList.Add(Color.FromArgb(255, 129, 129)); ColorList.Add(Color.FromArgb(217, 217, 217)); } private void btnImportExcel_Click(object sender, EventArgs e) { importExcel(); } private void importExcel() { //if (__mpn_ime.Count == 0) if (mpn_ime.Count == 0) { MessageBox.Show(LogString); } else { dgItems.Rows.Clear(); matchingItemCount = 0; lblMatchingProductCount.Text = matchingItemCount.ToString(); List<ExcelItem> Ham_MPN_Listesi = new List<ExcelItem>(); List<string> Donusturulmus_MPN_Listesi = new List<string>(); List<MPN> result = new List<MPN>(); if (ChooseFile(Ham_MPN_Listesi)) { foreach (ExcelItem mpn in Ham_MPN_Listesi) { Donusturulmus_MPN_Listesi.Add(RemoveIgnoredCharacters(mpn.MPN).ToUpper()); } List<ExcelItem> urun_bulunan_mpnler = new List<ExcelItem>(); foreach (string mpn in Donusturulmus_MPN_Listesi) { string tempMPN = mpn.ToString(); _tempMPN = tempMPN; removedWordCount = 0; List<string> b = MPN_Listesi.Where(x => x != null && x.Contains(tempMPN)).ToList(); if (b.Count() > 0) { int ham_mpn_indexi = Donusturulmus_MPN_Listesi.FindIndex(x => x.Contains(tempMPN)); _tempMPN = tempMPN; urun_bulunan_mpnler.Add(Ham_MPN_Listesi[ham_mpn_indexi]); } else { SearchItemWithMPN_InsertIntoFoundMPNs(tempMPN, b, Donusturulmus_MPN_Listesi, urun_bulunan_mpnler, Ham_MPN_Listesi); } //Bulunan ilk MPN'i değil, eşleşme olan tüm MPN'ler getirilmeli var a = MPN_Listesi.Where(x => x != null && x.Contains(_tempMPN)).ToList(); if (a.Count > 0) { foreach (string item in a) { int ham_mpn_indexi = Donusturulmus_MPN_Listesi.FindIndex(x => x == mpn); int index_a = MPN_Listesi.FindIndex(x => x == item); string __mpn = mpn_ime[index_a].ToString(); List<CompleteItems_v2> mpn_bulunan_urunler = db.CompleteItems_v2.Where(x => x.MPN == __mpn).ToList(); MPN _mpn = new MPN(); _mpn.LineNo = ham_mpn_indexi + 1; _mpn.customerMPN = Ham_MPN_Listesi[ham_mpn_indexi].MPN; _mpn.customerQuantity = Ham_MPN_Listesi[ham_mpn_indexi].Quantity; _mpn.items = mpn_bulunan_urunler.ToList(); result.Add(_mpn); } } else { int ham_mpn_indexi = Donusturulmus_MPN_Listesi.FindIndex(x => x == mpn); MPN m = new MPN(); m.LineNo = ham_mpn_indexi + 1; m.customerMPN = Ham_MPN_Listesi[ham_mpn_indexi].MPN; m.items = new List<CompleteItems_v2>(); result.Add(m); } } List<_Item> items = new List<_Item>(); foreach (MPN item in result) { if (item.items.Count > 0) { foreach (CompleteItems_v2 i in item.items) { _Item x = new _Item(); x.LineNo = item.LineNo; x.customerMPN = item.customerMPN; x.customerQuantity = item.customerQuantity; x.item = i; items.Add(x); } } else { _Item x = new _Item(); x.LineNo = item.LineNo; x.customerMPN = item.customerMPN; x.customerQuantity = item.customerQuantity; x.item = null; items.Add(x); } } string mpn_ = String.Empty; foreach (_Item item in items) { ItemDetailFill_Row(item); if (mpn_ != item.customerMPN && item.item != null) { matchingItemCount++; } mpn_ = item.customerMPN; } lblMatchingProductCount.Text = matchingItemCount.ToString(); string temp = String.Empty; Color c = new Color(); foreach (DataGridViewRow row in dgItems.Rows) { if (temp != row.Cells[dgMPN.Index].Value.ToString()) { temp = row.Cells[dgMPN.Index].Value.ToString(); //c = Color.FromArgb((100 + rnd.Next(128)), (100 + rnd.Next(128)), (100 + rnd.Next(128))); c = ColorList[Convert.ToInt32(row.Cells[dgNo.Index].Value) % 10]; } row.DefaultCellStyle.BackColor = c; } } else { MessageBox.Show("File not selected!", "Excel"); } } } void SearchItemWithMPN_InsertIntoFoundMPNs(string tempMPN, List<string> list, List<string> convertedMpnList, List<ExcelItem> ItemFoundMPNs, List<ExcelItem> RawMPNList) { if (tempMPN.Length >= 8 & removedWordCount < 4) { tempMPN = tempMPN.Substring(0, tempMPN.Length - 2); removedWordCount += 2; list = MPN_Listesi.Where(x => x != null && x.Contains(tempMPN)).ToList(); if (list.Count() > 0) { int ham_mpn_indexi = convertedMpnList.FindIndex(x => x.Contains(tempMPN)); ItemFoundMPNs.Add(RawMPNList[ham_mpn_indexi]); _tempMPN = tempMPN; } else { SearchItemWithMPN_InsertIntoFoundMPNs(tempMPN, list, convertedMpnList, ItemFoundMPNs, RawMPNList); } } } private void GetAllItems() { string[] lines = new string[0]; try { string fileName = "MPNList.txt"; string mpnFilePath = System.Windows.Forms.Application.StartupPath + "\\" + fileName; if (!File.Exists(mpnFilePath)) { File.Create(fileName).Dispose(); MPNlistFiller(); } lines = System.IO.File.ReadAllLines(mpnFilePath); foreach (string item in lines) { if (item != "") { mpn_ime.Add(item); } else { mpn_ime.Add(null); } } foreach (var item in mpn_ime) { if (item != null) { MPN_Listesi.Add(RemoveIgnoredCharacters(item).ToUpper()); } else { MPN_Listesi.Add(null); } } } catch (System.IO.FileNotFoundException ex) { LogString = "'Yerel Disk C' içeriside 'MPNList.txt' bulunamadı!"; } } private string RemoveIgnoredCharacters(string mpn) { string temp_mpn = mpn.Replace("-", ""); temp_mpn = temp_mpn.Replace("_", ""); temp_mpn = temp_mpn.Replace("/", ""); temp_mpn = temp_mpn.Replace("&", ""); temp_mpn = temp_mpn.Replace(" ", ""); temp_mpn = temp_mpn.Replace("\"", ""); temp_mpn = temp_mpn.Replace("#", ""); temp_mpn = temp_mpn.Replace("^", ""); temp_mpn = temp_mpn.Replace("(", ""); temp_mpn = temp_mpn.Replace(")", ""); temp_mpn = temp_mpn.Replace(",", ""); temp_mpn = temp_mpn.Replace("+", ""); temp_mpn = temp_mpn.Replace("*", ""); temp_mpn = temp_mpn.Replace("!", ""); temp_mpn = temp_mpn.Replace("%", ""); temp_mpn = temp_mpn.Replace("\\", ""); temp_mpn = temp_mpn.Replace("=", ""); temp_mpn = temp_mpn.Replace("?", ""); temp_mpn = temp_mpn.Replace(".", ""); temp_mpn = temp_mpn.Replace(",", ""); return temp_mpn; } private bool ChooseFile(List<ExcelItem> Ham_MPN_Listesi) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "txt files (*.xlsx)|*.xlsx"; DialogResult result1 = dialog.ShowDialog(); if (result1 == DialogResult.OK) { Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); Workbook wb = excel.Workbooks.Open(dialog.FileName); Worksheet ws = wb.Worksheets[1]; int i = 2; while (!String.IsNullOrEmpty(ws.Cells[i, 1].Value?.ToString())) { string text = ws.Cells[i, 1].Value.ToString(); object qty = ws.Cells[i, 2].Value; Ham_MPN_Listesi.Add(new ExcelItem { MPN = text, Quantity = Convert.ToDecimal(qty) }); i++; } wb.Close(0); excel.Quit(); Marshal.ReleaseComObject(excel); return true; } else { return false; } } private void ItemDetailFill_Row(_Item rowItem) { DataGridViewRow row = dgItems.Rows[dgItems.Rows.Add()]; row.Cells[dgNo.Index].Value = rowItem.LineNo; row.Cells[dgMPN.Index].Value = rowItem.customerMPN; row.Cells[dgRsMPN.Index].Value = rowItem.item?.MPN; row.Cells[dgArticleNo.Index].Value = rowItem.item?.Article_No; int? qty = 0; if(rowItem.item?.Pack_Quantity > rowItem.item?.Unit_Content) { qty = (int)rowItem.item?.Pack_Quantity; } else { qty = rowItem.item?.Unit_Content; } row.Cells[dgPackQuantity.Index].Value = qty; if (rowItem.item != null) { row.Cells[dgUnitMeasure.Index].Value = (!String.IsNullOrEmpty(rowItem.item?.Unit_Measure)) ? rowItem.item.Unit_Measure : "EACH"; } row.Cells[dgArticleDesc.Index].Value = rowItem.item?.Article_Desc; row.Cells[dgManufacturer.Index].Value = rowItem.item?.Manufacturer; row.Cells[dgCustomerQuantity.Index].Value = rowItem.customerQuantity; row.Cells[dgStockQuantity.Index].Value = (rowItem.item?.OnhandStockBalance != null) ? rowItem.item?.OnhandStockBalance.ToString() : ""; if(rowItem.item?.OnhandStockBalance <= 0 && rowItem.item?.CatalogueStatus != null) { if (rowItem.item?.CatalogueStatus == 2) { row.Cells[dgStockQuantity.Index].Value = "FD"; row.Cells[dgStockQuantity.Index].Style.ForeColor = Color.Red; } else if (rowItem.item?.CatalogueStatus == 3) { row.Cells[dgStockQuantity.Index].Value = "D"; row.Cells[dgStockQuantity.Index].Style.ForeColor = Color.Red; } } CalculateQuantityIntoRow(rowItem, row); //row.Cells[dgColBreak1.Index].Value = rowItem.item?.Col1Break; //row.Cells[dgPrice1.Index].Value = rowItem.item?.Col1Price; //row.Cells[dgColBreak2.Index].Value = rowItem.item?.Col2Break; //row.Cells[dgPrice2.Index].Value = rowItem.item?.Col2Price; row.Cells[dgMHCodeLevel1.Index].Value = rowItem.item?.MH_Code_Level_1; } private void CalculateQuantityIntoRow(_Item item, DataGridViewRow row) { CompleteItems_v2 i = item.item; if (i != null) { if(item.customerQuantity < i.Col1Break || i.Col1Break == 0) { row.Cells[dgColBreak1.Index].Value = i.Col1Break; row.Cells[dgPrice1.Index].Value = i.Col1Price; row.Cells[dgColBreak2.Index].Value = i.Col2Break; row.Cells[dgPrice2.Index].Value = i.Col2Price; } else if (item.customerQuantity >= i.Col1Break && (item.customerQuantity < i.Col2Break || i.Col2Break == 0)) { row.Cells[dgColBreak1.Index].Value = i.Col1Break; row.Cells[dgPrice1.Index].Value = i.Col1Price; row.Cells[dgColBreak2.Index].Value = i.Col2Break; row.Cells[dgPrice2.Index].Value = i.Col2Price; } else if (item.customerQuantity >= i.Col2Break && (item.customerQuantity < i.Col3Break || i.Col3Break == 0)) { row.Cells[dgColBreak1.Index].Value = i.Col2Break; row.Cells[dgPrice1.Index].Value = i.Col2Price; row.Cells[dgColBreak2.Index].Value = i.Col3Break; row.Cells[dgPrice2.Index].Value = i.Col3Price; } else if (item.customerQuantity >= i.Col3Break && (item.customerQuantity < i.Col4Break || i.Col4Break == 0)) { row.Cells[dgColBreak1.Index].Value = i.Col3Break; row.Cells[dgPrice1.Index].Value = i.Col3Price; row.Cells[dgColBreak2.Index].Value = i.Col4Break; row.Cells[dgPrice2.Index].Value = i.Col4Price; } else if (item.customerQuantity >= i.Col4Break && (item.customerQuantity < i.Col5Break || i.Col5Break == 0)) { row.Cells[dgColBreak1.Index].Value = i.Col4Break; row.Cells[dgPrice1.Index].Value = i.Col4Price; row.Cells[dgColBreak2.Index].Value = i.Col5Break; row.Cells[dgPrice2.Index].Value = i.Col5Price; } else if (item.customerQuantity >= i.Col5Break) { row.Cells[dgColBreak1.Index].Value = i.Col5Break; row.Cells[dgPrice1.Index].Value = i.Col5Price; row.Cells[dgColBreak2.Index].Value = "--"; row.Cells[dgPrice2.Index].Value = "--"; } } } private void button1_Click(object sender, EventArgs e) { LogString = "Yükleniyor"; label1.Text = LogString; label1.ForeColor = Color.MidnightBlue; this.Refresh(); try { pb_ProgressCircle.Visible = true; bw_TakeMPNList.RunWorkerAsync(); button1.Visible = false; } catch (Exception ex) { LogString = "Liste Yüklenemedi!"; label1.Text = LogString; label1.ForeColor = Color.Red; //__mpn_ime = new List<IGrouping<string, MPN_List>>(); mpn_ime = new List<string>(); } } private void bw_TakeMPNList_DoWork(object sender, DoWorkEventArgs e) { GetAllItems(); } private void bw_TakeMPNList_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { LogString = "Liste Hazır"; label1.Text = LogString; label1.ForeColor = Color.Green; pb_ProgressCircle.Visible = false; } private void pictureBox1_DoubleClick(object sender, EventArgs e) { MPNlistFiller(); } private void MPNlistFiller() { var list = db.MPN_List.GroupBy(x => x.MPN).ToList(); using (System.IO.StreamWriter file = new System.IO.StreamWriter(System.Windows.Forms.Application.StartupPath + "\\MPNList.txt")) { foreach (var item in list) { if (item.Key != null) { file.WriteLine(item.Key); } else { file.WriteLine(""); } } } } private void bw_ItemAnalyzer_DoWork(object sender, DoWorkEventArgs e) { importExcel(); } private void btnExportExcel_Click(object sender, EventArgs e) { if (dgItems.RowCount > 0) { Utils.ExportDataGridToExcel(dgItems, "Bulunan Ürünler"); } } } class MPN { public int LineNo { get; set; } public string customerMPN { get; set; } public decimal customerQuantity { get; set; } public List<CompleteItems_v2> items { get; set; } } class _Item { public int LineNo { get; set; } public string customerMPN { get; set; } public decimal customerQuantity { get; set; } public CompleteItems_v2 item { get; set; } } class ExcelItem { public string MPN { get; set; } public decimal Quantity { get; set; } } }
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif public abstract class BuildableBase : ScriptableObject { [SerializeField] private string structureName = string.Empty; [SerializeField, Min(0)] private int _cost = 0; [SerializeField, TextArea(3, 10)] private string _description = string.Empty; [SerializeField, Tooltip("If blank, this will be put in the miscellaneous tab.")] private Tab _tab = null; [SerializeField] private EnumFogOption _fogOption = EnumFogOption.LIFT; [SerializeField, HideInInspector, Tooltip("If not null or empty, this message will be used as the rotation msg")] private string _overrideRotationMsg = null; [SerializeField, HideInInspector, Tooltip("The rotation to display the tile with in the preview")] private EnumRotation _displayRotation = EnumRotation.UP; [SerializeField, Tooltip("If blank, this Buildable is constructed instantly.")] private FloatVariable _buildTime = null; [SerializeField, Tooltip("If set, this sprite will be using in the build popup.")] private Sprite _customPreview = null; public int cost => this._cost; public string description => this._description; public Tab tab => this._tab; public EnumFogOption fogOption => this._fogOption; public EnumRotation displayRotation => this._displayRotation; public float buildTime => this._buildTime == null ? 0 : this._buildTime.value; public Sprite customPreviewSprite => this._customPreview; private void OnValidate() { if(this._displayRotation == EnumRotation.NONE) { Debug.Log("Display Rotation can not be NONE"); this._displayRotation = EnumRotation.UP; } if(!this.isRotationValid(Rotation.fromEnum(this._displayRotation))) { Rotation r = Rotation.fromEnum(this.displayRotation); for(int i = 0; i < 4; i++) { if(this.isRotationValid(r)) { Debug.Log(this.displayRotation + " is not a valid rotation"); this._displayRotation = r.enumRot; break; } r = r.clockwise(); } } } public virtual string getName() { return this.structureName; } /// <summary> /// If true is returned, the buildable is considered "rotatable" /// and it's state can be changed with r and shift + r. /// </summary> public virtual bool isRotatable() { return false; } public virtual bool isRotationValid(Rotation rotation) { return true; } /// <summary> /// If this Buildable is rotatable (BuildableBase#isRotatable /// returns true) the rotate tip message uses the returned text. /// </summary> public virtual string getRotationMsg() { return string.IsNullOrWhiteSpace(this._overrideRotationMsg) ? "[r] to rotate" : this._overrideRotationMsg; } public virtual int getHighlightWidth() { return 1; } public virtual int getHighlightHeight() { return 1; } public void getSprites(ref Sprite groundSprite, ref Sprite objectSprite, ref Sprite overlaySprite) { if(this._customPreview != null) { objectSprite = this._customPreview; } else { this.applyPreviewSprites(ref groundSprite, ref objectSprite, ref overlaySprite); } } protected virtual void applyPreviewSprites(ref Sprite groundSprite, ref Sprite objectSprite, ref Sprite overlaySprite) { } /// <summary> /// Places the structure into the world. highlight is null if a Structure is placing this Buildable. /// </summary> public abstract void placeIntoWorld(World world, BuildAreaHighlighter highlight, Position pos, Rotation rotation); /// <summary> /// Returns true if the Structure can go at the passed position. /// </summary> public abstract bool isValidLocation(World world, Position pos, Rotation rotation); protected void applyFogOpperation(World world, Position pos) { if(this.fogOption == EnumFogOption.LIFT) { world.liftFog(pos); } else if(this.fogOption == EnumFogOption.PLACE) { world.placeFog(pos); } } public enum EnumFogOption { LIFT = 0, PLACE = 1, NOTHING = 2, } #if UNITY_EDITOR [CustomEditor(typeof(BuildableBase), true)] [CanEditMultipleObjects] public class BuildableBaseEditor : Editor { private SerializedProperty displayRotation; private SerializedProperty overrideRotationMsg; protected virtual void OnEnable() { this.displayRotation = this.serializedObject.FindProperty("_displayRotation"); this.overrideRotationMsg = this.serializedObject.FindProperty("_overrideRotationMsg"); } public override void OnInspectorGUI() { this.serializedObject.Update(); this.DrawDefaultInspector(); BuildableBase script = (BuildableBase)this.target; if(script.isRotatable()) { EditorGUILayout.PropertyField(this.displayRotation); EditorGUILayout.PropertyField(this.overrideRotationMsg); } this.serializedObject.ApplyModifiedProperties(); } } #endif }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Client.Features.Jobs.Models; namespace Client.Features.Jobs { public class JobRepository : IJobRepository { private readonly Internal.ILogger _logger; private readonly DAL.IDBContext _dBContext; public JobRepository() { _logger = (Internal.ILogger)Bootstrap.Instance.Services.GetService(typeof(Internal.ILogger)); _dBContext = (DAL.IDBContext)Bootstrap.Instance.Services.GetService(typeof(DAL.IDBContext)); } public async Task<bool> Delete(Job job) { try { if (job != null) { var result1 = await GetJobCollect(job.Id); if (result1 != null && result1.Count > 0) result1.ForEach(async item => { await _dBContext.Instance.DeleteAsync(item); }); var result3 = await JobConfigurationDuplicates(job.Id); if (result3 != null) await _dBContext.Instance.DeleteAsync(result3); var result2 = await GetJobConfiguration(job.Id); if (result2 != null) await _dBContext.Instance.DeleteAsync(result2); var result4 = await _dBContext.Instance.Table<JobService.Models.DuplicateResultProgress>().FirstOrDefaultAsync(x => x.JobId == job.Id); if (result4 != null) await _dBContext.Instance.DeleteAsync(result4); var result5 = await _dBContext.Instance.Table<JobService.Models.DuplicateResultProgressIndex>().Where(x => x.JobId == job.Id).ToListAsync(); if (result5 != null && result5.Count > 0) result5.ForEach(async item => { await _dBContext.Instance.DeleteAsync(item); }); await _dBContext.Instance.DeleteAsync(job); return true; } } catch (Exception ex) { _logger.Error(ex, "Failed to delete Job item"); } return false; } public async Task<bool> Delete(JobCollectPath jobCollectPath) { try { if (jobCollectPath != null) { await _dBContext.Instance.DeleteAsync(jobCollectPath); return true; } } catch (Exception ex) { _logger.Error(ex, "Failed to delete JobCollectPath item"); } return false; } private async Task<List<Models.JobCollectPath>> GetJobCollect(Guid jobId) { return await _dBContext.Instance.Table<Models.JobCollectPath>().Where(x => x.JobId == jobId).ToListAsync(); } public async Task<List<ViewModels.JobPathView>> GetJobCollectPath(Guid jobId) { return (from x in await _dBContext.Instance.Table<Models.JobCollectPath>().ToListAsync() join y in await _dBContext.Instance.Table<Features.Folders.Models.CollectPath>().ToListAsync() on x.CollectPathId equals y.Id where x.JobId == jobId select new ViewModels.JobPathView { JobId = x.JobId, CollectPathId = y.Id, IncludeSubFolders = x.IncludeSubFolders, JobCollectPathId = x.Id, Path = y.Path }).ToList(); } public async Task<JobConfiguration> GetJobConfiguration(Guid jobId) { return await _dBContext.Instance.Table<Models.JobConfiguration>().Where(x => x.JobId == jobId).FirstOrDefaultAsync(); } public async Task<JobCollectPath> GetJobPath(Guid id) { return await _dBContext.Instance.Table<Models.JobCollectPath>().FirstAsync(x => x.Id == id); } public async Task<List<Job>> GetJobs() { return await _dBContext.Instance.Table<Models.Job>().ToListAsync(); } public async Task<List<Job>> GetJobsByState(JobState jobState) { return await _dBContext.Instance.Table<Models.Job>().Where(x => x.JobState == jobState).ToListAsync(); } public async Task<Job> GetJobs(Guid jobId) { return await _dBContext.Instance.Table<Models.Job>().FirstAsync(x => x.Id == jobId); } public async Task<bool> Insert(Job job) { try { if (job != null) { await _dBContext.Instance.InsertAsync(job); return true; } } catch (Exception ex) { _logger.Error(ex, "Failed to insert new Job item"); } return false; } public async Task<bool> Insert(JobCollectPath jobCollectPath) { try { if (jobCollectPath != null) { await _dBContext.Instance.InsertAsync(jobCollectPath); return true; } } catch (Exception ex) { _logger.Error(ex, "Failed to insert new JobCollectPath item"); } return false; } public async Task<bool> Insert(JobConfiguration jobConfiguration) { try { if (jobConfiguration != null) { await _dBContext.Instance.InsertAsync(jobConfiguration); return true; } } catch (Exception ex) { _logger.Error(ex, "Failed to insert new JobConfiguration item"); } return false; } public async Task<bool> Update(Job job) { try { if (job != null) { await _dBContext.Instance.UpdateAsync(job); return true; } } catch (Exception ex) { _logger.Error(ex, "Failed to update new Job item"); } return false; } public async Task<bool> Update(JobConfiguration jobConfiguration) { try { if (jobConfiguration != null) { await _dBContext.Instance.UpdateAsync(jobConfiguration); return true; } } catch (Exception ex) { _logger.Error(ex, "Failed to update new JobConfiguration item"); } return false; } public async Task<bool> Update(JobCollectPath jobCollectPath) { try { if (jobCollectPath != null) { await _dBContext.Instance.UpdateAsync(jobCollectPath); return true; } } catch (Exception ex) { _logger.Error(ex, "Failed to update new JobCollectPath item"); } return false; } public async Task<JobConfigurationDuplicates> JobConfigurationDuplicates(Guid jobId) { return await _dBContext.Instance.Table<Models.JobConfigurationDuplicates>().FirstOrDefaultAsync(x => x.JobId == jobId); } public async Task<bool> JobConfigurationDuplicatesChange(JobConfigurationDuplicates jobConfigurationDuplicates) { try { var item = await _dBContext.Instance.Table<Models.JobConfigurationDuplicates>().FirstOrDefaultAsync(x => x.JobId == jobConfigurationDuplicates.JobId); if (item == null) { // insert new jobConfigurationDuplicates.Id = Guid.NewGuid(); await _dBContext.Instance.InsertAsync(jobConfigurationDuplicates); } else { // update item.CompareValueTypes = jobConfigurationDuplicates.CompareValueTypes; await _dBContext.Instance.UpdateAsync(item); } return true; } catch (Exception ex) { _logger.Error(ex, "Failed to change JobConfigurationDuplicates item"); } return false; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Crosshair : MonoBehaviour { public static Vector3 crosshairPos; public float moveSpeed; private Vector3 moveDirection; public CharacterController controller; // Start is called before the first frame update void Start() { controller = GetComponent<CharacterController>(); //Cursor.visible = false; } // Update is called once per frame void Update() { moveDirection = new Vector3(Input.GetAxis("Horizontal") * 10f * moveSpeed, Input.GetAxis("Vertical") * 10f * moveSpeed, 0f); controller.Move(moveDirection * Time.deltaTime); crosshairPos = transform.position; } }
using System; using Quark.Utilities; namespace Quark.Attributes { public class Stat : Attribute { public Stat(string tag, string name, AttributeCollection collection) : base(tag, name, collection) { } public float Maximum { get { return base.Value; } } float _lostValue; public override float Value { get { return base.Value - _lostValue; } } public float Rate { get { return Value / Maximum; } } public void Manipulate(float amount) { float temp = _lostValue; _lostValue -= amount; _lostValue = System.Math.Max(0, _lostValue); _lostValue = System.Math.Min(Maximum, _lostValue); OnManipulation(_lostValue - temp); } public void ClearEvents() { Manipulated = null; Manipulated = delegate { }; } protected void OnManipulation(float amount) { Logger.Debug("Stat::OnManipulation"); Messenger<Character, Stat, float>.Broadcast("Manipulated", Owner, this, amount); Manipulated(Owner, this, amount); } public event StatDel Manipulated = delegate { }; public override string ToString() { return string.Format("[Stat {0}: {1}/{2}]", Name, Value, Maximum); } } }
 using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web; namespace CRL.Business.OnlinePay.Company.ChinaPay { public class ChinaPayCompany : CompanyBase { public override CompanyType ThisCompanyType { get { return CompanyType.银联托管; } } #region 支付 public override void Submit(IPayHistory order) { BaseSubmit(order); var request = CreateHead<Charge.Request>(); request.UserId = order.UserId; request.Amt = (Convert.ToInt64(order.Amount) * 100).ToString(); request.SrcReqId = order.OrderId;//更改为订单ID request.CurCode = "156"; string notifyUrl = ChargeConfig.GetConfigKey(CompanyType.银联托管, ChargeConfig.DataType.NotifyUrl); string returnUrl = ChargeConfig.GetConfigKey(CompanyType.银联托管, ChargeConfig.DataType.ReturnUrl); request.NotifyUrl = ConvertUrl(notifyUrl); request.ReturnUrl = ConvertUrl(returnUrl); Submit(request); } public static string ConvertUrl(string path) { return CoreHelper.RequestHelper.GetCurrentHost() + path; } protected override string OnNotify(HttpContext context) { string error; var result = ChargeNotify(context, out error); if (result == null) { return error; } var a = DealChargeNotify(result, out error); return error; } /// <summary> /// 处理通知 /// </summary> /// <param name="result"></param> /// <param name="error"></param> /// <returns></returns> public bool DealChargeNotify(Charge.Response result,out string error) { error = ""; var orderId = result.SrcReqId; IPayHistory order = OnlinePayBusiness.Instance.GetOrder(orderId, ThisCompanyType); order.spBillno = result.SrcReqId; Confirm(order, GetType(), order.Amount); return true; } #endregion /// <summary> /// 生成请求头 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T CreateHead<T>() where T : RequestBase, new() { string merId = ChargeConfig.GetConfigKey(CompanyType.银联托管, ChargeConfig.DataType.User); string channelId = ChargeConfig.GetConfigKey(CompanyType.银联托管, ChargeConfig.DataType.Data); var obj = new T(); obj.SetCode(); obj.Ver = "100"; obj.MerId = merId; obj.SrcReqDate = DateTime.Now.ToString("yyyyMMdd"); obj.SrcReqId = CreateOrderId(); obj.ChannelId = channelId; return obj; } /// <summary> /// 跳转提交 /// </summary> /// <param name="send"></param> public static void Submit(RequestBase send) { var html = ChinaPayUtil.GetSubmit(send); CoreHelper.EventLog.Log(html, "ChinaPaySubmit", false); System.Web.HttpContext.Current.Response.Write(html); System.Web.HttpContext.Current.Response.End(); } /// <summary> /// 后台请求 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="send"></param> /// <param name="error"></param> /// <returns></returns> public static T Request<T>(RequestBase send,out string error) where T : ResponseBase, new() { var xml = ChinaPayUtil.GetRequest(send); var response = CoreHelper.HttpRequest.HttpPost(send.InterFaceUrl, xml, Encoding.UTF8, "application/xml"); var obj = ChinaPayUtil.Deserialize<T>(response, out error); if (obj == null) { CoreHelper.EventLog.Log("Request:" + xml, "ChinaPay"); } return obj; } public Charge.Response ChargeNotify(System.Web.HttpContext context, out string error) { error = ""; var result = ChinaPayUtil.Deserialize<Charge.Response>(context, out error); return result; } /// <summary> /// 创建账号通知 /// </summary> /// <param name="context"></param> /// <param name="error"></param> /// <returns></returns> public CreateAccount.Response CreateAccountNotify(System.Web.HttpContext context, out string error) { error = ""; var result = ChinaPayUtil.Deserialize<CreateAccount.Response>(context, out error); return result; } /// <summary> /// 投标通知 /// </summary> /// <param name="context"></param> /// <param name="error"></param> /// <returns></returns> public Tender.Response TenderNotify(System.Web.HttpContext context, out string error) { error = ""; var result = ChinaPayUtil.Deserialize<Tender.Response>(context, out error); return result; } /// <summary> /// 公司创建账号通知 /// </summary> /// <param name="context"></param> /// <param name="error"></param> /// <returns></returns> public CreateCompanyAccount.Response CreateCompanyAccountNotify(System.Web.HttpContext context, out string error) { error = ""; var result = ChinaPayUtil.Deserialize<CreateCompanyAccount.Response>(context, out error); return result; } public override bool CheckOrder(IPayHistory order, out string message) { throw new NotImplementedException(); } public override bool RefundOrder(IPayHistory order, out string message) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; using System.Linq; using System.Web; using UniqueAttribute.Attribute; namespace UniqueAttribute.Models { public class ApplicationDbContext : DbContext { public ApplicationDbContext() : base("DefaultConnection") { //test } public DbSet<TestModel> test { get; set; } } [Table("TestModels")] public class TestModel { [Key] public int Id { get; set; } [Display(Name = "Some", Description = "desc")] [Unique(ErrorMessage = "This already exist !!")] public string SomeThing { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace TinhLuongDataAdapter { public static class DataTableToListHelper { public static List<T> DataTableToList<T>(this DataTable table) where T : class, new() { try { List<T> list = new List<T>(); foreach (var row in table.AsEnumerable()) { T obj = new T(); foreach (var prop in obj.GetType().GetProperties()) { try { PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name); propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null); } catch { continue; } } list.Add(obj); } return list; } catch { return null; } } // remove "this" if not on C# 3.0 / .NET 3.5 public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data) { List<IDataRecord> list = data.Cast<IDataRecord>().ToList(); PropertyDescriptorCollection props = null; DataTable table = new DataTable(); if (list != null && list.Count > 0) { props = TypeDescriptor.GetProperties(list[0]); for (int i = 0; i < props.Count; i++) { PropertyDescriptor prop = props[i]; table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); } } if (props != null) { object[] values = new object[props.Count]; foreach (T item in data) { for (int i = 0; i < values.Length; i++) { values[i] = props[i].GetValue(item) ?? DBNull.Value; } table.Rows.Add(values); } } return table; } public static DataTable ToDataTable<T>(this List<T> items) { DataTable dataTable = new DataTable(typeof(T).Name); //Get all the properties PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in Props) { //Defining type of data column gives proper data table var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType); //Setting column names as Property names dataTable.Columns.Add(prop.Name, type); } foreach (T item in items) { var values = new object[Props.Length]; for (int i = 0; i < Props.Length; i++) { //inserting property values to datatable rows values[i] = Props[i].GetValue(item, null); } dataTable.Rows.Add(values); } //put a breakpoint here and check datatable return dataTable; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _3.LiskovSubstitutionPrinciple.Entity { public interface IEmployee { void GetEmployeeDetails(); void GetEmployeeSalary(); void getEmployeeType(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody2D))] [RequireComponent(typeof(Fuel_System))] public class Character : MonoBehaviour { // public variables // Speed public float spaceSpeed; public float planetSpeed; // Checks [Range(0, 10)] public float groundCheckRadius; [Range(500, 2000)] public float planetCheckRadius; public Transform groundCheck; public LayerMask isGroundLayer; // Arrow prefab public GameObject ArrowPrefab; // private variables Rigidbody2D rb; Player_Rotation rot; // Input Checks float dx; float dy; bool brakes; bool jump; bool drop; bool esc; int escCount; float spaceAngle; SpriteRenderer sr; // Checks public bool isGrounded; int isOnPlanet; // Fuel System Fuel_System fs; // Relative to planet stuff Vector2 planetCenter; Vector2 planetRadiusVector; float planetAngle; float planetRadius; float planetRotation; float planetScale; Animator anim; // Capture stuff public int playerId; public int inventoryPlanet; // The planet the player last got an item from Map_Gen galaxy; bool tryPickup; bool animatePickup; string displayMessage; // Called by Map_Gen on start to create public void InitCharacter(int id, int home) { this.playerId = id; Planet hp = this.GetPlanet(home); float startX = hp.transform.position.x + (hp.transform.localScale.x * hp.GetComponent<CircleCollider2D>().radius); float startY = hp.transform.position.y + (hp.transform.localScale.y * hp.GetComponent<CircleCollider2D>().radius); this.transform.position = new Vector3(startX, startY, 0); } void Start() { rb = GetComponent<Rigidbody2D>(); fs = GetComponent<Fuel_System>(); rot = GetComponent<Player_Rotation>(); galaxy = GetComponentInParent<Map_Gen>(); this.isOnPlanet = -1; this.inventoryPlanet = -1; if (!rb) { rb = gameObject.AddComponent<Rigidbody2D>(); Debug.LogWarning("Rigidbody not found on: " + name + ". Adding by default."); } rb.constraints = RigidbodyConstraints2D.FreezeRotation; rb.collisionDetectionMode = CollisionDetectionMode2D.Continuous; rb.sleepMode = RigidbodySleepMode2D.NeverSleep; // If was not changed in inspector if (spaceSpeed <= 0 || spaceSpeed > 5.0f) { spaceSpeed = 2.0f; Debug.LogWarning("Speed not set on: " + name + ". Defaulting to " + spaceSpeed); } if (planetSpeed <= 0 || planetSpeed > 5.0f) { planetSpeed = 0.03f; Debug.LogWarning("Speed not set on: " + name + ". Defaulting to " + planetSpeed); } if (!groundCheck) { groundCheck = GameObject.Find("GroundCheck").GetComponent<Transform>(); } anim = GetComponent<Animator>(); if (!anim) { Debug.LogError("Animator not found on object"); } isGrounded = false; spaceAngle = 0.0f; escCount = 0; sr = GetComponent<SpriteRenderer>(); } void AnimatorManager() { if (anim){ if (dx < 0 || dx > 0){ anim.SetFloat("Movement", 1.0f); } else if (dy < 0 || dy > 0){ anim.SetFloat("Movement", 1.0f); } else { anim.SetFloat("Movement", 0.0f); } if (isGrounded) { anim.SetBool("Grounded", true); } else { anim.SetBool("Grounded", false); } } } void FixedUpdate() { InputManager(); ActionManager(); MoveManager(); AnimatorManager(); UIManager(); Flip(); BoundingManager(); } void Flip() { if (dx < 0) { sr.flipX = true; } else if(dx > 0) { sr.flipX = false; } } void ActionManager() { if (this.tryPickup) { ItemPickupHandler(); this.tryPickup = false; } if (this.drop) { if (this.inventoryPlanet >= 0) { this.inventoryPlanet = -1; this.displayMessage = "You have dropped your artifact."; EventSystem es = GameObject.Find("UI_and_Upgrade_Menu").GetComponent<EventSystem>(); es.DisableIcon(); } else { // this.displayMessage = "You have no artifact to drop"; } this.drop = false; } } void MoveManager() { GroundCheck(); PlanetCheck(); if (isGrounded) { PlanetMoveManager(); } else { SpaceMoveManager(); } } void InputManager() { dx = Input.GetAxisRaw("Horizontal"); dy = Input.GetAxisRaw("Vertical"); jump = Input.GetButtonDown("Jump"); brakes = Input.GetButton("Fire1"); tryPickup = Input.GetButtonDown("Fire2"); drop = Input.GetButtonDown("Fire3"); esc = Input.GetButton("Cancel"); if (esc) { this.displayMessage = "Hold esc to exit"; escCount ++; if (escCount > 150) { Application.Quit(); Debug.Log("Exit"); } } else { escCount = 0; } } void GroundCheck() { if (groundCheck) { Vector2 size = new Vector2(groundCheckRadius / 2.0f, groundCheckRadius); isGrounded = Physics2D.OverlapCapsule(groundCheck.position, size, CapsuleDirection2D.Vertical, (planetAngle * Mathf.Rad2Deg) - 90.0f, isGroundLayer); if (isGrounded) { Collider2D planet = Physics2D.OverlapCapsule(groundCheck.position, size, CapsuleDirection2D.Vertical, (planetAngle * Mathf.Rad2Deg) - 90.0f, isGroundLayer); planetCenter = planet.transform.position; planetRadius = planet.GetComponent<CircleCollider2D>().radius; planetScale = planet.transform.localScale.x; planetRadiusVector = new Vector2(transform.position.x - planet.transform.position.x, transform.position.y - planet.transform.position.y); planetRotation = planet.GetComponent<Planet>().rotation; if (isOnPlanet < 0) { planetAngle = Mathf.Atan2(planetRadiusVector.y, planetRadiusVector.x); isOnPlanet = planet.GetComponent<Planet>().planetIdx; } } } } void PlanetCheck() { Collider2D[] planetcheck = Physics2D.OverlapCircleAll(transform.position, planetCheckRadius, isGroundLayer); for (int i = 0; i < planetcheck.Length; i++) { float xCam = Camera.main.WorldToViewportPoint(planetcheck[i].transform.position).x; float yCam = Camera.main.WorldToViewportPoint(planetcheck[i].transform.position).y; bool withinCamera = xCam > 0 && xCam < 1 && yCam > 0 && yCam < 1; if (!withinCamera) { float x, y; Vector2 directionvector = planetcheck[i].transform.position - transform.position; float mag = Mathf.Sqrt(Mathf.Pow(directionvector.x, 2) + Mathf.Pow(directionvector.y, 2)); Vector2 unitvector = directionvector.normalized; x = (unitvector.x * Camera.main.orthographicSize / 1.25f) + transform.position.x; y = (unitvector.y * Camera.main.orthographicSize / 1.25f) + transform.position.y; float angle_ = Mathf.Atan2(unitvector.y, unitvector.x) * Mathf.Rad2Deg; Quaternion rot = Quaternion.Euler(new Vector3(0.0f, 0.0f, angle_ - 90.0f)); GameObject arrow; arrow = Instantiate(ArrowPrefab, new Vector3(x, y, 0.0f), rot); float reduceSize = 85.0f; arrow.transform.localScale = new Vector3(arrow.transform.localScale.x / (mag / reduceSize), arrow.transform.localScale.y / (mag / reduceSize), arrow.transform.localScale.z); Destroy(arrow, 0.02f); } } } void PlanetMoveManager() { rb.velocity = Vector2.zero; planetAngle -= ((((dx * planetSpeed)) * Mathf.PI * 720)) / (Mathf.PI * Mathf.Pow(planetRadius * planetScale, 2)); planetAngle += planetRotation*Mathf.Deg2Rad; Vector2 offset = new Vector2(Mathf.Cos(planetAngle), Mathf.Sin(planetAngle)) * ((planetRadius * planetScale) + 2.0f); transform.position = planetCenter + offset; JetManager(); rot.SetRotation(planetAngle - (Mathf.PI / 2)); spaceAngle = planetAngle; } void SpaceMoveManager() { spaceAngle -= dx * Time.deltaTime * 4.0f; planetAngle = 0; isOnPlanet = -1; rot.SetRotation(spaceAngle - (Mathf.PI / 2)); JetManager(); //if (Mathf.Abs(this.transform.position.x) > 1500 || Mathf.Abs(this.transform.position.y) > 1500) { // this.displayMessage = "Press Shift to deploy Space brakes"; //} } void JetManager() { if (!isGrounded && dy != 0) { Vector3 spaceMovement = new Vector3(dy * Mathf.Cos(spaceAngle), Mathf.Sin(dy * spaceAngle), 0.0f); fs.UseJetForce(); rb.AddForce(spaceMovement * fs.jetForce, ForceMode2D.Force); fs.JetOn = true; } else if (!isGrounded && brakes) { rb.velocity = Vector3.zero; fs.UseJetForce(brakes); fs.JetOn = false; } else if (!isGrounded && jump) { Vector3 spaceMovement = new Vector3(Mathf.Cos(spaceAngle), Mathf.Sin(spaceAngle), 0.0f); float fuelRatio = fs.fuel / fs.maxFuel; rb.AddForce(spaceMovement * fs.jetForce * 4 * fuelRatio, ForceMode2D.Impulse); fs.UseJetForce(jump); fs.JetOn = true; } else if (jump && isGrounded) { ///Vector3 spaceMovement = new Vector3(dx, dy, 0.0f); Vector3 dirVec = new Vector3(transform.position.x - planetCenter.x, transform.position.y - planetCenter.y, 0.0f).normalized; fs.UseJetForce(); rb.AddForce(dirVec * fs.jetForce * 4, ForceMode2D.Impulse); fs.JetOn = true; } else { fs.JetOn = false; } fs.IdleJetForce(); } void UIManager() { if (this.displayMessage != null) { Upgrade_System ui = GameObject.Find("UI_and_Upgrade_Menu").GetComponent<Upgrade_System>(); ui.DisplayEventMessage(this.displayMessage, this.playerId); this.displayMessage = null; } } /** Called when Item pickup */ void ItemPickupHandler() { if (this.isOnPlanet < 0) { this.displayMessage = "You need to be on a Planet to pick up an item"; return; } if (this.inventoryPlanet >= 0) { this.displayMessage = "You already have an item, press <key> on a planet you know to toss"; return; } if (!this.galaxy.IsPlanetInNetwork(this.playerId, this.isOnPlanet)) { this.displayMessage = "You don't know anyone on this planet"; return; } this.displayMessage = "You have collected a souvenir from this world"; animatePickup = true; // TODO Animate; this.inventoryPlanet = isOnPlanet; EventSystem es = GameObject.Find("UI_and_Upgrade_Menu").GetComponent<EventSystem>(); es.EnableIcon(); } Planet GetPlanet(int idx) { return GetComponentInParent<Map_Gen>().GetPlanet(idx); } public void ItemAccepted() { this.galaxy.ConnectPlanets(this.isOnPlanet, this.inventoryPlanet, this.playerId); this.inventoryPlanet = -1; EventSystem es = GameObject.Find("UI_and_Upgrade_Menu").GetComponent<EventSystem>(); es.DisableIcon(); } void BoundingManager() { if (this.transform.position.x < -1000) { this.transform.position = new Vector2(1499, this.transform.position.y); } else if (this.transform.position.x > 1500) { this.transform.position = new Vector2(-999, this.transform.position.y); } if (this.transform.position.y < -1000) { this.transform.position = new Vector2(this.transform.position.x, 1499); } else if (this.transform.position.y > 1500) { this.transform.position = new Vector2(this.transform.position.x, -999); } } }
using System; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Graphics; using StarlightRiver.Abilities; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace StarlightRiver.NPCs.Pickups { class Fist : ModNPC { public override void SetStaticDefaults() { DisplayName.SetDefault("Gaia's Fist"); } public override void SetDefaults() { npc.width = 32; npc.height = 32; npc.aiStyle = -1; npc.immortal = true; npc.lifeMax = 1; npc.knockBackResist = 0; npc.noGravity = true; } public override bool CheckActive() { return true; } int animate = 0; public override void AI() { npc.TargetClosest(true); Player player = Main.player[npc.target]; AbilityHandler mp = player.GetModPlayer<AbilityHandler>(); if (npc.Hitbox.Intersects(player.Hitbox) && mp.smash.Locked) { mp.smash.Locked = false; mp.StatStaminaMaxPerm += 1; animate = 300; Main.PlaySound(mod.GetLegacySoundSlot(SoundType.Custom, "Sounds/Pickups/get")); } if (animate >= 1) { player.position = new Vector2(npc.position.X, npc.position.Y - 16); player.immune = true; player.immuneTime = 5; player.immuneNoBlink = true; if (animate > 100 && animate < 290) { float rot = (animate - 100) / 190f * 6.28f; } if (animate == 1) { player.AddBuff(BuffID.Featherfall, 120); Achievements.Achievements.QuickGive("Shatterer", player); StarlightRiver.Instance.abilitytext.Display( "Gaia's Fist", "Press " + StarlightRiver.Smash.GetAssignedKeys()[0] + " in the air to dive downwards", mp.smash); } } if (animate > 0) { animate--; } } float timer = 0; public override void PostDraw(SpriteBatch spriteBatch, Color drawColor) { AbilityHandler mp = Main.LocalPlayer.GetModPlayer<AbilityHandler>(); timer += (float)(Math.PI * 2) / 120; if (timer >= Math.PI * 2) { timer = 0; } if (mp.smash.Locked) { Vector2 pos = npc.position - Main.screenPosition - (new Vector2((int)((Math.Cos(timer * 3) + 1) * 4f), (int)((Math.Sin(timer * 3) + 1) * 4f)) / 2) + new Vector2(0, (float)Math.Sin(timer) * 4); spriteBatch.Draw(ModContent.GetTexture("StarlightRiver/NPCs/Pickups/Smash1"), npc.position + new Vector2(0, (float)Math.Sin(timer) * 4) - Main.screenPosition, Color.White); Dust.NewDustPerfect(npc.Center + Vector2.One.RotatedBy(timer) * (23 + (float)Math.Sin(timer * 10) * 4) , ModContent.DustType<Dusts.JungleEnergy>(), Vector2.Zero, 0, default, 0.8f); Dust.NewDustPerfect(npc.Center + Vector2.One.RotatedBy(timer) * 18, ModContent.DustType<Dusts.JungleEnergy>(), Vector2.Zero, 0, default, 0.8f); Dust.NewDustPerfect(npc.Center + Vector2.One.RotatedBy(timer) * 28, ModContent.DustType<Dusts.JungleEnergy>(), Vector2.Zero, 0, default, 0.8f); } } } }
using Autofac; using EmberKernel.Plugins.Components; using EmberSqlite.Integration; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Polly; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EmberKernel.Plugins { public static class PluginDbContextExtension { public static void ConfigureDbContext<T>(this IComponentBuilder builder) where T : EmberDbContext { if (!builder.ParentScope.TryResolve<SqliteConfiguration>(out _)) { throw new NullReferenceException("Can't resolve SqliteInformation, try build kernel with 'UseEFSqlite()' option."); } builder.ConfigureComponent<T>().SingleInstance(); } public static async ValueTask MigrateDbContext<T>(this ILifetimeScope scope, CancellationToken cancellationToken = default) where T : EmberDbContext { var logger = scope.Resolve<ILogger<T>>(); var conf = scope.Resolve<SqliteConfiguration>(); if (!scope.TryResolve<T>(out var sqliteDbContext)) { throw new NullReferenceException($"Can't resolve {typeof(T).Name}, ensure configured when 'BuildComponent'"); } try { var pendingMigrations = await sqliteDbContext.Database.GetPendingMigrationsAsync(); if (pendingMigrations.Count() > 0 && sqliteDbContext.Database.GetDbConnection() is SqliteConnection sqliteConn) { logger.LogInformation($"Will apply migrations, backup database..."); var backupPath = Path.Combine(Path.GetDirectoryName(conf.DbPath), "backup"); var newFile = Path.Combine(backupPath, $"{Path.GetRandomFileName()}.sqlite"); if (!Directory.Exists(backupPath)) Directory.CreateDirectory(backupPath); var oldConn = new SqliteConnection(new SqliteConnectionStringBuilder() { Cache = SqliteCacheMode.Shared, DataSource = conf.DbPath, Mode = SqliteOpenMode.ReadWriteCreate, }.ToString()); var newConn = new SqliteConnection(new SqliteConnectionStringBuilder() { Cache = SqliteCacheMode.Shared, DataSource = newFile, ForeignKeys = true, Mode = SqliteOpenMode.ReadWriteCreate, }.ToString()); await oldConn.OpenAsync(); oldConn.BackupDatabase(newConn); logger.LogInformation($"Database backup to {newFile}"); logger.LogInformation($"Migrating database with context {typeof(T).Name}"); var retry = Policy.Handle<Exception>() .WaitAndRetryAsync(new TimeSpan[] { TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(8) }); await retry.ExecuteAsync(() => sqliteDbContext.Database.MigrateAsync(cancellationToken)); logger.LogInformation($"Migrated database associated with context {typeof(T).Name}"); } } catch (Exception e) { logger.LogError(e, $"An error occurred while migrating the database used on {typeof(T).Name}"); } } } }
using System.ComponentModel.DataAnnotations; namespace starteAlkemy.Models { public class HomeImages { [Key] public int Id { get; set; } public string Link { get; set; } public string Text { get; set; } public bool Active { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace MuggleTranslator.Common { public class AutomationHelper { /// <summary> /// 获取用户当前选中文本 /// </summary> /// <returns></returns> public static async Task<string> GetSelectedText() { ClipboardHelper.Clear(); //AutoIt.AutoItX.Send("^c"); // 这个方法似乎有bug // https://stackoverflow.com/questions/14395377/how-to-simulate-a-ctrl-a-ctrl-c-using-keybd-event // Hold Control down and press C keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYDOWN, 0); keybd_event(C, 0, KEYEVENTF_KEYDOWN, 0); keybd_event(C, 0, KEYEVENTF_KEYUP, 0); keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0); // 获取数据 await Task.Delay(200); return ClipboardHelper.GetText(); } [DllImport("user32.dll", SetLastError = true)] static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo); public const int KEYEVENTF_KEYDOWN = 0x0000; // New definition public const int KEYEVENTF_EXTENDEDKEY = 0x0001; //Key down flag public const int KEYEVENTF_KEYUP = 0x0002; //Key up flag public const int VK_LCONTROL = 0xA2; //Left Control key code public const int A = 0x41; //A key code public const int C = 0x43; //C key code } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace ALFC_SOAP.Common { class AppColors { public static Color BGRed { get { return Color.FromRgba(182, 128, 136, 150); } } public static Color BGBlue { get { return Color.FromRgba(58, 69, 122, 150); } } public static Color BGGreen { get { return Color.FromRgba(52, 107, 128, 150); } } public static Color BGGreenHighLight { get { return Color.FromRgba(75, 130, 150, 150); } } public static Color BGPurple { get { return Color.FromRgba(98, 25, 37, 150); } } public static Color Black { get { return Color.FromRgb(5, 5, 5); } } public static Color Blue { get { return Color.FromRgb(58, 69, 122); } } public static Color Green { get { return Color.FromRgb(52, 107, 128); } } public static Color Purple { get { return Color.FromRgb(98, 25, 37); } } public static Color Rose { get { return Color.FromRgb(182, 128, 136); } } public static Color White { get { return Color.FromRgb(255, 255, 255); } } public static Color Transparent { get { return Color.Transparent; } } public static Color TextGray { get { return Color.FromRgb(98, 98, 98); } } public static Color TextRed { get { return Color.Red; } } } }
namespace Algorithms.Lib.Interfaces { public interface IWeighedArcs : IPrintable { INode From { get; } INode To { get; } int Weight { get; } } }
using System; namespace Algorithms.LeetCode { public class PartitioningIntoMinimumNumberOfDeciBinaryNumbersTask { public int MinPartitions(string n) { int maxDigit = 0; foreach (var digit in n) { maxDigit = Math.Max(maxDigit, digit - '0'); } return maxDigit; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EventDepartmentManager { [Serializable] public class ListOfProjects { public List<Project> Proj { get; set; } public ListOfProjects(List<Project> proj) { Proj = proj; } public ListOfProjects() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ESL.App { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); using (var s = new System.Speech.Synthesis.SpeechSynthesizer()) { s.SetOutputToDefaultAudioDevice(); s.Speak("Welcome to E S L universe."); s.Speak("all english learning tools for anyone who speaks english as a second language in a single package."); } } } }
namespace Krafteq.ElsterModel.Common { using LanguageExt; public class FullName { public static readonly FullName Empty = new FullName(Prelude.None, Prelude.None); public Option<FirstName> FirstName { get; } public Option<LastName> LastName { get; } // public string Title { get; set; } // public string MiddleName { get; set; } public FullName(Option<FirstName> firstName, Option<LastName> lastName) { this.FirstName = firstName; this.LastName = lastName; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ControllerScript : MonoBehaviour { public GameObject go; void Start() { go = new GameObject(); } void Update() { RaycastHit hit; transform.rotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTrackedRemote); if (Physics.Raycast(transform.position, transform.forward, out hit)) { if (hit.collider != null) { if (go != hit.collider.gameObject) { go.transform.SendMessage("OnVRExit"); go = hit.transform.gameObject; go.transform.SendMessage("OnVREnter"); } if (OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger)) { go.transform.SendMessage("OVRTriggerDown"); } /* if(OVRInput.GetDown(OVRInput.Button.One)) { } if (OVRInput.GetDown(OVRInput.Button.Two)) { } */ } } else { if (go != null) { go.transform.SendMessage("OnVRExit"); go = new GameObject(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.OleDb; /** * Tên Đề Tài; Phần Mền Quản Lý Biển Số Xe và Vi Phạm Giao Thông(VLNM (Vehicle license number management)) * Ho tên sinh viên: * 1. Phan Nhật Tiến 0812515 * 2. Huỳnh Công Toàn 0812527 * * GVHD. Trần Minh Triết **/ namespace QLBSX_DAL_WS { public class DataProvider { private static string chuoiKetNoi = @"Provider=Microsoft.Jet.OleDb.4.0;Data Source=|DataDirectory|\QLBSX_DB.mdb"; private static OleDbConnection _connection; public static OleDbConnection Connection { get { return DataProvider._connection; } //set { DataProvider._connection = value; } } public static void Connect() { if (_connection != null) //Đã tạo if (_connection.State == System.Data.ConnectionState.Open) //Đang mở kết nối thì không mở nữa return; _connection = new OleDbConnection(chuoiKetNoi); _connection.Open(); } public static void Disconnect() { if (_connection != null) { if (_connection.State == System.Data.ConnectionState.Open) _connection.Close(); } } } }
using System; using System.Runtime.Serialization; namespace ModelTransformationComponent { /// <summary> /// Ошибка в названии структуры /// <para/> /// Подвид синтаксической ошибки <see cref="SyntaxErrorPlaced"/> /// </summary> [Serializable] public class NameSyntaxError : SyntaxErrorPlaced { /// <summary> /// Строка формата сообщения ошибки по-умолчанию /// </summary> /// <value> /// "[{0},{1}] Синтаксическая ошибка: ожидалось валидное имя, а получили \"{2}\"" /// </value> new protected static string FormatString = "[{0},{1}] Синтаксическая ошибка: ожидалось валидное имя, а получили \"{2}\""; /// <summary> /// Ошибка в названии структуры /// </summary> /// <param name="line">Номер строки</param> /// <param name="symbol">Номер символа</param> /// <param name="got">Полученная строка</param> /// <param name="formatString">Строка формата сообщения об ошибке</param> public NameSyntaxError(int line, int symbol, string got, string formatString) : base(line,symbol,got,string.Empty,formatString.Replace("{2}","{3}")) {} /// <summary> /// Ошибка в названии структуры /// </summary> /// <param name="line">Номер строки</param> /// <param name="symbol">Номер символа</param> /// <param name="got">Полученная строка</param> public NameSyntaxError(int line, int symbol, string got) : this(line, symbol, got,FormatString) {} /// <summary> /// Ошибка в названии структуры /// </summary> /// <param name="got">Полученная строка</param> public NameSyntaxError(string got) : this(0,0,got) {} /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> /// <returns></returns> protected NameSyntaxError(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <returns></returns> public NameSyntaxError(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// /// </summary> public NameSyntaxError() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Complementares6 { class Complementares6Exe10 { static void Main11(string[] args) { } } }
using System; using System.Text.RegularExpressions; class chapter8 { static void Main() { string words = "08/14/57 46 02/25/59 45 06/05/85 18 " + "03/12/88 16 09/09/90 13"; string regExp1 = "(?<dates>(\\d{2}/\\d{2}/\\d{2}))\\s"; MatchCollection matchSet = Regex.Matches(words, regExp1); foreach (Match aMatch in matchSet) Console.WriteLine("Date: {0}", aMatch.Groups["dates"]); Console.ReadKey(); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace CYT.Web.FileManagement { public class FileManager { public string GetUserFilePath(int userId, string filepath) { string[] split = filepath.Split('/'); string filename = split[split.Length - 1]; return String.Format("{0}/{1}", GetUserDirectoryPath(userId), filename); } public string GetUserDirectoryPath(int userId) { string path = HttpContext.Current.Server.MapPath(String.Format("~/Content/Users/{0}", userId)); if (!Directory.Exists(path)) Directory.CreateDirectory(path); return path; } public string GetUserRecipesDirectoryPath(int userId) { string path= HttpContext.Current.Server.MapPath(String.Format("~/Content/Users/{0}/Recipes", userId)); if (!Directory.Exists(path)) Directory.CreateDirectory(path); return path; } public string GetRecipeDirectoryPath(int userId,int recipeId) { string path= HttpContext.Current.Server.MapPath(String.Format("~/Content/Users/{0}/Recipes/{1}", userId,recipeId)); if (!Directory.Exists(path)) Directory.CreateDirectory(path); return path; } public string GetRecipeImageFileUrl(int userId, int recipeId, string filename) { return String.Format("/Content/Users/{0}/Recipes/{1}/{2}", userId, recipeId, filename); } public string GetUserFileUrl(int userId, string filename) { return String.Format("/Content/Users/{0}/{1}", userId, filename); } public bool RemoveFile(string file) { if (File.Exists(file)) { File.Delete(file); return true; } return false; } public bool MoveFile(string from, string to) { if (File.Exists(from)) { File.Move(from, to); return true; } return false; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrainingWheels.Data { public class ArchiveEntity { [Key] public int ArchiveId { get; set; } // Foreign key to relate event with user public Guid Id { get; set; } public ApplicationUser ApplicationUser { get; set; } // Foreign key to relate event with Activity public int ActivityId { get; set; } public ActivityEntity ActivityEntity { get; set; } [Required] public DateTimeOffset CreatedUtc { get; set; } } }
#if UNITY_2018_3_OR_NEWER using System; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; namespace UnityAtoms.Editor { /// <summary> /// Internal utility class to regenerate all Atoms. Reachable via top menu bar and `Tools/Unity Atoms/Regenerate All Atoms`. /// </summary> internal class RegenereateAllAtoms { private class RegenerateItem { public string ValueType { get; set; } public string BaseWritePath { get; set; } public bool IsValueEquatable { get; set; } public List<AtomType> AtomTypesToGenerate { get; set; } public string ValueTypeNamespace { get; set; } public string SubUnityAtomsNamespace { get; set; } public RegenerateItem(string valueType, string baseWritePath, bool isValueEquatable, List<AtomType> atomTypesToGenerate, string typeNamespace, string subUnityAtomsNamespace) { this.ValueType = valueType; this.BaseWritePath = baseWritePath; this.IsValueEquatable = isValueEquatable; this.AtomTypesToGenerate = atomTypesToGenerate; this.ValueTypeNamespace = typeNamespace; this.SubUnityAtomsNamespace = subUnityAtomsNamespace; } } [MenuItem("Tools/Unity Atoms/Regenerate Atoms from Assets")] static void RegenereateAssets() { if (!EditorUtility.DisplayDialog("Regenerate", "This will regenerate all Atoms from Generation-Assets", "Ok", "Cancel")) { return; } var guids = AssetDatabase.FindAssets($"t:{nameof(AtomGenerator)}"); foreach (var guid in guids) { var path = AssetDatabase.GUIDToAssetPath(guid); AssetDatabase.LoadAssetAtPath<AtomGenerator>(path).Generate(); } } /// <summary> /// Create the editor window. /// </summary> [MenuItem("Tools/Unity Atoms/Regenerate all Atoms")] static void Regenereate() { if (!Runtime.IsUnityAtomsRepo) { Debug.LogWarning("This is currently only available working in the Unity Atoms project..."); } string path = EditorUtility.OpenFolderPanel("Select the 'Packages' folder (containing Core)", ".", ""); if (string.IsNullOrEmpty(path)) { Debug.LogWarning("Empty path. Abort."); return; } path = new Uri(Application.dataPath).MakeRelativeUri(new Uri(path)).ToString(); var i = EditorUtility.DisplayDialogComplex("Regenerate Atoms", $"Do you want to regenerate all Atoms and write them to '{path}'?\n", "Yes, I know what I'm doing!", "Cancel", ""); if (i == 1) { Debug.LogWarning("Cancelled generating Atoms."); return; } var itemsToRegenerate = new List<RegenerateItem>() { // Base Atoms new RegenerateItem( valueType: "Void", baseWritePath: Path.Combine(path, "BaseAtoms"), isValueEquatable: false, atomTypesToGenerate: new List<AtomType>() { AtomTypes.EVENT, AtomTypes.UNITY_EVENT, AtomTypes.BASE_EVENT_REFERENCE, AtomTypes.EVENT_INSTANCER, AtomTypes.BASE_EVENT_REFERENCE_LISTENER }, typeNamespace: "", subUnityAtomsNamespace: "BaseAtoms" ), new RegenerateItem(valueType: "bool", baseWritePath: Path.Combine(path, "BaseAtoms"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "", subUnityAtomsNamespace: "BaseAtoms"), new RegenerateItem(valueType: "Collider2D", baseWritePath: Path.Combine(path, "BaseAtoms"), isValueEquatable: false, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityEngine", subUnityAtomsNamespace: "BaseAtoms"), new RegenerateItem(valueType: "Collider", baseWritePath: Path.Combine(path, "BaseAtoms"), isValueEquatable: false, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityEngine", subUnityAtomsNamespace: "BaseAtoms"), new RegenerateItem(valueType: "Collision2D", baseWritePath : Path.Combine (path, "BaseAtoms"), isValueEquatable : false, atomTypesToGenerate : AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityEngine", subUnityAtomsNamespace: "BaseAtoms"), new RegenerateItem(valueType: "Collision", baseWritePath : Path.Combine (path, "BaseAtoms"), isValueEquatable : false, atomTypesToGenerate : AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityEngine", subUnityAtomsNamespace: "BaseAtoms"), new RegenerateItem(valueType: "Color", baseWritePath: Path.Combine(path, "BaseAtoms"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityEngine", subUnityAtomsNamespace: "BaseAtoms"), new RegenerateItem(valueType: "float", baseWritePath: Path.Combine(path, "BaseAtoms"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "", subUnityAtomsNamespace: "BaseAtoms"), new RegenerateItem(valueType: "GameObject", baseWritePath: Path.Combine(path, "BaseAtoms"), isValueEquatable: false, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityEngine", subUnityAtomsNamespace: "BaseAtoms"), new RegenerateItem(valueType: "int", baseWritePath: Path.Combine(path, "BaseAtoms"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "", subUnityAtomsNamespace: "BaseAtoms"), new RegenerateItem(valueType: "string", baseWritePath: Path.Combine(path, "BaseAtoms"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "", subUnityAtomsNamespace: "BaseAtoms"), new RegenerateItem(valueType: "Vector2", baseWritePath: Path.Combine(path, "BaseAtoms"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityEngine", subUnityAtomsNamespace: "BaseAtoms"), new RegenerateItem(valueType: "Vector3", baseWritePath: Path.Combine(path, "BaseAtoms"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityEngine", subUnityAtomsNamespace: "BaseAtoms"), new RegenerateItem( valueType: "AtomBaseVariable", baseWritePath: Path.Combine(path, "BaseAtoms"), isValueEquatable: false, atomTypesToGenerate: new List<AtomType>() { AtomTypes.EVENT, AtomTypes.ACTION, AtomTypes.UNITY_EVENT, AtomTypes.BASE_EVENT_REFERENCE, AtomTypes.EVENT_INSTANCER, AtomTypes.BASE_EVENT_REFERENCE_LISTENER }, typeNamespace: "", subUnityAtomsNamespace: "BaseAtoms" ), new RegenerateItem ( valueType: "double", baseWritePath: Path.Combine(path, "BaseAtoms"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "", subUnityAtomsNamespace: "BaseAtoms" ), new RegenerateItem ( valueType: "Quaternion", baseWritePath: Path.Combine(path, "BaseAtoms"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityEngine", subUnityAtomsNamespace: "BaseAtoms" ), //MonoHooks new RegenerateItem(valueType: "ColliderGameObject", baseWritePath: Path.Combine(path, "MonoHooks"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityAtoms.MonoHooks", subUnityAtomsNamespace: "MonoHooks"), new RegenerateItem(valueType: "Collider2DGameObject", baseWritePath: Path.Combine(path, "MonoHooks"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityAtoms.MonoHooks", subUnityAtomsNamespace: "MonoHooks"), new RegenerateItem(valueType: "CollisionGameObject", baseWritePath: Path.Combine(path, "MonoHooks"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityAtoms.MonoHooks", subUnityAtomsNamespace: "MonoHooks"), new RegenerateItem(valueType: "Collision2DGameObject", baseWritePath: Path.Combine(path, "MonoHooks"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityAtoms.MonoHooks", subUnityAtomsNamespace: "MonoHooks"), //Mobile new RegenerateItem(valueType: "TouchUserInput", baseWritePath: Path.Combine(path, "Mobile"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityAtoms.Mobile", subUnityAtomsNamespace: "Mobile"), //SceneMgmt new RegenerateItem(valueType: "SceneField", baseWritePath: Path.Combine(path, "SceneMgmt"), isValueEquatable: true, atomTypesToGenerate: AtomTypes.ALL_ATOM_TYPES, typeNamespace: "UnityAtoms.SceneMgmt", subUnityAtomsNamespace: "SceneMgmt"), //FSM new RegenerateItem( valueType: "FSMTransitionData", baseWritePath: Path.Combine(path, "FSM"), isValueEquatable: false, atomTypesToGenerate: new List<AtomType>() { AtomTypes.EVENT, AtomTypes.ACTION, AtomTypes.UNITY_EVENT, AtomTypes.BASE_EVENT_REFERENCE, AtomTypes.EVENT_INSTANCER, AtomTypes.BASE_EVENT_REFERENCE_LISTENER }, typeNamespace: "", subUnityAtomsNamespace: "FSM" ), //Input System new RegenerateItem ( valueType: "PlayerInput", baseWritePath: Path.Combine(path, "InputSystem"), isValueEquatable: false, atomTypesToGenerate: new List<AtomType>() { AtomTypes.EVENT, AtomTypes.ACTION, AtomTypes.UNITY_EVENT, AtomTypes.EVENT_INSTANCER }, typeNamespace: "UnityEngine.InputSystem", subUnityAtomsNamespace: "InputSystem" ), new RegenerateItem ( valueType: "InputAction.CallbackContext", baseWritePath: Path.Combine(path, "InputSystem"), isValueEquatable: false, atomTypesToGenerate: new List<AtomType>() { AtomTypes.EVENT, AtomTypes.ACTION, AtomTypes.UNITY_EVENT, AtomTypes.EVENT_INSTANCER }, typeNamespace: "UnityEngine.InputSystem", subUnityAtomsNamespace: "InputSystem" ), }; foreach (var item in itemsToRegenerate) { var templates = Generator.GetTemplatePaths(); var templateConditions = Generator.CreateTemplateConditions(item.IsValueEquatable, item.ValueTypeNamespace, item.SubUnityAtomsNamespace, item.ValueType); var templateVariables = Generator.CreateTemplateVariablesMap(item.ValueType, item.ValueTypeNamespace, item.SubUnityAtomsNamespace); var capitalizedValueType = item.ValueType.Replace('.', '_').Capitalize(); foreach (var atomType in item.AtomTypesToGenerate) { templateVariables["VALUE_TYPE_NAME"] = atomType.IsValuePair ? $"{capitalizedValueType}Pair" : capitalizedValueType; var valueType = atomType.IsValuePair ? $"{capitalizedValueType}Pair" : item.ValueType; templateVariables["VALUE_TYPE"] = valueType; Generator.Generate(new AtomReceipe(atomType, valueType), item.BaseWritePath, templates, templateConditions, templateVariables); } } AssetDatabase.Refresh(); } } } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //********************************************************************** // // 文件名称(File Name):LoadNodeLogResponse.CS // 功能描述(Description): // 作者(Author):Aministrator // 日期(Create Date): 2017-04-21 15:32:08 // // 修改记录(Revision History): // R1: // 修改作者: // 修改日期:2017-04-21 15:32:08 // 修改理由: //********************************************************************** namespace ND.FluentTaskScheduling.Model.response { public class LoadNodeLogResponse { public List<tb_log> NodeLogList { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Recursivitate { class Program { static void Main(string[] args) { // n! = n * (n - 1) * .... 2 * 1 int produs = 1, n = 7; for (int i = 1; i <= n; i++) { produs *= i; // produs = produs * i; matrice[v[i], a[i, j]] *= .... } Console.WriteLine("{0}", produs); // n! = n * (n - 1)! // Daca n = 1 atunci n! = 1; int factorial = 0; factorial = Factorial(n); // Suma cifrelor unui numar; // SumaCifre(n) = n % 10 + SumaCifre(n / 10), daca n > 0; // = 0 daca n = 0 int numar = 12468; Console.WriteLine("Suma cifrelor numarului {0} este {1}", numar, SumaCifre(numar)); // Sirul lui Fibonnaci // f0 = 1, f1 = 1, f(n) = f(n - 1) + f(n - 2); // 1, 1, 2, 3, 5, 8, 13, ... n = 10; Console.WriteLine("{0}", Fibo(n)); // Numarul de cifre al unui numar; // NumarCifre(n) = 1 daca n < 10 // = 1 + NumarCifre(n / 10) } private static int Fibo(int n) { if (n == 0 || n == 1) { return 1; } else { return Fibo(n - 1) + Fibo(n - 2); } } private static int SumaCifre(int n) { if (n == 0) { return 0; } else { return n % 10 + SumaCifre(n / 10); } } private static int Factorial(int n) { if (n == 1) { return 1; } else { return n * Factorial(n - 1); } } } }
using SharpShapes; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; namespace GrapeShapes { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); PopulateClassList(); Square square = new Square(30); square.FillColor = System.Windows.Media.Colors.AliceBlue; square.BorderColor = System.Windows.Media.Colors.Aqua; DrawSquare(50, 5, square); } private void DrawRectangle() { System.Windows.Shapes.Polygon myPolygon = new System.Windows.Shapes.Polygon(); myPolygon.Stroke = System.Windows.Media.Brushes.Tomato; myPolygon.Fill = System.Windows.Media.Brushes.Bisque; myPolygon.StrokeThickness = 2; myPolygon.HorizontalAlignment = HorizontalAlignment.Left; myPolygon.VerticalAlignment = VerticalAlignment.Center; System.Windows.Point Point1 = new System.Windows.Point(1, 50); System.Windows.Point Point2 = new System.Windows.Point(1, 80); System.Windows.Point Point3 = new System.Windows.Point(50, 80); System.Windows.Point Point4 = new System.Windows.Point(50, 50); PointCollection myPointCollection = new PointCollection(); myPointCollection.Add(Point1); myPointCollection.Add(Point2); myPointCollection.Add(Point3); myPointCollection.Add(Point4); myPolygon.Points = myPointCollection; ShapeCanvas.Children.Add(myPolygon); } private void DrawSquare(int x, int y, Square square) { System.Windows.Shapes.Polygon myPolygon = new System.Windows.Shapes.Polygon(); myPolygon.Stroke = System.Windows.Media.Brushes.Tomato; myPolygon.Fill = System.Windows.Media.Brushes.Bisque; myPolygon.StrokeThickness = 2; myPolygon.HorizontalAlignment = HorizontalAlignment.Right; myPolygon.VerticalAlignment = VerticalAlignment.Center; System.Windows.Point Point1 = new System.Windows.Point(x, y); System.Windows.Point Point2 = new System.Windows.Point(x + (int)(square.Width), y); System.Windows.Point Point3 = new System.Windows.Point(x + (int)(square.Width), y + (int)(square.Width)); System.Windows.Point Point4 = new System.Windows.Point(x, y + (int)(square.Width)); PointCollection myPointCollection = new PointCollection(); myPointCollection.Add(Point1); myPointCollection.Add(Point2); myPointCollection.Add(Point3); myPointCollection.Add(Point4); myPolygon.Points = myPointCollection; ShapeCanvas.Children.Add(myPolygon); } public static int ArgumentCountFor(string className) { Type classType = GetShapeTypeOf(className); ConstructorInfo classConstructor = classType.GetConstructors().First(); return classConstructor.GetParameters().Length; } private static Type GetShapeTypeOf(string className) { return Assembly.GetAssembly(typeof(Shape)).GetTypes().Where(shapeType => shapeType.Name == className).First(); } public static Shape InstantiateWithArguments(string className, object[] args) { Type classType = GetShapeTypeOf(className); ConstructorInfo classConstructor = classType.GetConstructors().First(); return (Shape)classConstructor.Invoke(args); } private void PopulateClassList() { var classList = new List<string>(); var shapeType = typeof(Shape); foreach (Type type in Assembly.GetAssembly(shapeType).GetTypes()) { if (type.IsSubclassOf(shapeType) && !type.IsAbstract) { classList.Add(type.Name); } } ShapeType.ItemsSource = classList; } private void ShapeType_SelectionChanged(object sender, SelectionChangedEventArgs e) { string className = (String)ShapeType.SelectedValue; int ArgumentNumber = ArgumentCountFor(className); Argument1.IsEnabled = true; Argument2.IsEnabled = (ArgumentNumber > 1); Argument3.IsEnabled = (ArgumentNumber > 2); Argument1.Text = "0"; Argument2.Text = "0"; Argument3.Text = "0"; } private void Button_Click(object sender, RoutedEventArgs e) { string className = (String)ShapeType.SelectedValue; int ArgumentNumber = ArgumentCountFor(className); object[] potentialArgs = new object[] { Int32.Parse(Argument1.Text), Int32.Parse(Argument2.Text), Int32.Parse(Argument3.Text) }; Shape shape = InstantiateWithArguments(className, potentialArgs.Take(ArgumentNumber).ToArray()); shape.DrawOnto(ShapeCanvas, 50, 50); } } }
using UnityEngine; using System.Collections; using System; public class CChair_STT_Second : IState,IMessageObsever { static public CChair_STT_Second Instance; CChair_STT_Second() { Instance = this; } public void OnMessage (CMessages.eMessages m, object data) { if(m == CMessages.eMessages.ChairActive) { Debug.Log("STT_CChair_Second state is activated by chariActive and done its job."); } } public IEnumerator OnBegin () { yield return true; } public void OnUpdate () { } public IEnumerator OnExit () { yield return true; } public IEnumerator OnEnd () { yield return true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace damdrempe_zadaca_3.Sustav { class PodjelaEkrana { private static int BrojRedakaGore = 0; private static int BrojacLinija = 1; private const String ASCIIEscapeChar = "\x1B["; public PodjelaEkrana(int brojRedakaGore) { BrojRedakaGore = brojRedakaGore; Console.Clear(); } private void IzvrsiKontrolu(string nastavakKontrole) { Console.WriteLine($"\x1B[{nastavakKontrole}"); } private void IzvrsiKontroluKursorURedak(int redak) { IzvrsiKontrolu($"{redak};0H"); } private void IzvrsiKontroluBrisiGore() { IzvrsiKontrolu("1J"); } private void IzvrsiKontroluBrisiDolje() { IzvrsiKontrolu("J"); } public void Ispis(string redakTeksta) { IzvrsiKontroluKursorURedak(BrojacLinija); Console.WriteLine(redakTeksta); BrojacLinija++; if (BrojacLinija >= BrojRedakaGore + 1) { string unos; do { IzvrsiKontroluKursorURedak(BrojRedakaGore + 1); IzvrsiKontroluBrisiDolje(); IzvrsiKontroluKursorURedak(BrojRedakaGore + 1); for (int i = 0; i < 80; i++) { Console.Write("-"); } Console.WriteLine(); Console.WriteLine("Za nastavak pritisnite n/N"); unos = Console.ReadLine(); } while (unos != "N" && unos != "n"); IzvrsiKontroluKursorURedak(BrojacLinija); IzvrsiKontroluBrisiGore(); BrojacLinija = 1; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Collections.ObjectModel; using System.Windows.Data; using System.Globalization; using GeoSearch.CSWQueryServiceReference; using System.Windows.Browser; namespace GeoSearch.Pages { public partial class AdvancedSearchPage : UserControl { ObservableCollection<ResourceTypeTree> allResourceTypes = null; bool isNoResourceTypeSelected = true; bool isAllResourceTypeSelected = true; bool classifiedWithCategories = true; public AdvancedSearchPage() { InitializeComponent(); allResourceTypes = ResourceTypeTree.getResourceTypeList(); TreeView_ResourceType.ItemsSource = allResourceTypes; RetrieveNumber rn = new RetrieveNumber(); rn.TotalNumber = int.Parse(ConstantCollection.maxRecords); rn.firstNumber = int.Parse(ConstantCollection.firstTimeSearchNum); rn.regularNumber = ConstantCollection.eachInvokeSearchNum_ExceptFirstTime; Grid_RetrieveNumber.DataContext = rn; CheckBox_QueryQoS.IsChecked = ConstantCollection.isQueryServicePerformanceScore; if (CheckBox_QueryQoS.IsChecked == true) { CheckBox_QueryQoS_AtServerSide.IsEnabled = true; CheckBox_QueryQoS_AtClientSide.IsEnabled = true; } else { CheckBox_QueryQoS_AtServerSide.IsEnabled = false; CheckBox_QueryQoS_AtClientSide.IsEnabled = false; } if (ConstantCollection.queryServicePerformanceScoreAtServerSide) CheckBox_QueryQoS_AtServerSide.IsChecked = true; else CheckBox_QueryQoS_AtClientSide.IsChecked = true; CheckBox_CalculateRelevance.IsChecked = ConstantCollection.isCalculateRelevance; if (CheckBox_CalculateRelevance.IsChecked == true) { CheckBox_CalculateRelevance_AtServerSide.IsEnabled = true; CheckBox_CalculateRelevance_AtClientSide.IsEnabled = false; } else { CheckBox_CalculateRelevance_AtServerSide.IsEnabled = false; CheckBox_CalculateRelevance_AtClientSide.IsEnabled = false; } CheckBox_CalculateRelevance_AtServerSide.IsChecked = true; setContentHeightWidthToFixBrowserWindowSize(); App.Current.Host.Content.Resized += new EventHandler(content_Resized); } //设置Results_Container的高度 public void setContentHeightWidthToFixBrowserWindowSize() { double content_height = (double)HtmlPage.Window.Eval("document.documentElement.clientHeight"); double content_width = (double)HtmlPage.Window.Eval("document.documentElement.clientWidth"); if (content_height < 300) content_height = 300; if (content_width < 600) content_width = 600; ContentArea_ScrollViewer.Height = content_height - 200; } //改变Browser窗体大小时的事件 void content_Resized(object sender, EventArgs e) { setContentHeightWidthToFixBrowserWindowSize(); } private void LayoutRoot_BindingValidationError(object sender, ValidationErrorEventArgs e) { if (e.Action == ValidationErrorEventAction.Added) { (e.OriginalSource as Control).Background = new SolidColorBrush(Colors.Yellow); //tbMessage.Text = e.Error.Exception.Message; ToolTipService.SetToolTip((e.OriginalSource as TextBox), e.Error.Exception.Message); } if (e.Action == ValidationErrorEventAction.Removed) { (e.OriginalSource as Control).Background = new SolidColorBrush(Colors.White); //tbMessage.Text = ""; ToolTipService.SetToolTip((e.OriginalSource as TextBox), null); } } private ResourceType createResourceType(ResourceTypeTree resourceType) { ResourceType root = new ResourceType(); root.Name = resourceType.Name; root.isSelected = resourceType.isSelected; if (root.isSelected == true) isNoResourceTypeSelected = false; else isAllResourceTypeSelected = false; root.ResourceTypeID = resourceType.ResourceTypeID; if (resourceType.Children != null) { root.Children = new ObservableCollection<ResourceType>(); foreach (ResourceTypeTree rtt in resourceType.Children) { ResourceType rt = createResourceType(rtt); root.Children.Add(rt); } } return root; } private void Button_AdvancedSearch_Click(object sender, RoutedEventArgs e) { SearchingContent searchingContent = createSearchingContent(); setSearchConfig(); if (RecordsSearchFunctions.cannotStartSearchYet == false) { RecordsSearchFunctions.cannotStartSearchYet = true; RecordsSearchFunctions sf = new RecordsSearchFunctions(); sf.isResult_CategorizedInTabItems = classifiedWithCategories; sf.sortingRule = (ComboBox_SortBy.SelectedItem as ComboBoxItem).Content as string; if (ComboBox_SortBy.SelectedIndex != 0) { sf.sortingRule = ((ComboBoxItem)ComboBox_SortBy.SelectedItem).Content as string; } Button_AdvancedSearch.IsEnabled = false; List<string> catalogURLList = getSearchCatalogURLList(); sf.AdvancedSearch_Using_WCFService(searchingContent, ConstantCollection.startPosition, ConstantCollection.maxRecords, catalogURLList); } } private List<string> getSearchCatalogURLList() { List<string> catalogURLList = new List<string>(); if (CheckBox_RecordsHost_CLH.IsChecked == true) catalogURLList.Add(ConstantCollection.CLHCSWURLString); if (CheckBox_RecordsHost_GOS.IsChecked == true) catalogURLList.Add(ConstantCollection.GOSCSWURLString); if (CheckBox_RecordsHost_USGIN_AASG_CSW.IsChecked == true) catalogURLList.Add(ConstantCollection.USGIN_AASG_CSWURLString); if (catalogURLList.Count == 0) catalogURLList.Add(ConstantCollection.CLHCSWURLString); return catalogURLList; } private SearchingContent createSearchingContent() { SearchingContent searchingContent = new SearchingContent(); string wordsInFullText = AllOfTheWords_Content.Text; if (wordsInFullText != null && wordsInFullText.Trim() != "") { string[] listOfKeywords = wordsInFullText.Split(' '); searchingContent.wordsInAnyText = new System.Collections.ObjectModel.ObservableCollection<string>(listOfKeywords); } string ExactPhrase = ExactPhrase_Content.Text; if (ExactPhrase != null && ExactPhrase.Trim() != "") { searchingContent.exactPhrase = ExactPhrase; } string WithoutWords = WithoutWords_Content.Text; if (WithoutWords != null && WithoutWords.Trim() != "") { string[] listOfKeywords = WithoutWords.Split(' '); searchingContent.withoutWordsInAnytext = new System.Collections.ObjectModel.ObservableCollection<string>(listOfKeywords); } string WordsInAbstract = WordsInAbstract_Content.Text; if (WordsInAbstract != null && WordsInAbstract.Trim() != "") { string[] listOfKeywords = WordsInAbstract.Split(' '); searchingContent.wordsInAbstract = new System.Collections.ObjectModel.ObservableCollection<string>(listOfKeywords); } string WordsInTitle = WordsInTitle_Content.Text; if (WordsInTitle != null && WordsInTitle.Trim() != "") { string[] listOfKeywords = WordsInTitle.Split(' '); searchingContent.wordsInTitle = new System.Collections.ObjectModel.ObservableCollection<string>(listOfKeywords); } string WordsInKeywords = Keywords_Content.Text; if (WordsInKeywords != null && WordsInKeywords.Trim() != "") { string[] listOfKeywords = WordsInKeywords.Split(' '); searchingContent.Keywords = new System.Collections.ObjectModel.ObservableCollection<string>(listOfKeywords); } ResourceType root = new ResourceType(); root.Children = new ObservableCollection<ResourceType>(); foreach (ResourceTypeTree rt in allResourceTypes) { //ResourceType node = new ResourceType(); //root.Children.Add(node); //createResourceType(rt, node); ResourceType node = createResourceType(rt); root.Children.Add(node); } root.isSelected = isAllResourceTypeSelected; searchingContent.resourceTypesTree = root; searchingContent.isNoResourceTypeSelected = isNoResourceTypeSelected; string NorthString = text_NorthBound.Text; string WestString = text_WestBound.Text; string SouthString = text_SouthBound.Text; string EastString = text_EastBound.Text; try { double NorthValue = double.Parse(NorthString); double SouthValue = double.Parse(SouthString); double EastValue = double.Parse(EastString); double WestValue = double.Parse(WestString); if(NorthValue.Equals(90.0) && SouthValue.Equals(-90.0) && EastValue.Equals(180.0) && WestValue.Equals(-180.0)) searchingContent.where_isAnyWhere = true; else { searchingContent.where_isAnyWhere = false; ComboBoxItem cbi = (ComboBoxItem)ComboBox_WhereType.SelectedItem; string item = cbi.Content as string; if (item.Equals("encloses")) searchingContent.where_Relationship = "BBOX"; else if (item.Equals("intersects")) searchingContent.where_Relationship = "Intersects"; else if (item.Equals("is")) searchingContent.where_Relationship = "Equals"; else if (item.Equals("is fully outside of")) searchingContent.where_Relationship = "Disjoint"; else if (item.Equals("overlaps")) searchingContent.where_Relationship = "Overlaps"; searchingContent.where_North = text_NorthBound.Text; searchingContent.where_West = text_WestBound.Text; searchingContent.where_South = text_SouthBound.Text; searchingContent.where_East = text_EastBound.Text; } if (RadioButton_Time_Anytime.IsChecked == true) { searchingContent.when_isAnytime = true; } else { searchingContent.when_isAnytime = false; if (RadioButton_Time_MetadataChangeDate.IsChecked == true && datePicker_Time_MetadataChangeDate_From.SelectedDate != null && datePicker_Time_MetadataChangeDate_To.SelectedDate != null) { searchingContent.when_TimeType = "MetadataChangeDate"; DateTime dt_from = (DateTime)datePicker_Time_MetadataChangeDate_From.SelectedDate; DateTime dt_to = (DateTime)datePicker_Time_MetadataChangeDate_To.SelectedDate; if (dt_from != null) { string from_time = dt_from.ToString("yyyy-MM-dd"); searchingContent.when_FromTime = from_time + "T00:00:00"; } if (dt_to != null) { string to_time = dt_to.ToString("yyyy-MM-dd"); searchingContent.when_ToTime = to_time + "T23:59:59"; } } else if (RadioButton_Time_TemporalExtent.IsChecked == true && datePicker_Time_TemporalExtent_From.SelectedDate != null && datePicker_Time_TemporalExtent_To.SelectedDate != null) { searchingContent.when_TimeType = "TempExtent"; DateTime dt_from = (DateTime)datePicker_Time_TemporalExtent_From.SelectedDate; DateTime dt_to = (DateTime)datePicker_Time_TemporalExtent_To.SelectedDate; if (dt_from != null) { string from_time = dt_from.ToString("yyyy-MM-dd"); searchingContent.when_FromTime = from_time + "T00:00:00"; } if (dt_to != null) { string to_time = dt_to.ToString("yyyy-MM-dd"); searchingContent.when_ToTime = to_time + "T00:00:00"; } } } } catch(Exception e) { e.GetType().ToString(); searchingContent.where_isAnyWhere = true; } if (RadioButton_OnlyDataCore.IsChecked == true) searchingContent.resourceIdentificationKeywords_GEOSSDataCORE = ConstantCollection.resourceIdentificationKeywords_GEOSSDataCORE_ONLY; else if (RadioButton_NonDataCore.IsChecked == true) searchingContent.resourceIdentificationKeywords_GEOSSDataCORE = ConstantCollection.resourceIdentificationKeywords_GEOSSDataCORE_NON; else if (RadioButton_BothDataCoreAndNonDataCore.IsChecked == true) searchingContent.resourceIdentificationKeywords_GEOSSDataCORE = ConstantCollection.resourceIdentificationKeywords_GEOSSDataCORE_BOTH; return searchingContent; } private void setSearchConfig() { if (TextBox_MaximumRetrievalNumber.Text != null && (!TextBox_MaximumRetrievalNumber.Text.Equals(""))) { int value = int.Parse(TextBox_MaximumRetrievalNumber.Text); if (value <= RetrieveNumber.maximum_totalNumber && value >= RetrieveNumber.minimum_totalNumber) { ConstantCollection.maxRecords = value+""; } } if (TextBox_FirstRetrievalNumber.Text != null && (!TextBox_FirstRetrievalNumber.Text.Equals(""))) { int value = int.Parse(TextBox_FirstRetrievalNumber.Text); if (value <= RetrieveNumber.maximum_firstNumber && value >= RetrieveNumber.minimum_firstNumber) { ConstantCollection.firstTimeSearchNum = value + ""; } } if (TextBox_RegularRetrievalNumber.Text != null && (!TextBox_RegularRetrievalNumber.Text.Equals(""))) { int value = int.Parse(TextBox_RegularRetrievalNumber.Text); if (value <= RetrieveNumber.maximum_regularNumber && value >= RetrieveNumber.minimum_regularNumber) { ConstantCollection.eachInvokeSearchNum_ExceptFirstTime = value; } } ConstantCollection.isQueryServicePerformanceScore = (bool)CheckBox_QueryQoS.IsChecked; if (ConstantCollection.isQueryServicePerformanceScore) ConstantCollection.queryServicePerformanceScoreAtServerSide = (bool)CheckBox_QueryQoS_AtServerSide.IsChecked; ConstantCollection.isCalculateRelevance = (bool)CheckBox_CalculateRelevance.IsChecked; if (ConstantCollection.isCalculateRelevance) ConstantCollection.calculateRelevanceAtServerSide = (bool)CheckBox_CalculateRelevance_AtServerSide.IsChecked; } private void HyperlinkButton_BackToBasicSearch(object sender, RoutedEventArgs e) { App app = (App)Application.Current; MainPage mp = new MainPage(); mp.SearchContentTextBox.Text = getWhatToSearchString_NotAccurate(); App.Navigate(mp); //HtmlPage.Window.Invoke("HideBingMap"); } public string getWhatToSearchString_NotAccurate() { List<string> searchContentWordsList = new List<string>(); if (RecordsSearchFunctions.isContentSearchable(AllOfTheWords_Content.Text) == true) splitStringAndPutIntoList(' ', AllOfTheWords_Content.Text, searchContentWordsList); if (RecordsSearchFunctions.isContentSearchable(ExactPhrase_Content.Text) == true) searchContentWordsList.Add(ExactPhrase_Content.Text); if (RecordsSearchFunctions.isContentSearchable(WordsInTitle_Content.Text) == true) splitStringAndPutIntoList(' ', WordsInTitle_Content.Text, searchContentWordsList); if (RecordsSearchFunctions.isContentSearchable(WordsInAbstract_Content.Text) == true) splitStringAndPutIntoList(' ', WordsInAbstract_Content.Text, searchContentWordsList); if (RecordsSearchFunctions.isContentSearchable(Keywords_Content.Text) == true) splitStringAndPutIntoList(' ', Keywords_Content.Text, searchContentWordsList); if (RecordsSearchFunctions.isContentSearchable(WithoutWords_Content.Text) == true) splitStringAndRemoveSameOneFromList(' ', WithoutWords_Content.Text, searchContentWordsList); string content = ""; foreach (string word in searchContentWordsList) { content += word + " "; } content = content.TrimEnd().TrimStart(); return content; } private void splitStringAndPutIntoList(char identify, string stringToSplit, List<string> whereToPut) { string[] words = stringToSplit.Split(identify); for (int i = 0; i < words.Length; i++) { if ((!words[i].Trim().Equals("")) && (!whereToPut.Contains(words[i].Trim()))) whereToPut.Add(words[i].Trim()); } } private void splitStringAndRemoveSameOneFromList(char identify, string stringToSplit, List<string> listOfWords) { string[] words = stringToSplit.Split(identify); for (int i = 0; i < words.Length; i++) { if ((!words[i].Trim().Equals("")) && (listOfWords.Contains(words[i].Trim()))) listOfWords.Remove(words[i].Trim()); } } private void CheckBox_ResourceTypes_All_Click(object sender, RoutedEventArgs e) { CheckBox CheckBox_AllResourceTypes = (CheckBox)sender; if (CheckBox_AllResourceTypes.IsChecked == true) { foreach (TreeViewItem tvi in TreeView_ResourceType.GetContainers()) { ResourceTypeTree current = tvi.Header as ResourceTypeTree; if (current.isSelected != true) current.isSelected = true; if (current.Children != null && current.Children.Count > 0) { selecteAllChildItem(current); } } } else { foreach (TreeViewItem tvi in TreeView_ResourceType.GetContainers()) { ResourceTypeTree current = tvi.Header as ResourceTypeTree; if (current.isSelected != false) current.isSelected = false; if (current.Children != null && current.Children.Count > 0) { unSelecteAllChildItem(current); } } } } //private void OneOf_CheckBox_ResourceTypes_Click(object sender, RoutedEventArgs e) //{ // CheckBox OneOf_CheckBoxs_ResourceTypes = (CheckBox)sender; // if (OneOf_CheckBoxs_ResourceTypes.IsChecked == false) // CheckBox_ResourceTypes_All.IsChecked = false; // else // { // if(areAllResourceTypesSelected()) // CheckBox_ResourceTypes_All.IsChecked = true; // } //} //private bool areAllResourceTypesSelected() //{ // //if (CheckBox_ResourceTypes_Application.IsChecked == false) // // return false; // //if (CheckBox_ResourceTypes_Dataset.IsChecked == false) // // return false; // //if (CheckBox_ResourceTypes_Service.IsChecked == false) // // return false; // //if (CheckBox_ResourceTypes_Document.IsChecked == false) // // return false; // //if (CheckBox_ResourceTypes_Video.IsChecked == false) // // return false; // //if (CheckBox_ResourceTypes_Map.IsChecked == false) // // return false; // //if (CheckBox_ResourceTypes_Model.IsChecked == false) // // return false; // //if (CheckBox_ResourceTypes_CollectionSession.IsChecked == false) // // return false; // return true; //} private void datePickers_Time_GotFocus(object sender, RoutedEventArgs e) { DatePicker dp = sender as DatePicker; if (dp == datePicker_Time_MetadataChangeDate_From || dp == datePicker_Time_MetadataChangeDate_To) RadioButton_Time_MetadataChangeDate.IsChecked = true; else if (dp == datePicker_Time_TemporalExtent_From || dp == datePicker_Time_TemporalExtent_To) RadioButton_Time_TemporalExtent.IsChecked = true; } private void BBox_textbox_LostFocus(object sender, RoutedEventArgs e) { double north = 90.0000; double south = -90.0000; double west = -180.0000; double east = 180.0000; bool isTextBoxInpurError_North = false; bool isTextBoxInpurError_South = false; bool isTextBoxInpurError_West = false; bool isTextBoxInpurError_East = false; try { north = double.Parse(text_NorthBound.Text); } catch (Exception e1) { e1.GetType(); isTextBoxInpurError_North = true; } try { south = double.Parse(text_SouthBound.Text); } catch (Exception e1) { e1.GetType(); isTextBoxInpurError_South = true; } try { west = double.Parse(text_WestBound.Text); } catch (Exception e1) { e1.GetType(); isTextBoxInpurError_West = true; } try { east = double.Parse(text_EastBound.Text); } catch (Exception e1) { e1.GetType(); isTextBoxInpurError_East = true; } if (north > 90.0 || isTextBoxInpurError_North) { text_NorthBound.Text = "90.0000"; north = 90.0000; } if (south < -90.0 || isTextBoxInpurError_South) { text_SouthBound.Text = "-90.0000"; south = -90.0000; } if (west < -180.0 || isTextBoxInpurError_West) { text_WestBound.Text = "-180.0000"; west = -180.0000; } if (east > 180.0 || isTextBoxInpurError_East) { text_EastBound.Text = "180.0000"; east = 180.0000; } Thickness margin = new Thickness(); { double right = (180.0 - east) / 360.0 * 500.0; margin.Right = right; double left = (180.0 + west) / 360.0 * 500.0; margin.Left = left; double top = (90.0 - north) / 180.0 * 250.0; margin.Top = top; double bottom = (90.0 + south) / 180.0 * 250.0; margin.Bottom = bottom; } double height = 250; { height = (north - south) / 180 * 250.0; } double width = 250; { width = (east - west) / 360.0 * 500.0; } border_ExtentBBox.Margin = margin; border_ExtentBBox.Height = height; border_ExtentBBox.Width = width; border_ExtentBBox1.Margin = margin; border_ExtentBBox1.Height = height; border_ExtentBBox1.Width = width; } private void CheckBox_Checked(object sender, RoutedEventArgs e) { CheckBox button = sender as CheckBox; button.IsChecked = true; ResourceTypeTree resourceType = button.DataContext as ResourceTypeTree; if (resourceType != null) { if (resourceType.isSelected != true) resourceType.isSelected = true; if (TreeView_ResourceType.GetSelectedContainer() != null) { TreeViewItem tvi = TreeView_ResourceType.GetSelectedContainer(); ResourceTypeTree current = tvi.Header as ResourceTypeTree; if (current == resourceType) { if (resourceType.Children != null && resourceType.Children.Count > 0) { selecteAllChildItem(resourceType); } } } //if all child treeViemItem of Parent treeviewItem of current treeviewItem are select, the parent should be selected if (resourceType.Parent != null) { if (resourceType.Parent.ResourceTypeID != ConstantCollection.resourceType_PickID_All) resourceType.Parent.isSelected = true; bool allSelect = true; foreach (ResourceTypeTree type1 in resourceType.Parent.Children) { if (type1.isSelected != true) allSelect = false; } if (allSelect == true) { resourceType.Parent.isSelected = true; } } bool allSelect1 = true; foreach (ResourceTypeTree rt in allResourceTypes) { if (rt.isSelected == false) allSelect1 = false; } if(allSelect1) CheckBox_ResourceTypes_All.IsChecked = true; } ObservableCollection<ResourceTypeTree> a = TreeView_ResourceType.ItemsSource as ObservableCollection<ResourceTypeTree>; } void selecteAllChildItem(ResourceTypeTree resourceType) { if (resourceType.Children != null && resourceType.Children.Count > 0) { foreach (ResourceTypeTree type1 in resourceType.Children) { if (type1.isSelected != true) type1.isSelected = true; if (type1.Children != null && type1.Children.Count > 0) { selecteAllChildItem(type1); } } } } private void Checkbox_Unchecked(object sender, RoutedEventArgs e) { CheckBox button = sender as CheckBox; button.IsChecked = false; ResourceTypeTree resourceType = button.DataContext as ResourceTypeTree; if (resourceType != null) { if (resourceType.isSelected != false) resourceType.isSelected = false; //just unselect all the child treeviewItem of current selected treeviewItem, and the root treeViewItem "All" if (TreeView_ResourceType.GetSelectedContainer()!= null) { CheckBox_ResourceTypes_All.IsChecked = false; foreach (ResourceTypeTree r in allResourceTypes) { if (r.ResourceTypeID.Equals(ConstantCollection.resourceType_PickID_All)) r.isSelected = false; } TreeViewItem tvi = TreeView_ResourceType.GetSelectedContainer(); ResourceTypeTree current = tvi.Header as ResourceTypeTree; if (current == resourceType) { if (resourceType.Children != null && resourceType.Children.Count > 0) { unSelecteAllChildItem(resourceType); } } } //if (resourceType.ParentResourceType != null) //{ // resourceType.ParentResourceType.isSelected = false; // unSelecteAllAncestorItem(resourceType.ParentResourceType); //} //if all child treeViemItem of Parent treeviewItem of current treeviewItem are unselect, the parent should be unselected if (resourceType.Parent != null) { bool allUnSelect = true; foreach (ResourceTypeTree type1 in resourceType.Parent.Children) { if (type1.isSelected != false) allUnSelect = false; } if (allUnSelect == true) { resourceType.Parent.isSelected = false; } } } ObservableCollection<ResourceTypeTree> a = TreeView_ResourceType.ItemsSource as ObservableCollection<ResourceTypeTree>; } void unSelecteAllChildItem(ResourceTypeTree resourceType) { if (resourceType.Children != null && resourceType.Children.Count > 0) { foreach (ResourceTypeTree type1 in resourceType.Children) { if (type1.isSelected != false) type1.isSelected = false; if (type1.Children != null && type1.Children.Count > 0) { unSelecteAllChildItem(type1); } } } } void unSelecteAllAncestorItem(ResourceTypeTree resourceType) { if (resourceType.Parent != null) { resourceType.Parent.isSelected = false; unSelecteAllAncestorItem(resourceType.Parent); } } private void expander_ResourceType_Expanded(object sender, RoutedEventArgs e) { Dispatcher.BeginInvoke(() => { TreeView_ResourceType.ExpandToDepth(1); }); } private void CheckBox_ClassifiedWithResourceTypes_Click(object sender, RoutedEventArgs e) { CheckBox CheckBox_ClassifiedWithResourceTypes = (CheckBox)sender; if (CheckBox_ClassifiedWithResourceTypes.IsChecked == true) classifiedWithCategories = true; else classifiedWithCategories = false; } private void CheckBox_QueryQoS_Click(object sender, RoutedEventArgs e) { CheckBox CheckBox_QueryQoS = (CheckBox)sender; if (CheckBox_QueryQoS.IsChecked == true) { CheckBox_QueryQoS_AtServerSide.IsEnabled = true; CheckBox_QueryQoS_AtClientSide.IsEnabled = true; } else { CheckBox_QueryQoS_AtServerSide.IsEnabled = false; CheckBox_QueryQoS_AtClientSide.IsEnabled = false; } } private void CheckBox_CalculateRelevance_Click(object sender, RoutedEventArgs e) { CheckBox CheckBox_CalculateRelevance = (CheckBox)sender; if (CheckBox_CalculateRelevance.IsChecked == true) { CheckBox_CalculateRelevance_AtServerSide.IsEnabled = true; CheckBox_CalculateRelevance_AtClientSide.IsEnabled = false; } else { CheckBox_CalculateRelevance_AtServerSide.IsEnabled = false; CheckBox_CalculateRelevance_AtClientSide.IsEnabled = false; } } //private void isNoResourceTypeSelected(ResourceTypeTree tree, Boolean isNothingSelected) //{ // if (tree.isSelected) // { // isNothingSelected = false; // return; // } // else if(tree.Children != null) // { // foreach(ResourceTypeTree tree1 in tree.Children) // { // isNoResourceTypeSelected(tree1, isNothingSelected); // } // } //} } }
using System; using System.Runtime.InteropServices; namespace Vlc.DotNet.Core.Interops.Signatures { /// <summary> /// Get media descriptor's elementary streams description. /// </summary> [LibVlcFunction("libvlc_media_tracks_get")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate uint GetMediaTracks(IntPtr mediaInstance, out IntPtr tracksPointerArray); /// <summary> /// Release media descriptor's elementary streams description array. /// </summary> [LibVlcFunction("libvlc_media_tracks_release")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void ReleaseMediaTracks(IntPtr tracksPointerArray, uint tracksCount); }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class MainMenu : MonoBehaviour { private RectTransform rectTransSetting; private GameObject settingGO, musicGO; private int settingCount = 0, musicCount = 0; public Sprite[] music; private void Start() { settingGO = GameObject.FindGameObjectWithTag("Setting"); musicGO = GameObject.FindGameObjectWithTag("Music"); rectTransSetting = settingGO.GetComponent<RectTransform>(); musicGO.GetComponent<Image>().sprite = music[0]; } public void PlayGame() { SceneManager.LoadScene(1); } public void settingBtnAmin() { if (settingCount % 2 == 0) rectTransSetting.anchoredPosition = new Vector3(rectTransSetting.anchoredPosition.x, 960f, 0f); else rectTransSetting.anchoredPosition = new Vector3(rectTransSetting.anchoredPosition.x, 1150f, 0f); settingCount++; } public void MusicBtn() { if (musicCount == 0) { musicGO.GetComponent<Image>().sprite = music[1]; musicCount = 1; AudioListener.volume = 0f; } else { musicGO.GetComponent<Image>().sprite = music[0]; musicCount = 0; AudioListener.volume = 0.25f; } } }
using DataAccess.Abstract; using Entities.Concreate; using Core.DataAccess.EntityFramework; namespace DataAccess.Concreate.EntityFramework { public class EfBrandDal : EfEntityRepositoryBase<Brand, ReCapContext>, IBrandDal { //Artık bunlar EfEntityRepositoryBase'deki IEntitiyRepository den gelecek artık. //public void Add(Brand entity) //{ // using (ReCapContext context = new ReCapContext()) // { // var addedBrand = context.Entry(entity); // addedBrand.State = EntityState.Added; // context.SaveChanges(); //} //public void Delete(Brand entity) //{ // using (ReCapContext context = new ReCapContext()) // { // var deletedBrand = context.Entry(entity); // deletedBrand.State = EntityState.Deleted; // context.SaveChanges(); // } //} //public List<Brand> GetAll(Expression<Func<Brand, bool>> filter = null) //{ // using (ReCapContext context = new ReCapContext()) // { // return filter == null ? context.Set<Brand>().ToList() : context.Set<Brand>().Where(filter).ToList(); // } //} //public Brand GetById(Expression<Func<Brand, bool>> filter) //{ // using (ReCapContext context = new ReCapContext()) // { // return context.Set<Brand>().SingleOrDefault(filter); // } //} //public void Update(Brand entity) //{ // using (ReCapContext context = new ReCapContext()) // { // var updatedBrand = context.Entry(entity); // updatedBrand.State = EntityState.Modified; // context.SaveChanges(); // } //} } }
using Ezconet.GerenciamentoProjetos.Domain.Contracts.Repositories; using Ezconet.GerenciamentoProjetos.Domain.Contracts.Services; using Ezconet.GerenciamentoProjetos.Domain.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Moq; using Ezconet.GerenciamentoProjetos.Domain.Entities; using Ezconet.GerenciamentoProjetos.Domain.ValueObjects; using Ezconet.GerenciamentoProjetos.Domain.Tests.Mocks; namespace Ezconet.GerenciamentoProjetos.Domain.Tests.Services { [TestClass] public sealed class SolicitacaoDomainServiceTest { private ISolicitacaoDomainService _solicitacaoDomainService; private ISolicitacaoRepository _solicitacaoRepository; private Mock<IUsuarioRepository> _usuarioRepositoryMock; private UsuarioEntity _usuario; private SolicitacaoEntity _solicitacao; [TestInitialize] public void Initialize() { _solicitacaoRepository = new SolicitacaoRepositoryMock(); _usuarioRepositoryMock = new Mock<IUsuarioRepository>(); _solicitacaoDomainService = new SolicitacaoDomainService( _solicitacaoRepository, _usuarioRepositoryMock.Object); _usuario = new UsuarioEntity("Nome1", "login@1"); typeof(UsuarioEntity) .GetProperty("Codigo") .SetValue(_usuario, 10); _solicitacao = new SolicitacaoEntity( "Nome", SolicitacaoObjetivoValueObject.AumentoVendas, "Descricao", _usuario, "Área"); } [TestMethod] public void QuandoEuCadastrarUmaSolicitacao() { //arrange _usuarioRepositoryMock .Setup(x => x.GetByCodigo(_usuario.Codigo)) .Returns(_usuario); //act _solicitacaoDomainService.Cadastrar(_solicitacao); //assert } [TestMethod] [ExpectedException(typeof(ApplicationException))] public void QuandoEuCadastrarUmaSolicitacaoGarantirUsuarioCadastrado() { //arrange //act _solicitacaoDomainService .Cadastrar(_solicitacao); //assert } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public static class SoundManager { public enum Sound { alerta, gas, puas, PlayerMove, atqShaman, bonk, crack, explosion, bossTheme, woods, mainTheme, powerBall, Proellum, rockCrack, sword, victory, wound, } private static Dictionary<Sound, float> soundTimerDictionary; private static GameObject oneShotGameObject; private static AudioSource oneShotAudioSource; public static void Initialize() { soundTimerDictionary = new Dictionary<Sound, float>(); soundTimerDictionary[Sound.PlayerMove] = 0f; } public static void PlaySound(Sound sound, Vector3 position) { if (CanPlaySound(sound)) { GameObject soundGameObject = new GameObject("Sound"); soundGameObject.transform.position = position; AudioSource audioSource = soundGameObject.AddComponent<AudioSource>(); audioSource.clip = GetAudioClip(sound); audioSource.maxDistance = 100f; audioSource.spatialBlend = 1f; audioSource.rolloffMode = AudioRolloffMode.Linear; audioSource.dopplerLevel = 0f; audioSource.Play(); Object.Destroy(soundGameObject, audioSource.clip.length); } } public static void PlaySound(Sound sound) { if (CanPlaySound(sound)) { if (oneShotGameObject == null) { oneShotGameObject = new GameObject("One Shot Sound"); oneShotAudioSource = oneShotGameObject.AddComponent<AudioSource>(); } oneShotAudioSource.PlayOneShot(GetAudioClip(sound)); } } private static bool CanPlaySound(Sound sound) { switch (sound) { default: return true; case Sound.PlayerMove: if (soundTimerDictionary.ContainsKey(sound)) { float lastTimePlayed = soundTimerDictionary[sound]; float playerMoveTimerMax = 2.0f; if (lastTimePlayed + playerMoveTimerMax < Time.time) { soundTimerDictionary[sound] = Time.time; return true; } else { return false; } } else { return true; } //break; } } private static AudioClip GetAudioClip(Sound sound) { foreach (GameAssets.SoundAudioClip soundAudioClip in GameAssets.i.soundAudioClipArray) { if (soundAudioClip.sound == sound) { return soundAudioClip.audioClip; } } Debug.LogError("Sound " + sound + " not found!"); return null; } }
namespace Fuzzing.Tests.TestTypes { public class TestClassImplementsGenericInterface : ITestGenericInterface<string> { public string Property { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ProyectoPP.Models { public class HUConIdSeparado { [Display(Name = "Tipo de requerimiento")] [Required(ErrorMessage = "Campo requerido")] public string tipoDeRequerimiento { get; set; } [Display(Name = "Módulo")] [Required(ErrorMessage = "Campo requerido")] public string modulo { get; set; } [Display(Name = "Número de sprint")] [Required(ErrorMessage = "Campo requerido")] public string numSprint { get; set; } [Display(Name = "Número de H.U.")] [Required(ErrorMessage = "Campo requerido")] public string numHU { get; set; } [Display(Name = "Rol")] [Required(ErrorMessage = "Campo requerido")] public string rol { get; set; } [Display(Name = "Funcionalidad")] [Required(ErrorMessage = "Campo requerido")] public string funcionalidad { get; set; } [Display(Name = "Resultado")] [Required(ErrorMessage = "Campo requerido")] public string resultado { get; set; } [Display(Name = "Prioridad")] [Required(ErrorMessage = "Campo requerido")] public int prioridad { get; set; } [Display(Name = "Estimación")] [Required(ErrorMessage = "Campo requerido")] public int estimacion { get; set; } [Display(Name = "Nombre del Proyecto")] [Required(ErrorMessage = "Campo requerido")] public string proyectoId { get; set; } [Display(Name = "Número de escenario")] [Required(ErrorMessage = "Campo requerido")] public int NumeroEscenario { get; set; } [Display(Name = "Sprint Id")] [Required(ErrorMessage = "Campo requerido")] public string id { get; set; } } }
using FluentAssertions; using MicroSqlBulk.Attributes; using MicroSqlBulk.Helper; using NUnit.Framework; using System; namespace MicroSqlBulk.Test.Script { public class ScriptTest { [SetUp] public void SetUp() { } [Test] public void ShouldBeReturnedTheTempTableCreationScript() { TableHelper .GenerateLocalTempTableScript<TableDummy>() .Should() .Be( @"CREATE TABLE #TABLE_DUMMY_TEMP ( ID BIGINT NOT NULL, DESCRIPTION NVARCHAR(MAX), DATE DATETIME NOT NULL, FLAG BIT NOT NULL, MONEY DECIMAL(18,0) NOT NULL, Status INT NOT NULL ) "); } } [Table("TABLE_DUMMY")] public class TableDummy { [Column("ID", true)] public int Id { get; set; } [Column("DESCRIPTION")] public string Description { get; set; } [Column("DATE")] public DateTime Date { get; set; } [Column("FLAG")] public bool Flag { get; set; } [Column("MONEY")] public decimal Money { get; set; } [Column("Status")] public Status Status { get; set; } } public enum Status { Pending = 0, Active = 1, Inactive = 2, Deleted = 3 } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using starteAlkemy.Controllers; using starteAlkemy.Models; using starteAlkemy.Models.ViewModels; using starteAlkemy.Repository.IRepository; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; namespace Starte.UnitTest { [TestClass] public class TestControllerProject { [TestMethod] public void TestValidProjectDelete() { ProjectController _Controller = new ProjectController(); ProjectViewModel model = new ProjectViewModel(); model.Id = 1; model.TitleProject = "Projecto1"; model.ContentProject = "Contenido 1"; model.DescProject = "descripcion"; model.ProjectAddedDate = DateTime.Now; model.Active = true; ViewResult view = (ViewResult)_Controller.ConfirmDelete(model.Id); Assert.IsNotNull(view); Assert.AreEqual(model.TitleProject, "Project1"); } [TestMethod] public void TestInvalidProjectDelete() { ProjectController _Controller = new ProjectController(); ProjectViewModel model = new ProjectViewModel(); model.Id = 100; model.TitleProject = "Projecto100"; model.ContentProject = "Contenido 100"; model.DescProject = "descripcion100"; model.ProjectAddedDate = DateTime.Now; model.Active = true; ViewResult view = (ViewResult)_Controller.ConfirmDelete(model.Id); Assert.AreEqual(model.Id, "100"); } [TestMethod] public void TestDetails() { int id = 2; Boolean bTestSuccess = false; string sMessage = ""; ProjectController Controller = new ProjectController(); ActionResult result = Controller.Details(id); var actResult = (RedirectResult)result; id = 0; // User Added successfully if (actResult.Url.StartsWith("/Details?id=")) { // We remove the URL and pull the ID for the new user we just created string sURL = actResult.Url.Replace("/Details?id=", ""); id = Convert.ToInt32(sURL); // If the user ID not 0 if (id != 0) { bTestSuccess = true; sMessage = "Project Details ok"; } else { // If UserId is 0 something went wrong and the User didn't save ok, // So the test fails. bTestSuccess = false; sMessage = "Project Details failed"; } } else { // If the result URL is Save user string sURL = actResult.Url.Replace("/Details?message=", ""); // The test has passed if this code is hit. bTestSuccess = true; sMessage = ""; } // Test fails if bTestSuccess is false; Assert.IsTrue(bTestSuccess, sMessage); } [TestMethod] public void TestGetAll() { } [TestMethod] public void IsValidModelCreateProject() { //arrange ProjectController projectController = new ProjectController(); ProjectViewModel model = new ProjectViewModel(); //Act ViewResult result = projectController.Create(model) as ViewResult; //Assert Assert.IsNull(result); } [TestMethod] public void DetallesArrojaUnError() { // Preparación Exception expectedException = null; ProjectController projectController = new ProjectController(); ProjectViewModel model = new ProjectViewModel(); // Prueba try { projectController.ListProjectToCRUD(); } catch (Exception ex) { expectedException = ex; Assert.Fail("Un error debió ser arrojado"); } // Verificación // Assert.IsTrue(expectedException is ApplicationException); Assert.IsNotNull(expectedException.Message); } [TestMethod] public void LoadProjectPartialGet() { ProjectController projectController = new ProjectController(); ViewResult view = (ViewResult)projectController.PartialImagesGet(); Assert.AreEqual(view,"PartialImagesGet" ); } public void LoadProjectPartialPost() { ProjectViewModel model = new ProjectViewModel(); ProjectController projectController = new ProjectController(); ViewResult view = (ViewResult)projectController.PartialImagesPost(model.link); Assert.IsNotNull(view); } [TestMethod] public void DeleteProjectTest() { int id = 2; Boolean bTestSuccess = false; string sMessage = ""; ProjectController Controller = new ProjectController(); ActionResult result = Controller.Delete(id); var actResult = (RedirectResult)result; id = 0; // User Added successfully if (actResult.Url.StartsWith("/Delete?id=")) { // We remove the URL and pull the ID for the new user we just created string sURL = actResult.Url.Replace("/Delete?id=", ""); id = Convert.ToInt32(sURL); // If the user ID not 0 if (id != 0) { bTestSuccess = true; sMessage = "Project Delete ok"; } else { // If UserId is 0 something went wrong and the User didn't save ok, // So the test fails. bTestSuccess = false; sMessage = "Project Delete failed"; } } else { // If the result URL is Save user string sURL = actResult.Url.Replace("/Delete?message=", ""); // The test has passed if this code is hit. bTestSuccess = true; sMessage = ""; } // Test fails if bTestSuccess is false; Assert.IsTrue(bTestSuccess, sMessage); } } }
using UnityEngine; using UnityEditor; using UnityEngine.XR.WSA.Input; using System.Collections.Generic; using System.Linq; namespace MileCode { public class LBP_Layout : EditorWindow { //static string LBPFolder = "Assets/MilesWorkshop/Prefabs/LBP/"; static Shader LBPShader; [MenuItem("Lightmap/LBP/Layout")] public static void LayOutGameObject() { LBPShader = Shader.Find("MileShader/LightBakedPrefab"); if(LBPShader == null) { Debug.LogError("LBP Shader can't be found!"); return; } FetchGameObjects(); } static void FetchGameObjects() { GameObject[] gameObjects = GameObject.FindGameObjectsWithTag("LBP"); if(gameObjects.Length <= 0) { Debug.Log("Can't find gameObjects with the tag(LBP)"); return; } else { Debug.LogWarning(gameObjects.Length + " LBP Tags."); } int LayoutNumber = GetLayoutBaseNumber(gameObjects); AllInPosition(gameObjects, LayoutNumber); } static void AllInPosition(GameObject[] gos, int LayoutNumber) { Queue<GameObject> GoQueue = new Queue<GameObject>(gos); if(LayoutNumber == 1) { // don't have to layout if there's only one object return; } else { int row = 40; int column = 40; for(int i = 0; i < LayoutNumber; i++) { for(int j = 0; j < LayoutNumber; j++) { if(GoQueue.Count >= 1) { GameObject go = GoQueue.Dequeue(); go.transform.position = new Vector3(i * column, 0, j * row); } else { return; } } } } } static int GetLayoutBaseNumber(GameObject[] gos) { float num = Mathf.Sqrt(gos.Length); int layoutBaseNumber; if(num == (int)num) { layoutBaseNumber = (int)num; } else { layoutBaseNumber = (int)Mathf.Ceil(num); } //Debug.Log(layoutBaseNumber); return layoutBaseNumber; } } }
//------------------------------------------------------------------------------------------------------------------ // Volumetric Fog & Mist // Created by Ramiro Oliva (Kronnect) //------------------------------------------------------------------------------------------------------------------ using UnityEngine; using UnityEngine.Rendering; #if UNITY_EDITOR using UnityEditor; #endif using System; using System.Collections; using System.Collections.Generic; #if GAIA_PRESENT using Gaia; #endif namespace VolumetricFogAndMist { public enum FOG_PRESET { Clear = 0, Mist = 10, WindyMist = 11, LowClouds = 20, SeaClouds = 21, GroundFog = 30, FrostedGround = 31, FoggyLake = 32, Fog = 41, HeavyFog = 42, SandStorm1 = 50, Smoke = 51, ToxicSwamp = 52, SandStorm2 = 53, WorldEdge = 200, Custom = 1000 } public enum SPSR_BEHAVIOUR { AutoDetectInEditor = 0, ForcedOn = 1, ForcedOff = 2 } public enum TRANSPARENT_MODE { None = 0, Blend = 1 } public enum COMPUTE_DEPTH_SCOPE { OnlyTreeBillboards = 0, EverythingInLayer = 1, TreeBillboardsAndTransparentObjects = 2 } public enum LIGHTING_MODEL { Classic = 0, Natural = 1, SingleLight = 2 } public enum SUN_SHADOWS_BAKE_MODE { Realtime = 0, Discrete = 1 } public enum FOG_VOID_TOPOLOGY { Sphere = 0, Box = 1 } public enum FOG_AREA_TOPOLOGY { Sphere = 1, Box = 2 } public enum FOG_AREA_SORTING_MODE { DistanceToCamera = 0, Altitude = 1, Fixed = 2 } public enum FOG_AREA_FOLLOW_MODE { FullXYZ = 0, RestrictToXZPlane = 1 } public enum FOG_VISIBILITY_SCOPE { Global = 0, Volume = 1 } public struct FOG_TEMPORARY_PROPERTIES { public Color color; public float density; } [ExecuteInEditMode] [AddComponentMenu("Image Effects/Rendering/Volumetric Fog & Mist")] [HelpURL("http://kronnect.com/taptapgo")] public partial class VolumetricFog : MonoBehaviour { public const string SKW_FOG_DISTANCE_ON = "FOG_DISTANCE_ON"; public const string SKW_LIGHT_SCATTERING = "FOG_SCATTERING_ON"; public const string SKW_FOG_AREA_BOX = "FOG_AREA_BOX"; public const string SKW_FOG_AREA_SPHERE = "FOG_AREA_SPHERE"; public const string SKW_FOG_VOID_BOX = "FOG_VOID_BOX"; public const string SKW_FOG_VOID_SPHERE = "FOG_VOID_SPHERE"; public const string SKW_FOG_HAZE_ON = "FOG_HAZE_ON"; public const string SKW_FOG_OF_WAR_ON = "FOG_OF_WAR_ON"; public const string SKW_FOG_BLUR = "FOG_BLUR_ON"; public const string SKW_SUN_SHADOWS = "FOG_SUN_SHADOWS_ON"; public const string SKW_FOG_USE_XY_PLANE = "FOG_USE_XY_PLANE"; public const string SKW_FOG_COMPUTE_DEPTH = "FOG_COMPUTE_DEPTH"; public const string SKW_POINT_LIGHTS = "FOG_POINT_LIGHTS"; const string DEPTH_CAM_NAME = "VFMDepthCamera"; const string DEPTH_SUN_CAM_NAME = "VFMDepthSunCamera"; const string VFM_BUILD_FIRST_INSTALL = "VFMFirstInstall"; const string VFM_BUILD_HINT = "VFMBuildHint106RC2"; static VolumetricFog _fog; public static VolumetricFog instance { get { if (_fog == null) { if (Camera.main != null) _fog = Camera.main.GetComponent<VolumetricFog>(); if (_fog == null) { foreach (Camera camera in Camera.allCameras) { _fog = camera.GetComponent<VolumetricFog>(); if (_fog != null) break; } } } return _fog; } } [HideInInspector] public bool isDirty; #region General settings [SerializeField] FOG_PRESET _preset = FOG_PRESET.Mist; public FOG_PRESET preset { get { return _preset; } set { if (value != _preset) { _preset = value; UpdatePreset(); isDirty = true; } } } [SerializeField] VolumetricFogProfile _profile; public VolumetricFogProfile profile { get { return _profile; } set { if (value != _profile) { _profile = value; if (_profile != null) { _profile.Load(this); _preset = FOG_PRESET.Custom; } isDirty = true; } } } [SerializeField] bool _profileSync; public bool profileSync { get { return _profileSync; } set { if (value != _profileSync) { _profileSync = value; isDirty = true; } } } [SerializeField] bool _useFogVolumes = false; public bool useFogVolumes { get { return _useFogVolumes; } set { if (value != _useFogVolumes) { _useFogVolumes = value; isDirty = true; } } } [SerializeField] bool _debugPass = false; public bool debugDepthPass { get { return _debugPass; } set { if (value != _debugPass) { _debugPass = value; isDirty = true; } } } [SerializeField] bool _showInSceneView = true; public bool showInSceneView { get { return _showInSceneView; } set { if (value != _showInSceneView) { _showInSceneView = value; isDirty = true; } } } [SerializeField] TRANSPARENT_MODE _transparencyBlendMode = TRANSPARENT_MODE.None; public TRANSPARENT_MODE transparencyBlendMode { get { return _transparencyBlendMode; } set { if (value != _transparencyBlendMode) { _transparencyBlendMode = value; UpdateRenderComponents(); UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 1f)] float _transparencyBlendPower = 1.0f; public float transparencyBlendPower { get { return _transparencyBlendPower; } set { if (value != _transparencyBlendPower) { _transparencyBlendPower = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] LayerMask _transparencyLayerMask = -1; public LayerMask transparencyLayerMask { get { return _transparencyLayerMask; } set { if (_transparencyLayerMask != value) { _transparencyLayerMask = value; isDirty = true; } } } [SerializeField] FOG_VISIBILITY_SCOPE _visibilityScope = FOG_VISIBILITY_SCOPE.Global; public FOG_VISIBILITY_SCOPE visibilityScope { get { return _visibilityScope; } set { if (_visibilityScope != value) { _visibilityScope = value; isDirty = true; } } } [SerializeField] Bounds _visibilityVolume = new Bounds(Vector3.zero, new Vector3(1000, 1000, 1000)); public Bounds visibilityVolume { get { return _visibilityVolume; } set { if (_visibilityVolume != value) { _visibilityVolume = value; isDirty = true; } } } [SerializeField] LIGHTING_MODEL _lightingModel = LIGHTING_MODEL.Classic; public LIGHTING_MODEL lightingModel { get { return _lightingModel; } set { if (value != _lightingModel) { _lightingModel = value; UpdateMaterialProperties(); UpdateTexture(); isDirty = true; } } } [SerializeField] bool _enableMultipleCameras = false; public bool enableMultipleCameras { get { return _enableMultipleCameras; } set { if (value != _enableMultipleCameras) { _enableMultipleCameras = value; UpdateMultiCameraSetup(); isDirty = true; } } } [SerializeField] bool _computeDepth = false; public bool computeDepth { get { return _computeDepth; } set { if (value != _computeDepth) { _computeDepth = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] COMPUTE_DEPTH_SCOPE _computeDepthScope = COMPUTE_DEPTH_SCOPE.OnlyTreeBillboards; public COMPUTE_DEPTH_SCOPE computeDepthScope { get { return _computeDepthScope; } set { if (value != _computeDepthScope) { _computeDepthScope = value; if (_computeDepthScope == COMPUTE_DEPTH_SCOPE.TreeBillboardsAndTransparentObjects) { _transparencyBlendMode = TRANSPARENT_MODE.None; } UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] float _transparencyCutOff = 0.1f; public float transparencyCutOff { get { return _transparencyCutOff; } set { if (value != _transparencyCutOff) { _transparencyCutOff = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] bool _renderBeforeTransparent; public bool renderBeforeTransparent { get { return _renderBeforeTransparent; } set { if (value != _renderBeforeTransparent) { _renderBeforeTransparent = value; if (_renderBeforeTransparent) { _transparencyBlendMode = TRANSPARENT_MODE.None; } UpdateRenderComponents(); UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] GameObject _sun; public GameObject sun { get { return _sun; } set { if (value != _sun) { _sun = value; UpdateSun(); isDirty = true; } } } [SerializeField, Range(0, 0.5f)] float _timeBetweenTextureUpdates = 0.2f; public float timeBetweenTextureUpdates { get { return _timeBetweenTextureUpdates; } set { if (value != _timeBetweenTextureUpdates) { _timeBetweenTextureUpdates = value; isDirty = true; } } } [SerializeField] bool _sunCopyColor = true; public bool sunCopyColor { get { return _sunCopyColor; } set { if (value != _sunCopyColor) { _sunCopyColor = value; UpdateMaterialProperties(); isDirty = true; } } } #endregion #region Fog Geometry settings [SerializeField, Range(0, 1.25f)] float _density = 1.0f; public float density { get { return _density; } set { if (value != _density) { _preset = FOG_PRESET.Custom; _density = value; UpdateMaterialProperties(); UpdateTextureAlpha(); UpdateTexture(); isDirty = true; } } } [SerializeField, Range(0, 1f)] float _noiseStrength = 0.8f; public float noiseStrength { get { return _noiseStrength; } set { if (value != _noiseStrength) { _preset = FOG_PRESET.Custom; _noiseStrength = value; UpdateMaterialProperties(); UpdateTextureAlpha(); UpdateTexture(); isDirty = true; } } } [SerializeField, Range(1f, 2f)] float _noiseFinalMultiplier = 1f; public float noiseFinalMultiplier { get { return _noiseFinalMultiplier; } set { if (value != _noiseFinalMultiplier) { _preset = FOG_PRESET.Custom; _noiseFinalMultiplier = value; UpdateMaterialProperties(); UpdateTextureAlpha(); UpdateTexture(); isDirty = true; } } } [SerializeField, Range(-0.3f, 2f)] float _noiseSparse; public float noiseSparse { get { return _noiseSparse; } set { if (value != _noiseSparse) { _preset = FOG_PRESET.Custom; _noiseSparse = value; UpdateMaterialProperties(); UpdateTextureAlpha(); UpdateTexture(); isDirty = true; } } } [SerializeField, Range(0, 1000f)] float _distance = 0f; public float distance { get { return _distance; } set { if (value != _distance) { _preset = FOG_PRESET.Custom; _distance = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] float _maxFogLength = 1000f; public float maxFogLength { get { return _maxFogLength; } set { if (value != _maxFogLength) { _maxFogLength = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 1f)] float _maxFogLengthFallOff = 0f; public float maxFogLengthFallOff { get { return _maxFogLengthFallOff; } set { if (value != _maxFogLengthFallOff) { _maxFogLengthFallOff = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 5f)] float _distanceFallOff = 0f; public float distanceFallOff { get { return _distanceFallOff; } set { if (value != _distanceFallOff) { _preset = FOG_PRESET.Custom; _distanceFallOff = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0.0001f, 500f)] float _height = 4.0f; public float height { get { return _height; } set { if (value != _height) { _preset = FOG_PRESET.Custom; _height = Mathf.Max(value, 0.0001f); UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 1f)] float _heightFallOff = 0.6f; public float heightFallOff { get { return _heightFallOff; } set { if (value != _heightFallOff) { _preset = FOG_PRESET.Custom; _heightFallOff = Mathf.Clamp01(value); UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] float _deepObscurance = 1f; public float deepObscurance { get { return _deepObscurance; } set { if (value != _deepObscurance && value >= 0) { _preset = FOG_PRESET.Custom; _deepObscurance = Mathf.Clamp01(value); UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] float _baselineHeight = 0f; public float baselineHeight { get { return _baselineHeight; } set { if (value != _baselineHeight) { _preset = FOG_PRESET.Custom; _baselineHeight = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] bool _baselineRelativeToCamera = false; public bool baselineRelativeToCamera { get { return _baselineRelativeToCamera; } set { if (value != _baselineRelativeToCamera) { _preset = FOG_PRESET.Custom; _baselineRelativeToCamera = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 1f)] float _baselineRelativeToCameraDelay = 0; public float baselineRelativeToCameraDelay { get { return _baselineRelativeToCameraDelay; } set { if (value != _baselineRelativeToCameraDelay) { _baselineRelativeToCameraDelay = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] float _noiseScale = 1; public float noiseScale { get { return _noiseScale; } set { if (value != _noiseScale && value >= 0.2f) { _preset = FOG_PRESET.Custom; _noiseScale = value; UpdateMaterialProperties(); isDirty = true; } } } #endregion #region Fog Style settings [SerializeField, Range(0, 1.05f)] float _alpha = 1.0f; public float alpha { get { return _alpha; } set { if (value != _alpha) { _preset = FOG_PRESET.Custom; _alpha = value; currentFogAlpha = _alpha; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] Color _color = new Color(0.89f, 0.89f, 0.89f, 1); public Color color { get { return _color; } set { if (value != _color) { _preset = FOG_PRESET.Custom; _color = value; currentFogColor = _color; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] Color _specularColor = new Color(1, 1, 0.8f, 1); public Color specularColor { get { return _specularColor; } set { if (value != _specularColor) { _preset = FOG_PRESET.Custom; _specularColor = value; currentFogSpecularColor = _specularColor; UpdateTexture(); UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 1f)] float _specularThreshold = 0.6f; public float specularThreshold { get { return _specularThreshold; } set { if (value != _specularThreshold) { _preset = FOG_PRESET.Custom; _specularThreshold = value; UpdateTexture(); isDirty = true; } } } [SerializeField, Range(0, 1f)] float _specularIntensity = 0.2f; public float specularIntensity { get { return _specularIntensity; } set { if (value != _specularIntensity) { _preset = FOG_PRESET.Custom; _specularIntensity = value; UpdateMaterialProperties(); UpdateTexture(); isDirty = true; } } } [SerializeField] Vector3 _lightDirection = new Vector3(1, 0, -1); public Vector3 lightDirection { get { return _lightDirection; } set { if (value != _lightDirection) { _preset = FOG_PRESET.Custom; _lightDirection = value; UpdateMaterialProperties(); UpdateTexture(); isDirty = true; } } } [SerializeField] float _lightIntensity = 0.2f; public float lightIntensity { get { return _lightIntensity; } set { if (value != _lightIntensity) { _preset = FOG_PRESET.Custom; _lightIntensity = value; UpdateMaterialProperties(); UpdateTexture(); isDirty = true; } } } [SerializeField] Color _lightColor = Color.white; public Color lightColor { get { return _lightColor; } set { if (value != _lightColor) { _preset = FOG_PRESET.Custom; _lightColor = value; currentLightColor = _lightColor; UpdateMaterialProperties(); UpdateTexture(); isDirty = true; } } } [SerializeField, Range(1, 5)] int _updateTextureSpread = 1; public int updateTextureSpread { get { return _updateTextureSpread; } set { if (value != _updateTextureSpread) { _updateTextureSpread = value; isDirty = true; } } } [SerializeField, Range(0, 1f)] float _speed = 0.01f; public float speed { get { return _speed; } set { if (value != _speed) { _preset = FOG_PRESET.Custom; _speed = value; if (!Application.isPlaying) UpdateWindSpeedQuick(); isDirty = true; } } } [SerializeField] Vector3 _windDirection = new Vector3(-1, 0, 0); public Vector3 windDirection { get { return _windDirection; } set { if (value != _windDirection) { _preset = FOG_PRESET.Custom; _windDirection = value.normalized; if (!Application.isPlaying) UpdateWindSpeedQuick(); isDirty = true; } } } [SerializeField] bool _useRealTime = false; public bool useRealTime { get { return _useRealTime; } set { if (value != _useRealTime) { _useRealTime = value; isDirty = true; } } } #endregion #region Sky Haze settings [SerializeField] Color _skyColor = new Color(0.89f, 0.89f, 0.89f, 1); public Color skyColor { get { return _skyColor; } set { if (value != _skyColor) { _preset = FOG_PRESET.Custom; _skyColor = value; ComputeLightColor(); UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] float _skyHaze = 50.0f; public float skyHaze { get { return _skyHaze; } set { if (value != _skyHaze) { _preset = FOG_PRESET.Custom; _skyHaze = value; if (!Application.isPlaying) UpdateWindSpeedQuick(); isDirty = true; } } } [SerializeField] float _skyNoiseScale = 1.5f; public float skyNoiseScale { get { return _skyNoiseScale; } set { if (value != _skyNoiseScale) { _skyNoiseScale = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 1f)] float _skySpeed = 0.3f; public float skySpeed { get { return _skySpeed; } set { if (value != _skySpeed) { _preset = FOG_PRESET.Custom; _skySpeed = value; isDirty = true; } } } [SerializeField, Range(0, 1f)] float _skyNoiseStrength = 0.1f; public float skyNoiseStrength { get { return _skyNoiseStrength; } set { if (value != _skyNoiseStrength) { _preset = FOG_PRESET.Custom; _skyNoiseStrength = value; if (!Application.isPlaying) UpdateWindSpeedQuick(); isDirty = true; } } } [SerializeField, Range(0, 1f)] float _skyAlpha = 1.0f; public float skyAlpha { get { return _skyAlpha; } set { if (value != _skyAlpha) { _preset = FOG_PRESET.Custom; _skyAlpha = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 0.999f)] float _skyDepth = 0.999f; public float skyDepth { get { return _skyDepth; } set { if (value != _skyDepth) { _skyDepth = value; if (!Application.isPlaying) UpdateWindSpeedQuick(); isDirty = true; } } } #endregion #region Fog Void settings [SerializeField] GameObject _character; public GameObject character { get { return _character; } set { if (value != _character) { _character = value; isDirty = true; } } } [SerializeField] FOG_VOID_TOPOLOGY _fogVoidTopology = FOG_VOID_TOPOLOGY.Sphere; public FOG_VOID_TOPOLOGY fogVoidTopology { get { return _fogVoidTopology; } set { if (value != _fogVoidTopology) { _fogVoidTopology = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 10f)] float _fogVoidFallOff = 1.0f; public float fogVoidFallOff { get { return _fogVoidFallOff; } set { if (value != _fogVoidFallOff) { _preset = FOG_PRESET.Custom; _fogVoidFallOff = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] float _fogVoidRadius = 0.0f; public float fogVoidRadius { get { return _fogVoidRadius; } set { if (value != _fogVoidRadius) { _preset = FOG_PRESET.Custom; _fogVoidRadius = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] Vector3 _fogVoidPosition = Vector3.zero; public Vector3 fogVoidPosition { get { return _fogVoidPosition; } set { if (value != _fogVoidPosition) { _preset = FOG_PRESET.Custom; _fogVoidPosition = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] float _fogVoidDepth = 0.0f; public float fogVoidDepth { get { return _fogVoidDepth; } set { if (value != _fogVoidDepth) { _preset = FOG_PRESET.Custom; _fogVoidDepth = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] float _fogVoidHeight = 0.0f; public float fogVoidHeight { get { return _fogVoidHeight; } set { if (value != _fogVoidHeight) { _preset = FOG_PRESET.Custom; _fogVoidHeight = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] bool _fogVoidInverted = false; [Obsolete("Fog Void inverted is now deprecated. Use Fog Area settings.")] public bool fogVoidInverted { get { return _fogVoidInverted; } set { _fogVoidInverted = value; } } #endregion #region Fog Area settings [SerializeField] bool _fogAreaShowGizmos = true; public bool fogAreaShowGizmos { get { return _fogAreaShowGizmos; } set { if (value != _fogAreaShowGizmos) { _fogAreaShowGizmos = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] GameObject _fogAreaCenter; public GameObject fogAreaCenter { get { return _fogAreaCenter; } set { if (value != _fogAreaCenter) { _fogAreaCenter = value; isDirty = true; } } } [SerializeField, Range(0.001f, 10f)] float _fogAreaFallOff = 1.0f; public float fogAreaFallOff { get { return _fogAreaFallOff; } set { if (value != _fogAreaFallOff) { _fogAreaFallOff = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] FOG_AREA_FOLLOW_MODE _fogAreaFollowMode = FOG_AREA_FOLLOW_MODE.FullXYZ; public FOG_AREA_FOLLOW_MODE fogAreaFollowMode { get { return _fogAreaFollowMode; } set { if (value != _fogAreaFollowMode) { _fogAreaFollowMode = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] FOG_AREA_TOPOLOGY _fogAreaTopology = FOG_AREA_TOPOLOGY.Sphere; public FOG_AREA_TOPOLOGY fogAreaTopology { get { return _fogAreaTopology; } set { if (value != _fogAreaTopology) { _fogAreaTopology = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] float _fogAreaRadius = 0.0f; public float fogAreaRadius { get { return _fogAreaRadius; } set { if (value != _fogAreaRadius) { _fogAreaRadius = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] Vector3 _fogAreaPosition = Vector3.zero; public Vector3 fogAreaPosition { get { return _fogAreaPosition; } set { if (value != _fogAreaPosition) { _fogAreaPosition = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] float _fogAreaDepth = 0.0f; public float fogAreaDepth { get { return _fogAreaDepth; } set { if (value != _fogAreaDepth) { _fogAreaDepth = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] float _fogAreaHeight = 0.0f; public float fogAreaHeight { get { return _fogAreaHeight; } set { if (value != _fogAreaHeight) { _fogAreaHeight = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] FOG_AREA_SORTING_MODE _fogAreaSortingMode = FOG_AREA_SORTING_MODE.DistanceToCamera; public FOG_AREA_SORTING_MODE fogAreaSortingMode { get { return _fogAreaSortingMode; } set { if (value != _fogAreaSortingMode) { _fogAreaSortingMode = value; lastTimeSortInstances = 0; isDirty = true; } } } [SerializeField] int _fogAreaRenderOrder = 1; public int fogAreaRenderOrder { get { return _fogAreaRenderOrder; } set { if (value != _fogAreaRenderOrder) { _fogAreaRenderOrder = value; lastTimeSortInstances = 0; isDirty = true; } } } #endregion #region Point Light settings [Serializable] public struct PointLightParams { public Light light; [HideInInspector] public VolumetricFogLightParams lightParams; public float range; public float rangeMultiplier; public float intensity; public float intensityMultiplier; public Vector3 position; public Color color; } public PointLightParams[] pointLightParams; [SerializeField] bool pointLightDataMigrated; Vector4[] pointLightColorBuffer; Vector4[] pointLightPositionBuffer; [SerializeField] GameObject[] _pointLights = new GameObject[6]; [SerializeField] float[] _pointLightRanges = new float[6]; [SerializeField] float[] _pointLightIntensities = new float[6] { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; [SerializeField] float[] _pointLightIntensitiesMultiplier = new float[6] { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; [SerializeField] Vector3[] _pointLightPositions = new Vector3[6]; [SerializeField] Color[] _pointLightColors = new Color[6] { new Color(1, 1, 0, 1), new Color(1, 1, 0, 1), new Color(1, 1, 0, 1), new Color(1, 1, 0, 1), new Color(1, 1, 0, 1), new Color(1, 1, 0, 1) }; [SerializeField] bool _pointLightTrackingAuto = false; public bool pointLightTrackAuto { get { return _pointLightTrackingAuto; } set { if (value != _pointLightTrackingAuto) { _pointLightTrackingAuto = value; TrackPointLights(); isDirty = true; } } } [SerializeField] Transform _pointLightTrackingPivot; public Transform pointLightTrackingPivot { get { return _pointLightTrackingPivot; } set { if (value != _pointLightTrackingPivot) { _pointLightTrackingPivot = value; TrackPointLights(); isDirty = true; } } } [SerializeField] int _pointLightTrackingCount = 0; public int pointLightTrackingCount { get { return _pointLightTrackingCount; } set { if (value != _pointLightTrackingCount) { _pointLightTrackingCount = Mathf.Clamp(value, 0, MAX_POINT_LIGHTS); CheckPointLightData(); TrackPointLights(); isDirty = true; } } } [SerializeField, Range(0, 5f)] float _pointLightTrackingCheckInterval = 1f; public float pointLightTrackingCheckInterval { get { return _pointLightTrackingCheckInterval; } set { if (value != _pointLightTrackingCheckInterval) { _pointLightTrackingCheckInterval = value; TrackPointLights(); isDirty = true; } } } [SerializeField] float _pointLightTrackingNewLightsCheckInterval = 3f; public float pointLightTrackingNewLightsCheckInterval { get { return _pointLightTrackingNewLightsCheckInterval; } set { if (value != _pointLightTrackingNewLightsCheckInterval) { _pointLightTrackingNewLightsCheckInterval = value; TrackPointLights(); isDirty = true; } } } [SerializeField] float _pointLightInscattering = 1f; public float pointLightInscattering { get { return _pointLightInscattering; } set { if (value != _pointLightInscattering) { _pointLightInscattering = value; isDirty = true; } } } [SerializeField] float _pointLightIntensity = 1f; public float pointLightIntensity { get { return _pointLightIntensity; } set { if (value != _pointLightIntensity) { _pointLightIntensity = value; isDirty = true; } } } [SerializeField] float _pointLightInsideAtten = 0f; public float pointLightInsideAtten { get { return _pointLightInsideAtten; } set { if (value != _pointLightInsideAtten) { _pointLightInsideAtten = value; UpdateMaterialProperties(); isDirty = true; } } } #endregion #region Optimization settings [SerializeField, Range(1, 8)] int _downsampling = 1; public int downsampling { get { return _downsampling; } set { if (value != _downsampling) { _preset = FOG_PRESET.Custom; _downsampling = value; isDirty = true; } } } [SerializeField] bool _forceComposition = false; public bool forceComposition { get { return _forceComposition; } set { if (value != _forceComposition) { _preset = FOG_PRESET.Custom; _forceComposition = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] bool _edgeImprove = false; public bool edgeImprove { get { return _edgeImprove; } set { if (value != _edgeImprove) { _preset = FOG_PRESET.Custom; _edgeImprove = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0.00001f, 0.005f)] float _edgeThreshold = 0.0005f; public float edgeThreshold { get { return _edgeThreshold; } set { if (value != _edgeThreshold) { _preset = FOG_PRESET.Custom; _edgeThreshold = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(1, 20)] float _stepping = 12.0f; public float stepping { get { return _stepping; } set { if (value != _stepping) { _preset = FOG_PRESET.Custom; _stepping = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 50)] float _steppingNear = 1f; public float steppingNear { get { return _steppingNear; } set { if (value != _steppingNear) { _preset = FOG_PRESET.Custom; _steppingNear = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] bool _dithering = false; public bool dithering { get { return _dithering; } set { if (value != _dithering) { _dithering = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0.1f, 5f)] float _ditherStrength = 0.75f; public float ditherStrength { get { return _ditherStrength; } set { if (value != _ditherStrength) { _ditherStrength = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 2f)] float _jitterStrength = 0.5f; public float jitterStrength { get { return _jitterStrength; } set { if (value != _jitterStrength) { _jitterStrength = value; UpdateMaterialProperties(); isDirty = true; } } } #endregion #region Shafts settings [SerializeField] bool _lightScatteringEnabled = false; public bool lightScatteringEnabled { get { return _lightScatteringEnabled; } set { if (value != _lightScatteringEnabled) { _lightScatteringEnabled = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 1f)] float _lightScatteringDiffusion = 0.7f; public float lightScatteringDiffusion { get { return _lightScatteringDiffusion; } set { if (value != _lightScatteringDiffusion) { _lightScatteringDiffusion = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 1f)] float _lightScatteringSpread = 0.686f; public float lightScatteringSpread { get { return _lightScatteringSpread; } set { if (value != _lightScatteringSpread) { _lightScatteringSpread = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(4, 64)] int _lightScatteringSamples = 16; public int lightScatteringSamples { get { return _lightScatteringSamples; } set { if (value != _lightScatteringSamples) { _lightScatteringSamples = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 50f)] float _lightScatteringWeight = 1.9f; public float lightScatteringWeight { get { return _lightScatteringWeight; } set { if (value != _lightScatteringWeight) { _lightScatteringWeight = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 50f)] float _lightScatteringIllumination = 18f; public float lightScatteringIllumination { get { return _lightScatteringIllumination; } set { if (value != _lightScatteringIllumination) { _lightScatteringIllumination = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0.9f, 1.1f)] float _lightScatteringDecay = 0.986f; public float lightScatteringDecay { get { return _lightScatteringDecay; } set { if (value != _lightScatteringDecay) { _lightScatteringDecay = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 0.2f)] float _lightScatteringExposure = 0; public float lightScatteringExposure { get { return _lightScatteringExposure; } set { if (value != _lightScatteringExposure) { _lightScatteringExposure = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 1f)] float _lightScatteringJittering = 0.5f; public float lightScatteringJittering { get { return _lightScatteringJittering; } set { if (value != _lightScatteringJittering) { _lightScatteringJittering = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(1, 4f)] int _lightScatteringBlurDownscale = 1; public int lightScatteringBlurDownscale { get { return _lightScatteringBlurDownscale; } set { if (value != _lightScatteringBlurDownscale) { _lightScatteringBlurDownscale = value; UpdateMaterialProperties(); isDirty = true; } } } #endregion #region Fog Blur [SerializeField] bool _fogBlur = false; public bool fogBlur { get { return _fogBlur; } set { if (value != _fogBlur) { _fogBlur = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 1f)] float _fogBlurDepth = 0.05f; public float fogBlurDepth { get { return _fogBlurDepth; } set { if (value != _fogBlurDepth) { _fogBlurDepth = value; UpdateMaterialProperties(); isDirty = true; } } } #endregion #region Sun Shadows [SerializeField] bool _sunShadows = false; public bool sunShadows { get { return _sunShadows; } set { if (value != _sunShadows) { _sunShadows = value; CleanUpTextureDepthSun(); if (_sunShadows) { needUpdateDepthSunTexture = true; } else { DestroySunShadowsDependencies(); } UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] LayerMask _sunShadowsLayerMask = -1; public LayerMask sunShadowsLayerMask { get { return _sunShadowsLayerMask; } set { if (_sunShadowsLayerMask != value) { _sunShadowsLayerMask = value; isDirty = true; } } } [SerializeField, Range(0, 1f)] float _sunShadowsStrength = 0.5f; public float sunShadowsStrength { get { return _sunShadowsStrength; } set { if (value != _sunShadowsStrength) { _sunShadowsStrength = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] float _sunShadowsBias = 0.1f; public float sunShadowsBias { get { return _sunShadowsBias; } set { if (value != _sunShadowsBias) { _sunShadowsBias = value; needUpdateDepthSunTexture = true; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 0.5f)] float _sunShadowsJitterStrength = 0.1f; public float sunShadowsJitterStrength { get { return _sunShadowsJitterStrength; } set { if (value != _sunShadowsJitterStrength) { _sunShadowsJitterStrength = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 4)] int _sunShadowsResolution = 2; // default = 2^(9+2) = 2048 texture size public int sunShadowsResolution { get { return _sunShadowsResolution; } set { if (value != _sunShadowsResolution) { _sunShadowsResolution = value; needUpdateDepthSunTexture = true; CleanUpTextureDepthSun(); UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(50f, 2000f)] float _sunShadowsMaxDistance = 200f; public float sunShadowsMaxDistance { get { return _sunShadowsMaxDistance; } set { if (value != _sunShadowsMaxDistance) { _sunShadowsMaxDistance = value; needUpdateDepthSunTexture = true; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] SUN_SHADOWS_BAKE_MODE _sunShadowsBakeMode = SUN_SHADOWS_BAKE_MODE.Discrete; public SUN_SHADOWS_BAKE_MODE sunShadowsBakeMode { get { return _sunShadowsBakeMode; } set { if (value != _sunShadowsBakeMode) { _sunShadowsBakeMode = value; needUpdateDepthSunTexture = true; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] float _sunShadowsRefreshInterval = 0; // 0 = no update unless Sun changes position public float sunShadowsRefreshInterval { get { return _sunShadowsRefreshInterval; } set { if (value != _sunShadowsRefreshInterval) { _sunShadowsRefreshInterval = value; UpdateMaterialProperties(); isDirty = true; } } } [SerializeField, Range(0, 1f)] float _sunShadowsCancellation = 0f; public float sunShadowsCancellation { get { return _sunShadowsCancellation; } set { if (value != _sunShadowsCancellation) { _sunShadowsCancellation = value; UpdateMaterialProperties(); isDirty = true; } } } #endregion #region Turbulence [SerializeField, Range(0, 10f)] float _turbulenceStrength = 0f; public float turbulenceStrength { get { return _turbulenceStrength; } set { if (value != _turbulenceStrength) { _turbulenceStrength = value; if (_turbulenceStrength <= 0f) UpdateTexture(); // reset texture to normal UpdateMaterialProperties(); isDirty = true; } } } #endregion #region Other settings [SerializeField] bool _useXYPlane = false; public bool useXYPlane { get { return _useXYPlane; } set { if (value != _useXYPlane) { _useXYPlane = value; if (_sunShadows) { needUpdateDepthSunTexture = true; } UpdateMaterialProperties(); isDirty = true; } } } [SerializeField] bool _useSinglePassStereoRenderingMatrix = false; public bool useSinglePassStereoRenderingMatrix { get { return _useSinglePassStereoRenderingMatrix; } set { if (value != _useSinglePassStereoRenderingMatrix) { _useSinglePassStereoRenderingMatrix = value; isDirty = true; } } } [SerializeField] SPSR_BEHAVIOUR _spsrBehaviour = SPSR_BEHAVIOUR.AutoDetectInEditor; public SPSR_BEHAVIOUR spsrBehaviour { get { return _spsrBehaviour; } set { if (value != _spsrBehaviour) { _spsrBehaviour = value; isDirty = true; } } } [SerializeField] bool _reduceFlickerBigWorlds; public bool reduceFlickerBigWorlds { get { return _reduceFlickerBigWorlds; } set { if (value != _reduceFlickerBigWorlds) { _reduceFlickerBigWorlds = value; isDirty = true; } } } #endregion #region Screen Mask options [SerializeField] bool _enableMask; public bool enableMask { get { return _enableMask; } set { if (value != _enableMask) { _enableMask = value; UpdateVolumeMask(); isDirty = true; } } } [SerializeField] LayerMask _maskLayer = 1 << 23; public LayerMask maskLayer { get { return _maskLayer; } set { if (value != _maskLayer) { _maskLayer = value; UpdateVolumeMask(); isDirty = true; } } } [SerializeField, Range(1, 4)] int _maskDownsampling = 1; public int maskDownsampling { get { return _maskDownsampling; } set { if (value != _maskDownsampling) { _maskDownsampling = value; UpdateVolumeMask(); isDirty = true; } } } #endregion // State variables public Camera fogCamera { get { return mainCamera; } } /// <summary> /// If this fog instances is being rendered /// </summary> public bool isRendering; /// <summary> /// Returns the number of fog instances being rendered /// </summary> /// <value>The rendering instances count.</value> public int renderingInstancesCount { get { return _renderingInstancesCount; } } /// <summary> /// Returns a list of actual rendering fog instances /// </summary> /// <value>The rendering instances.</value> public List<VolumetricFog> renderingInstances { get { return fogRenderInstances; } } /// <summary> /// Returns a list of registered fog instances /// </summary> /// <value>The instances.</value> public List<VolumetricFog> instances { get { return fogInstances; } } public bool hasCamera { get { if (!_hasCameraChecked) { _hasCamera = GetComponent<Camera>() != null; _hasCameraChecked = true; } return _hasCamera; } } [NonSerialized] public float distanceToCameraMin, distanceToCameraMax, distanceToCamera, distanceToCameraYAxis; [NonSerialized] public FOG_TEMPORARY_PROPERTIES temporaryProperties; public VolumetricFog fogRenderer; VolumetricFog[] allFogRenderers; #region Internal variables bool isPartOfScene; int noiseTextureSize; // transitions float initialFogAlpha, targetFogAlpha; float initialSkyHazeAlpha, targetSkyHazeAlpha; bool transitionAlpha, transitionColor, transitionSpecularColor, transitionLightColor, transitionProfile; bool targetColorActive, targetSpecularColorActive, targetLightColorActive; Color initialFogColor, targetFogColor; Color initialFogSpecularColor, targetFogSpecularColor; Color initialLightColor, targetLightColor; float transitionDuration; float transitionStartTime; float currentFogAlpha, currentSkyHazeAlpha; Color currentFogColor, currentFogSpecularColor, currentLightColor; VolumetricFogProfile initialProfile, targetProfile; // fog height related float oldBaselineRelativeCameraY; float currentFogAltitude; // sky related float skyHazeSpeedAcum; Color skyHazeLightColor; // rendering bool _hasCamera, _hasCameraChecked; // if this script is attached to a camera or to another object Camera mainCamera; List<string> shaderKeywords; Material blurMat; RenderBuffer[] mrt; int _renderingInstancesCount; bool shouldUpdateMaterialProperties; int lastFrameCount; [NonSerialized] public Material fogMat; RenderTexture depthTexture, depthSunTexture, reducedDestination; // point light related Light[] lastFoundLights, lightBuffer; Light[] currentLights; float trackPointAutoLastTime; float trackPointCheckNewLightsLastTime; Vector4 black = new Vector4(0, 0, 0, 1f); // transparency support related Shader depthShader, depthShaderAndTrans; GameObject depthCamObj; Camera depthCam; // fog texture/lighting/colors related float lastTextureUpdate; Vector3 windSpeedAcum; Texture2D adjustedTexture; Color[] noiseColors, adjustedColors; float sunLightIntensity = 1.0f; bool needUpdateTexture, hasChangeAdjustedColorsAlpha; int updatingTextureSlice; Color updatingTextureLightColor; Color lastRenderSettingsAmbientLight; float lastRenderSettingsAmbientIntensity; int lastFrameAppliedChaos, lastFrameAppliedWind; // Sun related Light sunLight; Vector2 oldSunPos; float sunFade = 1f; // Sun shadows related GameObject depthSunCamObj; Camera depthSunCam; Shader depthSunShader; [NonSerialized] public bool needUpdateDepthSunTexture; float lastShadowUpdateFrame; bool sunShadowsActive; int currentDepthSunTextureRes; Matrix4x4 lightMatrix; // turbulence related Texture2D adjustedChaosTexture; Material chaosLerpMat; float turbAcum; float deltaTime, timeOfLastRender; // fog instances stuff List<VolumetricFog> fogInstances = new List<VolumetricFog>(); List<VolumetricFog> fogRenderInstances = new List<VolumetricFog>(); MeshRenderer mr; float lastTimeSortInstances; const float FOG_INSTANCES_SORT_INTERVAL = 2f; Vector3 lastCamPos; bool needResort; // Screen mask CommandBuffer maskCommandBuffer; RenderTextureDescriptor rtMaskDesc; Material maskMaterial; #endregion #region Game loop events void OnEnable() { // Note: OnEnable can be called several times when using fog areas isPartOfScene = isPartOfScene || IsPartOfScene(); if (!isPartOfScene) return; temporaryProperties.color = Color.white; temporaryProperties.density = 1f; if (_fogVoidInverted) { // conversion to fog area from fog void from previous versions _fogVoidInverted = false; _fogAreaCenter = _character; _fogAreaDepth = _fogVoidDepth; _fogAreaFallOff = _fogVoidFallOff; _fogAreaHeight = _fogVoidHeight; _fogAreaPosition = _fogVoidPosition; _fogAreaRadius = _fogVoidRadius; _fogVoidRadius = 0; _character = null; } // Setup fog rendering system mainCamera = gameObject.GetComponent<Camera>(); _hasCamera = mainCamera != null; _hasCameraChecked = true; if (_hasCamera) { fogRenderer = this; if (mainCamera.depthTextureMode == DepthTextureMode.None) { mainCamera.depthTextureMode = DepthTextureMode.Depth; } UpdateVolumeMask(); } else { if (fogRenderer == null) { FindMainCamera(); if (mainCamera == null) { Debug.LogError("Volumetric Fog: no camera found!"); return; } fogRenderer = mainCamera.GetComponent<VolumetricFog>(); if (fogRenderer == null) { fogRenderer = mainCamera.gameObject.AddComponent<VolumetricFog>(); fogRenderer.density = 0; } } else { mainCamera = fogRenderer.mainCamera; if (mainCamera == null) mainCamera = fogRenderer.GetComponent<Camera>(); } } // Initialize material if (fogMat == null) { InitFogMaterial(); if (_profile != null && _profileSync) { _profile.Load(this); } } else { UpdateMaterialPropertiesNow(); } // Register on other Volumetric Fog & Mist renderer if needed RegisterWithRenderers(); #if UNITY_EDITOR if (EditorPrefs.GetInt(VFM_BUILD_HINT) == 0) { EditorPrefs.SetInt(VFM_BUILD_HINT, 1); if (EditorPrefs.GetInt(VFM_BUILD_FIRST_INSTALL) == 1) { EditorUtility.DisplayDialog("Volumetric Fog & Mist updated!", "Please review the 'Shader Options' section in Volumetric Fog inspector and make sure you disable unused features to optimize build size and compilation time.\n\nOtherwise when you build the game it will take a long time or even get stuck during shader compilation.", "Ok"); } EditorPrefs.SetInt(VFM_BUILD_FIRST_INSTALL, 1); } #endif needResort = true; } void OnDisable() { RemoveMaskCommandBuffer(); RemoveDirectionalLightCommandBuffer(); } void OnDestroy() { // Unregister on other Volumetric Fog & Mist renderer if needed if (!_hasCamera) { UnregisterWithRenderers(); } else { RemoveMaskCommandBuffer(); UnregisterFogArea(this); } if (depthCamObj != null) { DestroyImmediate(depthCamObj); depthCamObj = null; } if (adjustedTexture != null) { DestroyImmediate(adjustedTexture); adjustedTexture = null; } if (chaosLerpMat != null) { DestroyImmediate(chaosLerpMat); chaosLerpMat = null; } if (adjustedChaosTexture != null) { DestroyImmediate(adjustedChaosTexture); adjustedChaosTexture = null; } if (blurMat != null) { DestroyImmediate(blurMat); blurMat = null; } if (fogMat != null) { DestroyImmediate(fogMat); fogMat = null; } FogOfWarDestroy(); CleanUpDepthTexture(); DestroySunShadowsDependencies(); } public void DestroySelf() { DestroyRenderComponent<VolumetricFogPreT>(); DestroyRenderComponent<VolumetricFogPosT>(); DestroyImmediate(this); } void Start() { currentFogAlpha = _alpha; currentSkyHazeAlpha = _skyAlpha; lastTextureUpdate = Time.time + _timeBetweenTextureUpdates; RegisterWithRenderers(); // ensures it's properly registered Update(); } // Check possible alpha transition void Update() { if (!isPartOfScene || fogRenderer == null) return; // Updates sun illumination if (fogRenderer.sun != null) { Vector3 lightDir = fogRenderer.sun.transform.forward; bool mayUpdateTexture = !Application.isPlaying || (updatingTextureSlice < 0 && Time.time - lastTextureUpdate >= _timeBetweenTextureUpdates); if (mayUpdateTexture) { if (lightDir != _lightDirection) { _lightDirection = lightDir; needUpdateTexture = true; needUpdateDepthSunTexture = true; } if (sunLight != null) { if (_sunCopyColor && sunLight.color != _lightColor) { _lightColor = sunLight.color; currentLightColor = _lightColor; needUpdateTexture = true; } if (sunLightIntensity != sunLight.intensity) { sunLightIntensity = sunLight.intensity; needUpdateTexture = true; } } } } // Check changes in render settings that affect fog colors if (!needUpdateTexture) { if (_lightingModel == LIGHTING_MODEL.Classic) { if (lastRenderSettingsAmbientIntensity != RenderSettings.ambientIntensity) { needUpdateTexture = true; } else if (lastRenderSettingsAmbientLight != RenderSettings.ambientLight) { needUpdateTexture = true; } } else if (_lightingModel == LIGHTING_MODEL.Natural) { if (lastRenderSettingsAmbientLight != RenderSettings.ambientLight) { needUpdateTexture = true; } } } // Check profile transition if (transitionProfile) { float t = (Time.time - transitionStartTime) / transitionDuration; if (t > 1) t = 1; VolumetricFogProfile.Lerp(initialProfile, targetProfile, t, this); if (t >= 1f) { transitionProfile = false; } } // Check alpha transition if (transitionAlpha) { if (targetFogAlpha >= 0 || targetSkyHazeAlpha >= 0) { if (targetFogAlpha != currentFogAlpha || targetSkyHazeAlpha != currentSkyHazeAlpha) { if (transitionDuration > 0) { currentFogAlpha = Mathf.Lerp(initialFogAlpha, targetFogAlpha, (Time.time - transitionStartTime) / transitionDuration); currentSkyHazeAlpha = Mathf.Lerp(initialSkyHazeAlpha, targetSkyHazeAlpha, (Time.time - transitionStartTime) / transitionDuration); } else { currentFogAlpha = targetFogAlpha; currentSkyHazeAlpha = targetSkyHazeAlpha; transitionAlpha = false; } fogMat.SetFloat("_FogAlpha", currentFogAlpha); UpdateSkyColor(currentSkyHazeAlpha); } } else if (currentFogAlpha != _alpha || currentSkyHazeAlpha != _skyAlpha) { if (transitionDuration > 0) { currentFogAlpha = Mathf.Lerp(initialFogAlpha, _alpha, (Time.time - transitionStartTime) / transitionDuration); currentSkyHazeAlpha = Mathf.Lerp(initialSkyHazeAlpha, alpha, (Time.time - transitionStartTime) / transitionDuration); } else { currentFogAlpha = _alpha; currentSkyHazeAlpha = _skyAlpha; transitionAlpha = false; } fogMat.SetFloat("_FogAlpha", currentFogAlpha); UpdateSkyColor(currentSkyHazeAlpha); } } // Check color transition if (transitionColor) { if (targetColorActive) { if (targetFogColor != currentFogColor) { if (transitionDuration > 0) { currentFogColor = Color.Lerp(initialFogColor, targetFogColor, (Time.time - transitionStartTime) / transitionDuration); } else { currentFogColor = targetFogColor; transitionColor = false; } } } else if (currentFogColor != _color) { if (transitionDuration > 0) { currentFogColor = Color.Lerp(initialFogColor, _color, (Time.time - transitionStartTime) / transitionDuration); } else { currentFogColor = _color; transitionColor = false; } } UpdateMaterialFogColor(); } // Check color specular transition if (transitionSpecularColor) { if (targetSpecularColorActive) { if (targetFogSpecularColor != currentFogSpecularColor) { if (transitionDuration > 0) { currentFogSpecularColor = Color.Lerp(initialFogSpecularColor, targetFogSpecularColor, (Time.time - transitionStartTime) / transitionDuration); } else { currentFogSpecularColor = targetFogSpecularColor; transitionSpecularColor = false; } needUpdateTexture = true; } } else if (currentFogSpecularColor != _specularColor) { if (transitionDuration > 0) { currentFogSpecularColor = Color.Lerp(initialFogSpecularColor, _specularColor, (Time.time - transitionStartTime) / transitionDuration); } else { currentFogSpecularColor = _specularColor; transitionSpecularColor = false; } needUpdateTexture = true; } } // Check color specular transition if (transitionLightColor) { if (targetLightColorActive) { if (targetLightColor != currentLightColor) { if (transitionDuration > 0) { currentLightColor = Color.Lerp(initialLightColor, targetLightColor, (Time.time - transitionStartTime) / transitionDuration); } else { currentLightColor = targetLightColor; transitionLightColor = false; } needUpdateTexture = true; } } else if (currentLightColor != _lightColor) { if (transitionDuration > 0) { currentLightColor = Color.Lerp(initialLightColor, _lightColor, (Time.time - transitionStartTime) / transitionDuration); } else { currentLightColor = _lightColor; transitionLightColor = false; } needUpdateTexture = true; } } if (_baselineRelativeToCamera) { UpdateMaterialHeights(mainCamera); } else if (_character != null) { _fogVoidPosition = _character.transform.position; UpdateMaterialHeights(mainCamera); } #if UNITY_EDITOR CheckFogAreaDimensions(); // This is called in OnRenderImage BUT if Game View is not visible, fog area dimensions are not updated and gizmos won't appear with correct size, so we force dimensions check here just in case #endif if (_fogAreaCenter != null) { if (_fogAreaFollowMode == FOG_AREA_FOLLOW_MODE.FullXYZ) { _fogAreaPosition = _fogAreaCenter.transform.position; } else { _fogAreaPosition.x = _fogAreaCenter.transform.position.x; _fogAreaPosition.z = _fogAreaCenter.transform.position.z; } UpdateMaterialHeights(mainCamera); } if (_pointLightTrackingAuto) { if (!Application.isPlaying || Time.time - trackPointAutoLastTime > _pointLightTrackingCheckInterval) { trackPointAutoLastTime = Time.time; TrackPointLights(); } } if (updatingTextureSlice >= 0) { UpdateTextureColors(adjustedColors, false); } else if (needUpdateTexture) { UpdateTexture(); } if (_hasCamera) { // Restores fog of war if (_fogOfWarEnabled) UpdateFogOfWar(); // Autoupdate of fog shadows if (sunShadowsActive) { CastSunShadows(); } // Sort fog instances int fogInstancesCount = fogInstances.Count; if (fogInstancesCount > 1) { Vector3 camPos = mainCamera.transform.position; if (!Application.isPlaying || Time.time - lastTimeSortInstances >= FOG_INSTANCES_SORT_INTERVAL) { needResort = true; } if (!needResort) { float camDist = (camPos.x - lastCamPos.x) * (camPos.x - lastCamPos.x) + (camPos.y - lastCamPos.y) * (camPos.y - lastCamPos.y) + (camPos.z - lastCamPos.z) * (camPos.z - lastCamPos.z); if (camDist > 625) { // forces udpate every 25 meters lastCamPos = camPos; needResort = true; } } if (needResort) { needResort = false; lastTimeSortInstances = Time.time; float camX = camPos.x; float camY = camPos.y; float camZ = camPos.z; for (int k = 0; k < fogInstancesCount; k++) { VolumetricFog fogInstance = fogInstances[k]; if (fogInstance != null) { Vector3 pos = fogInstance.transform.position; pos.y = fogInstance.currentFogAltitude; float xdx = camX - pos.x; float xdy = camY - pos.y; float distYAxis = xdy * xdy; float xdyh = camY - (pos.y + fogInstance.height); float distYAxis2 = xdyh * xdyh; fogInstance.distanceToCameraYAxis = distYAxis < distYAxis2 ? distYAxis : distYAxis2; float xdz = camZ - pos.z; float distSqr = xdx * xdx + xdy * xdy + xdz * xdz; fogInstance.distanceToCamera = distSqr; Vector3 min = pos - fogInstance.transform.localScale * 0.5f; Vector3 max = pos + fogInstance.transform.localScale * 0.5f; fogInstance.distanceToCameraMin = mainCamera.WorldToScreenPoint(min).z; fogInstance.distanceToCameraMax = mainCamera.WorldToScreenPoint(max).z; } } fogInstances.Sort((VolumetricFog x, VolumetricFog y) => { if (!x || !y) { return 0; } if (x._fogAreaSortingMode == FOG_AREA_SORTING_MODE.Fixed || y._fogAreaSortingMode == FOG_AREA_SORTING_MODE.Fixed) { if (x._fogAreaRenderOrder < y._fogAreaRenderOrder) { return -1; } else if (x._fogAreaRenderOrder > y._fogAreaRenderOrder) { return 1; } else { return 0; } } bool overlaps = (x.distanceToCameraMin < y.distanceToCameraMin && x.distanceToCameraMax > y.distanceToCameraMax) || (y.distanceToCameraMin < x.distanceToCameraMin && y.distanceToCameraMax > x.distanceToCameraMax); if (overlaps || x._fogAreaSortingMode == FOG_AREA_SORTING_MODE.Altitude || y._fogAreaSortingMode == FOG_AREA_SORTING_MODE.Altitude) { if (x.distanceToCameraYAxis < y.distanceToCameraYAxis) { return 1; } else if (x.distanceToCameraYAxis > y.distanceToCameraYAxis) { return -1; } else { return 0; } } if (x.distanceToCamera < y.distanceToCamera) { return 1; } else if (x.distanceToCamera > y.distanceToCamera) { return -1; } else { return 0; } }); } } } } void OnPreCull() { if (!enabled || !gameObject.activeSelf || fogMat == null || !_hasCamera || mainCamera == null) return; if (mainCamera.depthTextureMode == DepthTextureMode.None) { mainCamera.depthTextureMode = DepthTextureMode.Depth; } if (_computeDepth) { GetTransparentDepth(); } // Apply chaos if (_hasCamera) { if (Application.isPlaying) { int count = fogRenderInstances.Count; for (int k = 0; k < count; k++) { if (fogRenderInstances[k] != null && fogRenderInstances[k].turbulenceStrength > 0) { fogRenderInstances[k].ApplyChaos(); } } } } // if (Application.isPlaying && _turbulenceStrength > 0f) // ApplyChaos (); } void OnDidApplyAnimationProperties() { // support for animating property based fields shouldUpdateMaterialProperties = true; } #endregion #region Setting up void FindMainCamera() { mainCamera = Camera.main; if (mainCamera == null) { Camera[] cams = FindObjectsOfType<Camera>(); for (int k=0;k<cams.Length;k++) { if (cams[k].isActiveAndEnabled) { mainCamera = cams[k]; return; } } } } bool IsPartOfScene() { VolumetricFog[] fogs = FindObjectsOfType<VolumetricFog>(); for (int k = 0; k < fogs.Length; k++) { if (fogs[k] == this) return true; } return false; } void InitFogMaterial() { targetFogAlpha = -1; targetSkyHazeAlpha = -1; _skyColor.a = _skyAlpha; updatingTextureSlice = -1; fogMat = new Material(Shader.Find("VolumetricFogAndMist/VolumetricFog")); fogMat.hideFlags = HideFlags.DontSave; Texture2D noiseTexture = Resources.Load<Texture2D>("Textures/Noise3"); noiseTextureSize = noiseTexture.width; noiseColors = noiseTexture.GetPixels(); adjustedColors = new Color[noiseColors.Length]; adjustedTexture = new Texture2D(noiseTexture.width, noiseTexture.height, TextureFormat.RGBA32, false); adjustedTexture.hideFlags = HideFlags.DontSave; timeOfLastRender = Time.time; // Init & apply settings CheckPointLightData(); if (_pointLightTrackingAuto) { TrackPointLights(); } FogOfWarInit(); CopyTransitionValues(); UpdatePreset(); oldBaselineRelativeCameraY = mainCamera.transform.position.y; if (_sunShadows) needUpdateDepthSunTexture = true; } void UpdateRenderComponents() { if (!_hasCamera) return; if (_renderBeforeTransparent) { AssignRenderComponent<VolumetricFogPreT>(); DestroyRenderComponent<VolumetricFogPosT>(); } else if (_transparencyBlendMode == TRANSPARENT_MODE.Blend) { AssignRenderComponent<VolumetricFogPreT>(); AssignRenderComponent<VolumetricFogPosT>(); } else { AssignRenderComponent<VolumetricFogPosT>(); DestroyRenderComponent<VolumetricFogPreT>(); } } void DestroyRenderComponent<T>() where T : IVolumetricFogRenderComponent { T[] cc = GetComponentsInChildren<T>(true); for (int k = 0; k < cc.Length; k++) { if (cc[k].fog == this || cc[k].fog == null) { cc[k].DestroySelf(); } } } void AssignRenderComponent<T>() where T : UnityEngine.Component, IVolumetricFogRenderComponent { T[] cc = GetComponentsInChildren<T>(true); int freeCC = -1; for (int k = 0; k < cc.Length; k++) { if (cc[k].fog == this) { return; } if (cc[k].fog == null) freeCC = k; } if (freeCC < 0) { gameObject.AddComponent<T>().fog = this; } else { cc[freeCC].fog = this; } } /// <summary> /// Used internally to chain multiple fog areas into the main fog renderer. /// </summary> void RegisterFogArea(VolumetricFog fog) { if (fogInstances.Contains(fog)) return; fogInstances.Add(fog); } /// <summary> /// Used internally to disconnect a non-enabled fog area from the main fog renderer. /// </summary> void UnregisterFogArea(VolumetricFog fog) { if (!fogInstances.Contains(fog)) return; fogInstances.Remove(fog); } void RegisterWithRenderers() { // Get a list of Volumetric Fog & Mist scripts in the scene allFogRenderers = FindObjectsOfType<VolumetricFog>(); if (!_hasCamera && fogRenderer != null) { if (fogRenderer.enableMultipleCameras) { for (int k = 0; k < allFogRenderers.Length; k++) { if (allFogRenderers[k].hasCamera) { allFogRenderers[k].RegisterFogArea(this); } } } else { // Only register with designated renderer fogRenderer.RegisterFogArea(this); } } else { fogInstances.Clear(); RegisterFogArea(this); // Find all fog areas and attach them to this renderer if enableMultipleCameras is enabled, or only the fog area linked to this fog area for (int k = 0; k < allFogRenderers.Length; k++) { if (!allFogRenderers[k].hasCamera && (_enableMultipleCameras || allFogRenderers[k].fogRenderer == this)) { RegisterFogArea(allFogRenderers[k]); } } } lastTimeSortInstances = 0; } void UnregisterWithRenderers() { if (allFogRenderers != null) { for (int k = 0; k < allFogRenderers.Length; k++) { if (allFogRenderers[k] != null && allFogRenderers[k].hasCamera) { allFogRenderers[k].UnregisterFogArea(this); } } } } public void UpdateMultiCameraSetup() { allFogRenderers = FindObjectsOfType<VolumetricFog>(); for (int k = 0; k < allFogRenderers.Length; k++) { if (allFogRenderers[k] != null && allFogRenderers[k].hasCamera) { allFogRenderers[k].SetEnableMultipleCameras(_enableMultipleCameras); } } RegisterWithRenderers(); } void SetEnableMultipleCameras(bool state) { _enableMultipleCameras = state; RegisterWithRenderers(); } #endregion #region Rendering stuff internal void DoOnRenderImage(RenderTexture source, RenderTexture destination) { // Check integrity of fog instances list int registeredInstancesCount = fogInstances.Count; fogRenderInstances.Clear(); Vector3 camPos = Camera.current.transform.position; for (int k = 0; k < registeredInstancesCount; k++) { VolumetricFog fogInstance = fogInstances[k]; fogInstance.isRendering = false; if (fogInstance != null && fogInstance.isActiveAndEnabled && fogInstance.density > 0) { if (fogInstance._visibilityScope == FOG_VISIBILITY_SCOPE.Global || fogInstance._visibilityVolume.Contains(camPos)) { fogRenderInstances.Add(fogInstances[k]); } } } _renderingInstancesCount = fogRenderInstances.Count; if (_renderingInstancesCount == 0 || mainCamera == null) { // No available instances, cancel any rendering Graphics.Blit(source, destination); return; } #pragma warning disable 0162 if (USE_DIRECTIONAL_LIGHT_COOKIE) { if (_sun != null) { lightMatrix = Matrix4x4.TRS(_sun.transform.position, _sun.transform.rotation, Vector3.one).inverse; } } #pragma warning restore 0162 if (_hasCamera && _density <= 0 && shouldUpdateMaterialProperties) { // This fog renderer might require updating its material properties (Sun Shadows, ...) but won't render, so we do it here UpdateMaterialPropertiesNow(Camera.current); } if (_renderingInstancesCount == 1) { // One instance, render directly to destination fogRenderInstances[0].DoOnRenderImageInstance(source, destination); } else { RenderTextureDescriptor rtDesc = source.descriptor; rtDesc.depthBufferBits = 0; rtDesc.msaaSamples = 1; //rtDesc.colorFormat = RenderTextureFormat.ARGB32; <-- causes banding issues with Linear Color space RenderTexture rt1 = RenderTexture.GetTemporary(rtDesc); fogRenderInstances[0].DoOnRenderImageInstance(source, rt1); if (_renderingInstancesCount == 2) { // Two instance, render to intermediate, then to destination fogRenderInstances[1].DoOnRenderImageInstance(rt1, destination); } if (_renderingInstancesCount >= 3) { // 3 or more instances, render them and finally to destinatio RenderTexture rt2 = RenderTexture.GetTemporary(rtDesc); RenderTexture prev = rt1; RenderTexture next = rt2; int last = _renderingInstancesCount - 1; for (int k = 1; k < last; k++) { if (k > 1) next.DiscardContents(); fogRenderInstances[k].DoOnRenderImageInstance(prev, next); if (next == rt2) { prev = rt2; next = rt1; } else { prev = rt1; next = rt2; } } fogRenderInstances[last].DoOnRenderImageInstance(prev, destination); RenderTexture.ReleaseTemporary(rt2); } RenderTexture.ReleaseTemporary(rt1); } } internal void DoOnRenderImageInstance(RenderTexture source, RenderTexture destination) { Camera mainCamera = Camera.current; if (mainCamera == null || fogMat == null) { Graphics.Blit(source, destination); return; } isRendering = true; if (!_hasCamera) { CheckFogAreaDimensions(); if (_sunShadows && !fogRenderer.sunShadows) { fogRenderer.sunShadows = true; // forces casting shadows on fog renderer } } if (shouldUpdateMaterialProperties) { UpdateMaterialPropertiesNow(mainCamera); } if (lastFrameCount != Time.frameCount && Application.isPlaying) { if (_useRealTime) { deltaTime = Time.time - timeOfLastRender; timeOfLastRender = Time.time; } else { deltaTime = Time.deltaTime; } UpdateWindSpeedQuick(); } if (_hasCamera) { #if UNITY_EDITOR if (_spsrBehaviour == SPSR_BEHAVIOUR.AutoDetectInEditor) { useSinglePassStereoRenderingMatrix = PlayerSettings.stereoRenderingPath != StereoRenderingPath.MultiPass; } #endif if (_spsrBehaviour == SPSR_BEHAVIOUR.ForcedOn && !_useSinglePassStereoRenderingMatrix) { useSinglePassStereoRenderingMatrix = true; } else if (_spsrBehaviour == SPSR_BEHAVIOUR.ForcedOff && _useSinglePassStereoRenderingMatrix) { useSinglePassStereoRenderingMatrix = false; } } // set light matrix #pragma warning disable 0162 if (USE_DIRECTIONAL_LIGHT_COOKIE) { fogMat.SetMatrix ("_VolumetricFogLightMatrix", lightMatrix); if (sunLight != null && sunLight.cookieSize > 0) { fogMat.SetFloat ("_VolumetricFogCookieSize", 1f / sunLight.cookieSize); } } #pragma warning restore 0162 bool vrOn = UnityEngine.XR.XRSettings.enabled; Vector3 camPos = mainCamera.transform.position; bool shiftToZero = fogRenderer.reduceFlickerBigWorlds; if (shiftToZero) { fogMat.SetVector("_FlickerFreeCamPos", camPos); mainCamera.transform.position = Vector3.zero; if (vrOn) { mainCamera.ResetWorldToCameraMatrix(); } } else { fogMat.SetVector("_FlickerFreeCamPos", Vector3.zero); } if (mainCamera.orthographic) { fogMat.SetVector("_ClipDir", mainCamera.transform.forward); } if (vrOn && fogRenderer.useSinglePassStereoRenderingMatrix) { fogMat.SetMatrix("_ClipToWorld", mainCamera.cameraToWorldMatrix); } else { fogMat.SetMatrix("_ClipToWorld", mainCamera.cameraToWorldMatrix * mainCamera.projectionMatrix.inverse); } if (shiftToZero) { mainCamera.transform.position = camPos; } if (_lightScatteringEnabled && fogRenderer.sun) { UpdateScatteringData(mainCamera); } if (lastFrameCount != Time.frameCount || !Application.isPlaying) { // Updates point light illumination if (pointLightParams.Length != MAX_POINT_LIGHTS) { CheckPointLightData(); } for (int k = 0; k < pointLightParams.Length; k++) { Light pointLightComponent = pointLightParams[k].light; if (pointLightComponent != null) { if (pointLightParams[k].color != pointLightComponent.color) { pointLightParams[k].color = pointLightComponent.color; isDirty = true; } if (pointLightParams[k].range != pointLightComponent.range) { pointLightParams[k].range = pointLightComponent.range; isDirty = true; } if (pointLightParams[k].position != pointLightComponent.transform.position) { pointLightParams[k].position = pointLightComponent.transform.position; isDirty = true; } if (pointLightParams[k].intensity != pointLightComponent.intensity) { pointLightParams[k].intensity = pointLightComponent.intensity; isDirty = true; } if (pointLightParams[k].lightParams == null) { pointLightParams[k].lightParams = pointLightParams[k].light.GetComponent<VolumetricFogLightParams>(); if (pointLightParams[k].lightParams == null) { pointLightParams[k].lightParams = pointLightParams[k].light.gameObject.AddComponent<VolumetricFogLightParams>(); } } pointLightParams[k].rangeMultiplier = pointLightParams[k].lightParams.rangeMultiplier; pointLightParams[k].intensityMultiplier = pointLightParams[k].lightParams.intensityMultiplier; } } SetPointLightMaterialProperties(mainCamera); } // Get shaft RenderTexture blurTmp2 = null; if (LIGHT_SCATTERING_BLUR_ENABLED && _lightScatteringEnabled && _lightScatteringExposure > 0) { RenderTextureDescriptor rtShaft = source.descriptor; rtShaft.msaaSamples = 1; RenderTexture shaftDestination = RenderTexture.GetTemporary(rtShaft); Graphics.Blit(source, shaftDestination, fogMat, 5); RenderTextureDescriptor rtBlur = rtShaft; rtBlur.width = GetScaledSize(rtBlur.width, _lightScatteringBlurDownscale); rtBlur.height = GetScaledSize(rtBlur.height, _lightScatteringBlurDownscale); RenderTexture blurTmp = RenderTexture.GetTemporary(rtBlur); blurTmp2 = RenderTexture.GetTemporary(rtBlur); Graphics.Blit(shaftDestination, blurTmp, fogMat, 7); Graphics.Blit(blurTmp, blurTmp2, fogMat, 6); RenderTexture.ReleaseTemporary(blurTmp); RenderTexture.ReleaseTemporary(shaftDestination); fogMat.SetTexture("_ShaftTex", blurTmp2); } // Render fog before transparent objects are drawn and only having into account the depth of opaque objects if (_downsampling > 1f || _forceComposition) { int scaledWidth = GetScaledSize(source.width, _downsampling); int scaledHeight = GetScaledSize(source.width, _downsampling); RenderTextureDescriptor rtReducedDestinationDesc = source.descriptor; rtReducedDestinationDesc.width = scaledWidth; rtReducedDestinationDesc.height = scaledHeight; rtReducedDestinationDesc.msaaSamples = 1; reducedDestination = RenderTexture.GetTemporary(rtReducedDestinationDesc); // scaledWidth, scaledHeight, 0, RenderTextureFormat.ARGB32); RenderTextureDescriptor rtReducedDepthDesc = source.descriptor; rtReducedDepthDesc.width = scaledWidth; rtReducedDepthDesc.height = scaledHeight; rtReducedDepthDesc.msaaSamples = 1; RenderTextureFormat rtFormat = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RFloat) ? RenderTextureFormat.RFloat : RenderTextureFormat.ARGBFloat; rtReducedDestinationDesc.colorFormat = rtFormat; RenderTexture reducedDepthTexture = RenderTexture.GetTemporary(rtReducedDestinationDesc); // scaledWidth, scaledHeight, 0, rtFormat); if (_fogBlur) { SetBlurTexture(source, rtReducedDestinationDesc); } if (!_edgeImprove || vrOn || SystemInfo.supportedRenderTargetCount < 2) { Graphics.Blit(source, reducedDestination, fogMat, 3); if (_edgeImprove) { Graphics.Blit(source, reducedDepthTexture, fogMat, 4); fogMat.SetTexture("_DownsampledDepth", reducedDepthTexture); } else { fogMat.SetTexture("_DownsampledDepth", null); // required for metal } } else { fogMat.SetTexture("_MainTex", source); if (mrt == null) mrt = new RenderBuffer[2]; mrt[0] = reducedDestination.colorBuffer; mrt[1] = reducedDepthTexture.colorBuffer; Graphics.SetRenderTarget(mrt, reducedDestination.depthBuffer); Graphics.Blit(null, fogMat, 1); fogMat.SetTexture("_DownsampledDepth", reducedDepthTexture); } fogMat.SetTexture("_FogDownsampled", reducedDestination); Graphics.Blit(source, destination, fogMat, 2); RenderTexture.ReleaseTemporary(reducedDepthTexture); RenderTexture.ReleaseTemporary(reducedDestination); } else { if (_fogBlur) { RenderTextureDescriptor rtReducedDestinationDesc = source.descriptor; rtReducedDestinationDesc.width = 256; rtReducedDestinationDesc.height = 256; SetBlurTexture(source, rtReducedDestinationDesc); } Graphics.Blit(source, destination, fogMat, 0); } if (shiftToZero && vrOn) { mainCamera.ResetWorldToCameraMatrix(); } if (blurTmp2 != null) { RenderTexture.ReleaseTemporary(blurTmp2); } lastFrameCount = Time.frameCount; } int GetScaledSize(int size, float factor) { size = (int)(size / factor); size /= 4; if (size < 1) size = 1; return size * 4; } #endregion #region Transparency support void CleanUpDepthTexture() { if (depthTexture) { RenderTexture.ReleaseTemporary(depthTexture); depthTexture = null; } } void GetTransparentDepth() { CleanUpDepthTexture(); if (depthCam == null) { if (depthCamObj == null) { depthCamObj = GameObject.Find(DEPTH_CAM_NAME); } if (depthCamObj == null) { depthCamObj = new GameObject(DEPTH_CAM_NAME); depthCam = depthCamObj.AddComponent<Camera>(); depthCam.enabled = false; depthCamObj.hideFlags = HideFlags.HideAndDontSave; } else { depthCam = depthCamObj.GetComponent<Camera>(); if (depthCam == null) { DestroyImmediate(depthCamObj); depthCamObj = null; return; } } } depthCam.CopyFrom(mainCamera); depthCam.depthTextureMode = DepthTextureMode.None; depthTexture = RenderTexture.GetTemporary(mainCamera.pixelWidth, mainCamera.pixelHeight, 24, RenderTextureFormat.Depth, RenderTextureReadWrite.Linear); depthCam.backgroundColor = new Color(0, 0, 0, 0); depthCam.clearFlags = CameraClearFlags.SolidColor; depthCam.cullingMask = _transparencyLayerMask; depthCam.targetTexture = depthTexture; depthCam.renderingPath = RenderingPath.Forward; if (depthShader == null) { depthShader = Shader.Find("VolumetricFogAndMist/CopyDepth"); } if (depthShaderAndTrans == null) { depthShaderAndTrans = Shader.Find("VolumetricFogAndMist/CopyDepthAndTrans"); } switch (_computeDepthScope) { case COMPUTE_DEPTH_SCOPE.OnlyTreeBillboards: depthCam.RenderWithShader(depthShader, "RenderType"); break; case COMPUTE_DEPTH_SCOPE.TreeBillboardsAndTransparentObjects: depthCam.RenderWithShader(depthShaderAndTrans, "RenderType"); break; default: depthCam.RenderWithShader(depthShaderAndTrans, null); break; } Shader.SetGlobalTexture("_VolumetricFogDepthTexture", depthTexture); } #endregion #region Shadow support #pragma warning disable 0429 #pragma warning disable 0162 void CastSunShadows() { if (USE_UNITY_SHADOW_MAP || !enabled || !gameObject.activeSelf || fogMat == null) return; if (_sunShadowsBakeMode == SUN_SHADOWS_BAKE_MODE.Discrete && _sunShadowsRefreshInterval > 0 && Time.time > lastShadowUpdateFrame + _sunShadowsRefreshInterval) { needUpdateDepthSunTexture = true; } if (!Application.isPlaying || needUpdateDepthSunTexture || depthSunTexture == null || !depthSunTexture.IsCreated()) { needUpdateDepthSunTexture = false; lastShadowUpdateFrame = Time.time; GetSunShadows(); } } #pragma warning restore 0162 #pragma warning restore 0429 void GetSunShadows() { if (_sun == null || !_sunShadows) return; if (depthSunCam == null) { if (depthSunCamObj == null) { depthSunCamObj = GameObject.Find(DEPTH_SUN_CAM_NAME); } if (depthSunCamObj == null) { depthSunCamObj = new GameObject(DEPTH_SUN_CAM_NAME); depthSunCamObj.hideFlags = HideFlags.HideAndDontSave; depthSunCam = depthSunCamObj.AddComponent<Camera>(); } else { depthSunCam = depthSunCamObj.GetComponent<Camera>(); if (depthSunCam == null) { DestroyImmediate(depthSunCamObj); depthSunCamObj = null; return; } } if (depthSunShader == null) { depthSunShader = Shader.Find("VolumetricFogAndMist/CopySunDepth"); } depthSunCam.SetReplacementShader(depthSunShader, "RenderType"); depthSunCam.nearClipPlane = 1f; depthSunCam.renderingPath = RenderingPath.Forward; depthSunCam.orthographic = true; depthSunCam.aspect = 1f; depthSunCam.backgroundColor = new Color(0, 0, 0.5f, 0); depthSunCam.clearFlags = CameraClearFlags.SolidColor; depthSunCam.depthTextureMode = DepthTextureMode.None; } float shadowOrthoSize = _sunShadowsMaxDistance / 0.95f; const float farClip = 2000; depthSunCam.transform.position = mainCamera.transform.position - _sun.transform.forward * farClip; depthSunCam.transform.rotation = _sun.transform.rotation; depthSunCam.farClipPlane = farClip * 2f; depthSunCam.orthographicSize = shadowOrthoSize; if (sunLight != null) { depthSunCam.cullingMask = _sunShadowsLayerMask; } if (depthSunTexture == null || currentDepthSunTextureRes != _sunShadowsResolution) { currentDepthSunTextureRes = _sunShadowsResolution; int shadowTexResolution = (int)Mathf.Pow(2, _sunShadowsResolution + 9); depthSunTexture = new RenderTexture(shadowTexResolution, shadowTexResolution, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); depthSunTexture.hideFlags = HideFlags.DontSave; depthSunTexture.filterMode = FilterMode.Point; depthSunTexture.wrapMode = TextureWrapMode.Clamp; depthSunTexture.Create(); } depthSunCam.targetTexture = depthSunTexture; Shader.SetGlobalFloat("_VF_ShadowBias", _sunShadowsBias); if (Application.isPlaying && _sunShadowsBakeMode == SUN_SHADOWS_BAKE_MODE.Realtime) { if (!depthSunCam.enabled) { depthSunCam.enabled = true; } } else { if (depthSunCam.enabled) { depthSunCam.enabled = false; } depthSunCam.Render(); } Shader.SetGlobalMatrix("_VolumetricFogSunProj", depthSunCam.projectionMatrix * depthSunCam.worldToCameraMatrix); Shader.SetGlobalTexture("_VolumetricFogSunDepthTexture", depthSunTexture); Vector4 swp = depthSunCam.transform.position; swp.w = Mathf.Min(_sunShadowsMaxDistance, _maxFogLength); Shader.SetGlobalVector("_VolumetricFogSunWorldPos", swp); UpdateSunShadowsData(); } #endregion #region Fog Blur support void SetBlurTexture(RenderTexture source, RenderTextureDescriptor desc) { if (blurMat == null) { Shader blurShader = Shader.Find("VolumetricFogAndMist/Blur"); blurMat = new Material(blurShader); blurMat.hideFlags = HideFlags.DontSave; } if (blurMat == null) return; blurMat.SetFloat("_BlurDepth", _fogBlurDepth); RenderTexture temp1 = RenderTexture.GetTemporary(desc); // source.width, source.height, 0, source.format); Graphics.Blit(source, temp1, blurMat, 0); RenderTexture temp2 = RenderTexture.GetTemporary(desc); // source.width, source.height, 0, source.format); Graphics.Blit(temp1, temp2, blurMat, 1); blurMat.SetFloat("_BlurDepth", _fogBlurDepth * 2f); temp1.DiscardContents(); Graphics.Blit(temp2, temp1, blurMat, 0); temp2.DiscardContents(); Graphics.Blit(temp1, temp2, blurMat, 1); fogMat.SetTexture("_BlurTex", temp2); RenderTexture.ReleaseTemporary(temp2); RenderTexture.ReleaseTemporary(temp1); } void DestroySunShadowsDependencies() { if (depthSunCamObj != null) { DestroyImmediate(depthSunCamObj); depthSunCamObj = null; } CleanUpTextureDepthSun(); } void CleanUpTextureDepthSun() { if (depthSunTexture != null) { depthSunTexture.Release(); depthSunTexture = null; } } #endregion #region Settings area public string GetCurrentPresetName() { return Enum.GetName(typeof(FOG_PRESET), _preset); } public void UpdatePreset() { switch (_preset) { case FOG_PRESET.Clear: _density = 0; _fogOfWarEnabled = false; _fogVoidRadius = 0; break; case FOG_PRESET.Mist: _skySpeed = 0.3f; _skyHaze = 15; _skyNoiseStrength = 0.1f; _skyAlpha = 0.8f; _density = 0.3f; _noiseStrength = 0.6f; _noiseScale = 1; _skyNoiseScale = 1; _noiseSparse = 0f; _distance = 0; _distanceFallOff = 0f; _maxFogLengthFallOff = 0.5f; _height = 6; _heightFallOff = 0.6f; _deepObscurance = 1f; _stepping = 8; _steppingNear = 0; _alpha = 1; _color = new Color(0.89f, 0.89f, 0.89f); _skyColor = new Color(0.81f, 0.81f, 0.81f); _specularColor = new Color(1, 1, 0.8f, 1); _specularIntensity = 0.1f; _specularThreshold = 0.6f; _lightColor = Color.white; _lightIntensity = 0.12f; _speed = 0.01f; _downsampling = 1; _baselineRelativeToCamera = false; CheckWaterLevel(false); _fogVoidRadius = 0; CopyTransitionValues(); break; case FOG_PRESET.WindyMist: _skySpeed = 0.3f; _skyHaze = 25; _skyNoiseStrength = 0.1f; _skyAlpha = 0.85f; _density = 0.3f; _noiseStrength = 0.5f; _noiseScale = 1.15f; _skyNoiseScale = 1.15f; _noiseSparse = 0f; _distance = 0; _distanceFallOff = 0f; _maxFogLengthFallOff = 0.5f; _height = 6.5f; _heightFallOff = 0.6f; _deepObscurance = 1f; _stepping = 10; _steppingNear = 0; _alpha = 1; _color = new Color(0.89f, 0.89f, 0.89f, 1); _skyColor = new Color(0.81f, 0.81f, 0.81f); _specularColor = new Color(1, 1, 0.8f, 1); _specularIntensity = 0.1f; _specularThreshold = 0.6f; _lightColor = Color.white; _lightIntensity = 0; _speed = 0.15f; _downsampling = 1; _baselineRelativeToCamera = false; CheckWaterLevel(false); _fogVoidRadius = 0; CopyTransitionValues(); break; case FOG_PRESET.GroundFog: _skySpeed = 0.3f; _skyHaze = 0; _skyNoiseStrength = 0.1f; _skyAlpha = 0.85f; _density = 0.6f; _noiseStrength = 0.479f; _noiseScale = 1.15f; _skyNoiseScale = 1.15f; _noiseSparse = 0f; _distance = 5; _distanceFallOff = 1f; _maxFogLengthFallOff = 0.6f; _height = 1.5f; _heightFallOff = 0.6f; _deepObscurance = 1f; _stepping = 8; _steppingNear = 0; _alpha = 0.95f; _color = new Color(0.89f, 0.89f, 0.89f, 1); _skyColor = new Color(0.79f, 0.79f, 0.79f, 1); _specularColor = new Color(1, 1, 0.8f, 1); _specularIntensity = 0.2f; _specularThreshold = 0.6f; _lightColor = Color.white; _lightIntensity = 0.2f; _speed = 0.01f; _downsampling = 1; _baselineRelativeToCamera = false; CheckWaterLevel(false); _fogVoidRadius = 0; CopyTransitionValues(); break; case FOG_PRESET.FrostedGround: _skySpeed = 0; _skyHaze = 0; _skyNoiseStrength = 0.729f; _skyAlpha = 0.55f; _density = 1; _noiseStrength = 0.164f; _noiseScale = 1.81f; _skyNoiseScale = 1.81f; _noiseSparse = 0f; _distance = 0; _distanceFallOff = 0; _height = 0.5f; _heightFallOff = 0.6f; _deepObscurance = 1f; _stepping = 20; _steppingNear = 50; _alpha = 0.97f; _color = new Color(0.546f, 0.648f, 0.710f, 1); _skyColor = _color; _specularColor = new Color(0.792f, 0.792f, 0.792f, 1); _specularIntensity = 1; _specularThreshold = 0.866f; _lightColor = new Color(0.972f, 0.972f, 0.972f, 1); _lightIntensity = 0.743f; _speed = 0; _downsampling = 1; _baselineRelativeToCamera = false; CheckWaterLevel(false); _fogVoidRadius = 0; CopyTransitionValues(); break; case FOG_PRESET.FoggyLake: _skySpeed = 0.3f; _skyHaze = 40; _skyNoiseStrength = 0.574f; _skyAlpha = 0.827f; _density = 1; _noiseStrength = 0.03f; _noiseScale = 5.77f; _skyNoiseScale = 5.77f; _noiseSparse = 0f; _distance = 0; _distanceFallOff = 0; _maxFogLengthFallOff = 0.6f; _height = 4; _heightFallOff = 0.6f; _deepObscurance = 1f; _stepping = 6; _steppingNear = 14.4f; _alpha = 1; _color = new Color(0, 0.960f, 1, 1); _skyColor = _color; _specularColor = Color.white; _lightColor = Color.white; _specularIntensity = 0.861f; _specularThreshold = 0.907f; _lightIntensity = 0.126f; _speed = 0; _downsampling = 1; _baselineRelativeToCamera = false; CheckWaterLevel(false); _fogVoidRadius = 0; CopyTransitionValues(); break; case FOG_PRESET.LowClouds: _skySpeed = 0.3f; _skyHaze = 60; _skyNoiseStrength = 0.97f; _skyAlpha = 0.96f; _density = 1; _noiseStrength = 0.7f; _noiseScale = 1; _skyNoiseScale = 1f; _noiseSparse = 0f; _distance = 0; _distanceFallOff = 0; _maxFogLengthFallOff = 0.6f; _height = 4f; _heightFallOff = 0.6f; _deepObscurance = 1f; _stepping = 12; _steppingNear = 0; _alpha = 0.98f; _color = new Color(0.89f, 0.89f, 0.89f, 1); _skyColor = new Color(0.79f, 0.79f, 0.79f, 1); _specularColor = new Color(1, 1, 0.8f, 1); _specularIntensity = 0.15f; _specularThreshold = 0.6f; _lightColor = Color.white; _lightIntensity = 0.15f; _speed = 0.008f; _downsampling = 1; _baselineRelativeToCamera = false; CheckWaterLevel(false); _fogVoidRadius = 0; CopyTransitionValues(); break; case FOG_PRESET.SeaClouds: _skySpeed = 0.3f; _skyHaze = 60; _skyNoiseStrength = 0.97f; _skyAlpha = 0.96f; _density = 1; _noiseStrength = 1; _noiseScale = 1.5f; _skyNoiseScale = 1.5f; _noiseSparse = 0f; _distance = 0; _distanceFallOff = 0; _maxFogLengthFallOff = 0.7f; _deepObscurance = 1f; _height = 12.4f; _heightFallOff = 0.6f; _stepping = 6; _alpha = 0.98f; _color = new Color(0.89f, 0.89f, 0.89f, 1); _skyColor = new Color(0.83f, 0.83f, 0.83f, 1); _specularColor = new Color(1, 1, 0.8f, 1); _specularIntensity = 0.259f; _specularThreshold = 0.6f; _lightColor = Color.white; _lightIntensity = 0.15f; _speed = 0.008f; _downsampling = 1; _baselineRelativeToCamera = false; CheckWaterLevel(false); _fogVoidRadius = 0; CopyTransitionValues(); break; case FOG_PRESET.Fog: _skySpeed = 0.3f; _skyHaze = 144; _skyNoiseStrength = 0.7f; _skyAlpha = 0.9f; _density = 0.35f; _noiseStrength = 0.3f; _noiseScale = 1; _skyNoiseScale = 1f; _noiseSparse = 0f; _distance = 20; _distanceFallOff = 0.7f; _maxFogLengthFallOff = 0.5f; _height = 8; _heightFallOff = 0.6f; _deepObscurance = 1f; _stepping = 8; _steppingNear = 0; _alpha = 0.97f; _color = new Color(0.89f, 0.89f, 0.89f, 1); _skyColor = new Color(0.79f, 0.79f, 0.79f, 1); _specularColor = new Color(1, 1, 0.8f, 1); _specularIntensity = 0; _specularThreshold = 0.6f; _lightColor = Color.white; _lightIntensity = 0; _speed = 0.05f; _downsampling = 1; _baselineRelativeToCamera = false; CheckWaterLevel(false); _fogVoidRadius = 0; CopyTransitionValues(); break; case FOG_PRESET.HeavyFog: _skySpeed = 0.05f; _skyHaze = 500; _skyNoiseStrength = 0.826f; _skyAlpha = 1; _density = 0.35f; _noiseStrength = 0.1f; _noiseScale = 1; _skyNoiseScale = 1f; _noiseSparse = 0f; _distance = 20; _distanceFallOff = 0.8f; _deepObscurance = 1f; _height = 18; _heightFallOff = 0.6f; _stepping = 6; _steppingNear = 0; _alpha = 1; _color = new Color(0.91f, 0.91f, 0.91f, 1f); _skyColor = new Color(0.79f, 0.79f, 0.79f, 1); _specularColor = new Color(1, 1, 0.8f, 1); _specularIntensity = 0; _specularThreshold = 0.6f; _lightColor = Color.white; _lightIntensity = 0; _speed = 0.015f; _downsampling = 1; _baselineRelativeToCamera = false; CheckWaterLevel(false); _fogVoidRadius = 0; CopyTransitionValues(); break; case FOG_PRESET.SandStorm1: _skySpeed = 0.35f; _skyHaze = 388; _skyNoiseStrength = 0.847f; _skyAlpha = 1; _density = 0.487f; _noiseStrength = 0.758f; _noiseScale = 1.71f; _skyNoiseScale = 1.71f; _noiseSparse = 0f; _distance = 0; _distanceFallOff = 0; _height = 16; _heightFallOff = 0.6f; _deepObscurance = 1f; _stepping = 6; _steppingNear = 0; _alpha = 1; _color = new Color(0.505f, 0.505f, 0.505f, 1); _skyColor = _color; _specularColor = new Color(1, 1, 0.8f, 1); _specularIntensity = 0; _specularThreshold = 0.6f; _lightColor = Color.white; _lightIntensity = 0; _speed = 0.3f; _windDirection = Vector3.right; _downsampling = 1; _baselineRelativeToCamera = false; CheckWaterLevel(false); _fogVoidRadius = 0; CopyTransitionValues(); break; case FOG_PRESET.Smoke: _skySpeed = 0.109f; _skyHaze = 10; _skyNoiseStrength = 0.119f; _skyAlpha = 1; _density = 1; _noiseStrength = 0.767f; _noiseScale = 1.6f; _skyNoiseScale = 1.6f; _noiseSparse = 0f; _distance = 0; _distanceFallOff = 0f; _maxFogLengthFallOff = 0.7f; _height = 8; _heightFallOff = 0.6f; _deepObscurance = 1f; _stepping = 12; _steppingNear = 25; _alpha = 1; _color = new Color(0.125f, 0.125f, 0.125f, 1); _skyColor = _color; _specularColor = new Color(1, 1, 1, 1); _specularIntensity = 0.575f; _specularThreshold = 0.6f; _lightColor = Color.white; _lightIntensity = 1; _speed = 0.075f; _windDirection = Vector3.right; _downsampling = 1; _baselineRelativeToCamera = false; CheckWaterLevel(false); _baselineHeight += 8f; _fogVoidRadius = 0; CopyTransitionValues(); break; case FOG_PRESET.ToxicSwamp: _skySpeed = 0.062f; _skyHaze = 22; _skyNoiseStrength = 0.694f; _skyAlpha = 1; _density = 1; _noiseStrength = 1; _noiseScale = 1; _skyNoiseScale = 1; _noiseSparse = 0f; _distance = 0; _distanceFallOff = 0; _height = 2.5f; _heightFallOff = 0.6f; _deepObscurance = 1f; _stepping = 20; _steppingNear = 50; _alpha = 0.95f; _color = new Color(0.0238f, 0.175f, 0.109f, 1); _skyColor = _color; _specularColor = new Color(0.593f, 0.625f, 0.207f, 1); _specularIntensity = 0.735f; _specularThreshold = 0.6f; _lightColor = new Color(0.730f, 0.746f, 0.511f, 1); _lightIntensity = 0.492f; _speed = 0.0003f; _windDirection = Vector3.right; _downsampling = 1; _baselineRelativeToCamera = false; CheckWaterLevel(false); _fogVoidRadius = 0; CopyTransitionValues(); break; case FOG_PRESET.SandStorm2: _skySpeed = 0; _skyHaze = 0; _skyNoiseStrength = 0.729f; _skyAlpha = 0.55f; _density = 0.545f; _noiseStrength = 1; _noiseScale = 3; _skyNoiseScale = 3; _noiseSparse = 0f; _distance = 0; _distanceFallOff = 0; _height = 12; _heightFallOff = 0.6f; _deepObscurance = 1f; _stepping = 5; _steppingNear = 19.6f; _alpha = 0.96f; _color = new Color(0.609f, 0.609f, 0.609f, 1); _skyColor = _color; _specularColor = new Color(0.589f, 0.621f, 0.207f, 1); _specularIntensity = 0.505f; _specularThreshold = 0.6f; _lightColor = new Color(0.726f, 0.742f, 0.507f, 1); _lightIntensity = 0.581f; _speed = 0.168f; _windDirection = Vector3.right; _downsampling = 1; _baselineRelativeToCamera = false; CheckWaterLevel(false); _fogVoidRadius = 0; CopyTransitionValues(); break; case FOG_PRESET.WorldEdge: _skySpeed = 0.3f; _skyHaze = 60; _skyNoiseStrength = 0.97f; _skyAlpha = 0.96f; _density = 1; _noiseStrength = 1; _noiseScale = 3f; _skyNoiseScale = 3f; _noiseSparse = 0f; _distance = 0; _distanceFallOff = 0; _maxFogLengthFallOff = 1f; _height = 20f; _heightFallOff = 0.6f; _deepObscurance = 1f; _stepping = 6; _alpha = 0.98f; _color = new Color(0.89f, 0.89f, 0.89f, 1); _skyColor = _color; _specularColor = new Color(1, 1, 0.8f, 1); _specularIntensity = 0.259f; _specularThreshold = 0.6f; _lightColor = Color.white; _lightIntensity = 0.15f; _speed = 0.03f; _downsampling = 2; _baselineRelativeToCamera = false; CheckWaterLevel(false); Terrain terrain = GetActiveTerrain(); if (terrain != null) { _fogVoidPosition = terrain.transform.position + terrain.terrainData.size * 0.5f; _fogVoidRadius = terrain.terrainData.size.x * 0.45f; _fogVoidHeight = terrain.terrainData.size.y; _fogVoidDepth = terrain.terrainData.size.z * 0.45f; _fogVoidFallOff = 6f; _fogAreaRadius = 0; _character = null; _fogAreaCenter = null; float terrainSize = terrain.terrainData.size.x; if (mainCamera.farClipPlane < terrainSize) mainCamera.farClipPlane = terrainSize; if (_maxFogLength < terrainSize * 0.6f) _maxFogLength = terrainSize * 0.6f; } CopyTransitionValues(); break; } currentFogAlpha = _alpha; currentFogColor = _color; currentFogSpecularColor = _specularColor; currentLightColor = _lightColor; currentSkyHazeAlpha = _skyAlpha; UpdateSun(); FogOfWarUpdateTexture(); UpdateMaterialProperties(true); UpdateRenderComponents(); UpdateTextureAlpha(); UpdateTexture(); if (_sunShadows) { needUpdateDepthSunTexture = true; } else { DestroySunShadowsDependencies(); } if (!Application.isPlaying) { UpdateWindSpeedQuick(); } TrackPointLights(); lastTimeSortInstances = 0; } public void CheckWaterLevel(bool baseZero) { if (mainCamera == null) return; if (_baselineHeight > mainCamera.transform.position.y || baseZero) _baselineHeight = 0; #if GAIA_PRESENT GaiaSceneInfo sceneInfo = GaiaSceneInfo.GetSceneInfo(); _baselineHeight = sceneInfo.m_seaLevel; #else // Finds water GameObject water = GameObject.Find("Water"); if (water == null) { GameObject[] gos = GameObject.FindObjectsOfType<GameObject>(); for (int k = 0; k < gos.Length; k++) { if (gos[k] != null && gos[k].layer == 4) { water = gos[k]; break; } } } if (water != null) { _renderBeforeTransparent = false; // adds compatibility with water if (_baselineHeight < water.transform.position.y) _baselineHeight = water.transform.position.y; } #endif UpdateMaterialHeights(mainCamera); } /// <summary> /// Get the currently active terrain - or any terrain /// </summary> /// <returns>A terrain if there is one</returns> public static Terrain GetActiveTerrain() { //Grab active terrain if we can Terrain terrain = Terrain.activeTerrain; if (terrain != null && terrain.isActiveAndEnabled) { return terrain; } //Then check rest of terrains for (int idx = 0; idx < Terrain.activeTerrains.Length; idx++) { terrain = Terrain.activeTerrains[idx]; if (terrain != null && terrain.isActiveAndEnabled) { return terrain; } } return null; } void UpdateMaterialFogColor() { Color color = currentFogColor; color.r *= 2f * temporaryProperties.color.r; color.g *= 2f * temporaryProperties.color.g; color.b *= 2f * temporaryProperties.color.b; color.a = 1f - _heightFallOff; fogMat.SetColor("_Color", color); } void UpdateMaterialHeights(Camera mainCamera) { currentFogAltitude = _baselineHeight; Vector3 adjustedFogAreaPosition = _fogAreaPosition; if (_fogAreaRadius > 0) { //if (_fogAreaCenter != null && _fogAreaFollowMode == FOG_AREA_FOLLOW_MODE.FullXYZ) { //currentFogAltitude += _fogAreaCenter.transform.position.y; //} currentFogAltitude += _fogAreaPosition.y; if (_useXYPlane) { adjustedFogAreaPosition.z = 0; // baseHeight; } else { adjustedFogAreaPosition.y = 0; // baseHeight; } } if (_baselineRelativeToCamera && !_useXYPlane) { oldBaselineRelativeCameraY += (mainCamera.transform.position.y - oldBaselineRelativeCameraY) * Mathf.Clamp01(1.001f - _baselineRelativeToCameraDelay); currentFogAltitude += oldBaselineRelativeCameraY - 1f; } float scale = 0.01f / _noiseScale; fogMat.SetVector("_FogData", new Vector4(currentFogAltitude, _height, 1.0f / (_density * temporaryProperties.density), scale)); fogMat.SetFloat("_FogSkyHaze", _skyHaze + currentFogAltitude); Vector3 v = _fogVoidPosition - currentFogAltitude * Vector3.up; fogMat.SetVector("_FogVoidPosition", v); fogMat.SetVector("_FogAreaPosition", adjustedFogAreaPosition); } /// <summary> /// Updates the material properties. /// </summary> public void UpdateMaterialProperties(bool forceNow = false) { if (forceNow || !Application.isPlaying) { UpdateMaterialPropertiesNow(); } else { shouldUpdateMaterialProperties = true; } } /// <summary> /// Updates material immediately /// </summary> public void UpdateMaterialPropertiesNow() { UpdateMaterialPropertiesNow(mainCamera); } void UpdateMaterialPropertiesNow(Camera mainCamera) { if (fogMat == null || fogRenderer==null) return; shouldUpdateMaterialProperties = false; UpdateSkyColor(_skyAlpha); fogMat.SetFloat("_DeepObscurance", _deepObscurance); Vector4 fogStepping = new Vector4(1.0f / (_stepping + 1.0f), 1 / (1 + _steppingNear), _edgeThreshold, _dithering ? _ditherStrength * 0.01f : 0f); fogMat.SetFloat("_Jitter", _jitterStrength); if (!_edgeImprove) { fogStepping.z = 0; } fogMat.SetVector("_FogStepping", fogStepping); fogMat.SetFloat("_FogAlpha", currentFogAlpha); UpdateMaterialHeights(mainCamera); float scale = 0.01f / _noiseScale; if (_maxFogLength < 0) { _maxFogLength = 0; } float maxFogLengthFallOff = _maxFogLength - _maxFogLength * (1f - _maxFogLengthFallOff) + 1.0f; fogMat.SetVector("_FogDistance", new Vector4(scale * scale * _distance * _distance, (_distanceFallOff * _distanceFallOff + 0.1f), _maxFogLength, maxFogLengthFallOff)); UpdateMaterialFogColor(); // enable shader options if (shaderKeywords == null) { shaderKeywords = new List<string>(); } else { shaderKeywords.Clear(); } if (_distance > 0) shaderKeywords.Add(SKW_FOG_DISTANCE_ON); if (_fogVoidRadius > 0 && _fogVoidFallOff > 0) { Vector4 voidData = new Vector4(1.0f / (1.0f + _fogVoidRadius), 1.0f / (1.0f + _fogVoidHeight), 1.0f / (1.0f + _fogVoidDepth), _fogVoidFallOff); if (_fogVoidTopology == FOG_VOID_TOPOLOGY.Box) { shaderKeywords.Add(SKW_FOG_VOID_BOX); } else { shaderKeywords.Add(SKW_FOG_VOID_SPHERE); } fogMat.SetVector("_FogVoidData", voidData); } if (_fogAreaRadius > 0 && _fogAreaFallOff > 0) { Vector4 areaData = new Vector4(1.0f / (0.0001f + _fogAreaRadius), 1.0f / (0.0001f + _fogAreaHeight), 1.0f / (0.0001f + _fogAreaDepth), _fogAreaFallOff); if (_fogAreaTopology == FOG_AREA_TOPOLOGY.Box) { shaderKeywords.Add(SKW_FOG_AREA_BOX); } else { shaderKeywords.Add(SKW_FOG_AREA_SPHERE); areaData.y = _fogAreaRadius * _fogAreaRadius; areaData.x /= scale; areaData.z /= scale; } fogMat.SetVector("_FogAreaData", areaData); } if (_skyHaze<0) { _skyHaze = 0; } if (_skyHaze > 0 && _skyAlpha > 0 && !_useXYPlane && hasCamera) { shaderKeywords.Add(SKW_FOG_HAZE_ON); } if (_fogOfWarEnabled) { shaderKeywords.Add(SKW_FOG_OF_WAR_ON); fogMat.SetTexture("_FogOfWar", fogOfWarTexture); fogMat.SetVector("_FogOfWarCenter", _fogOfWarCenter); fogMat.SetVector("_FogOfWarSize", _fogOfWarSize); Vector3 ca = _fogOfWarCenter - 0.5f * _fogOfWarSize; if (_useXYPlane) { fogMat.SetVector("_FogOfWarCenterAdjusted", new Vector3(ca.x / _fogOfWarSize.x, ca.y / (_fogOfWarSize.y + 0.0001f), 1f)); } else { fogMat.SetVector("_FogOfWarCenterAdjusted", new Vector3(ca.x / _fogOfWarSize.x, 1f, ca.z / (_fogOfWarSize.z + 0.0001f))); } } // Check proper array initialization of point lights CheckPointLightData(); bool usesPointLights = false; for (int k = 0; k < pointLightParams.Length; k++) { if (pointLightParams[k].light != null || pointLightParams[k].range * pointLightParams[k].intensity > 0) { usesPointLights = true; break; } } if (usesPointLights) { fogMat.SetFloat("_PointLightInsideAtten", _pointLightInsideAtten); shaderKeywords.Add(SKW_POINT_LIGHTS); } sunShadowsActive = false; if (fogRenderer.sun) { UpdateScatteringData(mainCamera); if (_lightScatteringEnabled) { if (_lightScatteringExposure > 0) { shaderKeywords.Add(SKW_LIGHT_SCATTERING); } } if (_sunShadows) { sunShadowsActive = true; shaderKeywords.Add(SKW_SUN_SHADOWS); UpdateSunShadowsData(); SetupDirectionalLightCommandBuffer(); } } if (_fogBlur) { shaderKeywords.Add(SKW_FOG_BLUR); fogMat.SetFloat("_FogBlurDepth", _fogBlurDepth); } if (_useXYPlane) { shaderKeywords.Add(SKW_FOG_USE_XY_PLANE); } if (fogRenderer.computeDepth) { shaderKeywords.Add(SKW_FOG_COMPUTE_DEPTH); } fogMat.shaderKeywords = shaderKeywords.ToArray(); if (_computeDepth && _computeDepthScope == COMPUTE_DEPTH_SCOPE.TreeBillboardsAndTransparentObjects) { Shader.SetGlobalFloat("_VFM_CutOff", _transparencyCutOff); } } /// <summary> /// Notifies other fog instancies of property changes on this main cam script /// </summary> public void NotifyChangesToFogInstances() { if (!hasCamera) return; int instancesCount = fogInstances != null ? fogInstances.Count : 0; for (int k = 0; k < instancesCount; k++) { VolumetricFog fog = fogInstances[k]; if (fog != null && fog != this) { fog.UpdateMaterialProperties(); } } } void UpdateSunShadowsData() { if (_sun == null || !_sunShadows || fogMat == null) return; float shadowStrength = _sunShadowsStrength * Mathf.Clamp01((-_sun.transform.forward.y) * 10f); if (shadowStrength < 0) { shadowStrength = 0; } if (shadowStrength > 0 && !fogMat.IsKeywordEnabled(SKW_SUN_SHADOWS)) { fogMat.EnableKeyword(SKW_SUN_SHADOWS); } else if (shadowStrength <= 0 && fogMat.IsKeywordEnabled(SKW_SUN_SHADOWS)) { fogMat.DisableKeyword(SKW_SUN_SHADOWS); } if (_hasCamera) { Shader.SetGlobalVector("_VolumetricFogSunShadowsData", new Vector4(shadowStrength, _sunShadowsJitterStrength, _sunShadowsCancellation, 0)); #pragma warning disable 0162 #pragma warning disable 0429 if (USE_DIRECTIONAL_LIGHT_COOKIE && sunLight != null) { fogMat.SetTexture ("_VolumetricFogLightCookie", sunLight.cookie); } #pragma warning restore 0429 #pragma warning restore 0162 } } #pragma warning disable 0162 #pragma warning disable 0429 void SetupDirectionalLightCommandBuffer() { if (!USE_UNITY_SHADOW_MAP || _sun == null) return; Light light = _sun.GetComponent<Light>(); if (light == null || light.type != LightType.Directional) { Debug.LogError("Sun reference does not have a valid directional light."); return; } if (_sun.GetComponent<ShadowMapCopy>() == null) { _sun.AddComponent<ShadowMapCopy>(); } } #pragma warning restore 0429 #pragma warning restore 0162 void RemoveDirectionalLightCommandBuffer() { if (_sun == null) return; ShadowMapCopy sm = _sun.GetComponent<ShadowMapCopy>(); if (sm != null) { DestroyImmediate(sm); } } void UpdateWindSpeedQuick() { if (fogMat == null) return; if (Application.isPlaying && lastFrameAppliedWind == Time.frameCount) { return; } lastFrameAppliedWind = Time.frameCount; // fog speed windSpeedAcum += deltaTime * _windDirection * _speed; fogMat.SetVector("_FogWindDir", new Vector3(windSpeedAcum.x % noiseTextureSize, 0, windSpeedAcum.z % noiseTextureSize)); // sky speed skyHazeSpeedAcum += deltaTime * _skySpeed / 20f; fogMat.SetVector("_FogSkyData", new Vector4(_skyHaze, _skyNoiseStrength / (0.0001f + _density * temporaryProperties.density), skyHazeSpeedAcum, _skyDepth)); } void UpdateScatteringData(Camera mainCamera) { Vector3 sunSkyPos = mainCamera.transform.position + _lightDirection * 1000f; Vector3 viewportPos = mainCamera.WorldToViewportPoint(sunSkyPos, UnityEngine.XR.XRSettings.enabled ? Camera.MonoOrStereoscopicEye.Left : Camera.MonoOrStereoscopicEye.Mono); if (viewportPos.z < 0) { Vector2 screenSunPos = new Vector2(viewportPos.x, viewportPos.y); float night = Mathf.Clamp01(1.0f - _lightDirection.y); if (screenSunPos != oldSunPos) { oldSunPos = screenSunPos; sunFade = Mathf.SmoothStep(1, 0, (screenSunPos - Vector2.one * 0.5f).magnitude * 0.5f) * night; } fogMat.SetVector("_SunPosition", screenSunPos); if (UnityEngine.XR.XRSettings.enabled) { Vector3 sunScrPosRightEye = mainCamera.WorldToViewportPoint(sunSkyPos, Camera.MonoOrStereoscopicEye.Right); fogMat.SetVector("_SunPositionRightEye", sunScrPosRightEye); } if (_lightScatteringEnabled && !fogMat.IsKeywordEnabled(SKW_LIGHT_SCATTERING)) { fogMat.EnableKeyword(SKW_LIGHT_SCATTERING); } float intensity = _lightScatteringExposure * sunFade; fogMat.SetVector("_FogScatteringData", new Vector4(_lightScatteringSpread / _lightScatteringSamples, intensity > 0 ? _lightScatteringSamples : 0, intensity, _lightScatteringWeight / (float)_lightScatteringSamples)); fogMat.SetVector("_FogScatteringData2", new Vector4(_lightScatteringIllumination, _lightScatteringDecay, _lightScatteringJittering, _lightScatteringEnabled && LIGHT_DIFFUSION_ENABLED ? 1.2f * _lightScatteringDiffusion * night * sunLightIntensity : 0)); fogMat.SetVector("_SunDir", -_lightDirection); fogMat.SetColor("_SunColor", _lightColor); } else { if (fogMat.IsKeywordEnabled(SKW_LIGHT_SCATTERING)) { fogMat.DisableKeyword(SKW_LIGHT_SCATTERING); } } } void UpdateSun() { if (fogRenderer != null && fogRenderer.sun != null) { sunLight = fogRenderer.sun.GetComponent<Light>(); } else { sunLight = null; } } void UpdateSkyColor(float alpha) { if (fogMat == null) return; Color skyColorAdj = skyHazeLightColor; skyColorAdj.a = alpha; fogMat.SetColor("_FogSkyColor", skyColorAdj); fogMat.SetFloat("_FogSkyNoiseScale", 0.01f / _skyNoiseScale); } #endregion #region Noise texture work void UpdateTextureAlpha() { // Precompute fog height into alpha channel if (adjustedColors == null) return; float fogNoise = Mathf.Clamp(_noiseStrength, 0, 0.95f); // clamped to prevent flat fog on top for (int k = 0; k < adjustedColors.Length; k++) { float t = 1.0f - (_noiseSparse + noiseColors[k].b) * fogNoise; t *= _density * temporaryProperties.density * _noiseFinalMultiplier; if (t < 0) t = 0; else if (t > 1) t = 1f; adjustedColors[k].a = t; } hasChangeAdjustedColorsAlpha = true; } void UpdateTexture() { if (fogMat == null) return; // Precompute light color ComputeLightColor(); if (Application.isPlaying) { // && !hasChangeAdjustedColorsAlpha) { updatingTextureSlice = 0; } else { updatingTextureSlice = -1; } UpdateTextureColors(adjustedColors, hasChangeAdjustedColorsAlpha); needUpdateTexture = false; // Check Sun position UpdateSkyColor(_skyAlpha); } void ComputeLightColor() { float fogIntensity = (_lightIntensity + sunLightIntensity); if (!_useXYPlane) { fogIntensity *= Mathf.Clamp01(1.0f - _lightDirection.y * 2.0f); // simulates sunset } switch (_lightingModel) { default: lastRenderSettingsAmbientLight = RenderSettings.ambientLight; lastRenderSettingsAmbientIntensity = RenderSettings.ambientIntensity; Color ambientMultiplied = lastRenderSettingsAmbientLight * lastRenderSettingsAmbientIntensity; updatingTextureLightColor = Color.Lerp(ambientMultiplied, currentLightColor * fogIntensity, fogIntensity); skyHazeLightColor = Color.Lerp(ambientMultiplied, _skyColor * fogIntensity, fogIntensity); break; case LIGHTING_MODEL.Natural: lastRenderSettingsAmbientLight = RenderSettings.ambientLight; lastRenderSettingsAmbientIntensity = RenderSettings.ambientIntensity; updatingTextureLightColor = Color.Lerp(lastRenderSettingsAmbientLight, currentLightColor * fogIntensity + lastRenderSettingsAmbientLight, _lightIntensity); skyHazeLightColor = Color.Lerp(lastRenderSettingsAmbientLight, _skyColor * fogIntensity + lastRenderSettingsAmbientLight, _lightIntensity); break; case LIGHTING_MODEL.SingleLight: lastRenderSettingsAmbientLight = Color.black; lastRenderSettingsAmbientIntensity = RenderSettings.ambientIntensity; updatingTextureLightColor = Color.Lerp(lastRenderSettingsAmbientLight, currentLightColor * fogIntensity, _lightIntensity); skyHazeLightColor = Color.Lerp(lastRenderSettingsAmbientLight, _skyColor * fogIntensity, _lightIntensity); break; } } void UpdateTextureColors(Color[] colors, bool forceUpdateEntireTexture) { Vector3 nlight; int nz, disp; float nyspec; float spec = 1.0001f - _specularThreshold; int tw = adjustedTexture.width; nlight = new Vector3(-_lightDirection.x, 0, -_lightDirection.z).normalized * 0.3f; nlight.y = _lightDirection.y > 0 ? Mathf.Clamp01(1.0f - _lightDirection.y) : 1.0f - Mathf.Clamp01(-_lightDirection.y); nz = Mathf.FloorToInt(nlight.z * tw) * tw; disp = (int)(nz + nlight.x * tw) + colors.Length; nyspec = nlight.y / spec; Color specularColor = currentFogSpecularColor * (1.0f + _specularIntensity) * _specularIntensity; bool hasChanged = false; if (updatingTextureSlice >= 1 || forceUpdateEntireTexture) hasChanged = true; float lcr = updatingTextureLightColor.r * 0.5f; float lcg = updatingTextureLightColor.g * 0.5f; float lcb = updatingTextureLightColor.b * 0.5f; float scr = specularColor.r * 0.5f; float scg = specularColor.g * 0.5f; float scb = specularColor.b * 0.5f; int count = colors.Length; int k0 = 0; int k1 = count; if (updatingTextureSlice >= 0) { if (updatingTextureSlice > _updateTextureSpread) { // detected change of configuration amid texture updates updatingTextureSlice = -1; needUpdateTexture = true; return; } k0 = count * updatingTextureSlice / _updateTextureSpread; k1 = count * (updatingTextureSlice + 1) / _updateTextureSpread; } int z = 0; for (int k = k0; k < k1; k++) { int indexg = (k + disp) % count; float a = colors[k].a; float r = (a - colors[indexg].a) * nyspec; if (r < 0f) r = 0f; else if (r > 1f) r = 1f; float cor = lcr + scr * r; float cog = lcg + scg * r; float cob = lcb + scb * r; if (!hasChanged) { if (z++ < 100) { if (cor != colors[k].r || cog != colors[k].g || cob != colors[k].b) { hasChanged = true; } } else if (!hasChanged) { break; } } colors[k].r = cor; colors[k].g = cog; colors[k].b = cob; } bool hasNewTextureData = forceUpdateEntireTexture; if (hasChanged) { if (updatingTextureSlice >= 0) { updatingTextureSlice++; if (updatingTextureSlice >= _updateTextureSpread) { updatingTextureSlice = -1; hasNewTextureData = true; } } else { hasNewTextureData = true; } } else { updatingTextureSlice = -1; } if (hasNewTextureData) { if (Application.isPlaying && _turbulenceStrength > 0f && adjustedChaosTexture) { adjustedChaosTexture.SetPixels(adjustedColors); adjustedChaosTexture.Apply(); } else { adjustedTexture.SetPixels(adjustedColors); adjustedTexture.Apply(); fogMat.SetTexture("_NoiseTex", adjustedTexture); } lastTextureUpdate = Time.time; } } internal void ApplyChaos() { if (!adjustedTexture || (Application.isPlaying && lastFrameAppliedChaos == Time.frameCount)) return; lastFrameAppliedChaos = Time.frameCount; if (chaosLerpMat == null) { Shader chaosLerp = Shader.Find("VolumetricFogAndMist/Chaos Lerp"); chaosLerpMat = new Material(chaosLerp); chaosLerpMat.hideFlags = HideFlags.DontSave; } turbAcum += deltaTime * _turbulenceStrength; chaosLerpMat.SetFloat("_Amount", turbAcum); if (!adjustedChaosTexture) { adjustedChaosTexture = Instantiate(adjustedTexture) as Texture2D; adjustedChaosTexture.hideFlags = HideFlags.DontSave; } RenderTexture rtAdjusted = RenderTexture.GetTemporary(adjustedTexture.width, adjustedTexture.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); rtAdjusted.wrapMode = TextureWrapMode.Repeat; Graphics.Blit(adjustedChaosTexture, rtAdjusted, chaosLerpMat); fogMat.SetTexture("_NoiseTex", rtAdjusted); RenderTexture.ReleaseTemporary(rtAdjusted); } #endregion #region Fog Volume void CopyTransitionValues() { currentFogAlpha = _alpha; currentSkyHazeAlpha = _skyAlpha; currentFogColor = _color; currentFogSpecularColor = _specularColor; currentLightColor = _lightColor; } public void SetTargetProfile(VolumetricFogProfile targetProfile, float duration) { if (!_useFogVolumes) return; this.initialProfile = ScriptableObject.CreateInstance<VolumetricFogProfile>(); this.initialProfile.Save(this); this.targetProfile = targetProfile; this.transitionDuration = duration; this.transitionStartTime = Time.time; this.transitionProfile = true; } public void ClearTargetProfile(float duration) { SetTargetProfile(initialProfile, duration); } public void SetTargetAlpha(float newFogAlpha, float newSkyHazeAlpha, float duration) { if (!_useFogVolumes) return; this.initialFogAlpha = currentFogAlpha; this.initialSkyHazeAlpha = currentSkyHazeAlpha; this.targetFogAlpha = newFogAlpha; this.targetSkyHazeAlpha = newSkyHazeAlpha; this.transitionDuration = duration; this.transitionStartTime = Time.time; this.transitionAlpha = true; } public void ClearTargetAlpha(float duration) { SetTargetAlpha(-1, -1, duration); } public void SetTargetColor(Color newColor, float duration) { if (!useFogVolumes) return; this.initialFogColor = currentFogColor; this.targetFogColor = newColor; this.transitionDuration = duration; this.transitionStartTime = Time.time; this.transitionColor = true; this.targetColorActive = true; } public void ClearTargetColor(float duration) { SetTargetColor(_color, duration); this.targetColorActive = false; } public void SetTargetSpecularColor(Color newSpecularColor, float duration) { if (!useFogVolumes) return; this.initialFogSpecularColor = currentFogSpecularColor; this.targetFogSpecularColor = newSpecularColor; this.transitionDuration = duration; this.transitionStartTime = Time.time; this.transitionSpecularColor = true; this.targetSpecularColorActive = true; } public void ClearTargetSpecularColor(float duration) { SetTargetSpecularColor(_specularColor, duration); this.targetSpecularColorActive = false; } public void SetTargetLightColor(Color newLightColor, float duration) { if (!useFogVolumes) return; this._sunCopyColor = false; this.initialLightColor = currentLightColor; this.targetLightColor = newLightColor; this.transitionDuration = duration; this.transitionStartTime = Time.time; this.transitionLightColor = true; this.targetLightColorActive = true; } public void ClearTargetLightColor(float duration) { SetTargetLightColor(_lightColor, duration); this.targetLightColorActive = false; } #endregion #region Point Light functions public void CheckPointLightData() { if (_pointLightTrackingPivot == null) { _pointLightTrackingPivot = transform; } // migrate old values if (!pointLightDataMigrated) { pointLightParams = new PointLightParams[MAX_POINT_LIGHTS]; for (int k = 0; k < _pointLightColors.Length; k++) { pointLightParams[k].color = _pointLightColors[k]; Light light = null; if (_pointLights[k] != null) { light = _pointLights[k].GetComponent<Light>(); } pointLightParams[k].light = light; pointLightParams[k].intensity = _pointLightIntensities[k]; pointLightParams[k].intensityMultiplier = _pointLightIntensitiesMultiplier[k]; pointLightParams[k].position = _pointLightPositions[k]; pointLightParams[k].range = _pointLightRanges[k]; pointLightParams[k].rangeMultiplier = 1f; } for (int k = _pointLightColors.Length; k < MAX_POINT_LIGHTS; k++) { PointLightDataSetDefaults(k); } pointLightDataMigrated = true; isDirty = true; #if UNITY_EDITOR EditorUtility.SetDirty(this); #endif } if (_pointLightTrackingCount > MAX_POINT_LIGHTS) { _pointLightTrackingCount = MAX_POINT_LIGHTS; isDirty = true; #if UNITY_EDITOR EditorUtility.SetDirty(this); #endif } // Ensure array consistency if (pointLightParams != null) { if (pointLightParams.Length != MAX_POINT_LIGHTS) { PointLightParams[] newData = new PointLightParams[MAX_POINT_LIGHTS]; int count = Mathf.Min(newData.Length, pointLightParams.Length); Array.Copy(pointLightParams, newData, count); pointLightParams = newData; for (int k = count; k < newData.Length; k++) { PointLightDataSetDefaults(k); } isDirty = true; #if UNITY_EDITOR EditorUtility.SetDirty(this); #endif } for (int k = 0; k < pointLightParams.Length; k++) { if (pointLightParams[k].rangeMultiplier <= 0) { pointLightParams[k].rangeMultiplier = 1f; } } } else { pointLightParams = new PointLightParams[MAX_POINT_LIGHTS]; for (int k = 0; k < pointLightParams.Length; k++) { PointLightDataSetDefaults(k); } isDirty = true; #if UNITY_EDITOR EditorUtility.SetDirty(this); #endif } if (currentLights == null || currentLights.Length != MAX_POINT_LIGHTS) { currentLights = new Light[MAX_POINT_LIGHTS]; } } void PointLightDataSetDefaults(int k) { if (k < pointLightParams.Length) { pointLightParams[k].color = new Color(1, 1, 0, 1); pointLightParams[k].intensity = 1f; pointLightParams[k].intensityMultiplier = 1f; pointLightParams[k].range = 0f; pointLightParams[k].rangeMultiplier = 1f; } } void SetPointLightMaterialProperties(Camera mainCamera) { int maxLights = pointLightParams.Length; if (pointLightColorBuffer == null || pointLightColorBuffer.Length != maxLights) { pointLightColorBuffer = new Vector4[maxLights]; } if (pointLightPositionBuffer == null || pointLightPositionBuffer.Length != maxLights) { pointLightPositionBuffer = new Vector4[maxLights]; } Vector3 camPos = mainCamera != null ? mainCamera.transform.position : Vector3.zero; for (int k = 0; k < maxLights; k++) { Vector3 pos = pointLightParams[k].position; if (!sunShadowsActive) { // when sun shadows are enabled, fogCeilingCut is not displaced in the shader pos.y -= _baselineHeight; } float range = pointLightParams[k].range * pointLightParams[k].rangeMultiplier * _pointLightInscattering / 25f; // note: 25 comes from Unity point light attenuation equation float multiplier = pointLightParams[k].intensity * pointLightParams[k].intensityMultiplier * _pointLightIntensity; if (range > 0 && multiplier > 0) { // Apply attenuation if light is affected by fog distance & falloff if (_distance > 0) { float scale = 0.01f / _noiseScale; float distScaled = _distance * scale; Vector2 lpos2 = new Vector2((camPos.x - pos.x) * scale, (camPos.z - pos.z) * scale); float atten = Mathf.Max((distScaled * distScaled - lpos2.sqrMagnitude), 0); atten *= (_distanceFallOff * _distanceFallOff + 0.1f); multiplier = multiplier > atten ? multiplier - atten : 0; } pointLightPositionBuffer[k].x = pos.x; pointLightPositionBuffer[k].y = pos.y; pointLightPositionBuffer[k].z = pos.z; pointLightPositionBuffer[k].w = 0; pointLightColorBuffer[k] = new Vector4(pointLightParams[k].color.r * multiplier, pointLightParams[k].color.g * multiplier, pointLightParams[k].color.b * multiplier, range); } else { pointLightColorBuffer[k] = black; } } #if UNITY_EDITOR if (!Application.isPlaying) { if (fogMat.HasProperty("_FogPointLightColor")) { Color[] existingColors = fogMat.GetColorArray("_FogPointLightColor"); if (existingColors.Length != pointLightColorBuffer.Length) { InitFogMaterial(); UnityEditorInternal.InternalEditorUtility.RepaintAllViews(); } } } #endif fogMat.SetVectorArray("_FogPointLightColor", pointLightColorBuffer); fogMat.SetVectorArray("_FogPointLightPosition", pointLightPositionBuffer); } public Light GetPointLight(int index) { if (index < 0 || index >= pointLightParams.Length) return null; return pointLightParams[index].light; } // Look for new lights void TrackNewLights() { lastFoundLights = GameObject.FindObjectsOfType<Light>(); } /// <summary> /// Look for nearest point lights /// </summary> public void TrackPointLights(bool forceImmediateUpdate = false) { if (!_pointLightTrackingAuto) return; if (_pointLightTrackingPivot == null) { _pointLightTrackingPivot = transform; } // Look for new lights? if (forceImmediateUpdate || lastFoundLights == null || !Application.isPlaying || (_pointLightTrackingNewLightsCheckInterval > 0 && Time.time - trackPointCheckNewLightsLastTime > _pointLightTrackingNewLightsCheckInterval)) { trackPointCheckNewLightsLastTime = Time.time; TrackNewLights(); } // Sort nearest lights int lightsFoundCount = lastFoundLights.Length; if (lightBuffer == null || lightBuffer.Length != lightsFoundCount) { lightBuffer = new Light[lightsFoundCount]; } for (int k = 0; k < lightsFoundCount; k++) { lightBuffer[k] = lastFoundLights[k]; } bool changes = false; for (int k = 0; k < pointLightParams.Length && k < currentLights.Length; k++) { Light g = null; if (k < _pointLightTrackingCount) { g = GetNearestLight(lightBuffer); } pointLightParams[k].light = g; if (pointLightParams[k].range != 0 && g == null) { pointLightParams[k].range = 0; // disables the light in case g is null } if (currentLights[k] != g) { currentLights[k] = g; changes = true; } } // Update if there's any change if (changes) { UpdateMaterialProperties(); } } Light GetNearestLight(Light[] lights) { float minDist = float.MaxValue; Vector3 camPos = _pointLightTrackingPivot.position; Light nearest = null; int selected = -1; for (int k = 0; k < lights.Length; k++) { Light light = lights[k]; if (light == null || !light.isActiveAndEnabled || light.type != LightType.Point) continue; float dist = (light.transform.position - camPos).sqrMagnitude; if (dist < minDist) { nearest = light; minDist = dist; selected = k; } } if (selected >= 0) { lights[selected] = null; } return nearest; } #endregion #region Fog Area API public static VolumetricFog CreateFogArea(Vector3 position, float radius, float height = 16, float fallOff = 1f) { VolumetricFog fog = CreateFogAreaPlaceholder(true, position, radius, height, radius); fog.preset = FOG_PRESET.SeaClouds; fog.transform.position = position; fog.skyHaze = 0; fog.dithering = true; return fog; } public static VolumetricFog CreateFogArea(Vector3 position, Vector3 boxSize) { VolumetricFog fog = CreateFogAreaPlaceholder(false, position, boxSize.x * 0.5f, boxSize.y * 0.5f, boxSize.z * 0.5f); fog.preset = FOG_PRESET.SeaClouds; fog.transform.position = position; fog.height = boxSize.y * 0.98f; fog.skyHaze = 0; return fog; } static VolumetricFog CreateFogAreaPlaceholder(bool spherical, Vector3 position, float radius, float height, float depth) { GameObject prefab = spherical ? Resources.Load<GameObject>("Prefabs/FogSphereArea") : Resources.Load<GameObject>("Prefabs/FogBoxArea"); GameObject box = Instantiate(prefab) as GameObject; box.transform.position = position; box.transform.localScale = new Vector3(radius, height, depth); return box.GetComponent<VolumetricFog>(); } public static void RemoveAllFogAreas() { VolumetricFog[] fogs = FindObjectsOfType<VolumetricFog>(); for (int k = 0; k < fogs.Length; k++) { if (fogs[k] != null && !fogs[k].hasCamera) { DestroyImmediate(fogs[k].gameObject); } } } void CheckFogAreaDimensions() { if (!_hasCamera && mr == null) mr = GetComponent<MeshRenderer>(); if (mr == null) return; Vector3 size = mr.bounds.extents; switch (_fogAreaTopology) { case FOG_AREA_TOPOLOGY.Box: fogAreaRadius = size.x; fogAreaHeight = size.y; fogAreaDepth = size.z; break; case FOG_AREA_TOPOLOGY.Sphere: fogAreaRadius = size.x; if (transform.localScale.z != transform.localScale.x) transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y, transform.localScale.x); break; } if (_fogAreaCenter != null) { if (_fogAreaFollowMode == FOG_AREA_FOLLOW_MODE.FullXYZ) { transform.position = _fogAreaCenter.transform.position; } else { transform.position = new Vector3(_fogAreaCenter.transform.position.x, transform.position.y, _fogAreaCenter.transform.position.z); } } fogAreaPosition = transform.position; } #if UNITY_EDITOR void OnDrawGizmos() { if (_fogAreaRadius > 0 && _fogAreaShowGizmos) { if (_fogAreaTopology == FOG_AREA_TOPOLOGY.Box) { Gizmos.DrawWireCube(fogAreaPosition, new Vector3(fogAreaRadius * 2f, fogAreaHeight * 2f, fogAreaDepth * 2f)); } else { Gizmos.DrawWireSphere(fogAreaPosition, fogAreaRadius); } } } void OnDrawGizmosSelected() { // Show the boundary of this fog effect if (_visibilityScope == FOG_VISIBILITY_SCOPE.Volume) { Gizmos.color = Color.green; Gizmos.DrawWireCube(visibilityVolume.center, visibilityVolume.size); } ShowFoWGizmo(); } #endif #endregion #region Screen Mask public void UpdateVolumeMask() { if (!_hasCamera || mainCamera == null) return; RemoveMaskCommandBuffer(); if (_enableMask) { if (maskCommandBuffer != null) { maskCommandBuffer.Clear(); } else { maskCommandBuffer = new CommandBuffer(); maskCommandBuffer.name = "Volumetric Fog Mask Write"; } if (maskMaterial == null) { maskMaterial = new Material(Shader.Find("VolumetricFogAndMist/MaskWrite")); } #if UNITY_2017_2_OR_NEWER if (UnityEngine.XR.XRSettings.enabled) { rtMaskDesc = UnityEngine.XR.XRSettings.eyeTextureDesc; } else { rtMaskDesc = new RenderTextureDescriptor(mainCamera.pixelWidth, mainCamera.pixelHeight); } #else rtMaskDesc = new RenderTextureDescriptor(mainCamera.pixelWidth, mainCamera.pixelHeight); #endif rtMaskDesc.colorFormat = RenderTextureFormat.Depth; rtMaskDesc.depthBufferBits = 24; rtMaskDesc.sRGB = false; rtMaskDesc.msaaSamples = 1; rtMaskDesc.useMipMap = false; rtMaskDesc.volumeDepth = 1; int downsampling = Mathf.Max(1, _maskDownsampling); rtMaskDesc.width /= downsampling; rtMaskDesc.height /= downsampling; var maskTarget = Shader.PropertyToID("_VolumetricFogScreenMaskTexture"); maskCommandBuffer.GetTemporaryRT(maskTarget, rtMaskDesc); maskCommandBuffer.SetRenderTarget(maskTarget); maskCommandBuffer.ClearRenderTarget(true, false, Color.white); Renderer[] rr = FindObjectsOfType<Renderer>(); for (int k = 0; k < rr.Length; k++) { if ((1 << rr[k].gameObject.layer & _maskLayer.value) != 0 && rr[k].gameObject.activeSelf) { if (rr[k].enabled && Application.isPlaying) rr[k].enabled = false; maskCommandBuffer.DrawRenderer(rr[k], maskMaterial); } } maskCommandBuffer.ReleaseTemporaryRT(maskTarget); mainCamera.AddCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, maskCommandBuffer); } } public void TogglePreviewMask() { Renderer[] rr = FindObjectsOfType<Renderer>(); for (int k = 0; k < rr.Length; k++) { if ((1 << rr[k].gameObject.layer & _maskLayer.value) != 0 && rr[k].gameObject.activeSelf) { rr[k].enabled = !rr[k].enabled; } } } void RemoveMaskCommandBuffer() { if (maskCommandBuffer != null && mainCamera != null) { mainCamera.RemoveCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, maskCommandBuffer); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio6 { class ContagemNomes { static void ContaIniciais(string Nome, ref int Conta) { { if ((Nome.Substring(0, 1) == "A") || (Nome.Substring(0, 1) == "B") || (Nome.Substring(0, 1) == "C")) Conta++; } } static void Main(string[] args) { int Conta = 0; string Nome; Console.Write("Digite um nome ou ZZZ "); Nome = Console.ReadLine().ToUpper(); while (Nome.ToUpper() != "ZZZ") { ContaIniciais(Nome, ref Conta); Console.Write("Digite um nome ou ZZZ "); Nome = Console.ReadLine().ToUpper(); } Console.WriteLine("Há {0} nomes começados por A, B ou C", Conta); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _3.CompareNumbers { class CompareNumbers { static void Main() { Console.WriteLine("Enter number with max floating-point precision of 7 digits:"); float firstNum = float.Parse(Console.ReadLine()); Console.WriteLine("Enter second number with max floating-point precision of 7 digits:"); float secondNum = float.Parse(Console.ReadLine()); bool equalNumbers = (firstNum == secondNum); Console.WriteLine("The numbers are equal up to the 7th floating point digit: {0}", equalNumbers); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; class Trigger { TriggerType triggertype; Vector2 position; int triggerW; int trigeersH; Rectangle rect; Script ActionScrint; bool NeedAction; public Trigger(Vector2 position , int triggerW,int triggerH , Script script, TriggerType triggerType) { this.triggertype = triggerType; this.position = position; this.trigeersH = triggerH; this.triggerW = triggerW; rect = new Rectangle((int)position.X, (int)position.Y, triggerW, triggerH); this.ActionScrint = script; NeedAction = true; } public virtual void Action (Rectangle targetRect) { if (rect.Intersects(targetRect) & NeedAction) { if (triggertype == TriggerType.OnEnter) { ActionScrint.Action(); NeedAction = false; } else if (triggertype == TriggerType.OnState) { ActionScrint.Action(); } } } }
namespace DFC.ServiceTaxonomy.CustomFields.ViewModels { public class EmptyViewModel {} }
namespace CarDealer.Models.ViewModels.Sales { using System.ComponentModel; public class ReviewSaleViewModel { public string Customer { get; set; } public int CustomerId { get; set; } public string Car { get; set; } public int CarId { get; set; } public double Discount { get; set; } [DisplayName("Car Price")] public double CarPrice { get; set; } [DisplayName("Final Car Price")] public double FinalPrice { get; set; } } }
using System; using UnityEngine; public class Timer : MonoBehaviour { private float _seconds; private bool _time = false; public event Action TimerDone; public void StartTimer(int seconds) { _seconds = seconds; _time = true; } private void Update() { if (_time) { _seconds -= Time.deltaTime; if(_seconds < 0) { TimerDone(); _time = false; _seconds = 0; } } } }
using EntVenta; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DatVentas { public class DatDetalleVenta { public int Insertar_DetalleVenta(DetalleVenta dv) { using (SqlConnection conn = new SqlConnection(MasterConnection.connection)) { try { int resultado = 0; conn.Open(); SqlCommand sc = new SqlCommand("[sp_detalle_venta]", conn); sc.CommandType = CommandType.StoredProcedure; sc.Parameters.AddWithValue("@productoid", dv.IdProducto); sc.Parameters.AddWithValue("@cantidad", dv.Cantidad); sc.Parameters.AddWithValue("@precio", dv.Precio); sc.Parameters.AddWithValue("@totalpagar", dv.TotalPago); sc.Parameters.AddWithValue("@unidadmedida", dv.UnidadMedida); sc.Parameters.AddWithValue("@cantidadmostrada", dv.CantidaMostrada); sc.Parameters.AddWithValue("@estado",dv.Estado); sc.Parameters.AddWithValue("@descripcion", dv.Descripcion); sc.Parameters.AddWithValue("@codigo", dv.Codigo); sc.Parameters.AddWithValue("@stock", dv.Stock); sc.Parameters.AddWithValue("@sevendea", dv.Se_Vende_A); sc.Parameters.AddWithValue("@usainventario", dv.UsaInventario); sc.Parameters.AddWithValue("@costo", dv.Costo); resultado = sc.ExecuteNonQuery(); conn.Close(); return resultado; } catch (Exception ex) { conn.Close(); throw ex; } } } public int Insertar_DetalleVentaEspera(DetalleVentaEspera dv) { using (SqlConnection conn = new SqlConnection(MasterConnection.connection)) { try { int resultado = 0; conn.Open(); SqlCommand sc = new SqlCommand("[sp_Insertar_detalleVentaEspera]", conn); sc.CommandType = CommandType.StoredProcedure; sc.Parameters.AddWithValue("@productoid", dv.IdProducto); sc.Parameters.AddWithValue("@idpresentacion", dv.IdPresentacion); sc.Parameters.AddWithValue("@descripcion", dv.Descripcion); sc.Parameters.AddWithValue("@unidadmedida", dv.UnidadMedida); sc.Parameters.AddWithValue("@cantidad", dv.Cantidad); sc.Parameters.AddWithValue("@precio", dv.Precio); sc.Parameters.AddWithValue("@totalpagar", dv.TotalPago); sc.Parameters.AddWithValue("@stock", dv.Stock); sc.Parameters.AddWithValue("@usainventario", dv.UsaInventario); resultado = sc.ExecuteNonQuery(); conn.Close(); return resultado; } catch (Exception ex) { conn.Close(); throw ex; } } } public DataTable ObtenerDetalle_VentaEnEspera(int idVenta) { using (SqlConnection con = new SqlConnection(MasterConnection.connection)) { try { DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(@"select * from tb_DetalleVentaEspera WHERE VentaId=" + idVenta, con); da.Fill(dt); return dt; } catch (Exception ex) { throw ex; } } } public int Eliminar_DetalleVentaEspera(int id) { using (SqlConnection conn = new SqlConnection(MasterConnection.connection)) { try { int resultado = 0; conn.Open(); SqlCommand sc = new SqlCommand("DELETE FROM tb_DetalleVentaEspera WHERE VentaId=" + id, conn); resultado = sc.ExecuteNonQuery(); conn.Close(); return resultado; } catch (Exception ex) { conn.Close(); throw ex; } } } public DataTable ObtenerDetalle_VentaPendiente(int idVenta) { using (SqlConnection con = new SqlConnection(MasterConnection.connection)) { try { DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter($"select * from tb_DetalleVenta WHERE Venta_Id={idVenta} AND ProductoDevuelto = 0 ", con); da.Fill(dt); return dt; } catch (Exception ex) { throw ex; } } } public DataTable ObtenerDatos_DetalleVenta(int idVenta) { try { using (SqlConnection con = new SqlConnection(MasterConnection.connection)) { DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter($"sp_ObtenerDatos_DetalleVenta {idVenta}", con); da.Fill(dt); return dt; } } catch (Exception ex) { throw ex; } } public void EditarDevolucion_DetalleVenta(int idVenta) { try { using (SqlConnection con = new SqlConnection(MasterConnection.connection)) { SqlCommand cmd = new SqlCommand($"UPDATE tb_DetalleVenta SET ProductoDevuelto = 1 where Id_DetalleVenta ={idVenta}", con); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } catch (Exception ex) { throw ex; } } public static void Productos_MasVendidos(ref DataTable dtDatos) { try { using (SqlConnection con = new SqlConnection(MasterConnection.connection)) { SqlDataAdapter da = new SqlDataAdapter("sp_ProductoMasVendidos", con); da.Fill(dtDatos); } } catch (Exception ex) { throw ex; } } public static DataTable ObtenerDatos_Ticket(int idventa, string textoNumero) { using (SqlConnection conn = new SqlConnection(MasterConnection.connection)) { try { DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter("[sp_ReimprimirTicket]", conn); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@idventa", idventa); da.SelectCommand.Parameters.AddWithValue("@letranumero", textoNumero); da.Fill(dt); return dt; } catch (Exception ex) { conn.Close(); throw ex; } } } } }
using System.Collections; using System.Linq; using System.IO; using System.Collections.Generic; using UnityEngine; using Newtonsoft.Json; public class PizzaGenerator : MonoBehaviour { [SerializeField] int MaxIngredientCount = 3; [SerializeField] bool GenerateFullPizzaName = false; [SerializeField] TextAsset MeatPrefixesFile; [SerializeField] TextAsset VegPrefixesFile; [SerializeField] TextAsset MeatSuffixesFile; [SerializeField] TextAsset VegSuffixesFile; PizzaNameDefs pizzaDefs; private void Awake() { DontDestroyOnLoad(this); } void Start () { InitAllPizzaInfo(); } void InitAllPizzaInfo() { // get pizza things from json file pizzaDefs = new PizzaNameDefs(); //TextAsset jsonFile = Resources.Load<TextAsset>("/Text/PizzaJson"); //Debug.Log(jsonFile); pizzaDefs.MeatPrefixes = JsonConvert.DeserializeObject<List<string>>(MeatPrefixesFile.text); pizzaDefs.MeatSuffixes = JsonConvert.DeserializeObject<List<string>>(MeatSuffixesFile.text); pizzaDefs.VegPrefixes = JsonConvert.DeserializeObject<List<string>>(VegPrefixesFile.text); pizzaDefs.VegSuffixes = JsonConvert.DeserializeObject<List<string>>(VegSuffixesFile.text); } public void AssemblePizza(List<IPizzaIngredient> ingredients) { CraftedPizza newPizza = new CraftedPizza(); string finalName = ""; int mostCommonFood = GetMostCommonFoodType(ingredients); int randVal = 0; finalName += ingredients.Max(item => item.IngredientRarity).ToString() + " "; if(mostCommonFood == 0) { randVal = Random.Range(0, pizzaDefs.MeatPrefixes.Count() - 1); finalName += pizzaDefs.MeatPrefixes[randVal] + " "; } else { randVal = Random.Range(0, pizzaDefs.VegPrefixes.Count() - 1); finalName += pizzaDefs.VegPrefixes[randVal] + " "; } if (GenerateFullPizzaName) { finalName += GenerateNameFromIngredients(ingredients); } if(Random.Range(0, 2) == 0) { randVal = Random.Range(0, pizzaDefs.MeatSuffixes.Count() - 1); finalName += pizzaDefs.MeatSuffixes[randVal] + " "; } else { randVal = Random.Range(0, pizzaDefs.VegSuffixes.Count() - 1); finalName += pizzaDefs.VegSuffixes[randVal] + " "; } Debug.Log(finalName); } string GenerateNameFromIngredients(List<IPizzaIngredient> ings) { string name = ""; int counter = 0; foreach(IPizzaIngredient p in ings) { if(counter == ings.Count) { name += p.IngredientNameFormatted + " "; } counter++; name += p.IngredientNameFormatted + " and "; } return name; } int GetMostCommonFoodType(List<IPizzaIngredient> ingredients) { int meatCount = 0; int vegCount = 0; foreach(IPizzaIngredient p in ingredients) { if(p.IngredientFoodType == FoodType.Meaty) { meatCount++; } else { vegCount++; } } if(meatCount > vegCount) { return 0; } else { return 1; } } }
public interface IBaseBehaviour { void Initialize(BaseDynamicModel model); }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameController : MonoBehaviour { DoorColliderControl DoorCollider; DoorControl Door; //TargetLamps NPCFlight; fps fps; SunFollow sunFollow; LampsPosition lampsPos; //AirController Air; //LightControl lightControl; PointLightControl pointLight; TokiColliderControl Toki; CharacterController characterControl; CharacterRotationControl characterRotControl; RaycastTest RayCast; GameObject NPC; GameObject LightS; void Start () { DoorCollider = GetComponent<DoorColliderControl>(); LightS = GameObject.FindGameObjectWithTag("pointL"); LightS.GetComponent<LightControl>(); NPC = GameObject.FindGameObjectWithTag("NPC"); NPC.GetComponentInChildren<TargetLamps>(); } void Update () { if(LightS.GetComponent<LightControl>().Night==false) { Lightman(); } else { Lighterman(); } } IEnumerator LightmanDeactive() { yield return new WaitForSeconds(2f); NPC.gameObject.transform.GetChild(0).gameObject.SetActive(false); } IEnumerator LightermanDeactive() { yield return new WaitForSeconds(2f); NPC.gameObject.transform.GetChild(1).gameObject.SetActive(false); } private void Lightman() { NPC.gameObject.transform.GetChild(0).gameObject.SetActive(true); if(NPC.GetComponentInChildren<TargetLamps>().HomeCount==true) { StartCoroutine(LightmanDeactive()); } } private void Lighterman() { NPC.gameObject.transform.GetChild(1).gameObject.SetActive(true); if (NPC.GetComponentInChildren<TargetLamps>().HomeCount == true) { StartCoroutine(LightermanDeactive()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicicio17 { class MultiplicacaoRussa { static void Main(string[] args) { { Console.Write("Multiplicando "); int X = Convert.ToInt32(Console.ReadLine()); Console.Write("Multiplicador "); int Y = Convert.ToInt32(Console.ReadLine()); int X1 = X, Y1 = Y, S = 0; while (X1 >= 1) { if (X1 % 2 != 0) S = S + Y1; X1 = (X1 / 2); Y1 = Y1 * 2; } Console.WriteLine("{0} x {1}= {2}", X, Y, S); } } } }
namespace CarDealer.Data.Models { using System.Data.Entity; using CarDealer.Models; using Interfaces; public class CarRepository : Repository<Car>, ICarRepository { public CarRepository(DbContext context) : base(context) { } } }
namespace Models { public class RockModel : IItem { public ItemType Type { get { return ItemType.Rock; } } public string Name { get { return "Rock"; } } } }
using System.ComponentModel; using System.Configuration; using System.Drawing; using System.Drawing.Imaging; using System.Threading; using Microsoft.PointOfService; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using Org.BouncyCastle.Asn1.Cms; using WebApplication1.Models; namespace WebApplication1.Printing { class ReceiptPrinter { PosExplorer explorer; PosPrinter m_Printer; public void printReceipt(Invoice invoice, bool openDrawer = false) { // return; setupPrinter(); try { m_Printer.Open(); //Get the exclusive control right for the opened device. //Then the device is disable from other application. m_Printer.Claim(1000); //Enable the device. bool result = m_Printer.DeviceEnabled = true; // this call also causes the "It is not initialized" error //string health = m_Printer.CheckHealth(HealthCheckLevel.External); } catch (PosControlException) { // ChangeButtonStatus(); } string receiptString = Receipt40Col.GetStandardReceipt(invoice); string barcodeString = invoice.Id ?? ""; while (barcodeString.Length < 8) { barcodeString = " " + barcodeString; } // int test = m_Printer.JrnLineChars //var file = Path.GetFullPath("Resources/logo.bmp"); // m_Printer.PrintNormal(PrinterStation.Receipt,((char)27).ToString() + "|cA" + receiptString); //m_Printer.PrintBitmap(PrinterStation.Receipt, file, 300, PosPrinter.PrinterBitmapCenter); var headerImage = Receipt40Col.GetInvoiceHeaderBitmap(); if (headerImage != null) { m_Printer.PrintBitmap(PrinterStation.Receipt, headerImage, 400, PosPrinter.PrinterBitmapCenter); } //m_Printer.PrintMemoryBitmap(new BitmapData()); m_Printer.PrintNormal(PrinterStation.Receipt, receiptString); var footerImage = Receipt40Col.GetInvoiceFooterBitmap(); if (footerImage != null) m_Printer.PrintBitmap(PrinterStation.Receipt, footerImage, 400, PosPrinter.PrinterBitmapCenter); m_Printer.PrintNormal(PrinterStation.Receipt, Receipt40Col.extraLines(8)); if (openDrawer) m_Printer.PrintNormal(PrinterStation.Receipt, ((char) 27).ToString() + "|\x07"); } //public void printReceipt(InvoiceLine[] giftCards) //{ // try // { // // return; // setupPrinter(); // try // { // m_Printer.Open(); // //Get the exclusive control right for the opened device. // //Then the device is disable from other application. // m_Printer.Claim(1000); // //Enable the device. // bool result = m_Printer.DeviceEnabled = true; // // this call also causes the "It is not initialized" error // //string health = m_Printer.CheckHealth(HealthCheckLevel.External); // } // catch (PosControlException) // { // // ChangeButtonStatus(); // } // foreach (var invoiceLine in giftCards) // { // string receiptString = Receipt40Col.GetStandardReceipt(invoiceLine); // // int test = m_Printer.JrnLineChars // var file = Path.GetFullPath("Resources/logo.bmp"); // // m_Printer.PrintNormal(PrinterStation.Receipt,((char)27).ToString() + "|cA" + receiptString); // m_Printer.PrintBitmap(PrinterStation.Receipt, file, 300, PosPrinter.PrinterBitmapCenter); // m_Printer.PrintNormal(PrinterStation.Receipt, receiptString); // m_Printer.PrintNormal(PrinterStation.Receipt, Receipt40Col.extraLines(8)); // Thread.Sleep(3000); // } // } // catch (Exception ex) // { // ErrorLogging.logError(ex); // } //} //public void printReceipt(Buyback buyback, bool openDrawer = false) //{ // //return; // setupPrinter(); // try // { // m_Printer.Open(); // //Get the exclusive control right for the opened device. // //Then the device is disable from other application. // m_Printer.Claim(1000); // //Enable the device. // bool result = m_Printer.DeviceEnabled = true; // // this call also causes the "It is not initialized" error // //string health = m_Printer.CheckHealth(HealthCheckLevel.External); // string receiptString = Receipt40Col.GetStandardReceipt(buyback); // string barcodeString = buyback.Id.ToString(); // while (barcodeString.Length < 8) // { // barcodeString = " " + barcodeString; // } // // int test = m_Printer.JrnLineChars // var file = Path.GetFullPath("Resources/logo.bmp"); // // m_Printer.PrintNormal(PrinterStation.Receipt,((char)27).ToString() + "|cA" + receiptString); // m_Printer.PrintBitmap(PrinterStation.Receipt, file, 300, PosPrinter.PrinterBitmapCenter); // m_Printer.PrintNormal(PrinterStation.Receipt, receiptString); // m_Printer.PrintNormal(PrinterStation.Receipt, Receipt40Col.extraLines(8)); // if (openDrawer) // m_Printer.PrintNormal(PrinterStation.Receipt, ((char)27).ToString() + "|\x07"); // } // catch (Exception ex) // { // ErrorLogging.logError(ex); // } //} void setupPrinter() { //Create PosExplorer var posExplorer = new PosExplorer(); var devices = posExplorer.GetDevices("PosPrinter"); DeviceInfo deviceInfo = null; try { var printerName = ConfigurationManager.AppSettings["ReceiptPrinter"]; deviceInfo = devices.OfType<DeviceInfo>().FirstOrDefault(x => x.ServiceObjectName.Contains(printerName)) ?? devices.OfType<DeviceInfo>().FirstOrDefault(x => x.ServiceObjectName.Contains("Star")); // this call returns a valid object var p = posExplorer.CreateInstance(deviceInfo); m_Printer = (PosPrinter) p; // posExplorer.CreateInstance(deviceInfo); } catch (Exception exception) { Console.WriteLine(exception); // ChangeButtonStatus(); return; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NfePlusAlpha.Domain.Entities { public class tbNotaFiscalEletronicaTotal { public tbNotaFiscalEletronicaTotal() { this.tbNotaFiscalEletronica = new tbNotaFiscalEletronica(); } public int nft_codigo { get; set; } public decimal nft_vBC { get; set; } public decimal nft_vICMS { get; set; } public decimal nft_vICMSDeson { get; set; } public decimal nft_vBCST { get; set; } public decimal nft_vST { get; set; } public decimal nft_vProd { get; set; } public decimal nft_vFrete { get; set; } public decimal nft_vSeg { get; set; } public decimal nft_vDesc { get; set; } public decimal nft_vII { get; set; } public decimal nft_vIPI { get; set; } public decimal nft_vPIS { get; set; } public decimal nft_vCOFINS { get; set; } public decimal nft_vOutro { get; set; } public decimal nft_vNF { get; set; } public decimal nft_vTotTrib { get; set; } public int nfe_codigo { get; set; } public virtual tbNotaFiscalEletronica tbNotaFiscalEletronica { get; set; } } }
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Senai.Ekips.WebApi.Domains; using Senai.Ekips.WebApi.Repositories; using Senai.Ekips.WebApi.ViewModels; namespace Senai.Ekips.WebApi.Controllers { [Route("api/[controller]")] [Produces("application/json")] [ApiController] public class FuncionariosController : ControllerBase { private readonly FuncionarioRepository FuncionarioRepository = new FuncionarioRepository(); private readonly UsuarioRepository UsuarioRepository = new UsuarioRepository(); /// <summary> /// Lista os funcionários /// </summary> /// <returns></returns> [Authorize] [HttpGet] public IActionResult ListarTodos() { if (IsAdministrator()) { return Ok(FuncionarioRepository.Listar()); } return Ok(new List<Funcionarios> { GetFuncionario() }); } private bool IsAdministrator() { return User.HasClaim(claim => claim.Type == ClaimTypes.Role && claim.Value == "ADMINISTRADOR"); } private Funcionarios GetFuncionario() { var usuarioId = User.Claims.FirstOrDefault(claim => claim.Type == JwtRegisteredClaimNames.Jti); var usuarioIdAsInt = int.Parse(usuarioId.Value); return FuncionarioRepository.BuscarPorUsuarioId(usuarioIdAsInt); } [HttpPost] [Authorize(Roles = "ADMINISTRADOR")] public IActionResult Cadastrar(FuncionarioViewModel viewModel) { try { var usuario = new Usuarios { Email = viewModel.Usuario.Email, Senha = viewModel.Usuario.Senha, Permissao = viewModel.Usuario.Permissao }; var usuarioId = UsuarioRepository.Cadastrar(usuario); var funcionario = new Funcionarios { Nome = viewModel.Nome, Cpf = viewModel.Cpf, DataNascimento = viewModel.DataNascimento, Salario = viewModel.Salario, IdDepartamento = viewModel.IdDepartamento, IdCargo = viewModel.IdCargo, IdUsuario = usuarioId }; FuncionarioRepository.Cadastrar(funcionario); return Ok(); } catch (Exception exception) { return BadRequest(new { message = "Oops... Não deu certo...", details = exception.Message }); } } [HttpPut("{id}")] [Authorize(Roles = "ADMINISTRADOR")] public IActionResult Atualizar (int id, FuncionarioViewModel viewModel) { try { var funcionarioAtual = FuncionarioRepository.BuscarPorId(id); funcionarioAtual.Nome = viewModel.Nome; funcionarioAtual.Cpf = viewModel.Cpf; funcionarioAtual.DataNascimento = viewModel.DataNascimento; funcionarioAtual.Salario = viewModel.Salario; funcionarioAtual.IdDepartamento = viewModel.IdDepartamento; funcionarioAtual.IdCargo = viewModel.IdCargo; FuncionarioRepository.Atualizar(funcionarioAtual); if (funcionarioAtual.IdUsuario != null) { var usuario = UsuarioRepository.BuscarPorId((int)funcionarioAtual.IdUsuario); usuario.Email = viewModel.Usuario.Email; usuario.Senha = viewModel.Usuario.Senha; usuario.Permissao = viewModel.Usuario.Permissao; UsuarioRepository.Atualizar(usuario); } return Ok(); } catch (Exception exception) { return BadRequest(new { message = "Oops... Não deu certo...", details = exception.Message }); } } [HttpDelete("{id}")] [Authorize(Roles = "ADMINISTRADOR")] public IActionResult Deletar (int id) { try { FuncionarioRepository.Deletar(id); return NoContent(); } catch (Exception exception) { return BadRequest(new { message = "Oops... Não deu certo...", details = exception.Message }); } } } }
using Microsoft.AspNet.Identity; using System.Web.Mvc; using WebApplication1.Models; namespace WebApplication1.Controllers { [Authorize] public class HomeController : Controller { public ActionResult Index() { // Check if user is admin when index page is opened /* Users model = new Users(); string email = User.Identity.GetUserName(); var user = Models.MongoDBHelper.MongoDBUserType(email); model.userType = user;*/ // Get campaign and display return View(); } } }
using System; using System.CodeDom; using System.Linq; using InRule.Repository.RuleElements; namespace InRuleLabs.AuthoringExtensions.GenerateSDKCode.Features.Rendering { public static partial class SdkCodeRenderingExtensions_TypeMapping { public static CodeExpression ToCodeExpression(this TypeMapping typeMapping, CodeTypeDeclarationEx outerClass) { //public TypeMapping(string name, string dataType, Type baseType, Type[] derivedTypes) CodeExpression baseType = ((Type)null).ToCodeExpression2(outerClass); CodeExpression[] derivedTypes = new CodeExpression[0]; if (typeMapping.BaseType != null) { baseType = new CodeMethodInvokeExpression(new CodeSnippetExpression("System.Type"), "GetType", typeMapping.BaseType.FullName.ToCodeExpression()); } if (typeMapping.DerivedTypes != null) { derivedTypes = typeMapping.DerivedTypes.Select( t => (CodeExpression)new CodeMethodInvokeExpression(new CodeSnippetExpression("System.Type"), "GetType", SdkCodeRenderingExtensions.ToCodeExpression2(t.FullName, outerClass))).ToArray(); } var derivedTypesArray = new CodeArrayCreateExpression(new CodeTypeReference(typeof(Type)), derivedTypes); return typeof(TypeMapping).CallCodeConstructor( typeMapping.Name.ToCodeExpression() , typeMapping.DataType.ToCodeExpression() , baseType , derivedTypesArray ); } } }
using Terraria; using Terraria.ModLoader; namespace ReducedGrinding.Items { public class Marble_Sundial : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("Marble Sundial"); Tooltip.SetDefault("Skips to day time.\nThis day won't count towards the Enchanted Sundial cooldown."); } public override void SetDefaults() { item.width = 20; item.height = 38; item.maxStack = 99; item.useTurn = true; item.autoReuse = true; item.useAnimation = 15; item.useTime = 10; item.useStyle = 1; item.consumable = true; item.value = Item.buyPrice(0, 0, 3, 0); item.rare = 1; item.createTile = mod.TileType("Marble_Sundial"); } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(3066, 1); //Smooth Marble Block recipe.AddIngredient(315, 1); //Blinkroot recipe.AddTile(283); //Heavy Workbench recipe.SetResult(this); recipe.AddRecipe(); } } }
using Claimdi.Web.TH.Controllers.Consumer; using Claimdi.Web.TH.Filters; using Claimdi.Web.TH.Helper; using ClaimDi.Business.Master; using ClaimDi.DataAccess.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Claimdi.Web.TH.Controllers.admin.Consumer { public class TemplateESlipController : Controller { // GET: TemplateESlip [AuthorizeUser(AccessLevel = "View", PageAction = "TemplateESlip")] public ActionResult CreateEdit(string id) { EmailConfigLogic config = new EmailConfigLogic(); Insurer result = new Insurer(); result = config.GetTemplateESlipByInsureId(id); UtilityConsumerController util = new UtilityConsumerController(); ViewBag.TaskTypes = util.GetDropDownTaskType(); return View(result); } [HttpPost] [AuthorizeUser(AccessLevel = "Edit", PageAction = "TemplateESlip")] [ValidateInput(false)] public ActionResult SaveCreateEdit(Insurer model) { var auth = ClaimdiSessionFacade.ClaimdiSession; // var insId = Request.Form.GetValues("insId"); TemplateESlipLogic config = new TemplateESlipLogic(); if (model.TemplateESlips == null) { model.TemplateESlips = new List<TemplateESlip>(); } var id = Request.Form.GetValues("Id"); var taskType = Request.Form.GetValues("taskType"); var noticeTitle = Request.Form.GetValues("noticeTitle"); var deDuctTitle = Request.Form.GetValues("deDuctTitle"); var driverTitle = Request.Form.GetValues("driverTitle"); var footer = Request.Form.GetValues("footer"); var noticeTitleEn = Request.Form.GetValues("noticeTitleEn"); var deDuctTitleEn = Request.Form.GetValues("deDuctTitleEn"); var driverTitleEn = Request.Form.GetValues("driverTitleEn"); var footerEn = Request.Form.GetValues("footerEn"); var insApprove = Request.Form.GetValues("approver"); var insApproveEn = Request.Form.GetValues("approverEn"); var msResTh = Request.Form.GetValues("messageResponseTh"); var msResEn = Request.Form.GetValues("messageResponseEn"); if (id != null && id.Length > 0) { for (int i = 0; i < id.Length; i++) { TemplateESlip tempCon = new TemplateESlip(); tempCon.Id = string.IsNullOrEmpty(id[i]) ? 0 : int.Parse(id[i]); tempCon.InsId = model.InsID; tempCon.TaskTypeId = string.IsNullOrEmpty(taskType[i]) ? "" : taskType[i]; tempCon.NoticeTitle = (string.IsNullOrEmpty(noticeTitle[i]) ? "" : noticeTitle[i]); tempCon.DeDuctTitle = (string.IsNullOrEmpty(deDuctTitle[i]) ? "" : deDuctTitle[i]); tempCon.DriverTitle = (string.IsNullOrEmpty(driverTitle[i]) ? "" : driverTitle[i]); tempCon.Footer = (string.IsNullOrEmpty(footer[i]) ? "" : footer[i]); tempCon.NoticeTitleEn = (string.IsNullOrEmpty(noticeTitleEn[i]) ? "" : noticeTitleEn[i]); tempCon.DeDuctTitleEn = (string.IsNullOrEmpty(deDuctTitleEn[i]) ? "" : deDuctTitleEn[i]); tempCon.DriverTitleEn = (string.IsNullOrEmpty(driverTitleEn[i]) ? "" : driverTitleEn[i]); tempCon.FooterEn = (string.IsNullOrEmpty(footerEn[i]) ? "" : footerEn[i]); tempCon.InsuranceApprover = (string.IsNullOrEmpty(insApprove[i]) ? "" : insApprove[i]); tempCon.InsuranceApproverEn = (string.IsNullOrEmpty(insApproveEn[i]) ? "" : insApproveEn[i]); tempCon.MessageResponse = (string.IsNullOrEmpty(msResTh[i]) ? "" : msResTh[i]); tempCon.MessageResponseEn = (string.IsNullOrEmpty(msResEn[i]) ? "" : msResEn[i]); model.TemplateESlips.Add(tempCon); } } var res = config.SaveTemplateESlip(model.TemplateESlips, auth.first_name + " " + auth.last_name); if (res.Result) { ViewBag.Message = "success"; } else { ViewBag.Message = "failed"; } UtilityConsumerController util = new UtilityConsumerController(); ViewBag.TaskTypes = util.GetDropDownTaskType(); return View("CreateEdit", model); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName="Zomz/AI/State",fileName="State_New")] public class State : ScriptableObject { public string AnimationTrigger; public Action[] Actions; public Color SceneGizmoColor = Color.grey; public Transition[] Transitions; public void UpdateState(AIStateController pController) { DoActions (pController); CheckTransitions (pController); } public void DoActions(AIStateController pController) { for(int i=0;i<Actions.Length;i++) { Actions [i].Act (pController); } } private void CheckTransitions(AIStateController pController) { for(int i=0;i<Transitions.Length;i++) { bool decisionSucceeded = Transitions [i].Decision.Decide (pController); if (decisionSucceeded) { pController.TransitionToState (Transitions [i].TrueState); } else { pController.TransitionToState (Transitions [i].FalseState); } } } }
using GalaSoft.MvvmLight.Command; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Windows.Input; using System.Linq; namespace Act1_Unidad2 {[Serializable] public class Episodios { public string Episodio { get; set; } public string Temporada { get; set; } public string Titulo { get; set; } public string TituloEspañol { get; set; } public string Descripcion { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AdventureWorksPeople.Models { public class EmployeeAddressDepartment { public int BusinessEntityID { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public string City { get; set; } public string StateProvinceCode { get; set; } public string PostalCode { get; set; } } }
using UnityEngine; using UnityEngine.Networking; using System.Collections; public class Client : NetworkBehaviour { static public Client singleton; NetworkClient client; public NetworkManager manager; void Awake() { singleton = this; } void Start () { client = manager.StartClient(); //client.RegisterHandler((short)CustomMessages.ClientReceivePlayerID, OnMsgClientReceivePlayerID); } void Update () { print (client.isConnected); } void OnConnectedToServer() { print("just connected to server"); } }
using Barker.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace Barker.Data.BarkService { public class BarkService : IBarkService { HttpClient client; string uri = "https://localhost:44374/Barks"; public BarkService() { client = new HttpClient(); } public async Task<Bark> CreateBarkAsync(Bark bark) { string barkAsJson = JsonSerializer.Serialize(bark); HttpContent content = new StringContent(barkAsJson, Encoding.UTF8, "application/json"); var returnContent = await client.PostAsync(uri, content); string returnJson = await returnContent.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize<Bark>(returnJson); } public async Task DeleteBarkAsync(int barkID) { await client.DeleteAsync($"{uri}/{barkID}"); } public async Task<Bark> GetBarkAsync(int barkID) { string message = await client.GetStringAsync($"{uri}/{barkID}"); return JsonSerializer.Deserialize<Bark>(message); } public async Task<List<Bark>> GetBarksByUserAsync(int userID) { string message = await client.GetStringAsync($"{uri}/byUser/{userID}"); return JsonSerializer.Deserialize<List<Bark>>(message); } public async Task<Bark> UpdateBarkAsync(Bark bark) { string barkAsJson = JsonSerializer.Serialize(bark); HttpContent content = new StringContent(barkAsJson, Encoding.UTF8, "application/json"); var returnContent = await client.PatchAsync(uri, content); string returnJson = await returnContent.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize<Bark>(returnJson); } } }
using Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FunctionRegression { public class RegressionTaskV5 : RegressionTaskV4 { public RegressionTaskV5() { LearningRange = new Range(0, 1, 0.025); Function = z => z * Math.Sin(25*z); MaxError = 0.5; IterationsCount = 102400 + 51200; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using CustomerDatabase.Models; namespace CustomerDatabase.Pages.Customers { /* Written by Paul Smyth * Date 31/01/2018 * Version 1.0 */ public class CreateModel : PageModel { private readonly CustomerDatabase.Models.CustomerContext _context; public CreateModel(CustomerDatabase.Models.CustomerContext context) { _context = context; } public IActionResult OnGet() { return Page(); } [BindProperty] public Customer Customer { get; set; } // Create Button public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } // Perform validation routines on data entered if (Customer.FullName == "") { // Go back to page with an error message } _context.Customer.Add(Customer); await _context.SaveChangesAsync(); return RedirectToPage("./Index"); } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using EdjCase.JsonRpc.Client; using EdjCase.JsonRpc.Core; using FiiiCoin.DTO; using FiiiCoin.Utility; using FiiiCoin.Utility.Api; using System; using System.Collections.Generic; using System.Net.Http.Headers; using System.Threading.Tasks; namespace FiiiCoin.ServiceAgent { public class Transaction { /// <summary> /// /// </summary> /// <param name="toAddress"></param> /// <param name="amount"></param> /// <param name="comment"></param> /// <param name="commentTo"></param> /// <param name="subtractFeeFromAmount"></param> /// <returns></returns> public async Task<string> SendToAddress(string toAddress, long amount, string comment = "", string commentTo = "", bool subtractFeeFromAmount = false) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("SendToAddress", new List<object> { toAddress, amount, comment, commentTo, subtractFeeFromAmount }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } string responseValue = response.GetResult<string>(); return responseValue; } /// <summary> /// /// </summary> /// <param name="fromAccount"></param> /// <param name="many"></param> /// <param name="subtractFeeFromAmount"></param> /// <returns></returns> public async Task<string> SendMany(string fromAccount, SendManyOM[] many, string[] subtractFeeFromAmount = null) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("SendMany", new List<object> { fromAccount, many, subtractFeeFromAmount }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } string responseValue = response.GetResult<string>(); return responseValue; } /// <summary> /// /// </summary> /// <param name="transactionFeePerKilobyte"></param> /// <returns></returns> public async Task SetTxFee(long transactionFeePerKilobyte) { AuthenticationHeaderValue authHeaderValue = null; //List<object> list = transactionFeePerKilobyte.ToList().ConvertAll(s => (object)s); RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("SetTxFee", new List<object> { transactionFeePerKilobyte }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } } /// <summary> /// /// </summary> /// <param name="confirmations"></param> /// <returns></returns> public async Task SetConfirmations(long confirmations) { AuthenticationHeaderValue authHeaderValue = null; //List<object> list = confirmations.ToList().ConvertAll(s => (object)s); RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("SetConfirmations", new List<object> { confirmations }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } } /// <summary> /// /// </summary> /// <returns></returns> public async Task<TransactionFeeSettingOM> GetTxSettings() { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithNoParameters("GetTxSettings", 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } TransactionFeeSettingOM responseValue = response.GetResult<TransactionFeeSettingOM>(); return responseValue; } /// <summary> /// /// </summary> /// <param name="toAddress"></param> /// <param name="amount"></param> /// <param name="comment"></param> /// <param name="commentTo"></param> /// <param name="subtractFeeFromAmount"></param> /// <returns></returns> public async Task<TxFeeForSendOM> EstimateTxFeeForSendToAddress(string toAddress, long amount, string comment = "", string commentTo = "", bool subtractFeeFromAmount = false) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("EstimateTxFeeForSendToAddress", new List<object> { toAddress, amount, comment, commentTo, subtractFeeFromAmount }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } TxFeeForSendOM responseValue = response.GetResult<TxFeeForSendOM>(); return responseValue; } /// <summary> /// /// </summary> /// <param name="fromAccount"></param> /// <param name="many"></param> /// <param name="subtractFeeFromAmount"></param> /// <returns></returns> public async Task<TxFeeForSendOM> EstimateTxFeeForSendMany(string fromAccount, SendManyOM[] many, string[] subtractFeeFromAmount = null) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("EstimateTxFeeForSendMany", new List<object> { fromAccount, many, subtractFeeFromAmount }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } TxFeeForSendOM responseValue = response.GetResult<TxFeeForSendOM>(); return responseValue; } /// <summary> /// /// </summary> /// <param name="account">The name of an account to get transactinos from. Use an empty string ("") to get transactions for the default account. Default is * to get transactions for all accounts.</param> /// <param name="count">The number of the most recent transactions to list. Default is 10</param> /// <param name="skip">The number of the most recent transactions which should not be returned. Allows for pagination of results. Default is 0</param> /// <param name="includeWatchOnly">If set to true, include watch-only addresses in details and calculations as if they were regular addresses belonging to the wallet. If set to false(the default), treat watch-only addresses as if they didn’t belong to this wallet</param> /// <returns></returns> public async Task<PaymentOM[]> ListTransactions(string account = "*", long count = 10, int skip = 0, bool includeWatchOnly = true) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("ListTransactions", new List<object> { account, count, skip, includeWatchOnly }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } PaymentOM[] responseValue = response.GetResult<PaymentOM[]>(); return responseValue; } public async Task<PaymentOM[]> ListFilterTrans(FilterIM filter, int count, int skip = 0, bool includeWatchOnly = true) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("ListFilterTrans", new List<object> { filter, count, skip, includeWatchOnly }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } PaymentOM[] responseValue = response.GetResult<PaymentOM[]>(); return responseValue; } /// <summary> /// /// </summary> /// <param name="senders"></param> /// <param name="receivers"></param> /// <param name="changeAddress"></param> /// <param name="lockTime"></param> /// <param name="feeRate"></param> /// <returns></returns> public async Task<string> SendRawTransaction(SendRawTransactionInputsIM[] senders, SendRawTransactionOutputsIM[] receivers, string changeAddress, long lockTime, long feeRate) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("SendRawTransaction", new List<object> { senders, receivers, changeAddress, lockTime, feeRate }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } string responseValue = response.GetResult<string>(); return responseValue; } public async Task<ListSinceBlockOM> ListSinceBlock(string blockHash, long confirmations) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("ListSinceBlock", new List<object> { blockHash, confirmations }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } ListSinceBlockOM responseValue = response.GetResult<ListSinceBlockOM>(); return responseValue; } public async Task<EstimateRawTransactionOM> EstimateRawTransaction(SendRawTransactionInputsIM[] senders, SendRawTransactionOutputsIM[] receivers, string changeAddress, long feeRate) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("EstimateRawTransaction", new List<object> { senders, receivers, changeAddress, feeRate }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } EstimateRawTransactionOM responseValue = response.GetResult<EstimateRawTransactionOM>(); return responseValue; } public async Task SendNotify(string txId) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("SendNotify", new List<object> { txId }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } } public async Task<TransactionOM> GetTransaction(string txId) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("GetTransaction", new List<object> { txId }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } TransactionOM responseValue = response.GetResult<TransactionOM>(); return responseValue; } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Lottery.Repository.Entities; using Lottery.Repository.Interfaces; namespace Lottery.Repository { public class LotteryDb : DbContext, IDatabaseContext { public LotteryDb() : base("name=LotteryDB") { this.Configuration.LazyLoadingEnabled = true; } public DbSet<BigLotteryRecord> BigLotteryRecord { get; set; } public DbSet<BigLotteryRecordSequence> BigLotteryRecordSequence { get; set; } public DbSet<PowerLotteryRecord> PowerLotteryRecord { get; set; } public DbSet<SimulateLotteryRecord> SimulateLotteryRecord { get; set; } public DbSet<FiveThreeNineLotteryRecord> FiveThreeNineLotteryRecord { get; set; } public DbSet<PowerLotteryRecordSequence> PowerLotteryRecordSequence { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { var typesToRegister = Assembly .GetExecutingAssembly() .GetTypes() .Where(type => !string.IsNullOrEmpty(type.Namespace) && type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>) ); foreach (var type in typesToRegister) { dynamic configurationInstance = Activator.CreateInstance(type); modelBuilder.Configurations.Add(configurationInstance); } base.OnModelCreating(modelBuilder); } } }
using UnityEngine; using System.Collections; /// <summary> /// Generic Singleton /// To use it, simply derive it and attach it to its own game object /// Note: you must call base.Awake() in Awake() /// </summary> /// <typeparam name="T"></typeparam> public class Singleton<T> : MonoBehaviour where T : Singleton<T> { public static T instance { get { if (_instance == null) { if (Debug.isDebugBuild) { Debug.LogError("There is no " + typeof(T).Name + " in the scene!"); } return null; } else return _instance; } } private static T _instance; protected virtual void Awake() { if (_instance == null) { _instance = this as T; //DontDestroyOnLoad(this); } else { if (Debug.isDebugBuild) { Debug.LogWarning("There are more than one " + typeof(T).Name + " in the scene!"); } Destroy(gameObject); } } }
// ReSharper disable once CheckNamespace must be in same namespace as other partial classes of this type. namespace SkillPrestige.SkillTypes { public partial class SkillType { public static SkillType Luck { get; protected set; } }; }
namespace KK.AspNetCore.EasyAuthAuthentication.Interfaces { using KK.AspNetCore.EasyAuthAuthentication.Models; using KK.AspNetCore.EasyAuthAuthentication.Services; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; /// <summary> /// A service that can be used as authentification service in the <see cref="EasyAuthAuthenticationHandler"/>. /// </summary> public interface IEasyAuthAuthentificationService { /// <summary> /// Define if this service can handle the authentification. /// </summary> /// <param name="httpContext">The <see cref="HttpContext"/> of the http request.</param> /// <returns>If the return is true the service can be used for this request.</returns> bool CanHandleAuthentification(HttpContext httpContext); /// <summary> /// Try to create a <see cref="AuthenticateResult"/> out of the <see cref="HttpContext"/> from the incomming request. /// </summary> /// <param name="context">The <see cref="HttpContext"/> of the http request.</param> /// <returns>If the user can be authentificated it will returend a full <see cref="AuthenticateResult"/>. If not this will return a <see cref="AuthenticateResult.Fail(string)"/> result. (only the <see cref="LocalAuthMeService"/> can return this.</returns> AuthenticateResult AuthUser(HttpContext context); /// <summary> /// Try to create a <see cref="AuthenticateResult"/> out of the <see cref="HttpContext"/> from the incomming request. /// </summary> /// <param name="context">The <see cref="HttpContext"/> of the http request.</param> /// <param name="options">The <see cref="ProviderOptions"/> that can change the behavior of the <see cref="AuthUser(HttpContext, ProviderOptions)"/> method.</param> /// <returns>If the user can be authentificated it will returend a full <see cref="AuthenticateResult"/>. If not this will return a <see cref="AuthenticateResult.Fail(string)"/> result. (only the <see cref="LocalAuthMeService"/> can return this.</returns> AuthenticateResult AuthUser(HttpContext context, ProviderOptions options); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Xna.Framework.Input { public struct JoyconCalibration { float[] acc_cal_coeff; float[] gyro_cal_coeff; float[] cal_x; float[] cal_y; bool hasUserCalStickL; bool hasUserCalStickR; bool hasUserCalSensor; byte[] factoryStickCal; byte[] userStickCal; byte[] sensorModel; byte[] stickModel; } }
using System.Threading; using Framework.Core.Common; using Tests.Pages.Van.Main.Common; using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; namespace Tests.Pages.Van.Main.Report { public class ReportFormatConfigurePage : VanBasePage { #region Elements public By EReportFormatBuilderPageCheckLocator = (By.Id("ctl00_ContentPlaceHolderVANPage_LabelHeadline1")); public IWebElement ReportFormatBuilderPageCheck { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_LabelHeadline1")); } } public IWebElement StartElement { get { return _driver.FindElement(By.Id("ReportItem_46")); } } public IWebElement EndElement { get { return _driver.FindElement(By.Id("Row2")); } } public IWebElement End1Element { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_ItemsNotOnReport")); } } public IWebElement AddColumnButton { get { return _driver.FindElement(By.XPath("//input[@value='Add Column']")); } } public IWebElement ClearButton { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_ButtonClearReport")); } } public IWebElement SaveButton { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_ButtonSaveReportData")); } } public IWebElement AddTextFieldButton { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_btnAddTextField")); } } #endregion public ReportFormatConfigurePage(Driver driver) : base(driver) { } #region Methods /// <summary> /// searches in helpers->data->minivan data /// </summary> public void MoveElement() { _driver.WaitForElementToDisplayBy(EReportFormatBuilderPageCheckLocator); _driver.PhysicalMoveToElement(StartElement, EndElement); Thread.Sleep(1000); _driver.PhysicalMoveToElement(StartElement,End1Element); } #endregion } }
using EddiDataDefinitions; using EddiStatusService; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using Utilities; namespace UnitTests { [TestClass] public class StatusMonitorTests : TestBase { readonly StatusService statusService = new StatusService(); [TestInitialize] public void start() { MakeSafe(); } [TestMethod] public void TestParseStatusFlagsDocked() { string line = "{ \"timestamp\":\"2018-03-25T00:39:48Z\", \"event\":\"Status\", \"Flags\":16842765, \"Pips\":[5,2,5], \"FireGroup\":0, \"GuiFocus\":0 }"; Status status = StatusService.Instance.ParseStatusEntry(line); // Variables set from status flags (when not signed in, flags are set to '0') DateTime expectedTimestamp = new DateTime(2018, 3, 25, 0, 39, 48, DateTimeKind.Utc); Assert.AreEqual(expectedTimestamp, status.timestamp); Assert.AreEqual(status.flags, (Status.Flags)16842765); Assert.AreEqual(status.vehicle, "Ship"); Assert.IsFalse(status.being_interdicted); Assert.IsFalse(status.in_danger); Assert.IsFalse(status.near_surface); Assert.IsFalse(status.overheating); Assert.IsFalse(status.low_fuel); Assert.AreEqual(status.fsd_status, "masslock"); Assert.IsFalse(status.srv_drive_assist); Assert.IsFalse(status.srv_under_ship); Assert.IsFalse(status.srv_turret_deployed); Assert.IsFalse(status.srv_handbrake_activated); Assert.IsFalse(status.scooping_fuel); Assert.IsFalse(status.silent_running); Assert.IsFalse(status.cargo_scoop_deployed); Assert.IsFalse(status.lights_on); Assert.IsFalse(status.in_wing); Assert.IsFalse(status.hardpoints_deployed); Assert.IsFalse(status.flight_assist_off); Assert.IsFalse(status.supercruise); Assert.IsTrue(status.shields_up); Assert.IsTrue(status.landing_gear_down); Assert.IsFalse(status.landed); Assert.IsTrue(status.docked); } [TestMethod] public void TestParseStatusFlagsDockedOdyssey() { string line = "{ \"timestamp\":\"2021-05-01T21:04:13Z\", \"event\":\"Status\", \"Flags\":151060493, \"Flags2\":0, \"Pips\":[4,8,0], \"FireGroup\":0, \"GuiFocus\":0, \"Fuel\":{ \"FuelMain\":32.000000, \"FuelReservoir\":0.630000 }, \"Cargo\":0.000000, \"LegalState\":\"Clean\" }"; Status status = statusService.ParseStatusEntry(line); // Variables set from status flags (when not signed in, flags are set to '0') DateTime expectedTimestamp = new DateTime(2021, 5, 1, 21, 4, 13, DateTimeKind.Utc); Assert.AreEqual(expectedTimestamp, status.timestamp); Assert.AreEqual((Status.Flags)151060493, status.flags); Assert.AreEqual((Status.Flags2)0, status.flags2); Assert.AreEqual(Constants.VEHICLE_SHIP, status.vehicle); Assert.IsFalse(status.being_interdicted); Assert.IsFalse(status.in_danger); Assert.IsFalse(status.near_surface); Assert.IsFalse(status.overheating); Assert.IsFalse(status.low_fuel); Assert.AreEqual("masslock", status.fsd_status); Assert.IsFalse(status.srv_drive_assist); Assert.IsFalse(status.srv_under_ship); Assert.IsFalse(status.srv_turret_deployed); Assert.IsFalse(status.srv_handbrake_activated); Assert.IsFalse(status.srv_high_beams); Assert.IsFalse(status.scooping_fuel); Assert.IsFalse(status.silent_running); Assert.IsFalse(status.cargo_scoop_deployed); Assert.IsFalse(status.lights_on); Assert.IsFalse(status.in_wing); Assert.IsFalse(status.hardpoints_deployed); Assert.IsFalse(status.flight_assist_off); Assert.IsFalse(status.supercruise); Assert.IsFalse(status.hyperspace); Assert.IsTrue(status.shields_up); Assert.IsTrue(status.landing_gear_down); Assert.IsFalse(status.landed); Assert.IsTrue(status.docked); Assert.IsTrue(status.analysis_mode); Assert.IsFalse(status.night_vision); Assert.IsFalse(status.altitude_from_average_radius); Assert.IsFalse(status.on_foot_in_station); Assert.IsFalse(status.on_foot_on_planet); Assert.IsFalse(status.aim_down_sight); Assert.IsFalse(status.low_oxygen); Assert.IsFalse(status.low_health); Assert.AreEqual("temperate", status.on_foot_temperature); Assert.IsFalse(status.hardpoints_deployed); Assert.AreEqual(2M, status.pips_sys); Assert.AreEqual(4M, status.pips_eng); Assert.AreEqual(0M, status.pips_wea); Assert.AreEqual(0, status.firegroup); Assert.AreEqual("none", status.gui_focus); Assert.AreEqual(32M, status.fuelInTanks); Assert.AreEqual(0.63M, status.fuelInReservoir); Assert.AreEqual(0, status.cargo_carried); Assert.AreEqual("Clean", status.legalstatus); Assert.IsFalse(status.aim_down_sight); Assert.IsNull(status.latitude); Assert.IsNull(status.longitude); Assert.IsNull(status.heading); Assert.IsNull(status.altitude); Assert.IsNull(status.bodyname); Assert.IsNull(status.planetradius); } [TestMethod] public void TestParseStatusFlagsDockedDropshipOdyssey() { string line = "{ \"timestamp\":\"2021-05-01T23:10:06Z\", \"event\":\"Status\", \"Flags\":16842761, \"Flags2\":2, \"Pips\":[4,4,4], \"FireGroup\":0, \"GuiFocus\":0, \"Fuel\":{ \"FuelMain\":8.000000, \"FuelReservoir\":0.570000 }, \"Cargo\":0.000000, \"LegalState\":\"Clean\" }"; Status status = statusService.ParseStatusEntry(line); // Variables set from status flags (when not signed in, flags are set to '0') DateTime expectedTimestamp = new DateTime(2021, 5, 1, 23, 10, 06, DateTimeKind.Utc); Assert.AreEqual(expectedTimestamp, status.timestamp); Assert.AreEqual((Status.Flags)16842761, status.flags); Assert.AreEqual((Status.Flags2)2, status.flags2); Assert.AreEqual(Constants.VEHICLE_TAXI, status.vehicle); Assert.IsFalse(status.being_interdicted); Assert.IsFalse(status.in_danger); Assert.IsFalse(status.near_surface); Assert.IsFalse(status.overheating); Assert.IsFalse(status.low_fuel); Assert.AreEqual("masslock", status.fsd_status); Assert.IsFalse(status.srv_drive_assist); Assert.IsFalse(status.srv_under_ship); Assert.IsFalse(status.srv_turret_deployed); Assert.IsFalse(status.srv_handbrake_activated); Assert.IsFalse(status.srv_high_beams); Assert.IsFalse(status.scooping_fuel); Assert.IsFalse(status.silent_running); Assert.IsFalse(status.cargo_scoop_deployed); Assert.IsFalse(status.lights_on); Assert.IsFalse(status.in_wing); Assert.IsFalse(status.hardpoints_deployed); Assert.IsFalse(status.flight_assist_off); Assert.IsFalse(status.supercruise); Assert.IsFalse(status.hyperspace); Assert.IsTrue(status.shields_up); Assert.IsFalse(status.landing_gear_down); Assert.IsFalse(status.landed); Assert.IsTrue(status.docked); Assert.IsFalse(status.analysis_mode); Assert.IsFalse(status.night_vision); Assert.IsFalse(status.altitude_from_average_radius); Assert.IsFalse(status.on_foot_in_station); Assert.IsFalse(status.on_foot_on_planet); Assert.IsFalse(status.aim_down_sight); Assert.IsFalse(status.low_oxygen); Assert.IsFalse(status.low_health); Assert.AreEqual("temperate", status.on_foot_temperature); Assert.IsFalse(status.hardpoints_deployed); Assert.AreEqual(2M, status.pips_sys); Assert.AreEqual(2M, status.pips_eng); Assert.AreEqual(2M, status.pips_wea); Assert.AreEqual(0, status.firegroup); Assert.AreEqual("none", status.gui_focus); Assert.AreEqual(8M, status.fuelInTanks); Assert.AreEqual(0.57M, status.fuelInReservoir); Assert.AreEqual(0, status.cargo_carried); Assert.AreEqual("Clean", status.legalstatus); Assert.IsFalse(status.aim_down_sight); Assert.IsNull(status.latitude); Assert.IsNull(status.longitude); Assert.IsNull(status.heading); Assert.IsNull(status.altitude); Assert.IsNull(status.bodyname); Assert.IsNull(status.planetradius); } [TestMethod] public void TestParseStatusFlagsSupercruiseTaxiOdyssey() { string line = "{ \"timestamp\":\"2021-05-01T22:30:27Z\", \"event\":\"Status\", \"Flags\":16777240, \"Flags2\":2, \"Pips\":[4,4,4], \"FireGroup\":0, \"GuiFocus\":0, \"Fuel\":{ \"FuelMain\":8.000000, \"FuelReservoir\":0.360000 }, \"Cargo\":0.000000, \"LegalState\":\"Clean\" }"; Status status = statusService.ParseStatusEntry(line); // Variables set from status flags (when not signed in, flags are set to '0') DateTime expectedTimestamp = new DateTime(2021, 5, 1, 22, 30, 27, DateTimeKind.Utc); Assert.AreEqual(expectedTimestamp, status.timestamp); Assert.AreEqual((Status.Flags)16777240, status.flags); Assert.AreEqual((Status.Flags2)2, status.flags2); Assert.AreEqual(Constants.VEHICLE_TAXI, status.vehicle); Assert.IsFalse(status.being_interdicted); Assert.IsFalse(status.in_danger); Assert.IsFalse(status.near_surface); Assert.IsFalse(status.overheating); Assert.IsFalse(status.low_fuel); Assert.AreEqual("ready", status.fsd_status); Assert.IsFalse(status.srv_drive_assist); Assert.IsFalse(status.srv_under_ship); Assert.IsFalse(status.srv_turret_deployed); Assert.IsFalse(status.srv_handbrake_activated); Assert.IsFalse(status.srv_high_beams); Assert.IsFalse(status.scooping_fuel); Assert.IsFalse(status.silent_running); Assert.IsFalse(status.cargo_scoop_deployed); Assert.IsFalse(status.lights_on); Assert.IsFalse(status.in_wing); Assert.IsFalse(status.hardpoints_deployed); Assert.IsFalse(status.flight_assist_off); Assert.IsTrue(status.supercruise); Assert.IsFalse(status.hyperspace); Assert.IsTrue(status.shields_up); Assert.IsFalse(status.landing_gear_down); Assert.IsFalse(status.landed); Assert.IsFalse(status.docked); Assert.IsFalse(status.analysis_mode); Assert.IsFalse(status.night_vision); Assert.IsFalse(status.altitude_from_average_radius); Assert.IsFalse(status.on_foot_in_station); Assert.IsFalse(status.on_foot_on_planet); Assert.IsFalse(status.aim_down_sight); Assert.IsFalse(status.low_oxygen); Assert.IsFalse(status.low_health); Assert.AreEqual("temperate", status.on_foot_temperature); Assert.IsFalse(status.hardpoints_deployed); Assert.AreEqual(2M, status.pips_sys); Assert.AreEqual(2M, status.pips_eng); Assert.AreEqual(2M, status.pips_wea); Assert.AreEqual(0, status.firegroup); Assert.AreEqual("none", status.gui_focus); Assert.AreEqual(8M, status.fuelInTanks); Assert.AreEqual(0.36M, status.fuelInReservoir); Assert.AreEqual(0, status.cargo_carried); Assert.AreEqual("Clean", status.legalstatus); Assert.IsFalse(status.aim_down_sight); Assert.IsNull(status.latitude); Assert.IsNull(status.longitude); Assert.IsNull(status.heading); Assert.IsNull(status.altitude); Assert.IsNull(status.bodyname); Assert.IsNull(status.planetradius); } [TestMethod] public void TestParseStatusFlagsInFighterOdyssey() { string line = "{ \"timestamp\":\"2021-05-01T21:15:30Z\", \"event\":\"Status\", \"Flags\":34078792, \"Flags2\":0, \"Pips\":[2,8,2], \"FireGroup\":0, \"GuiFocus\":0, \"Fuel\":{ \"FuelMain\":0.000000, \"FuelReservoir\":0.240000 }, \"Cargo\":0.000000, \"LegalState\":\"Clean\" }"; Status status = statusService.ParseStatusEntry(line); // Variables set from status flags (when not signed in, flags are set to '0') DateTime expectedTimestamp = new DateTime(2021, 5, 1, 21, 15, 30, DateTimeKind.Utc); Assert.AreEqual(expectedTimestamp, status.timestamp); Assert.AreEqual((Status.Flags)34078792, status.flags); Assert.AreEqual((Status.Flags2)0, status.flags2); Assert.AreEqual(Constants.VEHICLE_FIGHTER, status.vehicle); Assert.IsFalse(status.being_interdicted); Assert.IsFalse(status.in_danger); Assert.IsFalse(status.near_surface); Assert.IsFalse(status.overheating); Assert.IsTrue(status.low_fuel); // Always true in a fighter since the fighter has no main fuel tank Assert.AreEqual("ready", status.fsd_status); Assert.IsFalse(status.srv_drive_assist); Assert.IsFalse(status.srv_under_ship); Assert.IsFalse(status.srv_turret_deployed); Assert.IsFalse(status.srv_handbrake_activated); Assert.IsFalse(status.srv_high_beams); Assert.IsFalse(status.scooping_fuel); Assert.IsFalse(status.silent_running); Assert.IsFalse(status.cargo_scoop_deployed); Assert.IsFalse(status.lights_on); Assert.IsFalse(status.in_wing); Assert.IsTrue(status.hardpoints_deployed); Assert.IsFalse(status.flight_assist_off); Assert.IsFalse(status.supercruise); Assert.IsFalse(status.hyperspace); Assert.IsTrue(status.shields_up); Assert.IsFalse(status.landing_gear_down); Assert.IsFalse(status.landed); Assert.IsFalse(status.docked); Assert.IsFalse(status.analysis_mode); Assert.IsFalse(status.night_vision); Assert.IsFalse(status.altitude_from_average_radius); Assert.IsFalse(status.on_foot_in_station); Assert.IsFalse(status.on_foot_on_planet); Assert.IsFalse(status.aim_down_sight); Assert.IsFalse(status.low_oxygen); Assert.IsFalse(status.low_health); Assert.AreEqual("temperate", status.on_foot_temperature); Assert.IsTrue(status.hardpoints_deployed); Assert.AreEqual(1M, status.pips_sys); Assert.AreEqual(4M, status.pips_eng); Assert.AreEqual(1M, status.pips_wea); Assert.AreEqual(0, status.firegroup); Assert.AreEqual("none", status.gui_focus); Assert.AreEqual(0M, status.fuelInTanks); Assert.AreEqual(0.24M, status.fuelInReservoir); Assert.AreEqual(0, status.cargo_carried); Assert.AreEqual("Clean", status.legalstatus); Assert.IsFalse(status.aim_down_sight); Assert.IsNull(status.latitude); Assert.IsNull(status.longitude); Assert.IsNull(status.heading); Assert.IsNull(status.altitude); Assert.IsNull(status.bodyname); Assert.IsNull(status.planetradius); } [TestMethod] public void TestParseStatusFlagsLandedInShipOdyssey() { string line = "{ \"timestamp\":\"2021-05-01T21:24:57Z\", \"event\":\"Status\", \"Flags\":153157646, \"Flags2\":0, \"Pips\":[4,8,0], \"FireGroup\":0, \"GuiFocus\":0, \"Fuel\":{ \"FuelMain\":32.000000, \"FuelReservoir\":0.384769 }, \"Cargo\":0.000000, \"LegalState\":\"Clean\", \"Latitude\":40.761524, \"Longitude\":65.103111, \"Heading\":32, \"Altitude\":0, \"BodyName\":\"Nervi 2 a\", \"PlanetRadius\":866740.562500 }"; Status status = statusService.ParseStatusEntry(line); // Variables set from status flags (when not signed in, flags are set to '0') DateTime expectedTimestamp = new DateTime(2021, 5, 1, 21, 24, 57, DateTimeKind.Utc); Assert.AreEqual(expectedTimestamp, status.timestamp); Assert.AreEqual((Status.Flags)153157646, status.flags); Assert.AreEqual((Status.Flags2)0, status.flags2); Assert.AreEqual(Constants.VEHICLE_SHIP, status.vehicle); Assert.IsFalse(status.being_interdicted); Assert.IsFalse(status.in_danger); Assert.IsTrue(status.near_surface); Assert.IsFalse(status.overheating); Assert.IsFalse(status.low_fuel); Assert.AreEqual("masslock", status.fsd_status); Assert.IsFalse(status.srv_drive_assist); Assert.IsFalse(status.srv_under_ship); Assert.IsFalse(status.srv_turret_deployed); Assert.IsFalse(status.srv_handbrake_activated); Assert.IsFalse(status.srv_high_beams); Assert.IsFalse(status.scooping_fuel); Assert.IsFalse(status.silent_running); Assert.IsFalse(status.cargo_scoop_deployed); Assert.IsFalse(status.lights_on); Assert.IsFalse(status.in_wing); Assert.IsFalse(status.hardpoints_deployed); Assert.IsFalse(status.flight_assist_off); Assert.IsFalse(status.supercruise); Assert.IsFalse(status.hyperspace); Assert.IsTrue(status.shields_up); Assert.IsTrue(status.landing_gear_down); Assert.IsTrue(status.landed); Assert.IsFalse(status.docked); Assert.IsTrue(status.analysis_mode); Assert.IsFalse(status.night_vision); Assert.IsFalse(status.altitude_from_average_radius); Assert.IsFalse(status.on_foot_in_station); Assert.IsFalse(status.on_foot_on_planet); Assert.IsFalse(status.aim_down_sight); Assert.IsFalse(status.low_oxygen); Assert.IsFalse(status.low_health); Assert.AreEqual("temperate", status.on_foot_temperature); Assert.IsFalse(status.hardpoints_deployed); Assert.AreEqual(2M, status.pips_sys); Assert.AreEqual(4M, status.pips_eng); Assert.AreEqual(0M, status.pips_wea); Assert.AreEqual(0, status.firegroup); Assert.AreEqual("none", status.gui_focus); Assert.AreEqual(32M, status.fuelInTanks); Assert.AreEqual(0.384769M, status.fuelInReservoir); Assert.AreEqual(0, status.cargo_carried); Assert.AreEqual("Clean", status.legalstatus); Assert.IsFalse(status.aim_down_sight); Assert.AreEqual(40.761524M, status.latitude); Assert.AreEqual(65.103111M, status.longitude); Assert.AreEqual(32M, status.heading); Assert.AreEqual(0M, status.altitude); Assert.AreEqual("Nervi 2 a", status.bodyname); Assert.AreEqual(866740.562500M, status.planetradius); } [TestMethod] public void TestParseStatusFlagsInSRVOdyssey() { string line = "{ \"timestamp\":\"2021-05-01T21:26:19Z\", \"event\":\"Status\", \"Flags\":203423752, \"Flags2\":0, \"Pips\":[7,4,1], \"FireGroup\":0, \"GuiFocus\":0, \"Fuel\":{ \"FuelMain\":0.000000, \"FuelReservoir\":0.447595 }, \"Cargo\":0.000000, \"LegalState\":\"Clean\", \"Latitude\":40.745747, \"Longitude\":65.096542, \"Heading\":159, \"Altitude\":0, \"BodyName\":\"Nervi 2 a\", \"PlanetRadius\":866740.562500 }"; Status status = statusService.ParseStatusEntry(line); // Variables set from status flags (when not signed in, flags are set to '0') DateTime expectedTimestamp = new DateTime(2021, 5, 1, 21, 26, 19, DateTimeKind.Utc); Assert.AreEqual(expectedTimestamp, status.timestamp); Assert.AreEqual((Status.Flags)203423752, status.flags); Assert.AreEqual((Status.Flags2)0, status.flags2); Assert.AreEqual(Constants.VEHICLE_SRV, status.vehicle); Assert.IsFalse(status.being_interdicted); Assert.IsFalse(status.in_danger); Assert.IsTrue(status.near_surface); Assert.IsFalse(status.overheating); Assert.IsFalse(status.low_fuel); Assert.AreEqual("ready", status.fsd_status); Assert.IsFalse(status.srv_drive_assist); Assert.IsFalse(status.srv_under_ship); Assert.IsFalse(status.srv_turret_deployed); Assert.IsFalse(status.srv_handbrake_activated); Assert.IsFalse(status.srv_high_beams); Assert.IsFalse(status.scooping_fuel); Assert.IsFalse(status.silent_running); Assert.IsFalse(status.cargo_scoop_deployed); Assert.IsFalse(status.lights_on); Assert.IsFalse(status.in_wing); Assert.IsFalse(status.hardpoints_deployed); Assert.IsFalse(status.flight_assist_off); Assert.IsFalse(status.supercruise); Assert.IsFalse(status.hyperspace); Assert.IsTrue(status.shields_up); Assert.IsFalse(status.landing_gear_down); Assert.IsFalse(status.landed); Assert.IsFalse(status.docked); Assert.IsTrue(status.analysis_mode); Assert.IsFalse(status.night_vision); Assert.IsFalse(status.altitude_from_average_radius); Assert.IsFalse(status.on_foot_in_station); Assert.IsFalse(status.on_foot_on_planet); Assert.IsFalse(status.aim_down_sight); Assert.IsFalse(status.low_oxygen); Assert.IsFalse(status.low_health); Assert.AreEqual("temperate", status.on_foot_temperature); Assert.IsFalse(status.hardpoints_deployed); Assert.AreEqual(3.5M, status.pips_sys); Assert.AreEqual(2M, status.pips_eng); Assert.AreEqual(0.5M, status.pips_wea); Assert.AreEqual(0, status.firegroup); Assert.AreEqual("none", status.gui_focus); Assert.AreEqual(0M, status.fuelInTanks); Assert.AreEqual(0.447595M, status.fuelInReservoir); Assert.AreEqual(0, status.cargo_carried); Assert.AreEqual("Clean", status.legalstatus); Assert.IsFalse(status.aim_down_sight); Assert.AreEqual(40.745747M, status.latitude); Assert.AreEqual(65.096542M, status.longitude); Assert.AreEqual(159M, status.heading); Assert.AreEqual(0M, status.altitude); Assert.AreEqual("Nervi 2 a", status.bodyname); Assert.AreEqual(866740.562500M, status.planetradius); } [TestMethod] public void TestParseStatusFlagsOnFootOnPlanetOdyssey() { string line = "{ \"timestamp\":\"2021-05-01T21:30:38Z\", \"event\":\"Status\", \"Flags\":2097152, \"Flags2\":273, \"Oxygen\":1.000000, \"Health\":1.000000, \"Temperature\":163.527100, \"SelectedWeapon\":\"$humanoid_fists_name;\", \"SelectedWeapon_Localised\":\"Unarmed\", \"Gravity\":0.101595, \"LegalState\":\"Clean\", \"Latitude\":40.741016, \"Longitude\":65.076881, \"Heading\":-165, \"BodyName\":\"Nervi 2 a\" }"; Status status = statusService.ParseStatusEntry(line); // Variables set from status flags (when not signed in, flags are set to '0') DateTime expectedTimestamp = new DateTime(2021, 5, 1, 21, 30, 38, DateTimeKind.Utc); Assert.AreEqual(expectedTimestamp, status.timestamp); Assert.AreEqual((Status.Flags)2097152, status.flags); Assert.AreEqual((Status.Flags2)273, status.flags2); Assert.AreEqual(Constants.VEHICLE_LEGS, status.vehicle); Assert.IsFalse(status.being_interdicted); Assert.IsFalse(status.in_danger); Assert.IsTrue(status.near_surface); Assert.IsFalse(status.overheating); Assert.IsFalse(status.low_fuel); Assert.AreEqual("ready", status.fsd_status); Assert.IsFalse(status.srv_drive_assist); Assert.IsFalse(status.srv_under_ship); Assert.IsFalse(status.srv_turret_deployed); Assert.IsFalse(status.srv_handbrake_activated); Assert.IsFalse(status.srv_high_beams); Assert.IsFalse(status.scooping_fuel); Assert.IsFalse(status.silent_running); Assert.IsFalse(status.cargo_scoop_deployed); Assert.IsFalse(status.lights_on); Assert.IsFalse(status.in_wing); Assert.IsFalse(status.hardpoints_deployed); Assert.IsFalse(status.flight_assist_off); Assert.IsFalse(status.supercruise); Assert.IsFalse(status.hyperspace); Assert.IsFalse(status.shields_up); Assert.IsFalse(status.landing_gear_down); Assert.IsFalse(status.landed); Assert.IsFalse(status.docked); Assert.IsFalse(status.analysis_mode); Assert.IsFalse(status.night_vision); Assert.IsFalse(status.altitude_from_average_radius); Assert.IsFalse(status.on_foot_in_station); Assert.IsTrue(status.on_foot_on_planet); Assert.IsFalse(status.aim_down_sight); Assert.IsFalse(status.low_oxygen); Assert.IsFalse(status.low_health); Assert.AreEqual("cold", status.on_foot_temperature); Assert.IsFalse(status.hardpoints_deployed); Assert.IsNull(status.pips_sys); Assert.IsNull(status.pips_eng); Assert.IsNull(status.pips_wea); Assert.IsNull(status.firegroup); Assert.AreEqual("none", status.gui_focus); Assert.IsNull(status.fuelInTanks); Assert.IsNull(status.fuelInReservoir); Assert.IsNull(status.cargo_carried); Assert.AreEqual("Clean", status.legalstatus); Assert.IsFalse(status.aim_down_sight); Assert.AreEqual(40.741016M, status.latitude); Assert.AreEqual(65.076881M, status.longitude); Assert.AreEqual(-165M, status.heading); Assert.IsNull(status.altitude); Assert.AreEqual("Nervi 2 a", status.bodyname); Assert.IsNull(status.planetradius); Assert.AreEqual(100M, status.oxygen); Assert.AreEqual(100M, status.health); Assert.AreEqual(163.527100M, status.temperature); Assert.AreEqual("Unarmed", status.selected_weapon); Assert.AreEqual(0.101595M, status.gravity); } [TestMethod] public void TestParseStatusFlagsOnFootOnStationOdyssey() { string line = "{ \"timestamp\":\"2021-05-01T21:00:10Z\", \"event\":\"Status\", \"Flags\":0, \"Flags2\":9, \"Oxygen\":1.000000, \"Health\":1.000000, \"Temperature\":293.000000, \"SelectedWeapon\":\"\", \"LegalState\":\"Clean\", \"BodyName\":\"Savitskaya Vision\" }"; Status status = statusService.ParseStatusEntry(line); // Variables set from status flags (when not signed in, flags are set to '0') DateTime expectedTimestamp = new DateTime(2021, 5, 1, 21, 00, 10, DateTimeKind.Utc); Assert.AreEqual(expectedTimestamp, status.timestamp); Assert.AreEqual((Status.Flags)0, status.flags); Assert.AreEqual((Status.Flags2)9, status.flags2); Assert.AreEqual(Constants.VEHICLE_LEGS, status.vehicle); Assert.IsFalse(status.being_interdicted); Assert.IsFalse(status.in_danger); Assert.IsFalse(status.near_surface); Assert.IsFalse(status.overheating); Assert.IsFalse(status.low_fuel); Assert.AreEqual("ready", status.fsd_status); Assert.IsFalse(status.srv_drive_assist); Assert.IsFalse(status.srv_under_ship); Assert.IsFalse(status.srv_turret_deployed); Assert.IsFalse(status.srv_handbrake_activated); Assert.IsFalse(status.srv_high_beams); Assert.IsFalse(status.scooping_fuel); Assert.IsFalse(status.silent_running); Assert.IsFalse(status.cargo_scoop_deployed); Assert.IsFalse(status.lights_on); Assert.IsFalse(status.in_wing); Assert.IsFalse(status.hardpoints_deployed); Assert.IsFalse(status.flight_assist_off); Assert.IsFalse(status.supercruise); Assert.IsFalse(status.hyperspace); Assert.IsFalse(status.shields_up); Assert.IsFalse(status.landing_gear_down); Assert.IsFalse(status.landed); Assert.IsFalse(status.docked); Assert.IsFalse(status.analysis_mode); Assert.IsFalse(status.night_vision); Assert.IsFalse(status.altitude_from_average_radius); Assert.IsTrue(status.on_foot_in_station); Assert.IsFalse(status.on_foot_on_planet); Assert.IsFalse(status.aim_down_sight); Assert.IsFalse(status.low_oxygen); Assert.IsFalse(status.low_health); Assert.AreEqual("temperate", status.on_foot_temperature); Assert.IsFalse(status.hardpoints_deployed); Assert.IsNull(status.pips_sys); Assert.IsNull(status.pips_eng); Assert.IsNull(status.pips_wea); Assert.IsNull(status.firegroup); Assert.AreEqual("none", status.gui_focus); Assert.IsNull(status.fuelInTanks); Assert.IsNull(status.fuelInReservoir); Assert.IsNull(status.cargo_carried); Assert.AreEqual("Clean", status.legalstatus); Assert.IsFalse(status.aim_down_sight); Assert.IsNull(status.latitude); Assert.IsNull(status.longitude); Assert.IsNull(status.heading); Assert.IsNull(status.altitude); Assert.AreEqual("Savitskaya Vision", status.bodyname); Assert.IsNull(status.planetradius); Assert.AreEqual(100M, status.oxygen); Assert.AreEqual(100M, status.health); Assert.AreEqual(293M, status.temperature); Assert.AreEqual("", status.selected_weapon); Assert.IsNull(status.gravity); } [TestMethod] public void TestParseStatusFlagsNormalSpace() { string line = "{ \"timestamp\":\"2018-03-25T00:39:48Z\", \"event\":\"Status\", \"Flags\":16777320, \"Pips\":[7,1,4], \"FireGroup\":0, \"GuiFocus\":0 }"; Status status = statusService.ParseStatusEntry(line); // Variables set from status flags (when not signed in, flags are set to '0') Assert.AreEqual(status.flags, (Status.Flags)16777320); Assert.AreEqual(status.vehicle, "Ship"); Assert.IsFalse(status.being_interdicted); Assert.IsFalse(status.in_danger); Assert.IsFalse(status.near_surface); Assert.IsFalse(status.overheating); Assert.IsFalse(status.low_fuel); Assert.AreEqual(status.fsd_status, "ready"); Assert.IsFalse(status.srv_drive_assist); Assert.IsFalse(status.srv_under_ship); Assert.IsFalse(status.srv_turret_deployed); Assert.IsFalse(status.srv_handbrake_activated); Assert.IsFalse(status.scooping_fuel); Assert.IsFalse(status.silent_running); Assert.IsFalse(status.cargo_scoop_deployed); Assert.IsFalse(status.lights_on); Assert.IsFalse(status.in_wing); Assert.IsTrue(status.hardpoints_deployed); Assert.IsTrue(status.flight_assist_off); Assert.IsFalse(status.supercruise); Assert.IsTrue(status.shields_up); Assert.IsFalse(status.landing_gear_down); Assert.IsFalse(status.landed); Assert.IsFalse(status.docked); } [TestMethod] public void TestParseStatusFlagsSrv() { string line = "{ \"timestamp\":\"2018-03-25T00:39:48Z\", \"event\":\"Status\", \"Flags\":69255432, \"Pips\":[2,8,2], \"FireGroup\":0, \"GuiFocus\":0, \"Latitude\":-5.683115, \"Longitude\":-10.957623, \"Heading\":249, \"Altitude\":0, \"BodyName\":\"Myeia Thaa QI - B d13 - 1 1\", \"PlanetRadius\":2140275.000000}"; Status status = statusService.ParseStatusEntry(line); // Variables set from status flags (when not signed in, flags are set to '0') Assert.AreEqual(status.flags, (Status.Flags)69255432); Assert.AreEqual(status.vehicle, "SRV"); Assert.IsFalse(status.being_interdicted); Assert.IsFalse(status.in_danger); Assert.IsTrue(status.near_surface); Assert.IsFalse(status.overheating); Assert.IsFalse(status.low_fuel); Assert.AreEqual(status.fsd_status, "ready"); Assert.IsTrue(status.srv_drive_assist); Assert.IsTrue(status.srv_under_ship); Assert.IsFalse(status.srv_turret_deployed); Assert.IsFalse(status.srv_handbrake_activated); Assert.IsFalse(status.scooping_fuel); Assert.IsFalse(status.silent_running); Assert.IsFalse(status.cargo_scoop_deployed); Assert.IsTrue(status.lights_on); Assert.IsFalse(status.in_wing); Assert.IsFalse(status.hardpoints_deployed); Assert.IsFalse(status.flight_assist_off); Assert.IsFalse(status.supercruise); Assert.IsTrue(status.shields_up); Assert.IsFalse(status.landing_gear_down); Assert.IsFalse(status.landed); Assert.IsFalse(status.docked); Assert.AreEqual("Myeia Thaa QI - B d13 - 1 1", status.bodyname); Assert.AreEqual(2140275.000000M, status.planetradius); } [TestMethod] public void TestParseStatusFlagsSupercruise() { string line = "{ \"timestamp\":\"2018-03-25T00:39:48Z\", \"event\":\"Status\", \"Flags\":16777240, \"Pips\":[7,1,4], \"FireGroup\":0, \"GuiFocus\":0, \"Fuel\":{ \"FuelMain\":26.589718, \"FuelReservoir\":0.484983 }, \"Cargo\":3.000000, \"LegalState\":\"Clean\" }"; Status status = statusService.ParseStatusEntry(line); // Variables set from status flags (when not signed in, flags are set to '0') Assert.AreEqual((Status.Flags)16777240, status.flags); Assert.AreEqual("Ship", status.vehicle); Assert.AreEqual(26.589718M, status.fuelInTanks); Assert.AreEqual(0.484983M, status.fuelInReservoir); Assert.AreEqual(26.589718M + 0.484983M, status.fuel); Assert.AreEqual(3, status.cargo_carried); Assert.AreEqual(LegalStatus.Clean, status.legalStatus); Assert.IsTrue(status.supercruise); } [TestMethod] public void TestParseStatusPips() { string line = "{ \"timestamp\":\"2018-03-25T00:39:48Z\", \"event\":\"Status\", \"Flags\":16842765, \"Pips\":[5,2,5], \"FireGroup\":0, \"GuiFocus\":0 }"; Status status = statusService.ParseStatusEntry(line); Assert.AreEqual(2.5M, status.pips_sys); Assert.AreEqual(1M, status.pips_eng); Assert.AreEqual(2.5M, status.pips_wea); } [TestMethod] public void TestParseStatusFiregroup() { string line = "{ \"timestamp\":\"2018-03-25T00:39:48Z\", \"event\":\"Status\", \"Flags\":16842765, \"Pips\":[5,2,5], \"FireGroup\":1, \"GuiFocus\":0 }"; Status status = statusService.ParseStatusEntry(line); Assert.AreEqual(1, status.firegroup); } [TestMethod] public void TestParseStatusGuiFocus() { string line = "{ \"timestamp\":\"2018-03-25T00:39:48Z\", \"event\":\"Status\", \"Flags\":16842765, \"Pips\":[5,2,5], \"FireGroup\":1, \"GuiFocus\":5 }"; Status status = statusService.ParseStatusEntry(line); Assert.AreEqual("station services", status.gui_focus); } [TestMethod] public void TestParseStatusGps1() { string line = "{ \"timestamp\":\"2018-03-25T00:39:48Z\", \"event\":\"Status\", \"Flags\":16842765, \"Pips\":[5,2,5], \"FireGroup\":1, \"GuiFocus\":0 }"; Status status = statusService.ParseStatusEntry(line); Assert.IsNull(status.latitude); Assert.IsNull(status.longitude); Assert.IsNull(status.altitude); Assert.IsNull(status.heading); } [TestMethod] public void TestParseStatusGps2() { string line = "{ \"timestamp\":\"2018-03-25T00:39:48Z\", \"event\":\"Status\", \"Flags\":69255432, \"Pips\":[2,8,2], \"FireGroup\":0, \"GuiFocus\":0, \"Latitude\":-5.683115, \"Longitude\":-10.957623, \"Heading\":249, \"Altitude\":0}"; Status status = statusService.ParseStatusEntry(line); Assert.AreEqual(-5.683115M, status.latitude); Assert.AreEqual(-10.957623M, status.longitude); Assert.AreEqual(0M, status.altitude); Assert.AreEqual(249M, status.heading); } [TestMethod] public void TestParseStatusFlagsAnalysisFssMode() { string line = "{ \"timestamp\":\"2018 - 11 - 15T04: 41:06Z\", \"event\":\"Status\", \"Flags\":151519320, \"Pips\":[4,4,4], \"FireGroup\":2, \"GuiFocus\":9, \"Fuel\":{ \"FuelMain\":15.260000, \"FuelReservoir\":0.444812 }, \"Cargo\":39.000000 }"; Status status = statusService.ParseStatusEntry(line); Assert.AreEqual(true, status.analysis_mode); Assert.AreEqual("fss mode", status.gui_focus); } [TestMethod] public void TestParseStatusFlagsAnalysisSaaMode() { string line = "{ \"timestamp\":\"2018 - 11 - 15T04: 47:51Z\", \"event\":\"Status\", \"Flags\":150995032, \"Pips\":[4,4,4], \"FireGroup\":2, \"GuiFocus\":10, \"Fuel\":{ \"FuelMain\":15.260000, \"FuelReservoir\":0.444812 }, \"Cargo\":39.000000 }"; Status status = statusService.ParseStatusEntry(line); Assert.AreEqual(true, status.analysis_mode); Assert.AreEqual("saa mode", status.gui_focus); } [TestMethod] public void TestParseStatusFlagsNightMode() { string line = "{ \"timestamp\":\"2018 - 11 - 15T04: 58:37Z\", \"event\":\"Status\", \"Flags\":422117640, \"Pips\":[4,4,4], \"FireGroup\":2, \"GuiFocus\":0, \"Fuel\":{ \"FuelMain\":29.0, \"FuelReservoir\":0.564209 }, \"Cargo\":39.000000, \"Latitude\":88.365417, \"Longitude\":99.356514, \"Heading\":29, \"Altitude\":36 }"; Status status = statusService.ParseStatusEntry(line); Assert.AreEqual(true, status.night_vision); Assert.AreEqual(true, status.lights_on); Assert.AreEqual("none", status.gui_focus); Assert.AreEqual(29.564209M, status.fuel); Assert.AreEqual(39, status.cargo_carried); } } }
using System.Linq; using System.Threading.Tasks; using Lussatite.FeatureManagement; using Lussatite.FeatureManagement.SessionManagers; using Lussatite.FeatureManagement.SessionManagers.SqlClient; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.FeatureManagement; using RimDev.AspNetCore.FeatureFlags; using RimDev.AspNetCore.FeatureFlags.Core; using RimDev.AspNetCore.FeatureFlags.UI; namespace FeatureFlags.AspNetCore { public class Startup { private readonly IConfiguration configuration; public Startup(IConfiguration configuration) { this.configuration = configuration; } public void ConfigureServices(IServiceCollection services) { var featureFlagsConnectionString = configuration.GetConnectionString("featureFlags"); var featureFlagsInitializationConnectionString = configuration.GetConnectionString("featureFlagsInitialization"); var sqlSessionManagerSettings = new SQLServerSessionManagerSettings { FeatureSchemaName = "features", }; services.AddRimDevFeatureFlags( configuration, new[] { typeof(Startup).Assembly }, connectionString: featureFlagsConnectionString, initializationConnectionString: featureFlagsInitializationConnectionString, sqlSessionManagerSettings: sqlSessionManagerSettings ); // IFeatureManagerSnapshot should always be scoped / per-request lifetime services.AddScoped<IFeatureManagerSnapshot>(serviceProvider => { var featureFlagSessionManager = serviceProvider.GetRequiredService<FeatureFlagsSessionManager>(); var featureFlagsSettings = serviceProvider.GetRequiredService<FeatureFlagsSettings>(); return new LussatiteLazyCacheFeatureManager( featureFlagsSettings.FeatureFlagTypes.Select(x => x.Name).ToList(), new [] { // in other use cases, you might list multiple ISessionManager objects to have layers featureFlagSessionManager }); }); services.AddRimDevFeatureFlagsUI(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRimDevFeatureFlags(); app.UseRimDevFeatureFlagsUI(); app.UseRouting(); app.UseEndpoints(endpoints => { var featureFlagUISettings = app.ApplicationServices.GetService<FeatureFlagUISettings>(); endpoints.Map("/test-features", async context => { var testFeature = context.RequestServices.GetService<TestFeature>(); var testFeature2 = context.RequestServices.GetService<TestFeature2>(); var testFeature3 = context.RequestServices.GetService<TestFeature3>(); context.Response.ContentType = "text/html"; await context.Response.WriteAsync($@" {testFeature.GetType().Name}: {testFeature.Enabled}<br /> {testFeature2.GetType().Name}: {testFeature2.Enabled}<br /> {testFeature3.GetType().Name}: {testFeature3.Enabled}<br /> <a href=""{featureFlagUISettings.UIPath}"">View UI</a>"); }); endpoints.Map("", context => { context.Response.Redirect("/test-features"); return Task.CompletedTask; }); var featureFlagsSettings = app.ApplicationServices.GetRequiredService<FeatureFlagsSettings>(); endpoints.MapFeatureFlagsUI( uiSettings: featureFlagUISettings, settings: featureFlagsSettings ); }); } } }
using System; using System.ComponentModel; using System.Globalization; using ReactMusicStore.Core.Utilities.Common; namespace ReactMusicStore.Core.Utilities.ComponentModel.TypeConversion { public abstract class TypeConverterBase : ITypeConverter { private readonly Lazy<TypeConverter> _systemConverter; private readonly Type _type; protected TypeConverterBase(Type type) { Guard.NotNull(type, nameof(type)); _type = type; _systemConverter = new Lazy<TypeConverter>(() => TypeDescriptor.GetConverter(type), true); } public TypeConverter SystemConverter { get { if (_type == typeof(object)) { return null; } return _systemConverter.Value; } } public virtual bool CanConvertFrom(Type type) { return SystemConverter != null && SystemConverter.CanConvertFrom(type); } public virtual bool CanConvertTo(Type type) { return type == typeof(string) || (SystemConverter != null && SystemConverter.CanConvertTo(type)); } public virtual object ConvertFrom(CultureInfo culture, object value) { if (SystemConverter != null) { return SystemConverter.ConvertFrom(null, culture, value); } throw Error.InvalidCast(value.GetType(), _type); } public virtual object ConvertTo(CultureInfo culture, string format, object value, Type to) { if (SystemConverter != null) { return SystemConverter.ConvertTo(null, culture, value, to); } if (value == null) { return string.Empty; } return value.ToString(); } } }
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using MusicDating.Models.Entities; namespace MusicDating.Data { public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // Only needed when inheriting from IndentityDbContext // Call base functionality from the OnModelCreating method in the IndentityDbContext class. modelBuilder.Entity<GenreEnsemble>() .HasKey(bc => new { bc.GenreId, bc.EnsembleId }); modelBuilder.Entity<GenreEnsemble>() .HasOne(bc => bc.Genre) .WithMany(b => b.GenreEnsembles) .HasForeignKey(bc => bc.GenreId); modelBuilder.Entity<GenreEnsemble>() .HasOne(bc => bc.Ensemble) .WithMany(c => c.GenreEnsembles) .HasForeignKey(bc => bc.EnsembleId); modelBuilder.Entity<UserInstrument>() .HasKey(bc => new { bc.Id, bc.InstrumentId }); modelBuilder.Entity<UserInstrument>() .HasOne(bc => bc.ApplicationUser) .WithMany(b => b.UserInstruments) .HasForeignKey(bc => bc.Id); modelBuilder.Entity<UserInstrument>() .HasOne(bc => bc.Instrument) .WithMany(c => c.UserInstruments) .HasForeignKey(bc => bc.InstrumentId); modelBuilder.Entity<UserInstrumentGenre>() .HasKey(bc => bc.UserInstrumentGenreId); modelBuilder.Entity<UserInstrumentGenre>() .HasOne(bc => bc.Genre) .WithMany(b => b.UserInstrumentGenres) .HasForeignKey(bc => bc.GenreId); modelBuilder.Entity<UserInstrumentGenre>() .HasOne(bc => bc.UserInstrument) .WithMany(c => c.UserInstrumentGenres) .HasForeignKey(bc => new { bc.Id, bc.InstrumentId }); modelBuilder.Entity<ApplicationUser>().HasData( new ApplicationUser { Id = "1", UserName = "Kappa", LastName = "Kappa", DateCreated = new System.DateTime(2020, 12, 24) }, new ApplicationUser { Id = "2", UserName = "Dummy", LastName = "Dummy", DateCreated = new System.DateTime(2020, 12, 24) } ); // Add data - Instruments modelBuilder.Entity<Instrument>().HasData( new Instrument { InstrumentId = 1, Name = "Drums", }, new Instrument { InstrumentId = 2, Name = "Guitar", }, new Instrument { InstrumentId = 3, Name = "Bass", } ); // Add data - userinstruments modelBuilder.Entity<UserInstrument>().HasData( new UserInstrument { Id = "1", InstrumentId = 1, Level = 5 }, new UserInstrument { Id = "2", InstrumentId = 2, Level = 2 } ); modelBuilder.Entity<Ensemble>().HasData( new Ensemble { EnsembleId = 1, EnsembleName = "U2", coverImg = "U2-picture", EnsembleDescription = "Band" } ); modelBuilder.Entity<Genre>().HasData( new Genre { GenreId = 1, GenreName = "Rock" }, new Genre { GenreId = 2, GenreName = "Pop" }, new Genre { GenreId = 3, GenreName = "Classic" } ); modelBuilder.Entity<GenreEnsemble>().HasData( new GenreEnsemble { GenreId = 1, EnsembleId = 1 }, new GenreEnsemble { GenreId = 2, EnsembleId = 1 } ); modelBuilder.Entity<UserInstrumentGenre>().HasData( new UserInstrumentGenre { UserInstrumentGenreId = 1, InstrumentId = 2, GenreId = 3, Id = "2" }, new UserInstrumentGenre { UserInstrumentGenreId = 2, InstrumentId = 1, GenreId = 1, Id = "1" }, new UserInstrumentGenre { UserInstrumentGenreId = 3, InstrumentId = 2, GenreId = 2, Id = "2" } ); } // This means that EF (Entity Framework) will create a table called Instrument based // on our Instrument class. public DbSet<Instrument> Instruments { get; set; } // This means that EF (Entity Framework) will create a table called Instrument based // on our Instrument class. public DbSet<Agent> Agent { get; set; } public DbSet<ApplicationUser> ApplicationUsers { get; set; } public DbSet<Genre> Genres { get; set; } public DbSet<Ensemble> Ensembles { get; set; } public DbSet<GenreEnsemble> GenreEnsembles { get; set; } public DbSet<UserInstrument> UserInstruments { get; set; } public DbSet<UserInstrumentGenre> UserInstrumentGenres { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Reflection; using DevExpress.XtraEditors; using DevExpress.XtraTab; using DevExpress.XtraEditors.Controls; using IRAP.Global; using IRAP.Client.User; using IRAP.Entities.MDM; using IRAP.WCF.Client.Method; namespace IRAP.Client.GUI.BatchSystem { public partial class frmPrdtParamsCollection_Ionitriding : IRAP.Client.Global.GUI.frmCustomFuncBase { private string className = MethodBase.GetCurrentMethod().DeclaringType.FullName; private List<WIPStationInfo> stations = new List<WIPStationInfo>(); public frmPrdtParamsCollection_Ionitriding() { InitializeComponent(); } private void GetStations( int communityID, long sysLogID) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; List<WIPStation> datas = new List<WIPStation>(); stations.Clear(); IRAPMDMClient.Instance.ufn_GetList_WIPStationsOfAHost( communityID, sysLogID, ref datas, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode != 0) { IRAPMessageBox.Instance.ShowErrorMessage( errText, caption); } else { datas.Sort( new WIPStation_CompareByT133AltCode()); foreach (WIPStation data in datas) { stations.Add(WIPStationInfo.Mapper(data)); } } } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } private void frmPrdtParamsCollection_Ionitriding_Shown(object sender, EventArgs e) { ilstDevices.Items.Clear(); GetStations( IRAPUser.Instance.CommunityID, IRAPUser.Instance.SysLogID); if (stations.Count <= 0) { XtraTabPage page = new XtraTabPage(); page.Name = "emptyPage"; page.TabPageWidth = 0; LabelControl label = new LabelControl(); label.Appearance.Font = new Font("微软雅黑", 18f, FontStyle.Bold); label.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; label.Appearance.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; label.Appearance.Options.UseFont = true; label.Appearance.Options.UseTextOptions = true; label.AutoSizeMode = LabelAutoSizeMode.None; label.Dock = DockStyle.Fill; label.Text = "还没有配置设备!"; page.Controls.Add(label); tcMain.TabPages.Add(page); } else { foreach (WIPStationInfo station in stations) { #region 创建设备生产情况页 XtraTabPage page = new XtraTabPage(); page.Text = station.ToString(); page.Name = station.T133Code; UserControls.ucPrdtParams_Ionitriding prdt = new UserControls.ucPrdtParams_Ionitriding(station); prdt.Dock = DockStyle.Fill; page.Controls.Add(prdt); tcMain.TabPages.Add(page); #endregion #region 创建设备列表项 ilstDevices.Items.Add(station, -1); #endregion } } } private void ilstDevices_SelectedIndexChanged(object sender, EventArgs e) { int selectedPageIndex = -1; if (ilstDevices.SelectedItem != null && (ilstDevices.SelectedItem as ImageListBoxItem).Value is WIPStationInfo) { WIPStationInfo station = (ilstDevices.SelectedItem as ImageListBoxItem).Value as WIPStationInfo; for (int i = 0; i < tcMain.TabPages.Count; i++) { if (tcMain.TabPages[i].Name == station.T133Code) { spccMain.Panel2.Text = $"设备:[{station.WIPStationName}]\t生产情况"; selectedPageIndex = i; break; } } } tcMain.SelectedTabPageIndex = selectedPageIndex; if (selectedPageIndex < 0) { spccMain.Panel2.Text = "生产情况"; } } } internal class WIPStationInfo : WIPStation { public override string ToString() { return $"[{T133AltCode}]{T107Name}"; } public static WIPStationInfo Mapper(WIPStation s) { WIPStationInfo d = Activator.CreateInstance<WIPStationInfo>(); try { var Types = s.GetType();//获得类型 var Typed = typeof(WIPStationInfo); foreach (PropertyInfo sp in Types.GetProperties())//获得类型的属性字段 { foreach (PropertyInfo dp in Typed.GetProperties()) { if (dp.Name == sp.Name && dp.CanWrite)//判断属性名是否相同 { dp.SetValue(d, sp.GetValue(s, null), null);//获得s对象属性的值复制给d对象的属性 break; } } } } catch (Exception ex) { throw ex; } return d; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DataVisCommet { public string description { get; set; } public string name { get; set; } public string date { get; set; } }
using GHCIQuizSolution.Models; using GHCIQuizSolution.Models.FromDBContext; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace GHCIQuizSolution.DBContext { public partial class Quiz : IFileBased { public FileType file { get; set; } } }
namespace EXON.Model { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("SCHEDULES")] public partial class SCHEDULE { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public SCHEDULE() { SHIFTS = new HashSet<SHIFT>(); STRUCTURES = new HashSet<STRUCTURE>(); } public int ScheduleID { get; set; } public int? StartDate { get; set; } public int? EndDate { get; set; } public int TimeOfTest { get; set; } public int Status { get; set; } public int? ContestID { get; set; } public int? SubjectID { get; set; } public int? ContestTypeID { get; set; } public virtual CONTEST_TYPES CONTEST_TYPES { get; set; } public virtual CONTEST CONTEST { get; set; } public virtual SUBJECT SUBJECT { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<SHIFT> SHIFTS { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<STRUCTURE> STRUCTURES { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace MVCandEntityFrameworkPractice.Models.Domain { public abstract class CatalogStatus { // Properties public string DisplayName { get; set; } public Catalog Catalog { get; set; } // Methods public abstract void Activate(); public abstract void Deactivate(); } }
using System.Collections.Generic; using System.IO; using System.Linq; using ConsoleApplication1.Interfaces; using ConsoleApplication1.Models; using log4net; namespace ConsoleApplication1.Implementations { public class Application : IApplication { private readonly ILog logger = LogManager.GetLogger(typeof(Application)); private readonly IMakelaarRepository repository; private readonly IMakelaarDomainModelIListConverter makelaarDomainModelIListConverter; public Application(IMakelaarDomainModelIListConverter makelaarDomainModelIListConverter, IMakelaarRepository repository) { this.repository = repository; this.makelaarDomainModelIListConverter = makelaarDomainModelIListConverter; } public void Run(IList<MakelaarDomainModel> makelaars, TextWriter writer) { var message = $"{nameof(Application)} gestart met {makelaars.Count()} makelaars"; this.logger.Info(message: message); this.repository.Clear(); this.repository.Add(makelaars); var top10 = this.repository.Take(10).ToList(); var viewdata = this.makelaarDomainModelIListConverter.ToMakelaarPartialViewModels(top10); writer.WriteLine(message); viewdata.ToList().ForEach(makelaar => writer.WriteLine($"{makelaar.Positie}, {makelaar.Naam}, {makelaar.TotaalAantalObjecten}")); writer.WriteLine(); this.logger.Info(nameof(Application) + " gestopt."); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="EchoClient.cs"> // Copyright (c) 2021 Johannes Deml. All rights reserved. // </copyright> // <author> // Johannes Deml // public@deml.io // </author> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Net; using System.Net.Sockets; using System.Threading; using UdpClient = NetCoreServer.UdpClient; namespace NetworkBenchmark.NetCoreServer { internal class EchoClient : UdpClient, IClient { public bool IsStopped => !IsConnected; private volatile bool benchmarkPreparing; private volatile bool listen; private volatile bool benchmarkRunning; private readonly int id; private readonly Configuration config; private readonly BenchmarkStatistics benchmarkStatistics; private readonly bool manualMode; private readonly byte[] message; public EchoClient(int id, Configuration config, BenchmarkStatistics benchmarkStatistics) : base(config.Address, config.Port) { this.id = id; this.config = config; NetCoreServerBenchmark.ProcessTransmissionType(config.Transmission); manualMode = config.Test == TestType.Manual; // Use Pinned Object Heap to reduce GC pressure message = GC.AllocateArray<byte>(config.MessageByteSize, true); config.Message.CopyTo(message, 0); this.benchmarkStatistics = benchmarkStatistics; } public void StartClient() { listen = true; benchmarkPreparing = true; Connect(); } public void StartBenchmark() { benchmarkPreparing = false; benchmarkRunning = true; if (!manualMode) { SendMessages(config.ParallelMessages, config.Transmission); } } public void StopBenchmark() { benchmarkRunning = false; } public void StopClient() { listen = false; } public void DisconnectClient() { Disconnect(); } #region ManualMode public void SendMessages(int messageCount, TransmissionType transmissionType) { NetCoreServerBenchmark.ProcessTransmissionType(transmissionType); for (int i = 0; i < messageCount; i++) { SendMessage(); } } #endregion protected override void OnConnected() { // Start receive datagrams ReceiveAsync(); } protected override void OnDisconnected() { base.OnDisconnected(); if (benchmarkRunning || benchmarkPreparing) { Utilities.WriteVerboseLine($"Client {id} disconnected due to timeout. Probably the server is overwhelmed by the requests."); Interlocked.Increment(ref benchmarkStatistics.Errors); } } protected override void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size) { if (benchmarkRunning) { Interlocked.Increment(ref benchmarkStatistics.MessagesClientReceived); if (!manualMode) { SendMessage(); } } if (listen) { // Continue receive datagrams // Important: Receive using thread pool is necessary here to avoid stack overflow with Socket.ReceiveFromAsync() method! ThreadPool.QueueUserWorkItem(o => { ReceiveAsync(); }); } } protected override void OnError(SocketError error) { if (benchmarkRunning) { Utilities.WriteVerboseLine($"Error Client {id}: {error}"); Interlocked.Increment(ref benchmarkStatistics.Errors); } } private void SendMessage() { Send(message); Interlocked.Increment(ref benchmarkStatistics.MessagesClientSent); } } }