//Materials window GUI code internal void MaterialsWindow(int id) { GUI.DragWindow(new Rect(0, 0, materialsWindow.width, 25)); GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); materialsScroll = GUILayout.BeginScrollView(materialsScroll, false, false, skins.horizontalScrollbar, skins.verticalScrollbar, skins.box, GUILayout.MaxHeight(200), GUILayout.Width(140)); materialsID = GUILayout.SelectionGrid(materialsID, this.pChute.materials.materials.Values.ToArray(), 1, skins.button); GUILayout.EndScrollView(); GUILayout.BeginVertical(); MaterialDefinition material = this.pChute.materials.materials.Keys.ToArray()[materialsID]; StringBuilder builder = new StringBuilder(); builder.Append("Description: ").AppendLine(material.description); builder.Append("\nDrag coefficient: ").AppendLine(material.dragCoefficient.ToString("0.00#")); builder.Append("\nArea density: ").Append(material.areaDensity * 1000).AppendLine("kg/m²\n"); builder.Append("Area cost: ").Append(material.areaCost.ToString()).Append("f/m²"); GUILayout.Label(builder.ToString(), skins.label); GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Choose material", skins.button, GUILayout.Width(150))) { this.material = material; this.materialsVisible = false; } if (GUILayout.Button("Cancel", skins.button, GUILayout.Width(150))) { this.materialsVisible = false; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.EndVertical(); }
/// <summary> /// Loads the Parachute from a ConfigNode. /// </summary> /// <param name="node">Node to load the Parachute from</param> private void Load(ConfigNode node) { node.TryGetValue("material", ref material); node.TryGetValue("preDeployedDiameter", ref preDeployedDiameter); node.TryGetValue("deployedDiameter", ref deployedDiameter); node.TryGetValue("minIsPressure", ref minIsPressure); node.TryGetValue("minDeployment", ref minDeployment); node.TryGetValue("minPressure", ref minPressure); node.TryGetValue("deploymentAlt", ref deploymentAlt); node.TryGetValue("cutAlt", ref cutAlt); node.TryGetValue("preDeploymentSpeed", ref preDeploymentSpeed); node.TryGetValue("deploymentSpeed", ref deploymentSpeed); node.TryGetValue("parachuteName", ref parachuteName); node.TryGetValue("baseParachuteName", ref baseParachuteName); node.TryGetValue("capName", ref capName); node.TryGetValue("preDeploymentAnimation", ref preDeploymentAnimation); node.TryGetValue("deploymentAnimation", ref deploymentAnimation); node.TryGetValue("forcedOrientation", ref forcedOrientation); node.TryGetValue("depState", ref depState); if (!MaterialsLibrary.instance.TryGetMaterial(material, ref mat)) { material = "Nylon"; mat = MaterialsLibrary.instance.GetMaterial("Nylon"); } }
/// <summary> /// Populate lists when we connect. /// </summary> void InitStatics() { if (netMaterialList != null) { AddFakeMaterials(netMaterialList); MaterialTokenList.MaterialTokens = netMaterialList.material_list; Debug.Log("Materials fetched: " + netMaterialList.material_list.Count); } if (netTiletypeList != null) { TiletypeTokenList.tiletypeTokenList = netTiletypeList.tiletype_list; Debug.Log("Tiletypes fetched: " + netTiletypeList.tiletype_list.Count); } if (netItemList != null) { ItemTokenList.ItemTokens = netItemList.material_list; Debug.Log("Itemtypes fetched: " + netItemList.material_list.Count); } else { MaterialDefinition blankMaterial = new MaterialDefinition(); blankMaterial.id = "NONE"; blankMaterial.name = "NONE"; blankMaterial.mat_pair = new MatPair(); blankMaterial.mat_pair.mat_type = -1; blankMaterial.mat_pair.mat_index = -1; List <MaterialDefinition> blankItemList = new List <MaterialDefinition>(); blankItemList.Add(blankMaterial); ItemTokenList.ItemTokens = blankItemList; Debug.Log("Created dummy Itemtype list."); } if (netBuildingList != null) { BuildingTokenList.BuildingTokens = netBuildingList.building_list; Debug.Log("Buildingtypes fetched: " + netBuildingList.building_list.Count); } if (netTiletypeList != null) { MapDataStore.tiletypeTokenList = netTiletypeList.tiletype_list; Debug.Log("Tiletypes fetched: " + netTiletypeList.tiletype_list.Count); } if (netPlantRawList != null) { PlantTokenList.PlantRawList = netPlantRawList.plant_raws; Debug.Log("Plant Raws fetched: " + netPlantRawList.plant_raws.Count); } if (creatureRaws != null) { CreatureTokenList.CreatureRawList = creatureRaws; Debug.Log("Creature Raws fetched: " + creatureRaws.Count); } //Debug.Log("Buildingtypes fetched: " + netBuildingList.building_list.Count); //Debug.Log("Creature Raws fetched: " + netCreatureRawList.creature_raws.Count); }
private void AddSponzaAtriumObjects() { ObjParser parser = new ObjParser(); using (FileStream objStream = File.OpenRead(AssetHelper.GetPath("Models/SponzaAtrium/sponza.obj"))) { ObjFile atriumFile = parser.Parse(objStream); MtlFile atriumMtls; using (FileStream mtlStream = File.OpenRead(AssetHelper.GetPath("Models/SponzaAtrium/sponza.mtl"))) { atriumMtls = new MtlParser().Parse(mtlStream); } foreach (ObjFile.MeshGroup group in atriumFile.MeshGroups) { Vector3 scale = new Vector3(0.1f); ConstructedMeshInfo mesh = atriumFile.GetMesh(group); MaterialDefinition materialDef = atriumMtls.Definitions[mesh.MaterialName]; ImageSharpTexture overrideTextureData = null; ImageSharpTexture alphaTexture = null; MaterialPropsAndBuffer materialProps = CommonMaterials.Brick; if (materialDef.DiffuseTexture != null) { string texturePath = AssetHelper.GetPath("Models/SponzaAtrium/" + materialDef.DiffuseTexture); overrideTextureData = LoadTexture(texturePath, true); } if (materialDef.AlphaMap != null) { string texturePath = AssetHelper.GetPath("Models/SponzaAtrium/" + materialDef.AlphaMap); alphaTexture = LoadTexture(texturePath, false); } if (materialDef.Name.Contains("vase")) { materialProps = CommonMaterials.Vase; } if (group.Name == "sponza_117") { MirrorMesh.Plane = Plane.CreateFromVertices( atriumFile.Positions[group.Faces[0].Vertex0.PositionIndex] * scale.X, atriumFile.Positions[group.Faces[0].Vertex1.PositionIndex] * scale.Y, atriumFile.Positions[group.Faces[0].Vertex2.PositionIndex] * scale.Z); materialProps = CommonMaterials.Reflective; } AddTexturedMesh( mesh, overrideTextureData, alphaTexture, materialProps, Vector3.Zero, Quaternion.Identity, scale, group.Name); } } }
private void ProcessMesh(int arrayPos, Dme modelData, Mesh meshData, Vector3[] verts, Vector2[] uvs) { uint materialHash = modelData.Materials[(int)meshData.MaterialIndex].MaterialDefinitionHash; MaterialDefinition materialDefinition = materialDefinitionManager.GetMaterial(materialHash); uint vertexLayoutHash = materialDefinition.DrawStyles[DRAWSTYLE_INDEX].VertexLayoutNameHash; VertexLayout vertexLayout = materialDefinitionManager.GetVertexLayout(vertexLayoutHash); GetMeshVerts(verts, arrayPos, meshData, vertexLayout); GetMeshUVs(uvs, arrayPos, meshData, vertexLayout); }
private void AddFakeMaterials(MaterialList netMaterialList) { for (int i = 0; i <= (int)DesignationType.UpStairs; i++) { MaterialDefinition item = new MaterialDefinition(); item.id = "DESIGNATION:" + ((DesignationType)i).ToString(); item.name = ((DesignationType)i).ToString() + " Designation"; item.mat_pair = new MatPairStruct((int)MatBasic.DESIGNATION, i); netMaterialList.material_list.Add(item); } }
public VertexLayout GetVertexLayout(int drawStyleIndex) { MaterialDefinition materialDefinition = MaterialDefinitionLibrary.Instance.MaterialDefinitions[Model.Materials[(int)MaterialIndex].MaterialDefinitionHash]; if (materialDefinition == null) { return(null); } return(MaterialDefinitionLibrary.Instance.VertexLayouts[materialDefinition.DrawStyles[0].VertexLayoutNameHash]); }
internal static void AddFakeCreaturesToList(Dictionary <MatPairStruct, MaterialDefinition> creatures, string prefix) { foreach (string template in templateList) { MatPairStruct creatureCaste = new MatPairStruct(count, -1); MaterialDefinition creatureDef = new MaterialDefinition(); creatureDef.mat_pair = creatureCaste; creatureDef.id = prefix.ToUpper() + "_" + template.ToUpper() + ":DEFAULT"; creatureDef.name = prefix.ToLower() + " " + template.ToLower(); creatures[creatureCaste] = creatureDef; count--; } }
public Equip(InventoryItem item, MaterialDefinition itemDef, MaterialDefinition material) { if (itemDef != null) { itemType = itemDef.id.Split('/').Last(); } else { itemType = item.item.type.ToString(); } this.item = item; this.itemDef = itemDef; this.material = material; }
private bool generateCustomMaterials() { try { string line; // Create a new StreamReader, tell it which file to read and what encoding the file was saved as StreamReader theReader = new StreamReader(utmFile, Encoding.Default); // Immediately clean up the reader after this block of code is done. // You generally use the "using" statement for potentially memory-intensive objects // instead of relying on garbage collection. // (Do not confuse this with the using directive for namespace at the // beginning of a class!) using (theReader) { // inizializzo la definizione di materiale current = new MaterialDefinition(); current.setVerbose(true); MaterialDefinition.setModelName(modelName); MaterialDefinition.setCustomMaterialsFolder(customMaterialsFolder); MaterialDefinition.setBaseMaterialsFolder("Assets/" + baseMaterialsFolderName + "/Resources"); // mi assicuro che venga generata un'eccezione se qualcosa dovesse andare storto durante il parsing Assert.raiseExceptions = true; // leggo il file riga per riga do { line = theReader.ReadLine(); if (line != null) { parseLine(line); } }while (line != null); // se ho una definizione valida attiva, creo l'ultimo materiale current.create(); // Done reading, close the reader and return true to broadcast success theReader.Close(); return(true); } } catch (Exception e) { Debug.Log(e.Message); return(false); } }
private void ApplyItemUp(BodyPart part, InventoryItem item, MaterialDefinition itemDef, MaterialDefinition material, int up_step) { var parent = part.parent; //These are all flags for primary parts that take equipment. Other equipment doesn't cover it. if (parent.flags.grasp || parent.flags.upperbody || parent.flags.lowerbody || parent.flags.head || parent.flags.stance) { return; } parent.inventory.Add(new BodyPart.Equip(item, itemDef, material)); if (up_step > 0) { ApplyItemUp(parent, item, itemDef, material, up_step - 1); } }
private void ApplyItemDown(BodyPart part, InventoryItem item, MaterialDefinition itemDef, MaterialDefinition material, int down_step) { foreach (var child in part.children) { //These are all flags for primary parts that take equipment. Other equipment doesn't cover it. if (child.flags.grasp || child.flags.upperbody || child.flags.lowerbody || child.flags.head || child.flags.stance) { continue; } child.inventory.Add(new BodyPart.Equip(item, itemDef, material)); if (down_step > 0) { ApplyItemDown(child, item, itemDef, material, down_step - 1); } } }
static void AddMat(string prefix, string word, string suffix, MaterialDefinition token) { if (_tripleWords == null) { _tripleWords = new Dictionary <string, Dictionary <string, Dictionary <string, MaterialDefinition> > >(); } if (!_tripleWords.ContainsKey(prefix)) { _tripleWords[prefix] = new Dictionary <string, Dictionary <string, MaterialDefinition> >(); } if (!_tripleWords[prefix].ContainsKey(suffix)) { _tripleWords[prefix][suffix] = new Dictionary <string, MaterialDefinition>(); } _tripleWords[prefix][suffix][word] = token; }
private IEnumerable <(string name, string path)> GetMaps(MaterialDefinition mat) { if (mat is null) { throw new ArgumentNullException(nameof(mat)); } if (mat.DiffuseTexture is object) { yield return(nameof(mat.DiffuseTexture), mat.DiffuseTexture); } if (mat.AlphaMap is object) { yield return(nameof(mat.AlphaMap), mat.AlphaMap); } if (mat.BumpMap is object) { yield return(nameof(mat.BumpMap), mat.BumpMap); } if (mat.DisplacementMap is object) { yield return(nameof(mat.DisplacementMap), mat.DisplacementMap); } if (mat.AmbientTexture is object) { yield return(nameof(mat.AmbientTexture), mat.AmbientTexture); } if (mat.SpecularColorTexture is object) { yield return(nameof(mat.SpecularColorTexture), mat.SpecularColorTexture); } if (mat.SpecularHighlightTexture is object) { yield return(nameof(mat.SpecularHighlightTexture), mat.SpecularHighlightTexture); } if (mat.StencilDecalTexture is object) { yield return(nameof(mat.StencilDecalTexture), mat.StencilDecalTexture); } }
public static Mesh LoadFromStream(Model model, Stream stream) { BinaryReader binaryReader = new BinaryReader(stream); uint bytesPerVertex = 0; uint vertexStreamCount = 0; Mesh mesh = new Mesh(model); mesh.MaterialIndex = binaryReader.ReadUInt32(); mesh.Unknown1 = binaryReader.ReadUInt32(); mesh.Unknown2 = binaryReader.ReadUInt32(); mesh.Unknown3 = binaryReader.ReadUInt32(); vertexStreamCount = binaryReader.ReadUInt32(); mesh.IndexSize = binaryReader.ReadUInt32(); mesh.IndexCount = binaryReader.ReadUInt32(); mesh.VertexCount = binaryReader.ReadUInt32(); mesh.VertexStreams = new VertexStream[(int)vertexStreamCount]; // read vertex streams for (int j = 0; j < vertexStreamCount; ++j) { bytesPerVertex = binaryReader.ReadUInt32(); byte[] buffer = binaryReader.ReadBytes((int)mesh.VertexCount * (int)bytesPerVertex); VertexStream vertexStream = new VertexStream((int)bytesPerVertex, buffer); if (vertexStream != null) { mesh.VertexStreams[j] = vertexStream; } } // read indices mesh.IndexData = binaryReader.ReadBytes((int)mesh.IndexCount * (int)mesh.IndexSize); uint materialDefinitionHash = model.Materials[(int)mesh.MaterialIndex].MaterialDefinitionHash; MaterialDefinition materialDefinition = null; MaterialDefinitionLibrary.Instance.MaterialDefinitions.TryGetValue(materialDefinitionHash, out materialDefinition); string effectName = materialDefinition.DrawStyles[0].Effect; return(mesh); }
//Copies all fields to the symmetry counterpart public void CopyFromOriginal(RealChuteModule module, ProceduralChute pChute) { Parachute sym = module.parachutes[id]; ChuteTemplate template = pChute.chutes[id]; parachute = pChute.rcModule.parachutes[id]; material = sym.mat; parachute.deployedDiameter = sym.deployedDiameter; parachute.preDeployedDiameter = sym.preDeployedDiameter; isPressure = sym.minIsPressure; if (isPressure) { parachute.minPressure = sym.minPressure; } else { parachute.minDeployment = sym.minDeployment; } parachute.deploymentAlt = sym.deploymentAlt; parachute.cutAlt = sym.cutAlt; parachute.preDeploymentSpeed = sym.preDeploymentSpeed; parachute.deploymentSpeed = sym.deploymentSpeed; this.chuteID = template.chuteID; this.typeID = template.typeID; this.modelID = template.modelID; this.materialsID = template.materialsID; this.isPressure = template.isPressure; this.calcSelect = template.calcSelect; this.getMass = template.getMass; this.useDry = template.useDry; this.preDepDiam = template.preDepDiam; this.depDiam = template.depDiam; this.predepClause = template.predepClause; this.mass = template.mass; this.landingSpeed = template.landingSpeed; this.deceleration = template.deceleration; this.refDepAlt = template.refDepAlt; this.chuteCount = template.chuteCount; this.deploymentAlt = template.deploymentAlt; this.cutAlt = template.cutAlt; this.preDepSpeed = template.preDepSpeed; this.depSpeed = template.depSpeed; }
//Materials window GUI code internal void MaterialsWindow(int id) { GUI.DragWindow(drag); GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); this.materialsScroll = GUILayout.BeginScrollView(this.materialsScroll, false, false, this.skins.horizontalScrollbar, this.skins.verticalScrollbar, this.skins.box, GUILayout.MaxHeight(200), GUILayout.Width(140)); this.materialsID = GUILayout.SelectionGrid(this.materialsID, this.pChute.materials.materialNames, 1, this.skins.button); GUILayout.EndScrollView(); GUILayout.BeginVertical(); MaterialDefinition material = new MaterialDefinition(); if (this.pChute.materials.materialNames.IndexInRange(this.materialsID)) { string name = this.pChute.materials.materialNames[this.materialsID]; this.pChute.materials.TryGetMaterial(name, ref material); } StringBuilder builder = new StringBuilder(); builder.Append("Description: ").AppendLine(material.description); builder.Append("\nDrag coefficient: ").AppendLine(material.dragCoefficient.ToString("0.00#")); builder.Append("\nArea density: ").Append(material.areaDensity * 1000).AppendLine("kg/m²"); builder.Append("\nArea cost: ").Append(material.areaCost.ToString()).Append("F/m²"); builder.Append("\nMax temperature: ").Append((material.maxTemp + RCUtils.absoluteZero).ToString()).Append("°C"); builder.Append("\nSpecific heat: ").Append(material.specificHeat.ToString()).Append("J/kg∙K"); builder.Append("\nEmissivity constant: ").Append(material.emissivity.ToString()); GUILayout.Label(builder.ToString(), this.skins.label); GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Choose material", this.skins.button, GUILayout.Width(150))) { this.material = material; this.materialsVisible = false; } if (GUILayout.Button("Cancel", this.skins.button, GUILayout.Width(150))) { this.materialsVisible = false; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.EndVertical(); }
//Applies the preset on the chute internal void ApplyPreset(Preset preset) { Preset.ChuteParameters parameters = preset.parameters[id]; this.material = pChute.materials.GetMaterial(parameters.material); this.materialsID = pChute.materials.GetMaterialIndex(parameters.material); this.preDepDiam = parameters.preDeployedDiameter; this.depDiam = parameters.deployedDiameter; this.isPressure = parameters.minIsPressure; this.predepClause = this.isPressure ? parameters.minPressure : parameters.minDeployment; if (isPressure) { this.parachute.minDeployment = float.Parse(parameters.minDeployment); } else { this.parachute.minPressure = float.Parse(parameters.minPressure); } this.deploymentAlt = parameters.deploymentAlt; this.cutAlt = parameters.cutAlt; this.preDepSpeed = parameters.preDeploymentSpeed; this.depSpeed = parameters.deploymentSpeed; if (pChute.textureLibrary == preset.textureLibrary || pChute.textureLibrary != "none") { if (textures.canopyNames.Contains(parameters.chuteTexture) && textures.canopies.Count > 0 && !string.IsNullOrEmpty(parameters.chuteTexture)) { this.chuteID = textures.GetCanopyIndex(textures.GetCanopy(parameters.chuteTexture)); } if (textures.modelNames.Contains(parameters.modelName) && textures.models.Count > 0 && !string.IsNullOrEmpty(parameters.modelName)) { this.modelID = textures.GetModelIndex(textures.GetModel(parameters.modelName)); } } this.typeID = RCUtils.types.ToList().IndexOf(parameters.type); this.calcSelect = parameters.calcSelect; this.getMass = parameters.getMass; this.useDry = parameters.useDry; this.mass = parameters.mass; this.landingSpeed = parameters.landingSpeed; this.deceleration = parameters.deceleration; this.refDepAlt = parameters.refDepAlt; this.chuteCount = parameters.chuteCount; }
//Applies the preset on the chute internal void ApplyPreset(Preset preset) { Preset.ChuteParameters parameters = preset.parameters[id]; this.material = this.pChute.materials.GetMaterial(parameters.material); this.templateGUI.materialsID = this.pChute.materials.GetMaterialIndex(parameters.material); this.templateGUI.preDepDiam = parameters.preDeployedDiameter; this.templateGUI.depDiam = parameters.deployedDiameter; this.templateGUI.isPressure = parameters.minIsPressure; this.templateGUI.predepClause = this.templateGUI.isPressure ? parameters.minPressure : parameters.minDeployment; if (templateGUI.isPressure) { this.parachute.minDeployment = float.Parse(parameters.minDeployment); } else { this.parachute.minPressure = float.Parse(parameters.minPressure); } this.templateGUI.deploymentAlt = parameters.deploymentAlt; this.templateGUI.cutAlt = parameters.cutAlt; this.templateGUI.preDepSpeed = parameters.preDeploymentSpeed; this.templateGUI.depSpeed = parameters.deploymentSpeed; if (this.textures != null) { if (this.textures.ContainsCanopy(parameters.chuteTexture)) { this.templateGUI.chuteID = this.textures.GetCanopyIndex(parameters.chuteTexture); } if (this.textures.ContainsModel(parameters.modelName)) { this.templateGUI.modelID = this.textures.GetModelIndex(parameters.modelName); } } this.templateGUI.typeID = parameters.type; this.templateGUI.calcSelect = parameters.calcSelect; this.templateGUI.getMass = parameters.getMass; this.templateGUI.useDry = parameters.useDry; this.templateGUI.mass = parameters.mass; this.templateGUI.landingSpeed = parameters.landingSpeed; this.templateGUI.deceleration = parameters.deceleration; this.templateGUI.refDepAlt = parameters.refDepAlt; this.templateGUI.chuteCount = parameters.chuteCount; }
private void StartObject() { if (ParentObject == null) { base.Mesh = new Mesh(); MeshDefinition MeshD = Configured.i.Meshes.Find(new Guid("1e73382b-e366-41ec-931e-e17196340657")); MaterialDefinition MaterialD = Configured.i.Materials.Find(new Guid("2dbba7ea-61a9-4d76-bcb6-12b927f0ea08")); ParentObject = new GameObject(); ParentObject.transform.position = GameWorldPosition; ParentObject.transform.rotation = GameWorldRotation; ParentObject.AddComponent <MeshFilter>().sharedMesh = UnityEngine.Object.Instantiate(MeshD.Mesh); ParentObject.AddComponent <MeshRenderer>().sharedMaterial = UnityEngine.Object.Instantiate(MaterialD.Material); CarryThisWithUs(ParentObject); GO = CarryEmptyWithUs(); GO.ObjectItself.transform.parent = ParentObject.transform; GO.ObjectItself.AddComponent <MeshFilter>(); GO.ObjectItself.AddComponent <MeshRenderer>(); } }
private void AddSponzaAtriumObjects(CommandList cl) { ObjParser parser = new ObjParser(); using (FileStream objStream = File.OpenRead(AssetHelper.GetPath("Models/SponzaAtrium/sponza.obj"))) { ObjFile atriumFile = parser.Parse(objStream); MtlFile atriumMtls; using (FileStream mtlStream = File.OpenRead(AssetHelper.GetPath("Models/SponzaAtrium/sponza.mtl"))) { atriumMtls = new MtlParser().Parse(mtlStream); } foreach (ObjFile.MeshGroup group in atriumFile.MeshGroups) { ConstructedMeshInfo mesh = atriumFile.GetMesh(group); MaterialDefinition materialDef = atriumMtls.Definitions[mesh.MaterialName]; ImageSharpTexture overrideTextureData = null; ImageSharpTexture alphaTexture = null; MaterialPropsAndBuffer materialProps = CommonMaterials.Brick; if (materialDef.DiffuseTexture != null) { string texturePath = AssetHelper.GetPath("Models/SponzaAtrium/" + materialDef.DiffuseTexture); overrideTextureData = LoadTexture(texturePath, true); } if (materialDef.AlphaMap != null) { string texturePath = AssetHelper.GetPath("Models/SponzaAtrium/" + materialDef.AlphaMap); alphaTexture = LoadTexture(texturePath, false); } if (materialDef.Name.Contains("vase")) { materialProps = CommonMaterials.Vase; } AddTexturedMesh(cl, mesh, overrideTextureData, alphaTexture, materialProps, Vector3.Zero, Quaternion.Identity, new Vector3(0.1f)); } } }
/// <summary> /// Get data of WorkOrder and its final material /// </summary> /// <returns>All data provided are correct</returns> private bool GetWorkOrder() { var result = true; if (this.commandInput.ActualOperators <= 0) { this.response.SetError(-1000, "Inserire il numero di operatori"); result = false; } this.workOrder = Platform.ProjectionQuery <WorkOrder>() .Include(wo => wo.ProductionType) .Where(wo => wo.Id == this.commandInput.WorkOrderId).FirstOrDefault(); if (this.workOrder == null) { this.response.SetError(-1000, "Il WorkOrder selezionato non esiste"); result = false; } if ((this.workOrder.ProductionType.NId != "Serialized" && this.workOrder.ProductionType.NId != "FullSerialized")) { this.response.SetError(-1000, "L'ordine non è di tipo Serialized"); result = false; } this.finalMaterial = Platform.ProjectionQuery <MaterialDefinition>() .FirstOrDefault(md => md.Id == this.workOrder.FinalMaterial.Value); if (this.finalMaterial == null) { this.response.SetError(-1000, "Il final material del WorkOrder selezionato non esiste"); result = false; } return(result); }
public void UpdateMaterial(Item itemInput, UnitDefinition unit = null) { originalItem = itemInput; if (ItemRaws.Instance.ContainsKey(itemInput.type)) { itemRaw = ItemRaws.Instance[itemInput.type]; } else { itemRaw = ItemRaws.Instance[new MatPairStruct(itemInput.type.mat_type, -1)]; } if (phantom) { return; } if (meshRenderer == null) { meshRenderer = GetComponentInChildren <MeshRenderer>(); } //This means that it's just a placeholder on a body part. if (meshRenderer == null) { phantom = true; return; } if (originalMaterial == null) { originalMaterial = meshRenderer.sharedMaterial; } Color partColor = ContentLoader.GetColor(itemInput); float textureIndex = ContentLoader.GetPatternIndex(itemInput.material); float shapeIndex = ContentLoader.GetShapeIndex(itemInput.material); meshRenderer.sharedMaterial = ContentLoader.getFinalMaterial(originalMaterial, partColor.a); if (itemInput.type.mat_type == 53 && originalMaterial.shader.name == "Art/SingleImage") //plant. We have colored sprites for these. { partColor = new Color(0.5f, 0.5f, 0.5f, 0.5f); } if (((ItemFlags)(itemInput.flags1) & ItemFlags.rotten) == ItemFlags.rotten) { partColor = new Color(0, 0, 0, 0.5f); } MaterialPropertyBlock prop = new MaterialPropertyBlock(); prop.SetColor("_MatColor", partColor); prop.SetFloat("_MatIndex", textureIndex); prop.SetFloat("_ShapeIndex", shapeIndex); if (unit != null) { prop.SetColor("_JobColor", unit.profession_color); } if (ImageManager.Instance != null) { prop.SetFloat("_SpriteIndex", ImageManager.Instance.GetItemTile(itemInput.type)); } meshRenderer.SetPropertyBlock(prop); UpdateImprovements(gameObject, itemInput); var image = GetComponentInChildren <ItemImage>(); if (image != null) { image.UpdateImage(itemInput); } }
private void UpdateAndon_Handler(UpdateAndon evt, EventEnvelope envelope) { Platform.Tracer.Write("Siemens-SimaticIT-Trace-UADMRuntime", $"UpdateAndon Event {evt.WorkArea} START"); try { string kpiVar = $"{evt.WorkArea}_KPI"; string piVar = $"{evt.WorkArea}_PI"; string pi2Var = $"{evt.WorkArea}_PI2"; string vaVar = $"{evt.WorkArea}_VA"; string lineDesc = evt.WorkArea.Split('.').LastOrDefault(); DateTime today = DateTime.Today; //var localNow = DateTime.Now; string product = string.Empty; string productDesc = string.Empty; decimal orderTotal = 0; decimal orderActual = 0; string nextProduct = string.Empty; string nextProductDesc = string.Empty; decimal nextOrderTotal = 0; int team = 0; var equipIds = Platform.ProjectionQuery <Equipment>().Where(e => e.Parent == evt.WorkArea).Select(e => e.Id).ToList(); WorkOrder currentOrder = null; WorkOrder nextOrder = null; GetCurrentOrder(equipIds, out currentOrder, out nextOrder); if (currentOrder != null) { orderTotal = currentOrder.InitialQuantity; orderActual = Platform.ProjectionQuery <WorkOrderOperation>().Where(wo => wo.WorkOrder_Id == currentOrder.Id).Where(wo => !wo.Successors.Any()).Select(wo => wo.ProducedQuantity).FirstOrDefault(); //orderActual = currentOrder.ProducedQuantity; MaterialDefinition matDef = Platform.ProjectionQuery <MaterialDefinition>().FirstOrDefault(m => m.Id == currentOrder.FinalMaterial); if (matDef != null) { product = matDef.NId; productDesc = matDef.Description; } team = Platform.ProjectionQuery <WorkOrderExt>().Where(woe => woe.WorkOrderId == currentOrder.Id).Select(woe => woe.ActualOperators).FirstOrDefault().GetValueOrDefault(); } if (nextOrder != null) { nextOrderTotal = nextOrder.InitialQuantity; MaterialDefinition matDef = Platform.ProjectionQuery <MaterialDefinition>().FirstOrDefault(m => m.Id == nextOrder.FinalMaterial); if (matDef != null) { nextProduct = matDef.NId; nextProductDesc = matDef.Description; } } var kpiResponse = Platform.CallCommand <GetKPIs, GetKPIs.Response>(new GetKPIs { FromDate = today, ToDate = today.AddDays(1), WorkArea = evt.WorkArea, Realtime = true }); var piResponse = Platform.CallCommand <GetProductionInfo, GetProductionInfo.Response>(new GetProductionInfo { FromDate = today, ToDate = today.AddDays(1), WorkArea = evt.WorkArea, Realtime = true }); var andonData = new Andon.Types.AndonData { ListKPI = new List <Andon.Types.KPI> { new Andon.Types.KPI { var_name = kpiVar, defect_per_shift = kpiResponse.Defects, description = "KPI", LE_per_shift = Math.Round(decimal.ToDouble(kpiResponse.LE), 1), OEE_per_shift = Math.Round(decimal.ToDouble(kpiResponse.OEE), 1), rework_per_shift = kpiResponse.Rework } }, ListProductionInfo = new List <Andon.Types.ProductionInfo> { }, ListVisualAlerts = new List <Andon.Types.VisualAlerts> { } }; if (nextOrder != null) { andonData.ListProductionInfo.Add(new Andon.Types.ProductionInfo { line_description = lineDesc, order_actual = -1, order_customer = string.Empty, order_product = nextProduct, order_product_description = nextProductDesc, order_total = decimal.ToInt32(nextOrderTotal), shift_actual_production = decimal.ToInt32(piResponse.ActualProducedQuantity), shift_delay_production = kpiResponse.Delay, shift_total_production = 306,//decimal.ToInt32(piResponse.TotalProducedQuantity), team = team, var_name = pi2Var }); } else if (currentOrder != null) { andonData.ListProductionInfo.Add( new Andon.Types.ProductionInfo { line_description = lineDesc, order_actual = -1, order_customer = string.Empty, order_product = product, order_product_description = productDesc, order_total = decimal.ToInt32(orderTotal), shift_actual_production = decimal.ToInt32(piResponse.ActualProducedQuantity), shift_delay_production = kpiResponse.Delay, shift_total_production = 306, //decimal.ToInt32(piResponse.TotalProducedQuantity), team = team, var_name = pi2Var } ); } if (currentOrder != null) { andonData.ListProductionInfo.Add( new Andon.Types.ProductionInfo { line_description = lineDesc, order_actual = decimal.ToInt32(orderActual), order_customer = string.Empty, order_product = product, order_product_description = productDesc, order_total = decimal.ToInt32(orderTotal), shift_actual_production = decimal.ToInt32(piResponse.ActualProducedQuantity), shift_delay_production = kpiResponse.Delay, shift_total_production = 306, //decimal.ToInt32(piResponse.TotalProducedQuantity), team = team, var_name = piVar } ); } //Visual Alerts var operatorCalls = Platform.ProjectionQuery <TeamLeaderCall>().Where(tlc => tlc.Accepted == false && tlc.Date >= today).ToList(); var materialCalls = Platform.ProjectionQuery <MaterialCall>().Where(mc => mc.Accepted == false && mc.Date >= today).ToList(); andonData.ListVisualAlerts.Add(new Andon.Types.VisualAlerts { alerts = new List <Andon.Types.eachAlert>(), var_name = vaVar }); if (materialCalls.Any() || operatorCalls.Any()) { int operatorCallsNum = 0; int materialCallsNum = 0; foreach (var oc in operatorCalls.OrderBy(o => o.Date)) { string unitDesc = oc.Equipment.Split('.').LastOrDefault(); andonData.ListVisualAlerts.First().alerts.Add( new Andon.Types.eachAlert { line = evt.WorkArea, order = operatorCallsNum, status = Andon.Types.alertstatus.OperatorTeamSpeackerAlertActive, timestamp = oc.Date.ToLocalTime().ToString("yyyy-MM-dd HH':'mm':'ss"), // 07/03/2018 09:00 AAAA-MM-gg HH:MM:ss type = Andon.Types.alerttype.Operator, unit = unitDesc }); operatorCallsNum++; } foreach (var mc in materialCalls.OrderBy(m => m.Date)) { string unitDesc = mc.Equipment.Split('.').LastOrDefault(); andonData.ListVisualAlerts.First().alerts.Add( new Andon.Types.eachAlert { line = evt.WorkArea, order = operatorCallsNum + materialCallsNum, status = Andon.Types.alertstatus.MaintenanceOperatorWorking, timestamp = mc.Date.ToLocalTime().ToString("yyyy-MM-dd HH':'mm':'ss"), // 07/03/2018 09:00 AAAA-MM-gg HH:MM:ss type = Andon.Types.alerttype.Screwdriver, unit = unitDesc }); materialCallsNum++; } } var andon = new Andon.Andon(); andon.SetData("AppDAB", andonData); } catch (Exception e) { Platform.Tracer.Write("Siemens-SimaticIT-Trace-UADMRuntime", $"UpdateAndon Event {evt.WorkArea} END"); } Platform.Tracer.Write("Siemens-SimaticIT-Trace-UADMRuntime", $"UpdateAndon Event {evt.WorkArea} START"); }
//Applies changes to the parachute internal void ApplyChanges(bool toSymmetryCounterparts) { this.parachute.material = this.material.name; this.parachute.mat = this.material; if (this.templateGUI.calcSelect) { double m = this.templateGUI.getMass ? this.pChute.GetCraftMass(this.templateGUI.useDry) : double.Parse(this.templateGUI.mass); double alt = 0, acc = 0; switch (this.templateGUI.type) { case ParachuteType.Main: { alt = double.Parse(this.pChute.landingAlt); acc = (this.body.GeeASL * RCUtils.geeToAcc); break; } case ParachuteType.Drogue: { alt = double.Parse(this.templateGUI.refDepAlt); acc = (this.body.GeeASL * RCUtils.geeToAcc); break; } case ParachuteType.Drag: { alt = double.Parse(this.pChute.landingAlt); acc = double.Parse(this.templateGUI.deceleration); break; } default: break; } double density = this.body.GetDensityAtAlt(alt, this.body.GetMaxTemperatureAtAlt(alt)); double speed = double.Parse(this.templateGUI.landingSpeed); speed *= speed; Debug.Log(String.Format("[RealChute]: {0} {1} - m: {2}t, alt: {3}m, ρ: {4}kg/m³, v²: {5}m²/s², a: {6}m/s²", this.part.partInfo.title, RCUtils.ParachuteNumber(this.id), m, alt, density, speed, acc)); this.parachute.deployedDiameter = RCUtils.Round(Math.Sqrt((8000 * m * acc) / (Math.PI * speed * material.dragCoefficient * density * double.Parse(this.templateGUI.chuteCount)))); float maxDiam = (this.textures != null || this.textures.models.Count > 0) ? this.model.maxDiam : 70; if (this.parachute.deployedDiameter > this.model.maxDiam) { this.parachute.deployedDiameter = maxDiam; this.editorGUI.warning = true; } else { this.editorGUI.warning = false; } this.parachute.preDeployedDiameter = RCUtils.Round(this.templateGUI.type == ParachuteType.Main ? (this.parachute.deployedDiameter / 20) : (this.parachute.deployedDiameter / 2)); Debug.Log(String.Format("[RealChute]: {0} {1} - depDiam: {2}m, preDepDiam: {3}m", this.part.partInfo.title, RCUtils.ParachuteNumber(this.id), this.parachute.deployedDiameter, this.parachute.preDeployedDiameter)); } else { this.parachute.preDeployedDiameter = RCUtils.Round(float.Parse(this.templateGUI.preDepDiam)); this.parachute.deployedDiameter = RCUtils.Round(float.Parse(this.templateGUI.depDiam)); Debug.Log(String.Format("[RealChute]: {0} {1} - depDiam: {2}m, preDepDiam: {3}m", this.part.partInfo.title, RCUtils.ParachuteNumber(this.id), this.parachute.deployedDiameter, this.parachute.preDeployedDiameter)); } this.parachute.minIsPressure = this.templateGUI.isPressure; if (this.templateGUI.isPressure) { this.parachute.minPressure = float.Parse(this.templateGUI.predepClause); } else { this.parachute.minDeployment = float.Parse(this.templateGUI.predepClause); } this.parachute.deploymentAlt = float.Parse(this.templateGUI.deploymentAlt); this.parachute.cutAlt = GUIUtils.ParseEmpty(this.templateGUI.cutAlt); this.parachute.preDeploymentSpeed = float.Parse(this.templateGUI.preDepSpeed); this.parachute.deploymentSpeed = float.Parse(this.templateGUI.depSpeed); if (toSymmetryCounterparts) { foreach (Part part in this.part.symmetryCounterparts) { Parachute sym = ((RealChuteModule)part.Modules["RealChuteModule"]).parachutes[id]; sym.material = this.material.name; sym.mat = this.material; sym.deployedDiameter = this.parachute.deployedDiameter; sym.preDeployedDiameter = this.parachute.preDeployedDiameter; sym.minIsPressure = this.templateGUI.isPressure; sym.minPressure = this.parachute.minPressure; sym.minDeployment = this.parachute.minDeployment; sym.deploymentAlt = this.parachute.deploymentAlt; sym.cutAlt = this.parachute.cutAlt; sym.preDeploymentSpeed = this.parachute.preDeploymentSpeed; sym.deploymentSpeed = this.parachute.deploymentSpeed; TemplateGUI template = ((ProceduralChute)part.Modules["ProceduralChute"]).chutes[id].templateGUI; template.chuteID = this.templateGUI.chuteID; template.typeID = this.templateGUI.typeID; template.modelID = this.templateGUI.modelID; template.materialsID = this.templateGUI.materialsID; template.isPressure = this.templateGUI.isPressure; template.calcSelect = this.templateGUI.calcSelect; template.getMass = this.templateGUI.getMass; template.useDry = this.templateGUI.useDry; template.preDepDiam = this.templateGUI.preDepDiam; template.depDiam = this.templateGUI.depDiam; template.predepClause = this.templateGUI.predepClause; template.mass = this.templateGUI.mass; template.landingSpeed = this.templateGUI.landingSpeed; template.deceleration = this.templateGUI.deceleration; template.refDepAlt = this.templateGUI.refDepAlt; template.chuteCount = this.templateGUI.chuteCount; template.deploymentAlt = this.templateGUI.deploymentAlt; template.cutAlt = this.templateGUI.cutAlt; template.preDepSpeed = this.templateGUI.preDepSpeed; template.depSpeed = this.templateGUI.depSpeed; } } }
public RW4Mesh Import(RW4Mesh mesh, string fileName) { Collada141.COLLADA colladaFile = Collada141.COLLADA.Load(fileName); //Retrieve relevant information from the original RW4 Mesh uint verticesSectionNumber = mesh.vertices.vertices.section.Number; uint trianglesSectionNumber = mesh.triangles.triangles.section.Number; VertexFormat vertexFormatSection = (VertexFormat)mesh.model.Sections.First(s => s.TypeCode == SectionTypeCodes.VertexFormat).obj; //Get the visual_scene object that contains all the relevant scene information Collada141.library_visual_scenes scenes = colladaFile.Items.OfType <Collada141.library_visual_scenes>().First(); Collada141.visual_scene scene = scenes.visual_scene[0]; //Load the geometries container Collada141.library_geometries geometry = colladaFile.Items.OfType <Collada141.library_geometries>().First(); //Define the lists to which the temporary items can be saved List <int> triangleDefinitions = new List <int>(); List <Vertex> vertexList = new List <Vertex>(); List <string> vertexDefinitions = new List <string>(); //create the materials - but only if the material IDs start with "SCP-" List <MaterialDefinition> materialDatas = new List <MaterialDefinition>(); Collada141.library_materials materialLibrary = colladaFile.Items.OfType <Collada141.library_materials>().First(); if (((Collada141.material)materialLibrary.material[0]).id.StartsWith("SCP-")) { int materialIndex = 0; foreach (Collada141.material mat in materialLibrary.material) { string materialString = mat.id; string[] materialValues = materialString.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); MaterialDefinition mater = new MaterialDefinition() { Index = int.Parse(materialValues[15], CultureInfo.InvariantCulture.NumberFormat), Id = mat.name, ColorTop = byte.Parse(materialValues[8], CultureInfo.InvariantCulture.NumberFormat), ColorBottom = byte.Parse(materialValues[1], CultureInfo.InvariantCulture.NumberFormat), InteriorData1 = byte.Parse(materialValues[7], CultureInfo.InvariantCulture.NumberFormat), InteriorData2 = byte.Parse(materialValues[2], CultureInfo.InvariantCulture.NumberFormat), TopX = float.Parse(materialValues[3], CultureInfo.InvariantCulture.NumberFormat), TopY = float.Parse(materialValues[4], CultureInfo.InvariantCulture.NumberFormat), TopHeight = float.Parse(materialValues[5], CultureInfo.InvariantCulture.NumberFormat), TopWidth = float.Parse(materialValues[6], CultureInfo.InvariantCulture.NumberFormat), BottomX = float.Parse(materialValues[9], CultureInfo.InvariantCulture.NumberFormat), BottomY = float.Parse(materialValues[10], CultureInfo.InvariantCulture.NumberFormat), BottomHeight = float.Parse(materialValues[11], CultureInfo.InvariantCulture.NumberFormat), BottomWidth = float.Parse(materialValues[12], CultureInfo.InvariantCulture.NumberFormat), TilingTopX = float.Parse(materialValues[13], CultureInfo.InvariantCulture.NumberFormat), TilingTopY = float.Parse(materialValues[14], CultureInfo.InvariantCulture.NumberFormat), InteriorSizeX = 0, //1 / float.Parse(materialValues[9], CultureInfo.InvariantCulture.NumberFormat), InteriorSizeY = 0 //1 / float.Parse(materialValues[10], CultureInfo.InvariantCulture.NumberFormat) }; if (mater.InteriorData1 > 0) { mater.InteriorSizeX = 1; mater.InteriorSizeY = 1; } materialDatas.Add(mater); materialIndex++; } float[, ,] materialColors = new float[materialDatas.Max(m => m.Index + 1), 4, 4]; foreach (MaterialDefinition def in materialDatas) { materialColors[def.Index, 0, 0] = (float)def.ColorBottom / 256; materialColors[def.Index, 0, 1] = (float)def.ColorTop / 256; materialColors[def.Index, 0, 2] = (float)def.InteriorData1 / 256; materialColors[def.Index, 0, 3] = (float)def.InteriorData2 / 256; materialColors[def.Index, 1, 0] = def.TopX; materialColors[def.Index, 1, 1] = def.TopY; materialColors[def.Index, 1, 2] = def.TopHeight; materialColors[def.Index, 1, 3] = def.TopWidth; materialColors[def.Index, 2, 0] = def.BottomX; materialColors[def.Index, 2, 1] = def.BottomY; materialColors[def.Index, 2, 2] = def.BottomHeight; materialColors[def.Index, 2, 3] = def.BottomWidth; materialColors[def.Index, 3, 0] = def.TilingTopX; materialColors[def.Index, 3, 1] = def.TilingTopY; materialColors[def.Index, 3, 2] = def.InteriorSizeX; materialColors[def.Index, 3, 3] = def.InteriorSizeY; } //save the materialsbitmap MaterialTextureReference texRef = mesh.model.Materials.Where(m => m.Unknown4 == 0).First(); DatabaseIndex imageIndex = DatabaseManager.Instance.Indices.Find(idx => idx.InstanceId == texRef.TextureInstanceId && idx.TypeId == PropertyConstants.RW4ImageType); if (imageIndex != null) { using (MemoryStream imageByteStream = new MemoryStream(imageIndex.GetIndexData(true))) { RW4Model model = new RW4Model(); model.Read(imageByteStream); RW4Section textureSection = model.Sections.First(s => s.TypeCode == SectionTypeCodes.Texture); Texture oldSection = textureSection.obj as Texture; uint texDataSection = oldSection.texData.section.Number; Texture newTexture = MaterialTextureConverter.SetTexture(materialColors); newTexture.texData.section = new RW4Section() { Number = texDataSection }; newTexture.texData.section.obj = new TextureBlob() { blob = newTexture.texData.blob }; textureSection.obj = newTexture; SaveRW4Model(imageIndex, model); } } } int elementIndex = 0; //Loop through all nodes in the scene to read the information from the geometry and foreach (Collada141.node node in scene.node) { Collada141.instance_geometry geometryInstance = null; if (node.instance_geometry != null) { geometryInstance = node.instance_geometry[0]; } else if (node.node1 != null) { if (node.node1[0].instance_geometry != null) { geometryInstance = node.node1[0].instance_geometry[0]; } } //check if the node contains any geometry - lights will be ignored if (geometryInstance != null) { Collada141.geometry geo = geometry.geometry.First(g => "#" + g.id == geometryInstance.url); //Collada141.geometry geo = geometry.geometry.First(g => "#" + g.id == node.instance_geometry[0].url); // Collada141.geometry geo = geometry.geometry[0]; Collada141.mesh geoMesh = geo.Item as Collada141.mesh; ///get the array of positions for the vertices Collada141.source src = geoMesh.source.First(s => "#" + s.id == geoMesh.vertices.input.First(g => g.semantic == "POSITION").source); Collada141.float_array positions = src.Item as Collada141.float_array; foreach (Collada141.triangles triangles in geoMesh.Items) { List <string> localVertexDefinitions = new List <string>(); //calculate how many input indices each triangle exists of ulong triangleIndexSize = triangles.input.Max(t => t.offset) + 1; string[] triangleIndices = triangles.p.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < triangleIndices.Length; i += (int)triangleIndexSize) { string readVertexDefinition = string.Empty; for (int j = 0; j < (int)triangleIndexSize; j++) { readVertexDefinition += triangleIndices[i + j] + " "; } readVertexDefinition += elementIndex + " "; if (!vertexDefinitions.Contains(readVertexDefinition)) { vertexDefinitions.Add(readVertexDefinition); localVertexDefinitions.Add(readVertexDefinition); } triangleDefinitions.Add(vertexDefinitions.IndexOf(readVertexDefinition)); } //create a vertex for each definition for (int i = 0; i < localVertexDefinitions.Count; i++) { Vertex v = new Vertex(); v.Element = elementIndex; v.SetSize(vertexFormatSection.VertexSize); //Create vertexcomponents in the new vertex v.VertexComponents = new List <IVertexComponentValue>(); foreach (VertexUsage usage in vertexFormatSection.VertexElements) { IVertexComponentValue component = VertexComponentValueFactory.CreateComponent(usage.DeclarationType); component.Usage = usage.Usage; v.VertexComponents.Add(component); } string[] vdef = localVertexDefinitions[i].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); //create vertexcomponents based on int positionIndex = int.Parse(vdef[0]); VertexFloat3Value positionComponent = (VertexFloat3Value)v.VertexComponents.First(c => c.Usage == D3DDECLUSAGE.D3DDECLUSAGE_POSITION && c.DeclarationType == D3DDECLTYPE.D3DDECLTYPE_FLOAT3); if (positionComponent != null) { positionComponent.X = (float)positions.Values[(positionIndex * 3)]; positionComponent.Y = (float)positions.Values[(positionIndex * 3) + 1]; positionComponent.Z = (float)positions.Values[(positionIndex * 3) + 2]; } Collada141.source normalSrc = geoMesh.source.First(s => "#" + s.id == triangles.input.First(g => g.semantic == "NORMAL").source); Collada141.float_array normals = normalSrc.Item as Collada141.float_array; int normalIndex = int.Parse(vdef[1]); VertexUByte4Value normalComponent = (VertexUByte4Value)v.VertexComponents.FirstOrDefault(c => c.Usage == D3DDECLUSAGE.D3DDECLUSAGE_NORMAL && c.DeclarationType == D3DDECLTYPE.D3DDECLTYPE_UBYTE4); if (normalComponent != null) { normalComponent.X = (byte)((float)normals.Values[normalIndex * 3] * 127.5F + 127.5F); normalComponent.Y = (byte)((float)normals.Values[(normalIndex * 3) + 1] * 127.5F + 127.5F); normalComponent.Z = (byte)((float)normals.Values[(normalIndex * 3) + 2] * 127.5F + 127.5F); normalComponent.W = (byte)(255); } else { //check if there is a different normal component VertexFloat3Value normalComponent2 = (VertexFloat3Value)v.VertexComponents.FirstOrDefault(c => c.Usage == D3DDECLUSAGE.D3DDECLUSAGE_NORMAL && c.DeclarationType == D3DDECLTYPE.D3DDECLTYPE_FLOAT3); if (normalComponent2 != null) { normalComponent2.X = (float)normals.Values[normalIndex * 3]; normalComponent2.Y = (float)normals.Values[(normalIndex * 3) + 1]; normalComponent2.Z = (float)normals.Values[(normalIndex * 3) + 2]; } } //Get the external tangents IEnumerable <Collada141.InputLocalOffset> tangentInputs = triangles.input.Where(g => g.semantic == "TEXTANGENT"); Collada141.source bottomTangentSrc = geoMesh.source.First(s => "#" + s.id == tangentInputs.ElementAt(0).source); Collada141.float_array bottomTangents = bottomTangentSrc.Item as Collada141.float_array; int interiorTangentIndex = int.Parse(vdef[3]); IEnumerable <IVertexComponentValue> tangentComponents = v.VertexComponents.Where(c => c.Usage == D3DDECLUSAGE.D3DDECLUSAGE_TANGENT && c.DeclarationType == D3DDECLTYPE.D3DDECLTYPE_UBYTE4); if (tangentComponents.Count() != 0) { VertexUByte4Value tangentComponent = (VertexUByte4Value)tangentComponents.ElementAt(0); tangentComponent.X = (byte)((float)bottomTangents.Values[interiorTangentIndex * 3] * 127.5F + 127.5F); tangentComponent.Y = (byte)((float)bottomTangents.Values[(interiorTangentIndex * 3) + 1] * 127.5F + 127.5F); tangentComponent.Z = (byte)((float)bottomTangents.Values[(interiorTangentIndex * 3) + 2] * 127.5F + 127.5F); tangentComponent.W = (byte)(255); //Get the internal tangents if (tangentComponents.Count() > 1) { Collada141.source internalTangentSrc = geoMesh.source.First(s => "#" + s.id == tangentInputs.ElementAt(1).source); Collada141.float_array internalTangents = internalTangentSrc.Item as Collada141.float_array; interiorTangentIndex = int.Parse(vdef[5]); VertexUByte4Value internalTangentComponent = (VertexUByte4Value)tangentComponents.ElementAt(1); internalTangentComponent.X = (byte)((float)internalTangents.Values[interiorTangentIndex * 3] * 127.5F + 127.5F); internalTangentComponent.Y = (byte)((float)internalTangents.Values[(interiorTangentIndex * 3) + 1] * 127.5F + 127.5F); internalTangentComponent.Z = (byte)((float)internalTangents.Values[(interiorTangentIndex * 3) + 2] * 127.5F + 127.5F); internalTangentComponent.W = (byte)(255); } } else { //check for other tangents VertexFloat3Value tangentComponent2 = (VertexFloat3Value)v.VertexComponents.FirstOrDefault(c => c.Usage == D3DDECLUSAGE.D3DDECLUSAGE_TANGENT && c.DeclarationType == D3DDECLTYPE.D3DDECLTYPE_FLOAT3); if (tangentComponent2 != null) { tangentComponent2.X = (float)bottomTangents.Values[interiorTangentIndex * 3]; tangentComponent2.Y = (float)bottomTangents.Values[(interiorTangentIndex * 3) + 1]; tangentComponent2.Z = (float)bottomTangents.Values[(interiorTangentIndex * 3) + 2]; } } IEnumerable <Collada141.InputLocalOffset> textureCoordinateInputs = triangles.input.Where(g => g.semantic == "TEXCOORD"); Collada141.source bottomUVsource = geoMesh.source.First(s => "#" + s.id == textureCoordinateInputs.ElementAt(0).source); Collada141.source topUVsource = null; if (textureCoordinateInputs.Count() > 1) { topUVsource = geoMesh.source.First(s => "#" + s.id == textureCoordinateInputs.ElementAt(1).source); } else { topUVsource = geoMesh.source.First(s => "#" + s.id == textureCoordinateInputs.ElementAt(0).source); } Collada141.float_array bottomTextureCoordinates = bottomUVsource.Item as Collada141.float_array; Collada141.float_array topTextureCoordinates = topUVsource.Item as Collada141.float_array; int uvIndex = int.Parse(vdef[textureCoordinateInputs.ElementAt(0).offset]); int topUvIndex = 0; if (textureCoordinateInputs.Count() > 1) { topUvIndex = int.Parse(vdef[textureCoordinateInputs.ElementAt(1).offset]); } else { topUvIndex = int.Parse(vdef[textureCoordinateInputs.ElementAt(0).offset]); } //Get all the texture elements (should be 2 in the case of a building) IEnumerable <IVertexComponentValue> uvMapComponents = v.VertexComponents.Where(c => c.Usage == D3DDECLUSAGE.D3DDECLUSAGE_TEXCOORD && c.DeclarationType == D3DDECLTYPE.D3DDECLTYPE_FLOAT4); if (uvMapComponents.Count() != 0) { VertexFloat4Value uvBottomComponent = (VertexFloat4Value)uvMapComponents.ElementAt(0); uvBottomComponent.X = (float)bottomTextureCoordinates.Values[(uvIndex * 3)]; uvBottomComponent.Y = 1 - (float)bottomTextureCoordinates.Values[(uvIndex * 3) + 1]; uvBottomComponent.Z = (float)topTextureCoordinates.Values[(topUvIndex * 3)]; uvBottomComponent.W = 1 - (float)topTextureCoordinates.Values[(topUvIndex * 3) + 1]; if (uvMapComponents.Count() > 1) { VertexFloat4Value uvTopComponent = (VertexFloat4Value)uvMapComponents.ElementAt(1); uvTopComponent.X = 0; uvTopComponent.Y = 0; uvTopComponent.Z = 1; uvTopComponent.W = 1; } } else { //check for other UVs VertexFloat2Value uvComponent2 = (VertexFloat2Value)v.VertexComponents.FirstOrDefault(c => c.Usage == D3DDECLUSAGE.D3DDECLUSAGE_TEXCOORD && c.DeclarationType == D3DDECLTYPE.D3DDECLTYPE_FLOAT2); if (uvComponent2 != null) { uvComponent2.X = (float)bottomTextureCoordinates.Values[uvIndex * 3]; uvComponent2.Y = (float)bottomTextureCoordinates.Values[(uvIndex * 3) + 1]; } } VertexD3DColorValue colorComponent = (VertexD3DColorValue)v.VertexComponents.FirstOrDefault(c => c.Usage == D3DDECLUSAGE.D3DDECLUSAGE_COLOR && c.DeclarationType == D3DDECLTYPE.D3DDECLTYPE_D3DCOLOR); if (triangles.material.StartsWith("SCP")) { //get the index of the material MaterialDefinition def = materialDatas.First(m => m.Id == triangles.material); VertexD3DColorValue colorComponent2 = (VertexD3DColorValue)v.VertexComponents.First(c => c.Usage == D3DDECLUSAGE.D3DDECLUSAGE_COLOR && c.DeclarationType == D3DDECLTYPE.D3DDECLTYPE_D3DCOLOR); if (colorComponent != null) { //Unused colorComponent2.A = 0; //Unused colorComponent2.R = 0; //Material index colorComponent2.G = (byte)def.Index; //RNG for windows colorComponent2.B = 84; } //if the item has a defined interior, recalculate the interior UV's if (def.InteriorData1 > 0) { // IEnumerable<IVertexComponentValue> uvMapComponentInterior = v.VertexComponents.Where(c => c.Usage == D3DDECLUSAGE.D3DDECLUSAGE_TEXCOORD && c.DeclarationType == D3DDECLTYPE.D3DDECLTYPE_FLOAT4); // VertexFloat4Value uvInterior = (VertexFloat4Value)uvMapComponents.ElementAt(0); // uvInterior.X = (uvInterior.X / def.BottomX); // uvInterior.Y = (uvInterior.Y / def.TopX); } } if (node.Items != null) { for (int transIndex = node.Items.Length - 1; transIndex >= 0; transIndex--) { v = ApplyTransformation(v, node.Items[transIndex], node.ItemsElementName[transIndex]); } } vertexList.Add(v); } elementIndex++; } } } mesh.vertices.vertices = new SporeMaster.RenderWare4.VertexBuffer(vertexList.Count); mesh.vertices.vertices.section = new RW4Section() { Number = verticesSectionNumber }; mesh.vertices.vertexSize = vertexFormatSection.VertexSize; for (int i = 0; i < vertexList.Count; i++) { mesh.vertices.vertices[i] = vertexList[i]; } //mesh.triangles = new RW4TriangleArray(); mesh.triangles.triangles = new Buffer <Triangle>(triangleDefinitions.Count / 3); mesh.triangles.triangles.section = new RW4Section() { Number = trianglesSectionNumber }; for (int i = 0; i < triangleDefinitions.Count / 3; i++) { mesh.triangles.triangles[i] = new Triangle() { i = (uint)triangleDefinitions[(i * 3)], j = (uint)triangleDefinitions[(i * 3) + 1], k = (uint)triangleDefinitions[(i * 3) + 2], }; } return(mesh); }
private static void Start(CSharpBoxClass cSharpBox) { cSharpBox.ClearLogs(); MainConstruct mainConstruct = cSharpBox.MainConstruct as MainConstruct; string outPutFolderPath = Get.ProfilePaths.ProfileRootDir().Append(mainConstruct.GetBlueprintName()).ToString() + string.Format("-{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now); string texFolderPath = Path.Combine(outPutFolderPath, "Textures"); Directory.CreateDirectory(outPutFolderPath); Directory.CreateDirectory(texFolderPath); //TextureDefinition getTexDef(MaterialDefinition I) => Configured.i.Textures.Find(I.ColorTextureReference.Reference.Guid); IEnumerable <TextureDefinition> textureDefinitionList = Configured.i.Materials.Components .Select(I => Configured.i.Textures.Find(I.ColorTextureReference.Reference.Guid)) .Where(I => I != null) .Distinct(); StringBuilder sb = new StringBuilder(); foreach (TextureDefinition textureDefinition in textureDefinitionList) { ModSource modSource = textureDefinition.Source; if (modSource != ModSource.File && modSource != ModSource.Resources) { continue; } byte[] encodeResult = null; try { encodeResult = ForcedEncodeToJPG(textureDefinition.Texture.GetTexture()); } catch (Exception e) { Console.WriteLine(e.Message); continue; } if (encodeResult != null) { string texName = TexNameGenerate(textureDefinition); File.WriteAllBytes(Path.Combine(texFolderPath, texName + ".jpg"), encodeResult); cSharpBox.Log("newmtl " + texName); cSharpBox.Log("map_Kd " + Path.Combine("Textures", texName + ".jpg")); cSharpBox.Log(string.Empty); sb.Append("newmtl " + texName + "\n"); sb.Append("map_Kd " + Path.Combine("Textures", texName + ".jpg") + "\n"); sb.Append("\n"); } } using (StreamWriter sw = new StreamWriter(Path.Combine(outPutFolderPath, "Test.mtl"))) { sw.Write(sb.ToString()); } List <AllConstruct> allConstructList = new List <AllConstruct>(); mainConstruct.AllBasicsRestricted.GetAllConstructsBelowUsAndIncludingUs(allConstructList); foreach (AllConstruct allConstruct in allConstructList) { if (!(allConstruct.Chunks is ConstructableMeshMerger)) { continue; } Dictionary <MaterialDefinition, List <Mesh> > meshListDictionary = new Dictionary <MaterialDefinition, List <Mesh> >(); foreach (ICarriedObjectReference iCOR in allConstruct.CarriedObjects.Objects) { MeshRenderer meshRenderer = iCOR.ObjectItself.GetComponent <MeshRenderer>(); MeshFilter meshFilter = iCOR.ObjectItself.GetComponent <MeshFilter>(); if (meshRenderer == null || meshFilter == null) { continue; } KeyValuePair <Guid, MaterialDefinition> item = Configured.i.Materials.DictionaryOfComponents.FirstOrDefault(d => d.Value.Material == meshRenderer.sharedMaterial); if (item.Equals(default(KeyValuePair <Guid, MaterialDefinition>))) { continue; } if (!meshListDictionary.ContainsKey(item.Value)) { meshListDictionary.Add(item.Value, new List <Mesh>()); } Mesh newMesh = UnityEngine.Object.Instantiate(meshFilter.sharedMesh); IEnumerable <Vector3> newVertexList = newMesh.vertices.Select(d => meshFilter.transform.localToWorldMatrix.MultiplyPoint(d)); newVertexList = newVertexList.Select(d => allConstruct.myTransform.worldToLocalMatrix.MultiplyPoint(d)); newMesh.SetVertices(newVertexList.ToList()); meshListDictionary[item.Value].Add(newMesh); } ConstructableMeshMerger meshMerger = allConstruct.Chunks as ConstructableMeshMerger; cSharpBox.Log("AllBlockVertex Count : " + meshMerger.VertexCount); foreach (KeyValuePair <int, List <ChunkMesh> > chunkMeshListDictionary in meshMerger.D) { bool found; MaterialDefinition materialDefinition = Configured.i.Materials.FindUsingTheRuntimeId(chunkMeshListDictionary.Key, out found); bool flag_0 = chunkMeshListDictionary.Value.Count == 0; bool flag_1 = chunkMeshListDictionary.Value.All(d => d.VertCount == 0); if (!found || flag_0 || flag_1) { continue; } if (!meshListDictionary.ContainsKey(materialDefinition)) { meshListDictionary.Add(materialDefinition, new List <Mesh>()); } meshListDictionary[materialDefinition].AddRange(chunkMeshListDictionary.Value.Select(d => d.GetMesh())); } int subConstructIndex = allConstruct.PersistentSubConstructIndex; bool isSubConstruct = subConstructIndex != -1; Vector3 localPosition = Vector3.zero; Quaternion localRotation = Quaternion.identity; if (isSubConstruct) { MainConstruct mc = allConstruct.Main; localPosition = mc.SafeGlobalToLocal(allConstruct.SafePosition); localRotation = mc.SafeGlobalRotationToLocalRotation(allConstruct.SafeRotation); } List <Mesh> meshList = new List <Mesh>(); foreach (KeyValuePair <MaterialDefinition, List <Mesh> > meshListDictionaryData in meshListDictionary) { List <Vector3> vertices = new List <Vector3>(); List <Vector3> normals = new List <Vector3>(); List <Vector2> uv = new List <Vector2>(); List <int> triangles = new List <int>(); int loadVertexCount = 0; foreach (Mesh mesh in meshListDictionaryData.Value) { vertices.AddRange(mesh.vertices); normals.AddRange(mesh.normals); uv.AddRange(mesh.uv); triangles.AddRange(mesh.triangles.Select(d => d + loadVertexCount)); loadVertexCount += mesh.vertexCount; } if (isSubConstruct) { vertices = vertices.Select(I => localRotation * I + localPosition).ToList(); } TextureDefinition textureDefinition = Configured.i.Textures.Find(meshListDictionaryData.Key.ColorTextureReference.Reference.Guid); Mesh newMesh = new Mesh { indexFormat = UnityEngine.Rendering.IndexFormat.UInt32, name = TexNameGenerate(textureDefinition) }; newMesh.SetVertices(vertices); newMesh.SetNormals(normals); newMesh.SetUVs(0, uv); newMesh.SetTriangles(triangles, 0); FlipHorizontal(newMesh); meshList.Add(newMesh); cSharpBox.Log("vertexCount : " + newMesh.vertices.Length); } string fileName = $"Test ({OutputCount++})"; if (subConstructIndex == -1) { fileName = "MainConstruct"; } else { fileName = $"SubConstruct_{subConstructIndex}"; } MeshToFile(meshList, Path.Combine(outPutFolderPath, fileName + ".obj")); } }
/// <summary> /// Loads a material library. /// </summary> /// <param name="mtlFile"> /// The mtl file. /// </param> private void LoadMaterialLib(string mtlFile) { var path = Path.Combine(this.TexturePath, mtlFile); if (!File.Exists(path)) { return; } using (var mreader = new StreamReader(path)) { MaterialDefinition currentMaterial = null; while (!mreader.EndOfStream) { var line = mreader.ReadLine(); if (line == null) { break; } line = line.Trim(); if (line.StartsWith("#") || line.Length == 0) { continue; } string keyword, value; SplitLine(line, out keyword, out value); switch (keyword.ToLower()) { case "newmtl": if (value != null) { currentMaterial = new MaterialDefinition(); this.Materials.Add(value, currentMaterial); } break; case "ka": if (currentMaterial != null && value != null) { currentMaterial.Ambient = ColorParse(value); } break; case "kd": if (currentMaterial != null && value != null) { currentMaterial.Diffuse = ColorParse(value); } break; case "ks": if (currentMaterial != null && value != null) { currentMaterial.Specular = ColorParse(value); } break; case "ns": if (currentMaterial != null && value != null) { currentMaterial.SpecularCoefficient = DoubleParse(value); } break; case "d": if (currentMaterial != null && value != null) { currentMaterial.Dissolved = DoubleParse(value); } break; case "tr": if (!this.SkipTransparencyValues && currentMaterial != null && value != null) { currentMaterial.Dissolved = DoubleParse(value); } break; case "illum": if (currentMaterial != null && value != null) { currentMaterial.Illumination = int.Parse(value); } break; case "map_ka": if (currentMaterial != null) { currentMaterial.AmbientMap = value; } break; case "map_kd": if (currentMaterial != null) { currentMaterial.DiffuseMap = value; } break; case "map_ks": if (currentMaterial != null) { currentMaterial.SpecularMap = value; } break; case "map_d": if (currentMaterial != null) { currentMaterial.AlphaMap = value; } break; case "map_bump": case "bump": if (currentMaterial != null) { currentMaterial.BumpMap = value; } break; } } } }
public Equip(InventoryItem item, MaterialDefinition itemDef, MaterialDefinition material) { this.item = item; this.itemDef = itemDef; this.material = material; }
/// <summary> /// Loads a material library. /// </summary> /// <param name="mtlFile"> /// The mtl file. /// </param> private void LoadMaterialLib(string mtlFile) { var path = Path.GetFullPath(Path.Combine(this.TexturePath, "./" + mtlFile)); if (!File.Exists(path)) { return; } using (var fileStream = File.OpenRead(path)) { using (var mreader = new StreamReader(fileStream)) { MaterialDefinition currentMaterial = null; while (!mreader.EndOfStream) { var line = mreader.ReadLine(); if (line == null) { break; } line = line.Trim(); if (line.StartsWith("#") || line.Length == 0) { continue; } string keyword, value; SplitLine(line, out keyword, out value); switch (keyword.ToLower()) { case "newmtl": if (value != null) { if (this.Materials.ContainsKey(value)) { currentMaterial = null; } else { currentMaterial = new MaterialDefinition(); this.Materials.Add(value, currentMaterial); } } break; case "ka": if (currentMaterial != null && value != null) { currentMaterial.Ambient = ColorParse(value); } break; case "kd": if (currentMaterial != null && value != null) { currentMaterial.Diffuse = ColorParse(value); } break; case "ks": if (currentMaterial != null && value != null) { currentMaterial.Specular = ColorParse(value); } break; case "ns": if (currentMaterial != null && value != null) { currentMaterial.SpecularCoefficient = DoubleParse(value); } break; case "d": if (currentMaterial != null && value != null) { currentMaterial.Dissolved = DoubleParse(value); } break; case "tr": if (!this.SkipTransparencyValues && currentMaterial != null && value != null) { currentMaterial.Dissolved = DoubleParse(value); } break; case "illum": if (currentMaterial != null && value != null) { currentMaterial.Illumination = int.Parse(value); } break; case "map_ka": if (currentMaterial != null) { currentMaterial.AmbientMap = value; } break; case "map_kd": if (currentMaterial != null) { currentMaterial.DiffuseMap = value; } break; case "map_ks": if (currentMaterial != null) { currentMaterial.SpecularMap = value; } break; case "map_d": if (currentMaterial != null) { currentMaterial.AlphaMap = value; } break; case "map_bump": case "bump": if (currentMaterial != null) { currentMaterial.BumpMap = value; } break; } } } } }
/// <summary> /// Loads the material library from a streamreader /// </summary> /// <param name="materialReader"></param> private void ReadMaterial(StreamReader materialReader) { MaterialDefinition currentMaterial = null; while (!materialReader.EndOfStream) { var line = materialReader.ReadLine(); if (line == null) { break; } line = line.Trim(); if (line.StartsWith("#") || line.Length == 0) { continue; } string keyword, value; SplitLine(line, out keyword, out value); switch (keyword.ToLower()) { case "newmtl": if (value != null) { if (this.Materials.ContainsKey(value)) { currentMaterial = null; } else { currentMaterial = new MaterialDefinition(value); this.Materials.Add(value, currentMaterial); } } break; case "ka": if (currentMaterial != null && value != null) { currentMaterial.Ambient = ColorParse(value); } break; case "kd": if (currentMaterial != null && value != null) { currentMaterial.Diffuse = ColorParse(value); } break; case "ks": if (currentMaterial != null && value != null) { currentMaterial.Specular = ColorParse(value); } break; case "ns": if (currentMaterial != null && value != null) { currentMaterial.SpecularCoefficient = DoubleParse(value); } break; case "d": if (currentMaterial != null && value != null) { currentMaterial.Dissolved = DoubleParse(value); } break; case "tr": if (!this.SkipTransparencyValues && currentMaterial != null && value != null) { currentMaterial.Dissolved = DoubleParse(value); } break; case "illum": if (currentMaterial != null && value != null) { currentMaterial.Illumination = int.Parse(value); } break; case "map_ka": if (currentMaterial != null) { currentMaterial.AmbientMap = value; } break; case "map_kd": if (currentMaterial != null) { currentMaterial.DiffuseMap = value; } break; case "map_ks": if (currentMaterial != null) { currentMaterial.SpecularMap = value; } break; case "map_d": if (currentMaterial != null) { currentMaterial.AlphaMap = value; } break; case "map_bump": case "bump": if (currentMaterial != null) { currentMaterial.BumpMap = value; } break; } } }