/// <summary> /// Ensures required headers are populated. /// </summary> /// <param name="response"></param> private static void CheckDefaultHeaders(Dictionary <string, string> response) { response.SetDefault("PollTime", "60000"); response.SetDefault("Filter", "*.*"); response.SetDefault("Delete", "false"); response.SetDefault("Recursive", "false"); response.SetDefault("Port", "21"); }
public static Dictionary <int, double>[][] SetGroup(this IEnumerable <BuyBook> buybooks, IEnumerable <Book> books) { var buyBooks = buybooks as IList <BuyBook> ?? buybooks.ToList(); var maxquantity = buyBooks.Max(o => o.Quantity); //找尋最多數量的集數 var bookmax = books.Count(); //商品數量 var bookgriup = new Dictionary <int, double> [maxquantity][]; bookgriup[0] = new Dictionary <int, double> [bookmax]; // {0, 0, 0, 0, 0}; bookgriup.SetDefault(maxquantity, bookmax); var voluem = 0; foreach (var book in books) { var buybookVolume = buyBooks.SingleOrDefault(o => o.Serial == book.Serial); if (buybookVolume != null) { for (var kit = 0; kit <= buybookVolume.Quantity - 1; kit++) { var volumemapprice = new Dictionary <int, double> { { 1, buybookVolume.Price } }; bookgriup[kit][voluem] = volumemapprice; } } voluem++; } return(bookgriup); }
internal static MyMaterialProxy Create(MyMaterialDescription?desc, string materialTag) { int key = desc.HasValue ? desc.Value.CalculateKey() : 0; key = MyHashHelper.Combine(key, materialTag.GetHashCode()); var proxy = m_proxies.SetDefault(key, null); if (proxy != null) { return(proxy); } proxy = MyShaderMaterialReflection.CreateBindings(materialTag); if (desc == null) { // TODO: change later desc = MyAssetMesh.GetDebugMaterialDescriptor(); } LoadTextures(proxy, desc.Value); proxy.RecalcConstantsHash(); m_proxies[key] = proxy; m_descriptors[key] = desc.Value; m_reverseMapping[proxy] = desc.Value; return(proxy); }
void PrepareStream(int materialId, int triangles, int voxelLod) { float voxelSizeFactor = (float)Math.Pow(2, voxelLod * 2) * MyVoxelConstants.VOXEL_SIZE_IN_METRES; int predictedAllocation = (int)(triangles * AllocationFactor * voxelSizeFactor * MyVoxelMaterials1.Table[materialId].FoliageDensity); m_streams.SetDefault(materialId, new MyFoliageStream()).Reserve(predictedAllocation); }
public void SetDefaultTest() { Dictionary <string, string> testStr = new Dictionary <string, string>() { { "test1", "test1" }, { "test2", "test2" }, { "test3", "test3" } }; Dictionary <string, int> testInt = new Dictionary <string, int>() { { "test1", 1 }, { "test2", 2 }, { "test3", 3 } }; Assert.AreEqual("test1", testStr.SetDefault("test1", "abc")); Assert.AreEqual("abc", testStr.SetDefault("test4", "abc")); Assert.AreEqual("abc", testStr.SetDefault("test4", "cba")); Assert.AreEqual(2, testInt.SetDefault("test2", 4)); Assert.AreEqual(4, testInt.SetDefault("test4", 4)); Assert.AreEqual(4, testInt.SetDefault("test4", 5)); }
/// <summary>Adds a state change event.</summary> /// <remarks> /// <para> /// When the state is changed by setting the <see cref="currentState"/> property, the transition /// callbacks are only called when the state has actually changed. /// </para> /// <para> /// Note, that the code must not expect that the handlers will be called in the same order as they /// were added. Each handler must be independent from the others. /// </para> /// </remarks> /// <param name="state">The state to call a callback on.</param> /// <param name="enterHandler"> /// The callback to call when the state machine has switched to a new state. The callback is /// triggered <i>after</i> the state has actually changed. The callback's parameter is the /// <i>old</i> state, from which the machine has switched. /// </param> /// <param name="leaveHandler"> /// The callback to call when the state machine is going to leave the current state. The callback /// is triggered <i>before</i> the state has actually changed. The callback's parameter is the /// <i>new</i> state, to which the machine is going to switch. /// </param> /// <seealso cref="currentState"/> /// <example><code source="Examples/ProcessingUtils/SimpleStateMachine-Examples.cs" region="SimpleStateMachineFree"/></example> public void AddStateHandlers( T state, OnChange enterHandler = null, OnChange leaveHandler = null) { CheckIsNotStarted(); if (enterHandler != null) { enterHandlers.SetDefault(state).Add(enterHandler); } if (leaveHandler != null) { leaveHandlers.SetDefault(state).Add(leaveHandler); } }
void PrepareStream(int materialId, int triangles, int voxelLod) { float densityFactor = MyRender11.Settings.GrassDensityFactor * (float)MathHelper.Lerp(2 * AllocationFactor, 1.0, MyRender11.Settings.GrassDensityFactor / 10.0); if (densityFactor < 0.1f) { densityFactor = 0.1f; } int predictedAllocation = (int)(triangles * MyVoxelMaterials1.Table[materialId].FoliageDensity * densityFactor); var firstOrDefault = m_streams.GetValueOrDefault(materialId); if (firstOrDefault == null) { m_streams.SetDefault(materialId, new MyFoliageStream()).Reserve(predictedAllocation); } else { firstOrDefault.Reserve(predictedAllocation); } }
MyRenderMeshInfo LoadMesh(string assetName, out MyLODDescriptor[] LodDescriptors) { //Debug.Assert(assetName.EndsWith(".mwm")); #region Temporary for mwm endings if (!assetName.EndsWith(".mwm")) { assetName += ".mwm"; } #endregion var meshVertexInput = MyVertexInputLayout.Empty; LodDescriptors = null; MyRenderMeshInfo result = new MyRenderMeshInfo(); var importer = new MyModelImporter(); var fsPath = Path.IsPathRooted(assetName) ? assetName : Path.Combine(MyFileSystem.ContentPath, assetName); if (!MyFileSystem.FileExists(fsPath)) { System.Diagnostics.Debug.Fail("Model " + assetName + " does not exists!"); return(MyAssetsLoader.GetDebugMesh().LODs[0].m_meshInfo); } string contentPath = null; if (Path.IsPathRooted(assetName) && assetName.ToLower().Contains("models")) { contentPath = assetName.Substring(0, assetName.ToLower().IndexOf("models")); } try { importer.ImportData(fsPath, new string[] { MyImporterConstants.TAG_VERTICES, MyImporterConstants.TAG_BLENDINDICES, MyImporterConstants.TAG_BLENDWEIGHTS, MyImporterConstants.TAG_NORMALS, MyImporterConstants.TAG_TEXCOORDS0, MyImporterConstants.TAG_TANGENTS, MyImporterConstants.TAG_BINORMALS, MyImporterConstants.TAG_BONES, MyImporterConstants.TAG_MESH_PARTS, MyImporterConstants.TAG_BOUNDING_BOX, MyImporterConstants.TAG_BOUNDING_SPHERE, MyImporterConstants.TAG_LODS, }); Dictionary <string, object> tagData = importer.GetTagData(); // extract data var positions = (HalfVector4[])tagData[MyImporterConstants.TAG_VERTICES]; System.Diagnostics.Debug.Assert(positions.Length > 0); var verticesNum = positions.Length; var boneIndices = (Vector4I[])tagData[MyImporterConstants.TAG_BLENDINDICES]; var boneWeights = (Vector4[])tagData[MyImporterConstants.TAG_BLENDWEIGHTS]; var normals = (Byte4[])tagData[MyImporterConstants.TAG_NORMALS]; var texcoords = (HalfVector2[])tagData[MyImporterConstants.TAG_TEXCOORDS0]; var tangents = (Byte4[])tagData[MyImporterConstants.TAG_TANGENTS]; var bintangents = (Byte4[])tagData[MyImporterConstants.TAG_BINORMALS]; var tangentBitanSgn = new Byte4[verticesNum]; for (int i = 0; i < verticesNum; i++) { var N = VF_Packer.UnpackNormal(normals[i].PackedValue); var T = VF_Packer.UnpackNormal(tangents[i].PackedValue); var B = VF_Packer.UnpackNormal(bintangents[i].PackedValue); var tanW = new Vector4(T.X, T.Y, T.Z, 0); tanW.W = T.Cross(N).Dot(B) < 0 ? -1 : 1; tangentBitanSgn[i] = VF_Packer.PackTangentSignB4(ref tanW); } bool hasBonesInfo = false; if (boneIndices.Length > 0 && boneWeights.Length > 0) { hasBonesInfo = true; } var bones = (MyModelBone[])tagData[MyImporterConstants.TAG_BONES]; // var vertexBuffers = new List <VertexBufferId>(); IndexBufferId indexBuffer = IndexBufferId.NULL; var submeshes = new Dictionary <string, List <MyDrawSubmesh> >(); var submeshes2 = new Dictionary <string, List <MySubmeshInfo> >(); var submeshesMeta = new List <MySubmeshInfo>(); int indicesNum = 0; bool missingMaterial = false; if (tagData.ContainsKey(MyImporterConstants.TAG_MESH_PARTS)) { var indices = new List <uint>(positions.Length); uint maxIndex = 0; var meshParts = tagData[MyImporterConstants.TAG_MESH_PARTS] as List <MyMeshPartInfo>; foreach (MyMeshPartInfo meshPart in meshParts) { # region Bones indirection int[] bonesRemapping = null; if (boneIndices.Length > 0 && bones.Length > MyRender11Constants.SHADER_MAX_BONES) { Dictionary <int, int> vertexChanged = new Dictionary <int, int>(); Dictionary <int, int> bonesUsed = new Dictionary <int, int>(); int trianglesNum = meshPart.m_indices.Count / 3; for (int i = 0; i < trianglesNum; i++) { for (int j = 0; j < 3; j++) { int index = meshPart.m_indices[i * 3 + j]; if (boneWeights[index].X > 0) { bonesUsed[boneIndices[index].X] = 1; } if (boneWeights[index].Y > 0) { bonesUsed[boneIndices[index].Y] = 1; } if (boneWeights[index].Z > 0) { bonesUsed[boneIndices[index].Z] = 1; } if (boneWeights[index].W > 0) { bonesUsed[boneIndices[index].W] = 1; } } } if (bonesUsed.Count > MyRender11Constants.SHADER_MAX_BONES) { Debug.Assert(bonesUsed.Count <= MyRender11Constants.SHADER_MAX_BONES, "Model \"" + assetName + "\"'s part uses more than 60 bones, please split model on more parts"); } var partBones = new List <int>(bonesUsed.Keys); partBones.Sort(); if (partBones.Count > 0 && partBones[partBones.Count - 1] >= MyRender11Constants.SHADER_MAX_BONES) { for (int i = 0; i < partBones.Count; i++) { bonesUsed[partBones[i]] = i; } Dictionary <int, int> vertexTouched = new Dictionary <int, int>(); for (int i = 0; i < trianglesNum; i++) { for (int j = 0; j < 3; j++) { int index = meshPart.m_indices[i * 3 + j]; if (!vertexTouched.ContainsKey(index)) { if (boneWeights[index].X > 0) { boneIndices[index].X = bonesUsed[boneIndices[index].X]; } if (boneWeights[index].Y > 0) { boneIndices[index].Y = bonesUsed[boneIndices[index].Y]; } if (boneWeights[index].Z > 0) { boneIndices[index].Z = bonesUsed[boneIndices[index].Z]; } if (boneWeights[index].W > 0) { boneIndices[index].W = bonesUsed[boneIndices[index].W]; } vertexTouched[index] = 1; int changes = 0; vertexChanged.TryGetValue(index, out changes); vertexChanged[index] = changes + 1; } } } bonesRemapping = partBones.ToArray(); } if (vertexChanged.Values.Count > 0) { Debug.Assert(vertexChanged.Values.Max() < 2, "Vertex shared between model parts, will likely result in wrong skinning"); } } #endregion int startIndex = indices.Count; int indexCount = meshPart.m_indices.Count; uint minIndex = (uint)meshPart.m_indices[0]; foreach (var i in meshPart.m_indices) { indices.Add((uint)i); minIndex = Math.Min(minIndex, (uint)i); } uint baseVertex = minIndex; for (int i = startIndex; i < startIndex + indexCount; i++) { indices[i] -= minIndex; maxIndex = Math.Max(maxIndex, indices[i]); } #region Material var materialDesc = meshPart.m_MaterialDesc; var matId = MyMeshMaterials1.GetMaterialId(materialDesc, contentPath); var partKey = MyMeshMaterials1.Table[matId.Index].Technique; var materialName = MyMeshMaterials1.Table[matId.Index].Name; var list = submeshes.SetDefault(partKey, new List <MyDrawSubmesh>()); list.Add(new MyDrawSubmesh(indexCount, startIndex, (int)baseVertex, MyMeshMaterials1.GetProxyId(matId), bonesRemapping)); submeshesMeta.Add(new MySubmeshInfo { IndexCount = indexCount, StartIndex = startIndex, BaseVertex = (int)baseVertex, BonesMapping = bonesRemapping, Material = materialName.ToString(), Technique = partKey }); var list2 = submeshes2.SetDefault(partKey, new List <MySubmeshInfo>()); list2.Add(submeshesMeta[submeshesMeta.Count - 1]); #endregion } indicesNum = indices.Count; #region Fill gpu buffes unsafe { if (maxIndex <= ushort.MaxValue) { // create 16 bit indices var indices16 = new ushort[indices.Count]; for (int i = 0; i < indices.Count; i++) { indices16[i] = (ushort)indices[i]; } result.Indices = indices16; fixed(ushort *I = indices16) { indexBuffer = MyHwBuffers.CreateIndexBuffer(indices16.Length, Format.R16_UInt, BindFlags.IndexBuffer, ResourceUsage.Immutable, new IntPtr(I), assetName + " index buffer"); } } else { var indicesArray = indices.ToArray(); fixed(uint *I = indicesArray) { indexBuffer = MyHwBuffers.CreateIndexBuffer(indices.Count, Format.R32_UInt, BindFlags.IndexBuffer, ResourceUsage.Immutable, new IntPtr(I), assetName + " index buffer"); } } } unsafe { if (!hasBonesInfo) { var vertices = new MyVertexFormatPositionH4[verticesNum]; for (int i = 0; i < verticesNum; i++) { vertices[i] = new MyVertexFormatPositionH4(positions[i]); } meshVertexInput = meshVertexInput.Append(MyVertexInputComponentType.POSITION_PACKED); result.VertexPositions = vertices; fixed(MyVertexFormatPositionH4 *V = vertices) { vertexBuffers.Add(MyHwBuffers.CreateVertexBuffer(verticesNum, sizeof(MyVertexFormatPositionH4), BindFlags.VertexBuffer, ResourceUsage.Immutable, new IntPtr(V), assetName + " vertex buffer " + vertexBuffers.Count)); } } else { var vertices = new MyVertexFormatPositionSkinning[verticesNum]; for (int i = 0; i < verticesNum; i++) { vertices[i] = new MyVertexFormatPositionSkinning( positions[i], new Byte4(boneIndices[i].X, boneIndices[i].Y, boneIndices[i].Z, boneIndices[i].W), boneWeights[i]); } meshVertexInput = meshVertexInput.Append(MyVertexInputComponentType.POSITION_PACKED) .Append(MyVertexInputComponentType.BLEND_WEIGHTS).Append(MyVertexInputComponentType.BLEND_INDICES); fixed(MyVertexFormatPositionSkinning *V = vertices) { vertexBuffers.Add(MyHwBuffers.CreateVertexBuffer(verticesNum, sizeof(MyVertexFormatPositionSkinning), BindFlags.VertexBuffer, ResourceUsage.Immutable, new IntPtr(V), assetName + " vertex buffer " + vertexBuffers.Count)); } } // add second stream { var vertices = new MyVertexFormatTexcoordNormalTangent[verticesNum]; for (int i = 0; i < verticesNum; i++) { vertices[i] = new MyVertexFormatTexcoordNormalTangent(texcoords[i], normals[i], tangentBitanSgn[i]); } fixed(MyVertexFormatTexcoordNormalTangent *V = vertices) { vertexBuffers.Add(MyHwBuffers.CreateVertexBuffer(verticesNum, sizeof(MyVertexFormatTexcoordNormalTangent), BindFlags.VertexBuffer, ResourceUsage.Immutable, new IntPtr(V), assetName + " vertex buffer " + vertexBuffers.Count)); } result.VertexExtendedData = vertices; meshVertexInput = meshVertexInput .Append(MyVertexInputComponentType.NORMAL, 1) .Append(MyVertexInputComponentType.TANGENT_SIGN_OF_BITANGENT, 1) .Append(MyVertexInputComponentType.TEXCOORD0_H, 1); } } #endregion } #region Extract lods if (tagData.ContainsKey(MyImporterConstants.TAG_LODS)) { var tagLODs = tagData[MyImporterConstants.TAG_LODS]; if (((MyLODDescriptor[])tagLODs).Length > 0) { } LodDescriptors = (MyLODDescriptor[])((MyLODDescriptor[])tagLODs).Clone(); } #endregion if (missingMaterial) { Debug.WriteLine(String.Format("Mesh {0} has missing material", assetName)); } //indexBuffer.SetDebugName(assetName + " index buffer"); int c = 0; //vertexBuffers.ForEach(x => x.SetDebugName(assetName + " vertex buffer " + c++)); // result.BoundingBox = (BoundingBox)tagData[MyImporterConstants.TAG_BOUNDING_BOX]; result.BoundingSphere = (BoundingSphere)tagData[MyImporterConstants.TAG_BOUNDING_SPHERE]; result.VerticesNum = verticesNum; result.IndicesNum = indicesNum; result.VertexLayout = meshVertexInput; result.IB = indexBuffer; result.VB = vertexBuffers.ToArray(); result.IsAnimated = hasBonesInfo; result.Parts = submeshes.ToDictionary(x => x.Key, x => x.Value.ToArray()); result.PartsMetadata = submeshes2.ToDictionary(x => x.Key, x => x.Value.ToArray()); result.m_submeshes = submeshesMeta; IsAnimated |= result.IsAnimated; importer.Clear(); return(result); }
private int PruneDuplicates() { var byPath = new Dictionary<string, List<LaunchEntry>>(); foreach (var launchEntry in foundFiles) { byPath.SetDefault(launchEntry.FullPath).Add(launchEntry); if(!string.IsNullOrEmpty(launchEntry.LinkTarget)) byPath.SetDefault(launchEntry.LinkTarget).Add(launchEntry); } int dropped = 0; foreach (var byPathPair in byPath) { if(byPathPair.Value.Count <= 1) continue; foreach(var elToDrop in byPathPair.Value.OrderBy(entry => entry.NamePath.Length).Skip(1)) { foundFiles.Remove(elToDrop); dropped++; } } return dropped; }
public static void SetDefaultAddToDict(Dictionary <int, HashSet <string> > dict) { // If key 123 doesn't exist it will be created automatically. dict.SetDefault(123).Add("abc"); }
public IReadOnlyDictionary <string, object> ToDictionary(IEnumerable <string> names = null) { var thisType = this.GetType(); var ret = new Dictionary <string, object>(); if (_underscoreNames == null) { _underscoreNames = new Dictionary <string, string>(); } Func <PropertyInfo, string> getUnderscoreName = (pi) => { var piname = pi.Name; return(_underscoreNames.SetDefault(pi.Name, pi.Name.ToUnderscoreString())); }; Predicate <string> isValidName = (name) => (names == null || names.Contains(name)); var props = thisType.GetProperties(); // foreach (var pi in props) for (int i = 0; i < props.Length; i++) { var pi = props[i]; if (pi.Name == nameof(Booster) || pi.Name == nameof(EvalResult)) { continue; } var usName = getUnderscoreName(pi); if (!isValidName(usName)) { continue; } var propValue = pi.GetValue(this); if (propValue == null) { continue; } var propString = String.Empty; var propEnum = propValue as IEnumerable; if (propEnum != null && pi.PropertyType != typeof(string)) { propString = String.Join(",", propEnum .Cast <object>() .Select(o => Convert.ToString(o, CultureInfo.InvariantCulture))); } else if (pi.PropertyType == typeof(bool)) { propString = (bool)propValue ? "true" : "false"; } else if (pi.PropertyType == typeof(string)) { propString = (string)propValue; } else { propString = Convert.ToString(propValue, CultureInfo.InvariantCulture); } if (!String.IsNullOrWhiteSpace(propString)) { ret.Add(usName, propString); } } return(ret); }
private void ProcessReduceLevels(Dictionary<string, List<ReduceLevel>> aggregatedReduceLevels, IDbConnection conn) { //Basically resoving the foreign key reference var allReduceLevels = _storageCommands.SelectListAllReduceLevels(conn); foreach (var level in allReduceLevels) { level.AggregationClass = _settings.ReduceMethodProvider.Retrieve(level.AggregationClassName); //TODO This is a problem... this really doesn't work! var reduceLevelList = aggregatedReduceLevels.SetDefault(level.MonitorConfigName, new List<ReduceLevel>()); reduceLevelList.Add(level); } //Validate that the reduce level resolutions are all integral multiples of one another foreach (var reduceLevels in aggregatedReduceLevels.Values) { long lastResolution = 0; foreach (var reduceLevel in reduceLevels) { if (reduceLevel.Resolution < Constant.MinResolutionForDbWrites) throw new DataException("Will not write to DB at a resolution higher than " + Constant.MinResolutionForDbWrites + " ms; make sure your first reduce table has at least this resolution. Monitor Config \"" + reduceLevel.MonitorConfigName + "\""); if (Constant.MsPerDay % reduceLevel.Resolution != 0) throw new DataException("Only resolutions that divide evenly into a day are supported"); if (lastResolution == 0) { lastResolution = reduceLevel.Resolution; continue; } //if the resolutions are devisable by each other then we have a problem if (((double)reduceLevel.Resolution / (double)lastResolution) != (long)(reduceLevel.Resolution / lastResolution)) throw new DataException("Reduce level resolutions must be integral multiples of each other. Failed for \"" + reduceLevel.MonitorConfigName + "\" levels " + lastResolution + " and " + reduceLevel.Resolution); lastResolution = reduceLevel.Resolution; } } }
private void Checker() { var conditionStates = new Dictionary<Space, Dictionary<BaseCondition, bool>>(); while (true) { foreach (var space in Config.Spaces) foreach (var condition in Conditions) { var oldState = conditionStates.SetDefault(space, new Dictionary<BaseCondition, bool>()).SetDefault(condition, false); var newState = condition.Check(space); if (newState && !oldState) { ActivateSpace(space); } conditionStates[space][condition] = newState; } Thread.Sleep(5000); } }