private void Start() { LoadModel(); pathfinder = new AStarPathfinder(); file = model; InstantiateModel(model); }
/// <summary> /// Converts <paramref name="obj"/> to a <see cref="MeshGeometry3D"/> /// </summary> /// <param name="obj">The <see cref="OBJFile"/> to convert to a <see cref="MeshGeometry3D"/></param> /// <returns>A <see cref="MeshGeometry3D"/> converted from <paramref name="obj"/></returns> /// <remarks>Normals do not get converted</remarks> public static MeshGeometry3D ConvertOBJ(OBJFile obj) { MeshGeometry3D mesh = new MeshGeometry3D(); Int32Collection indices = new Int32Collection(); foreach (OBJFace face in obj.Faces) { indices.Add((int)face.VertexIndices[0]); indices.Add((int)face.VertexIndices[1]); indices.Add((int)face.VertexIndices[2]); } Point3DCollection vertices = new Point3DCollection(); foreach (Vector3 vertex in obj.Vertices) { vertices.Add(new Point3D(vertex.X, vertex.Y, vertex.Z)); } PointCollection uvs = new PointCollection(); foreach (Vector2 uv in obj.UVs) { uvs.Add(new Point(uv.X, uv.Y)); } mesh.TextureCoordinates = uvs; mesh.TriangleIndices = indices; mesh.Positions = vertices; return(mesh); }
public void InstantiateModel(OBJFile model) { nodes = new List <TestNode>(); foreach (Vector3 v in model.vertexPositions) { GameObject vertex = Instantiate(vertexPrefab, v, Quaternion.identity); VertexView ver = vertex.GetComponent <VertexView>(); TestNode testNode = new TestNode(ver); nodes.Add(testNode); } foreach (Face tri in model.faces) { GameObject connection1 = Instantiate(sidePrefab, Vector3.zero, Quaternion.identity); GameObject connection2 = Instantiate(sidePrefab, Vector3.zero, Quaternion.identity); GameObject connection3 = Instantiate(sidePrefab, Vector3.zero, Quaternion.identity); ConnectionView conn1 = connection1.GetComponent <ConnectionView>(); ConnectionView conn2 = connection2.GetComponent <ConnectionView>(); ConnectionView conn3 = connection3.GetComponent <ConnectionView>(); conn1.SetConection(tri.vertices[0].position, tri.vertices[1].position); conn2.SetConection(tri.vertices[0].position, tri.vertices[2].position); conn3.SetConection(tri.vertices[1].position, tri.vertices[2].position); } graph = new TestGraph(nodes, ConnectionView.conections); graph.GenerateGraphConections(); }
static void TestMapgeo() { MapGeometry mgeo = new MapGeometry(@"C:/Users/Crauzer/Desktop/data/maps/mapgeometry/sr/base_srx.mapgeo"); string randomMaterialName = mgeo.Models[180].Submeshes[0].Material; mgeo.Models.Clear(); OBJFile object1 = new OBJFile("room155.obj"); OBJFile object2 = new OBJFile("room156.obj"); OBJFile object3 = new OBJFile("room157.obj"); AddOBJ(object1, "MapGeo_Instance_0"); AddOBJ(object2, "MapGeo_Instance_1"); AddOBJ(object3, "MapGeo_Instance_2"); mgeo.Write("base_srx.mapgeo.edited", 7); void AddOBJ(OBJFile obj, string name) { //We will add each object 2 times just for fun to see how transformation works (List <ushort> indices, List <MapGeometryVertex> vertices) = obj.GetMGEOData(); Matrix4x4 transformation = Matrix4x4.CreateTranslation(new Vector3(0, 50, 100)); MapGeometrySubmesh submesh = new MapGeometrySubmesh("", 0, (uint)indices.Count, 0, (uint)vertices.Count); MapGeometryModel model1 = new MapGeometryModel(name, vertices, indices, new List <MapGeometrySubmesh>() { submesh }, MapGeometryLayer.AllLayers); mgeo.AddModel(model1); } }
public void LoadCapsule() { var obj = new OBJFile("Models/capsule.obj"); Assert.AreEqual(5252, obj.Vertices.Count); Assert.AreEqual(5252, obj.TextureVertices.Count); Assert.AreEqual(5252, obj.Normals.Count); Assert.AreEqual(1, obj.Materials.Count); Assert.AreEqual("material0", obj.Materials.First().Name); }
void openOBJFileButton_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Filter = "OBJ Files (*.obj)|*.OBJ|" + "Nif Files Files (*.nif)|*.nif|" + "All files (*.*)|*.*"; if (open.ShowDialog() == DialogResult.OK && this.menu.expressionsListView.SelectedItems.Count > 0) { try { FileStream stream = new FileStream(open.FileName, FileMode.Open); ListViewItem item = this.menu.expressionsListView.SelectedItems[0]; Expression exp = (Expression)Enum.Parse(typeof(Expression), item.Text); if (this.expressions.ContainsKey(exp)) { if (open.FileName.ToLower().EndsWith(".obj")) { OBJFile objFile = new OBJFile(stream); MeshBase mesh = objFile.Mesh; this.expressions[exp] = mesh; } else { NifFile nifFile = new NifFile(stream); MeshBase mesh = nifFile.MeshData[0]; this.expressions[exp] = mesh; } } else { if (open.FileName.ToLower().EndsWith(".obj")) { OBJFile objFile = new OBJFile(stream); MeshBase mesh = objFile.Mesh; this.expressions.Add(exp, mesh); } else { NifFile nifFile = new NifFile(stream); MeshBase mesh = nifFile.MeshData[0]; this.expressions.Add(exp, mesh); } } //this.reference = new OBJFile(stream); item.SubItems[2].Text = open.FileName; stream.Close(); } catch (Exception ex) { } } }
public void LoadCube() { var obj = new OBJFile("Models/cube.obj"); Assert.AreEqual(24, obj.Vertices.Count); Assert.AreEqual(24, obj.TextureVertices.Count); Assert.AreEqual(24, obj.Normals.Count); Assert.AreEqual(3, obj.LoadedMaterials.Count); Assert.AreEqual(1, obj.Materials.Count); Assert.AreEqual("DEFAULT_MTL", obj.Materials[0].Name); //Assert.AreEqual(0.695, obj.Materials[0].Kd.X, 0.001); //Assert.AreEqual(0.743, obj.Materials[0].Kd.Y, 0.001); //Assert.AreEqual(0.790, obj.Materials[0].Kd.Z, 0.001); }
public MeshObject(OBJFile objFile, AsciiTexture texture, Vector3 position) { Position = position; triangles = new List <Triangle>(); for (int i = 0; i < objFile.triangleVertices.Length; i += 3) { Vector3 v0 = objFile.vertices[objFile.triangleVertices[i]]; Vector3 v1 = objFile.vertices[objFile.triangleVertices[i + 1]]; Vector3 v2 = objFile.vertices[objFile.triangleVertices[i + 2]]; Vector2 uv0 = objFile.texcoords[objFile.triangleTexcoords[i]]; Vector2 uv1 = objFile.texcoords[objFile.triangleTexcoords[i + 1]]; Vector2 uv2 = objFile.texcoords[objFile.triangleTexcoords[i + 2]]; triangles.Add(new Triangle(v0, v1, v2, texture, uv0, uv1, uv2)); } }
//Base Map public static void Add_Layer1(OBJFile obj, string name, string path, MapGeometry mgeo, int i, string fullpath, string mapname, string Lightmode, string Fogmode, string Alphamode) { (List <ushort> indices, List <MapGeometryVertex> vertices) = obj.GetMGEOData(); MapGeometrySubmesh submesh = new MapGeometrySubmesh(path, 0, (uint)indices.Count, 0, (uint)vertices.Count); MapGeometryModel room = new MapGeometryModel(name, vertices, indices, new List <MapGeometrySubmesh>() { submesh }, MapGeometryLayer.Layer1); mgeo.AddModel(room); //Porting material file to league format string ShaderPath = "MapFile/ShaderTemp/DefaultEnv_Flat_AlphaTest.py"; List <string> materials = new List <string>(); materials = File.ReadAllLines(ShaderPath).ToList(); string number = $"{i}"; string readfile = File.ReadLines($@"{fullpath}").Skip(12).Take(1).First(); //Get texture name without extension string replace = readfile.Replace("\\\\", " \\\\ "); var gettexturename = string.Join(" ", replace.Split().Reverse().Take(1).Reverse()); string text = gettexturename.Replace(".dds", ""); string texturename = gettexturename; if (mapname == string.Empty) { mapname = "textures"; } //Add Settings to material var newList = materials.Select(s => s.Replace("Texture_Name", texturename)).ToList(); var newList2 = newList.Select(s => s.Replace("Map_Name", mapname)).ToList(); var newList3 = newList2.Select(s => s.Replace("Material_Name", path)).ToList(); var newList4 = newList3.Select(s => s.Replace("NOBAKEDLIGHTINGTEMP", Lightmode)).ToList(); var newList5 = newList4.Select(s => s.Replace("DISABLEDEPTHFOG", Fogmode)).ToList(); var newList6 = newList5.Select(s => s.Replace("PREMULTIPLIEDALPHA", Alphamode)).ToList(); //Sun Properties //Writes Directory.CreateDirectory("material_output"); File.AppendAllLines(@"material_output\" + "material.py", newList6); }
static void BildgeWaterRift(MapGeometry mgeo) { //Model Bulk Loading var fileCount = (from file in Directory.EnumerateFiles(@"K:\Riot Games\LeagueSkins\BildgewaterRift\3dmodelsnewnew", "*.obj", System.IO.SearchOption.AllDirectories) select file).Count(); int OBJsToCreate = fileCount + 1; OBJFile[] OBJs = new OBJFile[OBJsToCreate]; for (int i = 1; i < OBJsToCreate; i++) { OBJs[i] = new OBJFile($@"K:\Riot Games\LeagueSkins\BildgewaterRift\3dmodelsnewnew\room{i}.obj"); int j = i; AddModel(OBJs[i], $"MapGeo_Instance_{i}", $"Maps/KitPieces/Summoners_Rift/Materials/room{i}", mgeo, i, j); } mgeo.Write(@"K:\Riot Games\LeagueSkins\BildgewaterRift\Map11\data\maps\mapgeometry\sr\base_srx.mapgeo", 11); }
/// <summary> /// Converts <paramref name="obj"/> to an <see cref="SCBFile"/> /// </summary> /// <param name="obj">The <see cref="OBJFile"/> to convert to an <see cref="SCBFile"/></param> /// <returns>An <see cref="SCBFile"/> converted from <paramref name="obj"/></returns> public static SCBFile ConvertOBJ(OBJFile obj) { List <Vector3> vertices = obj.Vertices; List <OBJFace> faces = obj.Faces; List <uint> indices = new List <uint>(); bool zeroPointIndex = false; foreach (OBJFace face in faces) { for (int i = 0; i < 3; i++) { if (face.VertexIndices[i] == 0) { zeroPointIndex = true; break; } } if (zeroPointIndex) { break; } } if (!zeroPointIndex) { foreach (OBJFace face in faces) { for (int i = 0; i < 3; i++) { face.VertexIndices[i] -= 1; face.UVIndices[i] -= 1; } } } foreach (OBJFace face in faces) { indices.AddRange(face.VertexIndices.Cast <uint>()); } return(new SCBFile(obj.Vertices, indices, obj.UVs)); }
//--------------------------------- public void exportNavMeshToOBJ() { if (mPathMeshTris.Count == 0) { return; } //ouput our data to the file. OBJFile output = new OBJFile(); output.addObject("Terrain"); List <int> inds = new List <int>(); for (int i = 0; i < mPathMeshTris.Count; i++) { Export360.XTD_DeulanyTIN.triangle tri = mPathMeshTris[i]; //if this tri has 0 area, get rid of it.. //CLM deulany outputs a different clockwise winding than i want.. //this SHOULD be a proper clockwise winding test inds.Add(tri.vertIndex[0]); inds.Add(tri.vertIndex[1]); inds.Add(tri.vertIndex[2]); } output.addVertexList(0, mPathMeshVerts, inds); string filenameNoExt = Path.GetFileNameWithoutExtension(CoreGlobals.ScenarioFile); string targetFilename = CoreGlobals.ScenarioDirectory + @"\" + filenameNoExt + ".obj"; if (File.Exists(targetFilename)) { File.Delete(targetFilename); } output.write(new FileStream(targetFilename, FileMode.OpenOrCreate)); output = null; }
public static (List <ushort>, List <MapGeometryVertex>) GetMGEOData(this OBJFile obj) { List <ushort> indices = new List <ushort>(); List <MapGeometryVertex> vertices = new List <MapGeometryVertex>(); foreach (Vector3 vertex in obj.Vertices) { vertices.Add(new MapGeometryVertex() { Position = vertex }); } foreach (OBJFace face in obj.Faces) { for (int i = 0; i < 3; i++) { indices.Add((ushort)face.VertexIndices[i]); } if (face.NormalIndices != null) { for (int i = 0; i < 3; i++) { vertices[(int)face.VertexIndices[i]].Normal = obj.Normals[(int)face.NormalIndices[i]]; } } if (face.UVIndices != null) { for (int i = 0; i < 3; i++) { vertices[(int)face.VertexIndices[i]].DiffuseUV = obj.UVs[(int)face.UVIndices[i]]; } } } return(indices, vertices); }
public static SCOFile ConvertOBJ(OBJFile OBJ) { List <UInt16> Indices = new List <UInt16>(); bool ZeroPointIndex = false; foreach (OBJFace Face in OBJ.Faces) { for (int i = 0; i < 3; i++) { if (Face.VertexIndices[i] == 0) { ZeroPointIndex = true; break; } } if (ZeroPointIndex) { break; } } if (ZeroPointIndex == false) { foreach (OBJFace Face in OBJ.Faces) { for (int i = 0; i < 3; i++) { Face.VertexIndices[i] -= 1; Face.UVIndices[i] -= 1; } } } foreach (OBJFace Face in OBJ.Faces) { Indices.AddRange(Face.VertexIndices); } return(new SCOFile(Indices, OBJ.Vertices, OBJ.UVs)); }
public void LoadShips() { //http://pamargames.com/free-3d-models-game-assets/ var ship1 = new OBJFile("Models/Ship1/Ship.obj"); Assert.AreEqual(1073, ship1.Vertices.Count); Assert.AreEqual(1316, ship1.TextureVertices.Count); Assert.AreEqual(1276, ship1.Normals.Count); Assert.AreEqual(1076, ship1.Faces.Count); var ship2 = new OBJFile("Models/Ship2/Ship.obj"); Assert.AreEqual(657, ship2.Vertices.Count); Assert.AreEqual(788, ship2.TextureVertices.Count); Assert.AreEqual(751, ship2.Normals.Count); Assert.AreEqual(712, ship2.Faces.Count); var ship3 = new OBJFile("Models/Ship3/Ship.obj"); Assert.AreEqual(539, ship3.Vertices.Count); Assert.AreEqual(677, ship3.TextureVertices.Count); Assert.AreEqual(627, ship3.Normals.Count); Assert.AreEqual(546, ship3.Faces.Count); }
void openOBJFileButton_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Filter = "OBJ Files (*.obj)|*.OBJ|" + "Nif Files (*.nif)|*.nif|" + "All files (*.*)|*.*"; if (open.ShowDialog() == DialogResult.OK && this.menu.expressionsListView.SelectedItems.Count > 0) { try { FileStream stream = new FileStream(open.FileName, FileMode.Open); ListViewItem item = this.menu.expressionsListView.SelectedItems[0]; Expression exp = (Expression)Enum.Parse(typeof(Expression), item.Text); if (this.expressions.ContainsKey(exp)) { if (open.FileName.ToLower().EndsWith(".obj")) { OBJFile objFile = new OBJFile(stream); MeshBase mesh = objFile.Mesh; this.expressions[exp] = mesh; } else { NifFile nifFile = new NifFile(stream); MeshBase mesh = nifFile.MeshData[0]; this.expressions[exp] = mesh; } } else { if (open.FileName.ToLower().EndsWith(".obj")) { OBJFile objFile = new OBJFile(stream); MeshBase mesh = objFile.Mesh; this.expressions.Add(exp, mesh); } else { NifFile nifFile = new NifFile(stream); MeshBase mesh = nifFile.MeshData[0]; this.expressions.Add(exp, mesh); } } //this.reference = new OBJFile(stream); item.SubItems[2].Text = open.FileName; stream.Close(); } catch (Exception ex) { } } }
public static Tuple <List <NVRVertex>, List <int> > GetGeometryFromOBJ(OBJFile objFile) { List <NVRVertex> vertices = new List <NVRVertex>(); List <int> indices = new List <int>(); // We first add all the vertices in a list. List <NVRVertex> objVertices = new List <NVRVertex>(); foreach (Vector3 position in objFile.Vertices) { objVertices.Add(new NVRVertex8(position)); } foreach (OBJFace face in objFile.Faces) { for (int i = 0; i < 3; i++) { NVRVertex8 position = (NVRVertex8)objVertices[face.VertexIndices[i]]; Vector2 UV = new Vector2(0, 0); if (objFile.UVs.Count > 0) { UV = objFile.UVs[face.UVIndices[i]]; } Vector3 normal = new Vector3(0, 0, 0); if (objFile.Normals.Count > 0) { normal = objFile.Normals[face.NormalIndices[i]]; } if ((position.UV != null && position.Normal != null) && (!position.UV.Equals(UV) || !position.Normal.Equals(normal))) { // Needs to replicate position = new NVRVertex8(position.Position); } position.UV = UV; position.Normal = normal; position.DiffuseColor = new ColorBGRAVector4Byte(0, 0, 0, 255); position.EmissiveColor = new ColorBGRAVector4Byte(127, 127, 127, 255); int vertexIndex = vertices.IndexOf(position); if (vertexIndex == -1) { vertexIndex = vertices.Count; vertices.Add(position); } indices.Add(vertexIndex); } } //for (int i = 0; i < indices.Count; i += 3) //{ // NVRVertex8 v1 = (NVRVertex8)vertices[indices[i]]; // NVRVertex8 v2 = (NVRVertex8)vertices[indices[i + 1]]; // NVRVertex8 v3 = (NVRVertex8)vertices[indices[i + 2]]; // Vector3 faceNormal = CalcNormal(v1.Position, v2.Position, v3.Position); // v1.Normal = v1.Normal + faceNormal; // v2.Normal = v2.Normal + faceNormal; // v3.Normal = v3.Normal + faceNormal; //} //foreach (NVRVertex8 vert in vertices) //{ // float length = (float)Math.Sqrt(Math.Pow(vert.Normal.X, 2) + Math.Pow(vert.Normal.Y, 2) + Math.Pow(vert.Normal.Z, 2)); // vert.Normal.X = vert.Normal.X / length; // vert.Normal.Y = vert.Normal.Y / length; // vert.Normal.Z = vert.Normal.Z / length; //} return(new Tuple <List <NVRVertex>, List <int> >(vertices, indices)); }
public static GameObject LoadOBJFile(string meshName, OBJFile obj) { bool hasNormals = false; //OBJ LISTS List <Vector3> vertices = new List <Vector3>(); List <Vector3> normals = new List <Vector3>(); List <Vector2> uvs = new List <Vector2>(); //UMESH LISTS List <Vector3> uvertices = new List <Vector3>(); List <Vector3> unormals = new List <Vector3>(); List <Vector2> uuvs = new List <Vector2>(); //MESH CONSTRUCTION List <string> materialNames = new List <string>(); List <string> objectNames = new List <string>(); Dictionary <string, int> hashtable = new Dictionary <string, int>(); List <OBJFace> faceList = new List <OBJFace>(); string cmaterial = ""; string cmesh = "default"; //CACHE Material[] materialCache = null; foreach (string ln in obj.ObjLines) { if (ln.Length > 0 && ln[0] != '#') { string l = ln.Trim().Replace(" ", " "); string[] cmps = l.Split(' '); string data = l.Remove(0, l.IndexOf(' ') + 1); if (cmps[0] == "mtllib") { //load cache materialCache = LoadMTLFile(obj); } else if ((cmps[0] == "g" || cmps[0] == "o") && splitByMaterial == false) { cmesh = data; if (!objectNames.Contains(cmesh)) { objectNames.Add(cmesh); } } else if (cmps[0] == "usemtl") { cmaterial = data; if (!materialNames.Contains(cmaterial)) { materialNames.Add(cmaterial); } if (splitByMaterial) { if (!objectNames.Contains(cmaterial)) { objectNames.Add(cmaterial); } } } else if (cmps[0] == "v") { //VERTEX vertices.Add(ParseVectorFromCMPS(cmps)); } else if (cmps[0] == "vn") { //VERTEX NORMAL normals.Add(ParseVectorFromCMPS(cmps)); } else if (cmps[0] == "vt") { //VERTEX UV uvs.Add(ParseVectorFromCMPS(cmps)); } else if (cmps[0] == "f") { int[] indexes = new int[cmps.Length - 1]; for (int i = 1; i < cmps.Length; i++) { string felement = cmps[i]; int vertexIndex = -1; int normalIndex = -1; int uvIndex = -1; if (felement.Contains("//")) { //doubleslash, no UVS. string[] elementComps = felement.Split('/'); vertexIndex = int.Parse(elementComps[0]) - 1; normalIndex = int.Parse(elementComps[2]) - 1; } else if (felement.Count(x => x == '/') == 2) { //contains everything string[] elementComps = felement.Split('/'); vertexIndex = int.Parse(elementComps[0]) - 1; uvIndex = int.Parse(elementComps[1]) - 1; normalIndex = int.Parse(elementComps[2]) - 1; } else if (!felement.Contains("/")) { //just vertex inedx vertexIndex = int.Parse(felement) - 1; } else { //vertex and uv string[] elementComps = felement.Split('/'); vertexIndex = int.Parse(elementComps[0]) - 1; uvIndex = int.Parse(elementComps[1]) - 1; } string hashEntry = vertexIndex + "|" + normalIndex + "|" + uvIndex; if (hashtable.ContainsKey(hashEntry)) { indexes[i - 1] = hashtable[hashEntry]; } else { //create a new hash entry indexes[i - 1] = hashtable.Count; hashtable[hashEntry] = hashtable.Count; uvertices.Add(vertices[vertexIndex]); if (normalIndex < 0 || (normalIndex > (normals.Count - 1))) { unormals.Add(Vector3.zero); } else { hasNormals = true; unormals.Add(normals[normalIndex]); } if (uvIndex < 0 || (uvIndex > (uvs.Count - 1))) { uuvs.Add(Vector2.zero); } else { uuvs.Add(uvs[uvIndex]); } } } if (indexes.Length < 5 && indexes.Length >= 3) { OBJFace f1 = new OBJFace(); f1.materialName = cmaterial; f1.indexes = new int[] { indexes[0], indexes[1], indexes[2] }; f1.meshName = (splitByMaterial) ? cmaterial : cmesh; faceList.Add(f1); if (indexes.Length > 3) { OBJFace f2 = new OBJFace(); f2.materialName = cmaterial; f2.meshName = (splitByMaterial) ? cmaterial : cmesh; f2.indexes = new int[] { indexes[2], indexes[3], indexes[0] }; faceList.Add(f2); } } } } } if (objectNames.Count == 0) { objectNames.Add("default"); } //build objects GameObject parentObject = new GameObject(meshName); foreach (string item in objectNames) { GameObject subObject = new GameObject(item); subObject.transform.parent = parentObject.transform; subObject.transform.localScale = new Vector3(-1, 1, 1); //Create mesh Mesh m = new Mesh(); m.name = item; //LISTS FOR REORDERING List <Vector3> processedVertices = new List <Vector3>(); List <Vector3> processedNormals = new List <Vector3>(); List <Vector2> processedUVs = new List <Vector2>(); List <int[]> processedIndexes = new List <int[]>(); Dictionary <int, int> remapTable = new Dictionary <int, int>(); //POPULATE MESH List <string> meshMaterialNames = new List <string>(); OBJFace[] ofaces = faceList.Where(x => x.meshName == item).ToArray(); foreach (string mn in materialNames) { OBJFace[] faces = ofaces.Where(x => x.materialName == mn).ToArray(); if (faces.Length > 0) { int[] indexes = new int[0]; foreach (OBJFace f in faces) { int l = indexes.Length; System.Array.Resize(ref indexes, l + f.indexes.Length); System.Array.Copy(f.indexes, 0, indexes, l, f.indexes.Length); } meshMaterialNames.Add(mn); if (m.subMeshCount != meshMaterialNames.Count) { m.subMeshCount = meshMaterialNames.Count; } for (int i = 0; i < indexes.Length; i++) { int idx = indexes[i]; //build remap table if (remapTable.ContainsKey(idx)) { //ezpz indexes[i] = remapTable[idx]; } else { processedVertices.Add(uvertices[idx]); processedNormals.Add(unormals[idx]); processedUVs.Add(uuvs[idx]); remapTable[idx] = processedVertices.Count - 1; indexes[i] = remapTable[idx]; } } processedIndexes.Add(indexes); } else { } } //apply stuff m.vertices = processedVertices.ToArray(); m.normals = processedNormals.ToArray(); m.uv = processedUVs.ToArray(); for (int i = 0; i < processedIndexes.Count; i++) { m.SetTriangles(processedIndexes[i], i); } if (!hasNormals) { m.RecalculateNormals(); } m.RecalculateBounds(); MeshFilter mf = subObject.AddComponent <MeshFilter>(); MeshRenderer mr = subObject.AddComponent <MeshRenderer>(); Material[] processedMaterials = new Material[meshMaterialNames.Count]; for (int i = 0; i < meshMaterialNames.Count; i++) { if (materialCache == null) { processedMaterials[i] = new Material(Shader.Find("Legacy Shaders/Specular")); } else { Material mfn = Array.Find(materialCache, x => x.name == meshMaterialNames[i]); ; if (mfn == null) { processedMaterials[i] = new Material(Shader.Find("Legacy Shaders/Specular")); } else { processedMaterials[i] = mfn; } } processedMaterials[i].name = meshMaterialNames[i]; } mr.materials = processedMaterials; mf.mesh = m; } return(parentObject); }
public static Material[] LoadMTLFile(OBJFile obj) { Material currentMaterial = null; List <Material> matlList = new List <Material>(); foreach (string ln in obj.MtlLines) { string l = ln.Trim().Replace(" ", " "); string[] cmps = l.Split(' '); string data = l.Remove(0, l.IndexOf(' ') + 1); if (cmps[0] == "newmtl") { if (currentMaterial != null) { matlList.Add(currentMaterial); } currentMaterial = new Material(Shader.Find("Legacy Shaders/Specular")); currentMaterial.name = data; } else if (cmps[0] == "Kd") { currentMaterial.SetColor("_Color", ParseColorFromCMPS(cmps)); } else if (cmps[0] == "map_Kd") { //TEXTURE currentMaterial.SetTexture("_MainTex", TextureLoader.LoadTexture(obj.MtlImages[data], ".png")); } //else if (cmps[0] == "map_Bump") //{ // //TEXTURE // string fpth = OBJGetFilePath(data, mtlFileDirectory, baseFileName); // if (fpth != null) // { // currentMaterial.SetTexture("_BumpMap", TextureLoader.LoadTexture(fpth, true)); // currentMaterial.EnableKeyword("_NORMALMAP"); // } //} else if (cmps[0] == "Ks") { currentMaterial.SetColor("_SpecColor", ParseColorFromCMPS(cmps)); } else if (cmps[0] == "Ka") { currentMaterial.SetColor("_EmissionColor", ParseColorFromCMPS(cmps, 0.05f)); currentMaterial.EnableKeyword("_EMISSION"); } else if (cmps[0] == "d") { float visibility = float.Parse(cmps[1]); if (visibility < 1) { Color temp = currentMaterial.color; temp.a = visibility; currentMaterial.SetColor("_Color", temp); //TRANSPARENCY ENABLER currentMaterial.SetFloat("_Mode", 3); currentMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); currentMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); currentMaterial.SetInt("_ZWrite", 0); currentMaterial.DisableKeyword("_ALPHATEST_ON"); currentMaterial.EnableKeyword("_ALPHABLEND_ON"); currentMaterial.DisableKeyword("_ALPHAPREMULTIPLY_ON"); currentMaterial.renderQueue = 3000; } } else if (cmps[0] == "Ns") { float Ns = float.Parse(cmps[1]); Ns = (Ns / 1000); currentMaterial.SetFloat("_Glossiness", Ns); } } if (currentMaterial != null) { matlList.Add(currentMaterial); } return(matlList.ToArray()); }
public void LoadModel() { model = new OBJFile(); model.LoadFromString(objAsString); }
public void LoadModelAsJson() { model = new OBJFile(); objAsString = model.GetGetDataAsString(path); model = null; }
static void AddModel(OBJFile obj, string name, string path, MapGeometry mgeo, int i, int j) { (List <ushort> indices, List <MapGeometryVertex> vertices) = obj.GetMGEOData(); MapGeometrySubmesh submesh = new MapGeometrySubmesh(path, 0, (uint)indices.Count, 0, (uint)vertices.Count); MapGeometryModel room = new MapGeometryModel(name, vertices, indices, new List <MapGeometrySubmesh>() { submesh }, MapGeometryLayer.Layer1); //Fix for big models that league can't handle. List <MapGeometryModel> mgeoModels = new List <MapGeometryModel>(); //Porting material file to league format StringBuilder mtl = new StringBuilder(); string number = $"{i}"; string readfile = File.ReadLines($@"K:\Riot Games\LeagueSkins\BildgewaterRift\3dmodelsnewnew\room{i}.mtl").Skip(12).Take(1).First(); string replace = readfile.Replace("\\\\", " \\\\ "); var gettexturename = string.Join(" ", replace.Split().Reverse().Take(1).Reverse()); string text = gettexturename.Replace(".dds", ""); string texturename = text; // " is replaced by * // { is replaced by ( // } is replaced by ) //Will be replaced later if (readfile.IsNullOrEmpty()) { mtl.AppendLine($"*Maps/KitPieces/Summoners_Rift/Materials/room{i}* = StaticMaterialDef ("); mtl.AppendLine($" name: string = *Maps/KitPieces/Summoners_Rift/Materials/room{i}*"); mtl.AppendLine(" type: u32 = 0"); mtl.AppendLine(" defaultTechnique: string = *normal*"); mtl.AppendLine(" samplerValues: list[embed] = ("); mtl.AppendLine(" StaticMaterialShaderSamplerDef ("); mtl.AppendLine(" samplerName: string = *DiffuseTexture*"); mtl.AppendLine($" textureName: string = *ASSETS/Shared/Materials/white.dds*"); mtl.AppendLine(" addressW: u32 = 1"); mtl.AppendLine(" )"); mtl.AppendLine(" )"); mtl.AppendLine(" paramValues: list[embed] = ("); mtl.AppendLine(" StaticMaterialShaderParamDef ("); mtl.AppendLine(" name: string = *AlphaTestValue*"); mtl.AppendLine(" value: vec4 = ( 0.300000012, 0, 0, 0 )"); mtl.AppendLine(" )"); mtl.AppendLine(" )"); mtl.AppendLine(" shaderMacros: map[string,string] = ("); mtl.AppendLine(" *NO_BAKED_LIGHTING* = *1*"); mtl.AppendLine(" *DISABLE_DEPTH_FOG* = *1*"); mtl.AppendLine(" *PREMULTIPLIED_ALPHA* = *1*"); mtl.AppendLine(" )"); mtl.AppendLine(" techniques: list[embed] = ("); mtl.AppendLine(" StaticMaterialTechniqueDef ("); mtl.AppendLine(" name: string = *normal*"); mtl.AppendLine(" passes: list[embed] = ("); mtl.AppendLine(" StaticMaterialPassDef ("); mtl.AppendLine(" shader: link = *Shaders/Environment/DefaultEnv_Flat_AlphaTest*"); mtl.AppendLine(" blendEnable: bool = true"); mtl.AppendLine(" dstColorBlendFactor: u32 = 7"); mtl.AppendLine(" dstAlphaBlendFactor: u32 = 7"); mtl.AppendLine(" )"); mtl.AppendLine(" )"); mtl.AppendLine(" )"); mtl.AppendLine(" )"); mtl.AppendLine(" )"); Directory.CreateDirectory("material_output"); File.AppendAllText(@"material_output\" + "material.py", mtl.ToString()); //Console.Write(mtl.ToString()); } else { mtl.AppendLine($"*Maps/KitPieces/Summoners_Rift/Materials/room{i}* = StaticMaterialDef ("); mtl.AppendLine($" name: string = *Maps/KitPieces/Summoners_Rift/Materials/room{i}*"); mtl.AppendLine(" type: u32 = 0"); mtl.AppendLine(" defaultTechnique: string = *normal*"); mtl.AppendLine(" samplerValues: list[embed] = ("); mtl.AppendLine(" StaticMaterialShaderSamplerDef ("); mtl.AppendLine(" samplerName: string = *DiffuseTexture*"); mtl.AppendLine($" textureName: string = *ASSETS/Maps/KitPieces/SRX/bildgewater/{texturename}.dds*"); mtl.AppendLine(" addressW: u32 = 1"); mtl.AppendLine(" )"); mtl.AppendLine(" )"); mtl.AppendLine(" paramValues: list[embed] = ("); mtl.AppendLine(" StaticMaterialShaderParamDef ("); mtl.AppendLine(" name: string = *AlphaTestValue*"); mtl.AppendLine(" value: vec4 = ( 0.300000012, 0, 0, 0 )"); mtl.AppendLine(" )"); mtl.AppendLine(" )"); mtl.AppendLine(" shaderMacros: map[string,string] = ("); mtl.AppendLine(" *NO_BAKED_LIGHTING* = *1*"); mtl.AppendLine(" *DISABLE_DEPTH_FOG* = *1*"); mtl.AppendLine(" *PREMULTIPLIED_ALPHA* = *1*"); mtl.AppendLine(" )"); mtl.AppendLine(" techniques: list[embed] = ("); mtl.AppendLine(" StaticMaterialTechniqueDef ("); mtl.AppendLine(" name: string = *normal*"); mtl.AppendLine(" passes: list[embed] = ("); mtl.AppendLine(" StaticMaterialPassDef ("); mtl.AppendLine(" shader: link = *Shaders/Environment/DefaultEnv_Flat_AlphaTest*"); mtl.AppendLine(" blendEnable: bool = true"); mtl.AppendLine(" dstColorBlendFactor: u32 = 7"); mtl.AppendLine(" dstAlphaBlendFactor: u32 = 7"); mtl.AppendLine(" )"); mtl.AppendLine(" )"); mtl.AppendLine(" )"); mtl.AppendLine(" )"); mtl.AppendLine(" )"); //Console.Write(mtl.ToString()); Directory.CreateDirectory("material_output"); File.AppendAllText(@"material_output\" + "material.py", mtl.ToString()); } if (vertices.Count > 30000 & indices.Count > 27000) { /*MapGeometryModel newMgeoMesh = new MapGeometryModel(); * foreach (var vert in vertices) * { * MapGeometryVertex newMgeoVertex = new MapGeometryVertex(); * newMgeoVertex.Position = vert.Position; * newMgeoVertex.DiffuseUV = vert.DiffuseUV; * newMgeoMesh.Vertices.Add(newMgeoVertex); * } * foreach (var index in indices) * newMgeoMesh.Indices.Add(index); * mgeoModels.Add(newMgeoMesh);*///should work now Console.WriteLine($"{room.Name} is too big for Leauge and need to be splitted into smaller parts."); Console.WriteLine($"Vertices:{vertices.Count}"); Console.WriteLine($"Indices:{indices.Count}"); mgeo.Models.Remove(room); Console.WriteLine($"Ignored: {room.Name}"); Console.WriteLine("_________________________________________________________________________________"); //Writes Temporary a log file into a specific folder StringBuilder sb = new StringBuilder(); //Set Max values for vertices and indices int vtmax = 30000; int idmax = 27000; //Log Formatting sb.AppendLine($"room{i}.obj -> {room.Name} | Vertices:{vertices.Count} > {vtmax}, Indices:{indices.Count} > {idmax}"); //Addeds DateTime to file name int Day = DateTime.Now.Day; int Month = DateTime.Now.Month; int Year = DateTime.Now.Year; int Hour = DateTime.Now.Hour; int Minute = DateTime.Now.Minute; int Second = DateTime.Now.Second; string Time = $"{Day}_{Month}_{Year}_{Hour}_{Minute}"; Directory.CreateDirectory("logs"); File.AppendAllText(@"logs\" + $"{Time}_map_log.txt", sb.ToString()); sb.Clear(); } else { /*room.Indices.AddRange(room.Indices); * UInt32 mgeoCount = 1; * while (room.Indices.Count > 0) * { * MapGeometryModel newMgeoMesh = new MapGeometryModel(); * // Keeps the indices we can keep :D * UInt32 count = 0; * List<UInt32> keptIndices = new List<UInt32>(); * bool tooManyIndices = false; * while (count < (room.Indices.Count / (double)3)) * { * //Code on here cause out of range exception. IDK why * if (room.Indices[3 * room.Indices.Count] <= mgeoCount * 30000 && room.Indices[3 * indices.Count + 1] <= mgeoCount * 30000 && room.Indices[3 * room.Indices.Count + 2] <= mgeoCount * 30000) * { * * * if (keptIndices.Count <= 27000) * { * tooManyIndices = true; * count = (uint)(room.Indices.Count / (double)3); * } * else * { * keptIndices.Add(room.Indices[3 * room.Indices.Count]); * keptIndices.Add(room.Indices[3 * room.Indices.Count + 1]); * keptIndices.Add(room.Indices[3 * room.Indices.Count + 2]); * room.Indices.RemoveRange(3 * room.Indices.Count, 3); * } * } * else * count += 1; * } * foreach (var vert in vertices) * { * MapGeometryVertex newMgeoVertex = new MapGeometryVertex(); * newMgeoVertex.Position = vert.Position; //problably got all positions * newMgeoVertex.DiffuseUV = vert.DiffuseUV; * newMgeoMesh.Vertices.Add(newMgeoVertex); * } * //Check what vertex to keep depending on the index we put * List<UInt32> sortedIndices = new List<UInt32>(); * sortedIndices.AddRange(keptIndices); * sortedIndices.Sort(); * Int32 previousIndex = -1; * for (var p = 0; i <= sortedIndices.Count - 1; i++) * { * if ((sortedIndices[i] - previousIndex) > 1) * { * * UInt32 verticesToRemove = (uint)(sortedIndices[i] - previousIndex - 1); * // Removing vertices * newMgeoMesh.Vertices.RemoveRange(previousIndex + 1, (int)verticesToRemove); * NewMethod(keptIndices, sortedIndices, p, verticesToRemove); * for (j = i; j <= sortedIndices.Count - 1; j++) * // Adjusting sorted indices * sortedIndices[j] = sortedIndices[j] - verticesToRemove; * } * previousIndex = (int)sortedIndices[i]; * } * if (newMgeoMesh.Vertices.Count > previousIndex + 1) * newMgeoMesh.Vertices.RemoveRange(previousIndex + 1, newMgeoMesh.Vertices.Count - previousIndex - 1); * foreach (var index in keptIndices) * newMgeoMesh.Indices.Add((ushort)index); * mgeo.AddModel(newMgeoMesh); * if (!tooManyIndices) * mgeoCount += 1; * }*/ Console.WriteLine($"OBJ to MAPGEO Convert: room{i}.obj -> {room.Name}"); Console.WriteLine($"Vertices:{vertices.Count}"); Console.WriteLine($"Indices:{indices.Count}"); Console.WriteLine("_________________________________________________________________________________"); //Console.WriteLine(mgeoCount.ToString("")); } mgeo.AddModel(room); //mtl to league material format. }