// ############################################################################ // ############################################################################ // load the collision object "collision_object.obj" from streamingassets folder // ############################################################################ private void Change_Skybox_Collision_Object(stru_skymap_paths skymap_paths) { // collision object for reseting model (collision with blades) Mesh holder_mesh = new Mesh(); //ObjImporter newMesh = new ObjImporter(); holder_mesh = ObjImporter.ImportFile(skymap_paths.fullpath_collision_object); MeshFilter collision_object_mesh_filter = GameObject.Find("Collision Object").transform.Find("collisionobject").gameObject.GetComponent <MeshFilter>(); collision_object_mesh_filter.mesh = holder_mesh; MeshCollider collision_object_mesh_collider = GameObject.Find("Collision Object").transform.Find("collisionobject").gameObject.GetComponent <MeshCollider>(); collision_object_mesh_collider.sharedMesh = holder_mesh; collision_object_mesh_filter.mesh.RecalculateNormals(); collision_object_mesh_collider.sharedMesh.RecalculateNormals(); // collision object for landig Mesh holder_mesh2 = new Mesh(); holder_mesh2 = ObjImporter.ImportFile(skymap_paths.fullpath_collision_landing_object); // this is calulated in the helicopter_ODE-thread at high update frequency helicopter_ODE.Set_AABB_Skybox_Collision_Landing_Mesh(holder_mesh2); }
//! Adds blocks from mods to the game. public void AddModMeshes(Dictionary <string, Mesh> dictionary) { string modPath = Path.Combine(Application.persistentDataPath, "Mods"); Directory.CreateDirectory(modPath); string[] modDirs = Directory.GetDirectories(modPath); foreach (string path in modDirs) { string meshPath = path + "/Models/"; Directory.CreateDirectory(meshPath); DirectoryInfo d = new DirectoryInfo(meshPath); foreach (FileInfo file in d.GetFiles("*.obj")) { string filePath = meshPath + file.Name; string meshName = file.Name.Remove(file.Name.Length - 4); if (!dictionary.ContainsKey(meshName)) { ObjImporter importer = new ObjImporter(); Mesh newMesh = importer.ImportFile(filePath); dictionary.Add(meshName, newMesh); string modName = new DirectoryInfo(path).Name; string[] commandLineOptions = Environment.GetCommandLineArgs(); if (commandLineOptions.Contains("-devel")) { Debug.Log("Mod " + "[" + modName + "]" + " created a new mesh: [" + meshName + "]"); } } } } playerController.gameManager.InitModBlocks(); }
void loadmesh() { ObjImporter import = new ObjImporter(); leftmesh = import.ImportFile(Application.streamingAssetsPath + "/upper.obj"); rightmesh = import.ImportFile(Application.streamingAssetsPath + "/bottom.obj"); }
// Start is called before the first frame update void Start() { ObjImporter newMesh = new ObjImporter(); Mesh holderMesh = newMesh.ImportFile("/home/sourabh/Documents/TU-Berlin/Thesis/Sytheticdata/ml-imagesynthesis/Assets/CADPictures/PandaMale.obj"); MeshSaver.SaveMesh(holderMesh, "PandaMale"); }
private void loadShowcaseScene() { importer = new ObjImporter(); importer.AddMaterialFileStream(Path.GetFileName(ShowcaseTest.ShowcaseMTL), File.OpenRead(ShowcaseTest.ShowcaseMTL)); importer.ImportObjFile(ShowcaseTest.ShowcaseOBJ); interpreter = new OBJInterpreter(importer, new RAMTextureFactory()); }
public void LoadModel(string path) { meshFilter.mesh = ObjImporter.CreateMesh(path); material = ObjImporter.CreateMaterial(); //will be reached from options menu meshRenderer.material = material; RepositionObject(); }
public void Import(string mPath, string textPath) { modelPath = mPath; // Create mesh ObjImporter objImporter = new ObjImporter(); Mesh importedMesh = objImporter.ImportFile(modelPath); // Create empty gameobject GameObject emptyGameObject = new GameObject(); emptyGameObject.transform.position = new Vector3(0, 0, 0); // Add mesh to game object MeshFilter meshFilter = emptyGameObject.AddComponent(typeof(MeshFilter)) as MeshFilter; meshFilter.sharedMesh = importedMesh; // Add mesh renderer MeshRenderer meshRenderer = emptyGameObject.AddComponent(typeof(MeshRenderer)) as MeshRenderer; meshRenderer.material = mat; Texture2D tex = new Texture2D(2, 2); tex.LoadImage(File.ReadAllBytes(textPath)); meshRenderer.material.SetTexture("_MainTex", tex); // Tell the boys if (ObjectImported != null) { ObjectImported(emptyGameObject); } }
private ObjImporter.meshStruct LoadObjMesh( string fileName, double scale) { ObjImporter importer = new ObjImporter(); ObjImporter.meshStruct mesh = importer.ImportFile(fileName); Vector3d[] vertexStartPoint = new Vector3d[mesh.vertices.Length]; for (int i = 0; i < mesh.vertices.Length; i++) { vertexStartPoint[i] = mesh.vertices[i]; } OpenGLUtilities.UnitizeObject(ref vertexStartPoint); OpenGLUtilities.ScaleObject(ref vertexStartPoint, scale); for (int i = 0; i < mesh.vertices.Length; i++) { mesh.vertices[i] = vertexStartPoint[i]; } return(mesh); }
void Update() { if (Input.GetKeyUp(KeyCode.Space)) { print("space key was pressed"); //GameObject instance = Instantiate(Resources.Load("model", typeof(GameObject))) as GameObject; ObjImporter importer = new ObjImporter(); Mesh meshHello = importer.ImportFile("G:\\Dropbox\\Blender\\baseball.obj"); //to get this mesh in the scene, we need an object GameObject myMesh = new GameObject("MyMesh"); myMesh.transform.position = hookObject.transform.position; //add mesh fileter to this GameObject MeshFilter mf = myMesh.AddComponent <MeshFilter>(); //set the mesh filter's mesh to our mesh mf.mesh = meshHello; //to see it, we have to add a renderer MeshRenderer mr = myMesh.AddComponent <MeshRenderer>(); mr.material = material; //Rigidbody gameObjectsRigidBody = myMesh.AddComponent<Rigidbody>(); // Add the rigidbody. //gameObjectsRigidBody.mass = 5; // Set the GO's mass to 5 via the Rigidbody. //Collider gameObjectsCollider = myMesh.AddComponent<Collider>(); } }
// import a model public void Example1() { string objString = objFile.text; GameObject importedObject = ObjImporter.Import(objString); Debug.Log("Imported the object:" + importedObject); }
public bool ImportModel(string objLocation, string textureLocation = null, Action callback = null) { if (string.IsNullOrEmpty(objLocation)) { Debug.LogWarning("[ModelEntity] objLocation not defined. Cannot import a model!"); return(false); } else { var go = new GameObject(ID); go.transform.SetParent(transform); Debug.Log("[ModelEntity] Importing a mesh."); ObjImporter.ImportMeshAsync(go, objLocation, multithreaded: false, callback: () => { ModelImported(this, new EventArg <ModelEntity>(this)); callback(); }); if (!string.IsNullOrEmpty(textureLocation)) { //TODO: check this //ObImportTexture(go, textureLocation); } return(true); } }
public void OpenObj(string path) { var obj = Instantiate(Resources.Load("GenericMesh")) as GameObject; string objString = File.ReadAllText(path); var mesh = ObjImporter.ImportMeshFromString(objString); obj.GetComponent <MeshFilter>().mesh = mesh; obj.GetComponent <MeshCollider>().sharedMesh = mesh; obj.GetComponent <MeshRenderer>().material = Resources.Load <Material>("ModelMaterial"); obj.transform.position = new Vector3(0, mesh.bounds.extents.y, 0); float max = -1; for (int i = 0; i < 3; i++) { if (mesh.bounds.extents[i] > max) { max = mesh.bounds.extents[i]; } } obj.transform.localScale *= (max / 20); var editor = obj.AddComponent <MeshEditor>(); editor.StartGroupGeneration(); editor.UpdateFaces(); ObjectManager.instance.AddObject(obj); }
/// <summary> /// Loads a mesh from an obj file, and the similarly name mat file. /// Textures are loaded in the texturefactory /// </summary> public static IMesh LoadMeshFromObj(FileInfo objFile) { var importer = new ObjImporter(); //TODO: Garbage Collector fancyness var materialFilePath = objFile.FullName.Substring(0, objFile.FullName.Length - objFile.Extension.Length) + ".mtl"; var materialFileName = objFile.Name.Substring(0, objFile.Name.Length - objFile.Extension.Length) + ".mtl"; FileStream materialFileStream = null; try { if (File.Exists(materialFilePath)) { materialFileStream = File.Open(materialFilePath, FileMode.Open, FileAccess.Read); importer.AddMaterialFileStream(materialFileName, materialFileStream); } importer.ImportObjFile(objFile.FullName); return(instance.converter.CreateMesh(importer)); } finally { if (materialFileStream != null) { materialFileStream.Close(); } materialFileStream = null; } }
public void TestOBJToRAMMeshConverter() { var c = new OBJToRAMMeshConverter(new RAMTextureFactory()); var fsMat = new FileStream(TestFiles.CrateMtl, FileMode.Open); var importer = new ObjImporter(); importer.AddMaterialFileStream("Crate01.mtl", fsMat); importer.ImportObjFile(TestFiles.CrateObj); fsMat.Close(); var mesh = c.CreateMesh(importer); importer = new ObjImporter(); importer.AddMaterialFileStream("CollisionModelBoxes001.mtl", EmbeddedFile.GetStream("MHGameWork.TheWizards.Tests.Physics.Files.CollisionModelBoxes001.mtl", "CollisionModelBoxes001.mtl")); importer.ImportObjFile(EmbeddedFile.GetStream("MHGameWork.TheWizards.Tests.Physics.Files.CollisionModelBoxes001.obj", "CollisionModelBoxes001.obj")); mesh = c.CreateMesh(importer); }
void Awake() { // save the parent GO-s pos+rot Vector3 position = transform.position; Quaternion rotation = transform.rotation; // move to the origin for combining transform.position = Vector3.zero; transform.rotation = Quaternion.identity; MeshFilter[] filters = GetComponentsInChildren <MeshFilter>(); List <CombineInstance> combine = new List <CombineInstance>(); for (int i = 0; i < filters.Length; i++) { // skip the empty parent GO if (filters[i].sharedMesh == null) { continue; } // combine submeshes for (int j = 0; j < filters[i].sharedMesh.subMeshCount; j++) { CombineInstance ci = new CombineInstance(); ci.mesh = filters[i].sharedMesh; ci.subMeshIndex = j; ci.transform = filters[i].transform.localToWorldMatrix; combine.Add(ci); } // disable child mesh GO-s filters[i].gameObject.SetActive(false); } MeshFilter filter = GetComponent <MeshFilter>(); filter.mesh = new Mesh(); filter.mesh.CombineMeshes(combine.ToArray(), true, true); // restore the parent GO-s pos+rot transform.position = position; transform.rotation = rotation; ObjExporter.MeshToFile(filter, Application.persistentDataPath + "testobj.obj"); Mesh holderMesh = new Mesh(); ObjImporter newMesh = new ObjImporter(); holderMesh = newMesh.ImportFile(Application.persistentDataPath + "testobj.obj"); MeshRenderer renderer = g1.GetComponent <MeshRenderer>(); MeshFilter filter1 = g1.GetComponent <MeshFilter>(); filter1.mesh = holderMesh; }
//Returns true if sucessfully loaded private bool LoadNodeMesh(Node node, GameObject nodeObj, string modelIdAppend = "") { string pathToObj = Config.SUNCGDataPath; if (node.type == "Room" || node.type == "Ground") { pathToObj += "room/" + this.house.id + "/" + node.modelId + modelIdAppend + ".obj"; } else if (node.type == "Object") { pathToObj += "object/" + node.modelId + "/" + node.modelId + modelIdAppend + ".obj"; } if (!File.Exists(pathToObj)) { return(false); } MeshRenderer mr = nodeObj.AddComponent <MeshRenderer>(); MeshFilter mf = nodeObj.AddComponent <MeshFilter>(); Mesh m = new ObjImporter().ImportFile(pathToObj); mf.mesh = m; //Room meshes have no materials in JSON, they may have submeshes though if (node.materials != null) { if (node.materials.Length > 0) { UnityEngine.Material[] materials = new UnityEngine.Material[node.materials.Length]; int i = 0; foreach (Material currMat in node.materials) { materials[i] = LoadMaterial(currMat); i++; } mr.materials = materials; } } else { UnityEngine.Material[] materials = new UnityEngine.Material[m.subMeshCount]; UnityEngine.Material sharedMat = new UnityEngine.Material(Shader.Find("Standard")); for (int matIndex = 0; matIndex < materials.Length; matIndex++) { materials[matIndex] = sharedMat; } mr.sharedMaterials = materials; } //Room meshes have no transform if (node.transform != null) { Vector4 column1 = new Vector4(node.transform[0], node.transform[1], node.transform[2], node.transform[3]); Vector4 column2 = new Vector4(node.transform[4], node.transform[5], node.transform[6], node.transform[7]); Vector4 column3 = new Vector4(node.transform[8], node.transform[9], node.transform[10], node.transform[11]); Vector4 column4 = new Vector4(node.transform[12], node.transform[13], node.transform[14], node.transform[15]); Matrix4x4 objToWorld = new Matrix4x4(column1, column2, column3, column4); SetTransformFromMatrix(nodeObj.transform, ref objToWorld); } return(true); }
// import a model and materials public void Example2() { string objString = objFile.text; string mtlString = mtlFile.text; GameObject importedObject = ObjImporter.Import(objString, mtlString, textures); Debug.Log("Imported the object:" + importedObject); }
public void Initialize_Initialized_MtlLibrarySetUp() { ObjImporter objImporter = new ObjImporter(); IServiceManager serviceManager = A.Fake <IServiceManager>(); objImporter.Initialize(serviceManager); Assert.NotNull(objImporter.MtlLibrary); }
public void ContentLoader_Initialized_InitWithUnityWebRequestLoader() { ObjImporter objImporter = new ObjImporter(); IServiceManager serviceManager = A.Fake <IServiceManager>(); objImporter.Initialize(serviceManager); Assert.NotNull(objImporter.ContentLoader); Assert.True(objImporter.ContentLoader.GetType() == typeof(UnityWebRequestLoader)); }
void Start() { ObjImporter newMesh = new ObjImporter(); Mesh holderMesh = newMesh.ImportFile(fileLoc); // Mesh holderMesh = FastObjImporter.Instance.ImportFile(fileLoc); MeshSaver.SaveMesh(holderMesh, meshname); }
void Start() { readThread = new Thread(new ThreadStart(ReceiveData)); readThread.IsBackground = true; readThread.Start(); objImporter = GameObject.FindObjectOfType <ObjImporter>(); num_models_imported = 0; }
/// <summary> /// Reusable function to set up the ObjImporter service and to register it at the service manager /// </summary> /// <param name="objContent">The .obj that the fake loader of the obj importer should load</param> /// <param name="mtlContent">The .mtl that the fake loader of the obj importer should load</param> /// <returns></returns> private ObjImporter SetUpObjImporter(string objContent, string mtlContent) { ObjImporter objImporter = new ObjImporter(); IServiceManager serviceManager = A.Fake <IServiceManager>(); objImporter.Initialize(serviceManager); objImporter.ContentLoader = FakeContentLoaderFactory.CreateFakeLoader(objContent); objImporter.MtlLibrary.ContentLoader = FakeContentLoaderFactory.CreateFakeLoader(mtlContent); return(objImporter); }
public static RAMMesh CreateGuildHouseMesh(OBJToRAMMeshConverter c) { ObjImporter importer; importer = new ObjImporter(); importer.AddMaterialFileStream("GuildHouse01.mtl", File.OpenRead(TestFiles.GuildHouseMtl)); importer.ImportObjFile(TestFiles.GuildHouseObj); return(c.CreateMesh(importer)); }
// Use this for initialization void Start() { target.text = "Foge"; //LoadFBX ("http://163.143.133.204/test.fbx"); var mymeshfilter = GetComponent(typeof(MeshFilter)) as MeshFilter; ObjImporter objImporter = new ObjImporter(); mymeshfilter.mesh = objImporter.ImportFile(""); }
public void ImportModel() { if (Directory.Exists(Application.dataPath) && File.Exists(Application.dataPath + "/Model.obj")) { Mesh mesh = new Mesh(); ObjImporter objImporter = new ObjImporter(); mesh = objImporter.ImportFile(Application.dataPath + "/Model.obj"); GameObject.FindGameObjectWithTag("BasicMeshes").GetComponent <CreateMesh>().CreateImportedObject(mesh); } }
/// <summary> /// Loads a mesh from a .obj file at runtime. /// </summary> /// <param name="meshPath">Mesh path relative to "plugins" BepInEx folder</param> /// <returns>Texture2D loaded, or null if invalid path</returns> public static Mesh LoadMesh(string meshPath) { string path = Path.Combine(Paths.PluginPath, meshPath); if (!File.Exists(path)) { return(null); } return(ObjImporter.ImportFile(path)); }
public void Initialize(CustomObjectSerializable serializable) { base.Initialize(serializable); data = serializable; objImporter = GameWorld.FindMeepleObjectByGuid(data.ObjImporterGuid) as ObjImporter; if (objImporter is null) { throw new Exception("objImporter is not set properly"); } SetStartVisuals(); }
public static RAMMesh CreateMeshFromObj(OBJToRAMMeshConverter c, string obj, string mtl) { var fi = new FileInfo(mtl); ObjImporter importer; importer = new ObjImporter(); importer.AddMaterialFileStream(fi.Name, File.OpenRead(mtl)); importer.ImportObjFile(obj); return(c.CreateMesh(importer)); }
public void LoadObj(string fileLocation) { Mesh holderMesh = new Mesh(); ObjImporter newMesh = new ObjImporter(); holderMesh = newMesh.ImportFile(fileLocation); MeshRenderer renderer = gameObject.AddComponent <MeshRenderer>(); MeshFilter filter = gameObject.AddComponent <MeshFilter>(); filter.mesh = holderMesh; }
// Use this for initialization void Start() { Mesh holderMesh = new Mesh(); ObjImporter newMesh = new ObjImporter(); holderMesh = newMesh.ImportFile("C:/Users/cvpa2/Desktop/ng/output.obj"); MeshRenderer renderer = gameObject.AddComponent <MeshRenderer>(); MeshFilter filter = gameObject.AddComponent <MeshFilter>(); filter.mesh = holderMesh; }
public override IEnumerator Build(Way w, MapChunkLoader mcl) { //GameObject go = new GameObject(); //go.name = "Road"; GameObject road = new GameObject(); road.name = "Road - " + w.id.ToString(); road.isStatic = true; road.transform.parent = mcl.transform; string roadPath = Application.persistentDataPath + "Assets/Resources/Objs/" + road.name + ".obj"; if (!File.Exists(roadPath)) // If the file isn't cached we calculate everything and then we cache it { Debug.Log("STARTED CREATING ROAD"); PolyLine pl = new PolyLine(w.id.ToString()); pl.SetOffset(mcl.offsetPositionX, mcl.offsetPositionZ); pl.heigth = w.height; if (w.type == WayType.Footway) { pl.material = Resources.Load("Materials/Footway Material") as Material; pl.width = 1; } if (w.type == WayType.Motorway) { pl.material = Resources.Load("Materials/Road Material") as Material; pl.width = 4; pl.lanes = 2; } if (w.type == WayType.Residential) { pl.material = Resources.Load("Materials/Road Material") as Material; pl.width = 2; } if (w.type == WayType.River) { pl.material = Resources.Load("Materials/River Material") as Material; pl.width = 8; } for (int a = 0; a < w.nodes.Count; a++) { Node n = w.nodes[a]; Vector3 position = new Vector3((float)(n.easthing - mcl.offsetPositionX), 5000, (float)(n.northing - mcl.offsetPositionZ)); float baseHeight = 0; RaycastHit hit; if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, mcl.layerMask)) { baseHeight = hit.point.y; } n.height = baseHeight; pl.Add(n); } //Closed road; mcl.StartCoroutine(pl.Close(road)); if (mcl.exportObjs) { while (road.GetComponent<MeshFilter>() == null) { yield return null; } MeshFilter mf = road.GetComponent<MeshFilter>(); ObjExporter oe = new ObjExporter(); oe.MeshToFile(mf, roadPath); } } else { ObjImporter oi = new ObjImporter(); mcl.StartCoroutine(oi.FileToMesh("file://" + roadPath)); while (oi._myMesh == null) { yield return null; } MeshFilter mf = road.AddComponent<MeshFilter>(); MeshRenderer mr = road.AddComponent<MeshRenderer>(); mf.sharedMesh = oi._myMesh; Debug.LogWarning("Loaded Road from cache " + roadPath); if (w.type == WayType.Footway) { mr.material = Resources.Load("Materials/Footway Material") as Material; } if (w.type == WayType.Motorway) { mr.material = Resources.Load("Materials/Road Material") as Material; } if (w.type == WayType.Residential) { mr.material = Resources.Load("Materials/Road Material") as Material; } if (w.type == WayType.River) { mr.material = Resources.Load("Materials/River Material") as Material; } } }
// Use this for initialization IEnumerator Start() { Loom.Current.GetComponent<Loom>(); layerMask = 1 << 8; wayList = new List<long>(); //StartCoroutine(LoadChunk(-8.6f,41.1767f,-8.55f,41.1923f)); MapChunkLoader.precision = GeoUTMConverter.Precision; GeoUTMConverter latlon2Utm = new GeoUTMConverter(); latlon2Utm.ToUTM((minimumLat+maximumLat)/2f,(minimumLon+maximumLon)/2f); transform.position = new Vector3(((float)latlon2Utm.X - offsetPositionX), -0.1f, ((float)latlon2Utm.Y - offsetPositionZ)); GameObject floor = new GameObject(); floor.name = "Ground"; floor.isStatic = true; CreateGround cg = new CreateGround(); cg.maxLat = maximumLat + 0.01f * (maximumLat - minimumLat); //0.0001f; cg.maxLon = maximumLon + 0.01f * (maximumLat - minimumLat); cg.minLat = minimumLat - 0.01f * (maximumLat - minimumLat); cg.minLon = minimumLon - 0.01f * (maximumLat - minimumLat); cg.numberOfDivisions = numberOfDivisions; MeshFilter mf = floor.AddComponent<MeshFilter>(); MeshRenderer mr = floor.AddComponent<MeshRenderer>(); mr.material = groundMaterial; floor.transform.position = transform.position; floor.transform.parent = transform; floor.layer = LayerMask.NameToLayer("RayCast"); string floorPath = Application.persistentDataPath + "Assets/Resources/Objs/" + cg.maxLat + "I" + cg.maxLon + ".obj"; if (!File.Exists(floorPath)) // If the file isn't cached we calculate everything and then we cache it { mf.sharedMesh = cg.GetGroundMesh(); if (exportObjs) { ObjExporter oe = new ObjExporter(); oe.MeshToFile(mf, floorPath); } } else { ObjImporter oi = new ObjImporter(); StartCoroutine(oi.FileToMesh("file://" + floorPath)); while (oi._myMesh == null) { yield return null; } mf.sharedMesh = oi._myMesh; Debug.LogWarning("Loaded Ground Chunk from cache"); } //Texture2D t = new Texture2D(1024, 1024); MapTexture mt = new MapTexture(); mt.getTexture(cg.minLon.ToString(), cg.minLat.ToString(), cg.maxLon.ToString(), cg.maxLat.ToString(),Application.persistentDataPath,mr.material); while (mt.texture == null) { yield return null; } //t.LoadImage(mt.ReadFully(mt.mq_dataStream)); //mr.material.SetTexture("_MainTex", t); MeshCollider m = floor.AddComponent<MeshCollider>(); Loom l = Loom.Current; LoadChunk(minimumLon, minimumLat, maximumLon, maximumLat); //StartCoroutine(); }
public override IEnumerator Build(Way w, MapChunkLoader mcl) { //CreateBuilding(Way w) Mesh roofm = new Mesh(); Mesh wallsm = new Mesh(); GameObject build = new GameObject(); build.name = "Building - " + w.id.ToString(); build.transform.parent = mcl.transform; GameObject roof = new GameObject(); //roof.transform.position = new Vector3(0,baseHeight,0); roof.name = "Roof - " +(2 * w.id).ToString(); mcl.mapManager.mapHash.Add(2 * w.id); mcl.wayList.Add(2 * w.id); GameObject walls = new GameObject(); walls.name = "Walls - " + (3 * w.id).ToString(); //walls.transform.position = new Vector3(0,baseHeight,0); mcl.mapManager.mapHash.Add(3 * w.id); mcl.wayList.Add(3 * w.id); walls.AddComponent<MeshCollider>(); walls.AddComponent(typeof(MeshRenderer)); MeshFilter filter = walls.AddComponent(typeof(MeshFilter)) as MeshFilter; roof.AddComponent<MeshCollider>(); roof.AddComponent(typeof(MeshRenderer)); MeshFilter filter2 = roof.AddComponent(typeof(MeshFilter)) as MeshFilter; string buildPath = Application.persistentDataPath + "Assets/Resources/Objs/" + build.name + ".obj"; string roofPath = Application.persistentDataPath+"Assets/Resources/Objs/" + roof.name + ".obj"; if (!File.Exists(buildPath) && !File.Exists(roofPath)) // If the file isn't cached we calculate everything and then we cache it { Vector3[] nodes = new Vector3[w.nodes.Count]; Vector2[] xz = new Vector2[w.nodes.Count]; float height = (float)w.nodes[0].northing % referenceVariationHeight + referenceBaseHeight; if (w.height != 0) { height = w.height; referenceVariationHeight = Mathf.Abs(referenceVariationHeight - height); referenceBaseHeight = (referenceBaseHeight + height) / 2; } Vector3 centroid = new Vector3(); Vector3 position; RaycastHit hit; for (int a = 0; a < w.nodes.Count; a++) { yield return null; Node n = w.nodes[a]; position = new Vector3((float)((n.easthing - mcl.offsetPositionX) / MapChunkLoader.precision), 5000, (float)((n.northing - mcl.offsetPositionZ) / MapChunkLoader.precision)); float castH = 0; if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, mcl.layerMask)) { castH = hit.point.y; } nodes[a] = new Vector3(position.x, castH + height, position.z); xz[a] = new Vector2(position.x, position.z); centroid += nodes[a]; } centroid /= w.nodes.Count; centroid.y += 1; Vector2[] xzRoof = new Vector2[w.nodes.Count -1]; for (int a = 0; a < xzRoof.Length; a++) { xzRoof[a] = xz[a]; } int[] indices; Vector3[] roofNodes; if (nodes.Length != 5 && nodes.Length != 6 && nodes.Length != 7 && nodes.Length != 8) { Triangulator tr = new Triangulator(xzRoof); int[] tempIndices = tr.Triangulate(); indices = tempIndices; roofNodes = nodes; } else { int[] tempIndices = new int[(nodes.Length-1)*3]; Vector3 midpoint = new Vector3(); for (int i = 0; i < nodes.Length-1; i++) { midpoint.x += nodes[i].x; midpoint.y += nodes[i].y; midpoint.z += nodes[i].z; } roofNodes = new Vector3[nodes.Length]; midpoint.x = midpoint.x / (nodes.Length-1); midpoint.y = midpoint.y / (nodes.Length - 1) + height/5; midpoint.z = midpoint.z / (nodes.Length - 1); for (int i = 0; i < roofNodes.Length - 1; i++) { roofNodes[i] = nodes[i]; } roofNodes[roofNodes.Length - 1] = midpoint; Triangle test = new Triangle(); test.a = roofNodes[0]; test.b = roofNodes[1]; test.c = roofNodes[4]; Vector3 testVector = test.Normal; int u = 0; for (int i = 0; i < roofNodes.Length - 2; i += 1) { if (testVector.y > 0) { tempIndices[u] = i; tempIndices[u + 1] = i + 1; tempIndices[u + 2] = roofNodes.Length - 1; } else { tempIndices[u + 1] = i; tempIndices[u] = i + 1; tempIndices[u + 2] = roofNodes.Length - 1; } u += 3; if (u >= tempIndices.Length - 3) { i += 1; if (testVector.y > 0) { tempIndices[u] = i; tempIndices[u + 1] = 0; tempIndices[u + 2] = roofNodes.Length - 1; } else { tempIndices[u + 1] = i; tempIndices[u] = 0; tempIndices[u + 2] = roofNodes.Length - 1; } } } indices = tempIndices; } // Create the mesh Vector2[] uvs = new Vector2[roofNodes.Length]; for (int a = 0; a < roofNodes.Length; a++) { if (a < roofNodes.Length - 1) { uvs[a] = new Vector2(a,0); } else { uvs[a] = new Vector2(a/2, 1); } } roofm.vertices = roofNodes; roofm.triangles = indices; roofm.uv = uvs; roofm.RecalculateNormals(); roofm.RecalculateBounds(); // Set up game object with mesh; centroid = new Vector3(centroid.x, centroid.y, centroid.z); wallsm = BuildingCountourMesh(nodes, wallsm, height); if (w.name != null) { GameObject label = new GameObject(); FloatingLabel lb = label.AddComponent<FloatingLabel>(); lb.transform.parent = roof.transform; lb.text = w.name; lb.target = GameObject.FindGameObjectWithTag("Player").transform; lb.transform.position = centroid; } build.transform.parent = mcl.transform; walls.transform.parent = build.transform; roof.transform.parent = build.transform; //Wall filter.sharedMesh = wallsm; // wallmc.sharedMesh = wallsm; //Roof filter2.sharedMesh = roofm; //roofmc.sharedMesh = roofm; if (mcl.exportObjs) { ObjExporter oe1 = new ObjExporter(); ObjExporter oe2 = new ObjExporter(); oe1.MeshToFile(filter, buildPath); oe2.MeshToFile(filter2, roofPath); } } else { ObjImporter oi = new ObjImporter(); mcl.StartCoroutine(oi.FileToMesh("file://" + buildPath)); while (oi._myMesh == null) { yield return null; } filter.sharedMesh = oi._myMesh; Debug.LogWarning("Loaded Walls from cache " + buildPath); ObjImporter oi2 = new ObjImporter(); mcl.StartCoroutine(oi2.FileToMesh("file://" + roofPath)); while (oi2._myMesh == null) { yield return null; } filter2.sharedMesh = oi2._myMesh; Debug.LogWarning("Loaded Roof from cache " + roofPath); } /*if (w.height != 0) { walls.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Real Height Material") as Material; } else*/ { int textureIndex = UnityEngine.Random.Range(1,4); walls.GetComponent<MeshRenderer>().material = Resources.Load("Materials/BuildingMaterial" + textureIndex) as Material; } /*if (w.height != 0) { roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Real Height Material") as Material; } else*/ { int textureIndex = UnityEngine.Random.Range(1, 3); roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Roof" + textureIndex) as Material; } }
public override IEnumerator Build(Way w, MapChunkLoader mcl) { Vector3[] nodes = new Vector3[w.nodes.Count]; Vector2[] xz = new Vector2[w.nodes.Count]; float height = 0; mcl.mapManager.mapHash.Add(w.id); mcl.wayList.Add(w.id); GameObject roof = new GameObject(); // roof.transform.position = new Vector3(0, centroid.y, 0); roof.name = "Area - " + (2 * w.id).ToString(); mcl.mapManager.mapHash.Add(2 * w.id); mcl.wayList.Add(2 * w.id); roof.isStatic = true; if (w.name != null) { GameObject label = new GameObject(); FloatingLabel lb = label.AddComponent<FloatingLabel>(); lb.text = w.name; //lb.transform.position = centroid; lb.target = GameObject.FindGameObjectWithTag("Player").transform; label.transform.parent = roof.transform; } roof.transform.parent = mcl.transform; Mesh roofm = new Mesh(); roof.AddComponent<MeshRenderer>(); MeshFilter filter2 = roof.AddComponent<MeshFilter>(); roof.AddComponent<MeshCollider>(); string areaPath = Application.persistentDataPath + "Assets/Resources/Objs/" + roof.name + ".obj"; if (!File.Exists(areaPath)) // If the file isn't cached we calculate everything and then we cache it { if (w.height != 0) height = w.height; Vector3 centroid = new Vector3(); for (int a = 0; a < w.nodes.Count; a++) { yield return null; RaycastHit hit; Node n = w.nodes[a]; nodes[a] = new Vector3((float)((n.easthing - mcl.offsetPositionX) / MapChunkLoader.precision), 5000, (float)((n.northing - mcl.offsetPositionZ) / MapChunkLoader.precision)); if (Physics.Raycast(nodes[a], -Vector3.up, out hit, Mathf.Infinity, mcl.layerMask)) { nodes[a].y = hit.point.y + height + 0.5f; } else { nodes[a].y = 1; } xz[a] = new Vector2((float)((n.easthing - mcl.offsetPositionX) / MapChunkLoader.precision), (float)((n.northing - mcl.offsetPositionZ) / MapChunkLoader.precision)); centroid += nodes[a]; } centroid /= w.nodes.Count; centroid.y += 1; // Vector3 position = new Vector3(centroid.x, 5000, centroid.z); float baseHeight = 0; /*RaycastHit hit; if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, layerMask)) { baseHeight = hit.point.y; }*/ //centroid = new Vector3(centroid.x, centroid.y + baseHeight, centroid.z); Vector2[] xzRoof = new Vector2[w.nodes.Count - 1]; for (int a = 0; a < xzRoof.Length; a++) { xzRoof[a] = xz[a]; } Triangulator tr = new Triangulator(xzRoof); int[] indices = tr.Triangulate(); // Create the mesh roofm.vertices = nodes; roofm.triangles = indices; Vector2[] uvs = new Vector2[nodes.Length]; for (int a = 0; a < nodes.Length; a++) { if (a < nodes.Length - 1) { uvs[a] = new Vector2(Mathf.Abs(nodes[a].x) / nodes[nodes.Length - 1].x, Mathf.Abs(nodes[a].z) / nodes[nodes.Length - 1].x); } else { uvs[a] = new Vector2(1, 1); } } roofm.uv = uvs; roofm.RecalculateNormals(); roofm.RecalculateBounds(); filter2.sharedMesh = roofm; if (mcl.exportObjs) { ObjExporter oe = new ObjExporter(); oe.MeshToFile(filter2, areaPath); } } else { ObjImporter oi = new ObjImporter(); mcl.StartCoroutine(oi.FileToMesh("file://" + areaPath)); while (oi._myMesh == null) { yield return null; } filter2.sharedMesh = oi._myMesh; Debug.LogWarning("Loaded Area from cache " + areaPath); } if (w.type == WayType.Parking) roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Parking Material") as Material; if (w.type == WayType.Park) roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Park Material") as Material; if (w.type == WayType.RiverBank) roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/River Material") as Material; }