Inheritance: MonoBehaviour
示例#1
0
    void LoadAsset()
    {
        if (!string.IsNullOrEmpty(OBJUrl))
        {
            Destroy(loadedOBJGameObject);

            asyncOp = Environment.i.platform.webRequest.Get(
                url: OBJUrl,
                OnSuccess: (webRequestResult) =>
            {
                loadedOBJGameObject      = OBJLoader.LoadOBJFile(webRequestResult.downloadHandler.text, true);
                loadedOBJGameObject.name = "LoadedOBJ";
                loadedOBJGameObject.transform.SetParent(transform);
                loadedOBJGameObject.transform.localPosition = Vector3.zero;

                OnFinishedLoadingAsset?.Invoke();
                alreadyLoadedAsset = true;
            },
                OnFail: (webRequestResult) =>
            {
                Debug.Log("Couldn't get OBJ, error: " + webRequestResult.error + " ... " + OBJUrl);
            });
        }
        else
        {
            Debug.Log("couldn't load OBJ because url is empty");
        }

        if (loadingPlaceholder != null)
        {
            loadingPlaceholder.SetActive(false);
        }
    }
示例#2
0
        public Entity(string objectFileName = null, string textureFileName = null, string ext = ".png")
        {
            var      vertex   = OBJLoader.LoadOBJModel(objectFileName);
            RawModel rawModel = Loader.LoadToVAO(vertex, objectFileName);

            model = new TexturedModel(rawModel, Loader.LoadTexture(textureFileName, ext));
        }
示例#3
0
        public Dictionary <string, int> GetMaterialsList(string fileName)
        {
            Dictionary <string, ModelBase.MaterialDef> materials = new Dictionary <string, ModelBase.MaterialDef>();
            string modelFormat = fileName.Substring(fileName.Length - 3, 3).ToLower();

            switch (modelFormat)
            {
            case "obj":
                materials = new OBJLoader(fileName).GetModelMaterials();
                break;

            case "dae":
                materials = new DAELoader(fileName).GetModelMaterials();
                break;

            case "imd":
                materials = new NITROIntermediateModelDataLoader(fileName).GetModelMaterials();
                break;

            default:
                materials = new OBJLoader(fileName).GetModelMaterials();
                break;
            }

            Dictionary <string, int> matColTypes = new Dictionary <string, int>();

            foreach (string key in materials.Keys)
            {
                matColTypes.Add(key, 0);
            }

            return(matColTypes);
        }
示例#4
0
    // To be called by an external function. Loads an obj from a file path.
    public string OnLoadClicked(string objPath)
    {
        if (!File.Exists(objPath))
        {
            PopMessagePanel("Path doesn't exist.");
            return("File doesn't exist.");
        }

        // Remove any existing previously loaded models
        if (editTarget.transform.childCount > 0)
        {
            foreach (Transform child in editTarget.transform)
            {
                GameObject.Destroy(child.gameObject);
            }
            ResetEditTarget();
        }

        GameObject loadedObject = new OBJLoader().Load(objPath);

        loadedObject.transform.parent   = editTarget.transform;
        editTarget.transform.localScale = new Vector3(initialScale, initialScale, initialScale);
        DontDestroyOnLoad(editTarget); // Keeps loaded object passed onto edit scene.

        editMeshButton.interactable = true;


        PopMessagePanel("Load completed!");
        return("Load completed!");
    }
示例#5
0
    public bool AddTypeElement(System.Xml.Linq.XElement elemtype)
    {
        XAttribute fileAtt = elemtype.Attribute("file");

        if (fileAtt == null)
        {
            //Add error message here
            return(false);
        }
        string filePath = Path.Combine(Path.GetDirectoryName(new Uri(elemtype.BaseUri).LocalPath), fileAtt.Value);

        filePath = Path.GetFullPath(filePath);

        //	Load the OBJ in
        var lStream  = new FileStream(filePath, FileMode.Open);
        var lOBJData = OBJLoader.LoadOBJ(lStream);

        lStream.Close();
        mesh = new Mesh[(int)MeshLayer.Count];
        for (int i = 0; i < mesh.Length; i++)
        {
            mesh[i] = new Mesh();
            mesh[i].LoadOBJ(lOBJData, ((MeshLayer)i).ToString());
        }
        lStream  = null;
        lOBJData = null;
        return(true);
    }
示例#6
0
        static Scene Test2()
        {
            Scene scene = new Scene();

            MashTrigle[] objs;
            MashTrigle   obj;

            objs = OBJLoader.LoadModel("A:\\t2.obj");
            obj  = objs[0];
            //obj.Material.Metallic.Metallic = 0.3f;
            obj.Material.Roughness = 0.8f;
            //obj.Material.BaseColor = new PureColorMaterialMap(new Color(0.95f, 0.95f, 0.95f));
            scene.Objects.Add(obj);

            PointLight pLight1 = new PointLight()
            {
                Position = new Vector3f(-5, 5, 0),
                R        = 0.2f,
            };

            pLight1.Material.Light.Intensity = new RGBSpectrum(200.0f, 10.0f, 10.0f);
            PointLight pLight2 = new PointLight()
            {
                Position = new Vector3f(5, 5, -1),
                R        = 0.2f,
            };

            pLight2.Material.Light.Intensity = new RGBSpectrum(10.0f, 10.0f, 200.0f);
            //scene.LightObjects.Add(pLight1);
            //scene.LightObjects.Add(pLight2);
            scene.Objects.Add(pLight1);
            scene.Objects.Add(pLight2);

            return(scene);
        }
        public GameObject[] LoadColliderObjs(string dirPath)
        {
            isAllColliderReady = false;

            List <GameObject> outputObjs = new List <GameObject>();
            DirectoryInfo     dir        = new DirectoryInfo(dirPath);

            if (!dir.Exists)
            {
                Debug.Log(dirPath + " does not exist.");
            }
            else
            {
                FileInfo[] files = dir.GetFiles("*_cld.obj");
                for (int i = 0; i < files.Length; i++)
                {
                    FileInfo file     = files[i];
                    string   filePath = dirPath + "/" + file.Name;
                    Debug.Log(filePath);

                    GameObject go = OBJLoader.LoadOBJFile(filePath, LoadColliderDoneCallBack);
                    go.SetActive(false);
                    outputObjs.Add(go);
                }
            }
            return(outputObjs.ToArray());
        }
示例#8
0
        public override void Initialize(int width, int height)
        {
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);
            GL.Enable(EnableCap.Lighting);
            GL.Enable(EnableCap.Light0);

            GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);

            GL.Light(LightName.Light0, LightParameter.Position, new float[] { 0.0f, 0.5f, 0.5f, 0.0f });
            GL.Light(LightName.Light0, LightParameter.Ambient, new float[] { 0f, 1f, 0f, 1f });
            GL.Light(LightName.Light0, LightParameter.Diffuse, new float[] { 0f, 1f, 0f, 1f });
            GL.Light(LightName.Light0, LightParameter.Specular, new float[] { 1f, 1f, 1f, 1f });

            loader  = new OBJLoader("Assets/suzanne.obj");
            objs[0] = new OBJ(loader);
            objs[1] = new OBJ(loader);
            objs[2] = new OBJ(loader);

            objs[0].Scale = new Vector3(3.0f, 3.0f, 3.0f);

            objs[1].Position = new Vector3(6.0f, 6.0f, 6.0f);
            objs[1].Scale    = new Vector3(1.5f, 1.5f, 1.5f);

            objs[2].Position = new Vector3(-6.0f, -6.0f, -6.0f);
            objs[1].Scale    = new Vector3(1.5f, 1.5f, 1.5f);
            objs[2].Rotation = new Vector3(90.0f, 0.0f, 0.0f);
        }
示例#9
0
    public static void LoadData()
    {
        string jsonText = File.ReadAllText(Application.streamingAssetsPath + "/ModelShapes.json");

        var jsonDict = MiniJSON.Json.Deserialize(jsonText) as Dictionary <string, object>;
        var data     = jsonDict["data"] as List <object>;

        palette = new ModelShape[data.Count];
        table   = new Dictionary <string, ModelShape>();

        for (int i = 0; i < data.Count; i++)
        {
            var shape = data[i] as Dictionary <string, object>;

            string name        = (string)shape["name"];
            string path        = (string)shape["path"];
            string displayName = shape.ContainsKey("displayName") ? (string)shape["displayName"] : name;
            float  scale       = shape.ContainsKey("scale") ? (float)(double)shape["scale"] : 1.0f;
            float  offsetY     = shape.ContainsKey("offsetY") ? (float)(double)shape["offsetY"] : 0.0f;
            bool   enterable   = shape.ContainsKey("enterable") ? (bool)shape["enterable"] : false;

            var model = OBJLoader.LoadModel(Application.streamingAssetsPath + "/ObjectModels/" + path);
            if (model != null)
            {
                palette[i] = new ModelShape(name, displayName, model, new Vector3(0.0f, offsetY, 0.0f), scale, enterable);
                table.Add(name, palette[i]);
                ModelPalette.Instance.AddModel(name, displayName);
            }
        }
    }
示例#10
0
    private GameObject downloadObj()
    {
        print("Downloading files");

        using (var client = new System.Net.WebClient())
        {
            try {
                client.DownloadFile("http://" + DownloadLink + ":8000/random/arrow_color.obj", @"C:\Users\kone6\Documents\Office\Assets\" + name + ".obj");
                client.DownloadFile("http://" + DownloadLink + ":8000/random/arrow_color.obj", @"C:\Users\kone6\Documents\Office\Assets\" + name + ".mtl");

                //				client.DownloadFile("http://192.168.1.84:8000/random/arrow_color.obj", @"C:\Users\kone6\Documents\Office\Assets\arrow_color.obj");
//				client.DownloadFile("http://192.168.1.84:8000/random/arrow_color.mtl", @"C:\Users\kone6\Documents\Office\Assets\arrow_color.mtl");
            } catch (Exception e) {
                print("Problem downloading obj: " + e.ToString());
            }
        }

//		GameObject cuube = OBJLoader.LoadOBJFile(@"C:\Users\kone6\Documents\cube.obj");
        GameObject cuube = OBJLoader.LoadOBJFile(@"C:\Users\kone6\" + name + ".obj");

        cuube.name = name;         // rename the object

        print("Object loaded");
        return(cuube);
    }
示例#11
0
    public void ImportObjModel()
    {
        Debug.Log("Initalizing obj model: " + Path);
        GameObject objGameObject = OBJLoader.LoadOBJFile(Path);

        Material[] materials = OBJLoader.LoadMTLFile(Path);
    }
示例#12
0
    public void SaveObj()
    {
        SDMesh sdMesh = FindObjectOfType <SDMesh>();

        MeshFilter[]      meshFilters = sdMesh.GetComponentsInChildren <MeshFilter>();
        CombineInstance[] combine     = new CombineInstance[meshFilters.Length];
        int i = 0;

        while (i < meshFilters.Length)
        {
            combine[i].mesh      = meshFilters[i].sharedMesh;
            combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
            i++;
        }
        Mesh combinedMesh = new Mesh();

        combinedMesh.CombineMeshes(combine);

        OBJData data     = combinedMesh.EncodeOBJ();
        string  filepath = Application.persistentDataPath + "/Obj_"
                           + UnityEngine.Random.Range(0, 10000) + ".obj";
        var lStream = new FileStream(filepath, FileMode.Create);

        OBJLoader.ExportOBJ(data, lStream);
        lStream.Close();
    }
示例#13
0
    async Task ReadObjectDataAsync(String key, String bucketName, IAmazonS3 client)
    {
        try
        {
            GetObjectRequest request = new GetObjectRequest
            {
                BucketName = bucketName,
                Key        = key
            };



            using (GetObjectResponse response = await client.GetObjectAsync(request))
                using (Stream responseStream = response.ResponseStream)
                {
                    if (response.ResponseStream != null)
                    {
                        var stream = new MemoryStream();
                        await responseStream.CopyToAsync(stream);

                        stream.Position = 0;
                        var loadedObj = new OBJLoader().Load(stream);
                    }
                }
        }
        catch (AmazonS3Exception e)
        {
            Debug.Log("Error encountered ***. Message:'{0}' when writing an object " + e.Message);
        }
        catch (Exception e)
        {
            Debug.Log("Unknown encountered on server. Message:'{0}' when writing an object " + e.Message);
        }
    }
    private void AddObj(string fileName)
    {
        // Loading the obj and mtl files
        string[] splitString      = fileName.Split('/');
        string[] nameAndExtension = splitString[splitString.Length - 1].Split('.');
        splitString = splitString.Take(splitString.Length - 1).ToArray();
        string mltFilePath = splitString + nameAndExtension[0] + ".mtl";

        var loadedObj = new OBJLoader().Load(fileName);

        // Set previously selected model inactive
        nailModels[selectedNailIndex].SetActive(false);

        // Adding obj's name to dropdown list
        nailModelNames[nailCount - 1] = fileName;
        selectedNailIndex             = nailCount - 1;
        nailModelNames.Add("Browse...");
        nailCount++;
        nailDropdown.options.Clear();
        nailDropdown.AddOptions(nailModelNames);
        nailDropdown.SetValueWithoutNotify(selectedNailIndex);

        // Transform the obj to the correct position on screen
        loadedObj.transform.SetParent(GameObject.FindGameObjectWithTag("GroundPlane").transform, true);
        loadedObj.transform.localPosition = new Vector3(0, 1, 0);
        selectedNailModel = loadedObj;
        nailModels.Add(loadedObj);
    }
示例#15
0
    void beginFromObj()
    {
        string s          = objName.text;
        string directory  = System.IO.Directory.GetCurrentDirectory();
        Mesh   importMesh = new Mesh();
        string filePath   = directory + "/" + s + ".obj";

        buildDebug.text = filePath;
        if (File.Exists(filePath))
        {
            importMesh = new OBJLoader().Load(filePath).GetComponentInChildren <MeshFilter>().mesh;
            Destroy(GameObject.Find(s));
            float     distSample = 2f / Vector3.Distance(importMesh.vertices[importMesh.triangles[0]], importMesh.vertices[importMesh.triangles[1]]);
            Vector3[] vertices   = new Vector3[importMesh.vertices.Length];
            for (int i = 0; i < vertices.Length; i++)
            {
                vertices[i] = importMesh.vertices[i] * distSample;
            }
            importMesh.vertices = vertices;
            slowSetupPoly(.2f, importMesh);
        }
        else
        {
            Debug.Log("File DNE!");
            buildDebug.text += " FileDNE!";
        }
    }
示例#16
0
    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            GameObject line = new GameObject();
            line.transform.parent = collection.transform;
            m_MeshFilter          = line.AddComponent <MeshFilter>();
            line.AddComponent <MeshRenderer>();
            curLine = line.AddComponent <MeshLineRenderer>();

            curLine.setWidth(0.05f);
        }
        if (Input.GetButton("Fire1"))
        {
            curLine.AddPoint(place.transform.position);
        }

        if (Input.GetButtonUp("Fire1"))
        {
            var lStream  = new FileStream("C:/Users/apappu/Documents/NoBillBoardLines/Assets/line.obj", FileMode.Create);
            var lOBJData = m_MeshFilter.sharedMesh.EncodeOBJ();
            OBJLoader.ExportOBJ(lOBJData, lStream);
            lStream.Close();
        }
    }
    //------------------------------------------------------------------------------------------------------------
    private void OnGUI()
    {
        m_MeshFilter = (MeshFilter)EditorGUILayout.ObjectField("MeshFilter", m_MeshFilter, typeof(MeshFilter), true);

        if (m_MeshFilter != null)
        {
            if (GUILayout.Button("Export OBJ"))
            {
                var lOutputPath = EditorUtility.SaveFilePanel("Save Mesh as OBJ", "", m_MeshFilter.name + ".obj", "obj");

                if (File.Exists(lOutputPath))
                {
                    File.Delete(lOutputPath);
                }

                var lStream  = new FileStream(lOutputPath, FileMode.Create);
                var lOBJData = m_MeshFilter.sharedMesh.EncodeOBJ();
                OBJLoader.ExportOBJ(lOBJData, lStream);
                lStream.Close();
            }
        }
        else
        {
            GUILayout.Label("Please provide a MeshFilter");
        }
    }
示例#18
0
        public override void Initialize(int width, int height)
        {
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);
            GL.Enable(EnableCap.Lighting);
            GL.Enable(EnableCap.Light0);

            GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);

            GL.Light(LightName.Light0, LightParameter.Position, new float[] { 0.0f, 0.5f, 0.5f, 0.0f });
            GL.Light(LightName.Light0, LightParameter.Ambient, new float[] { 0f, 1f, 0f, 1f });
            GL.Light(LightName.Light0, LightParameter.Diffuse, new float[] { 0f, 1f, 0f, 1f });
            GL.Light(LightName.Light0, LightParameter.Specular, new float[] { 1f, 1f, 1f, 1f });

            obj = new OBJLoader("Assets/suzanne.obj");

            if (obj.NumCollisionTriangles != 968)
            {
                LogError("Suzanne triangle count expected at 968, got: " + obj.NumCollisionTriangles);
            }
            AABB test = new AABB(new Point(-1.367188f, -0.984375f, -0.851562f), new Point(1.367188f, 0.984375f, 0.851562f));

            if (!AlmostEqual(test, obj.BoundingBox))
            {
                LogError("Expected bounting box:\n" + test.ToString() + "\n Got bounding box: \n" + obj.BoundingBox.ToString());
            }
        }
    public void ExportWheelsForOther()
    {
        //Get the mesh filter component from the car model
        MeshFilter meshFilter = GameObject.Find("Wheels").GetComponent <MeshFilter> ();

        //Open the [Save as..] panel from your OS
        var path = EditorUtility.SaveFilePanel("Save as .obj", "Assets/", meshFilter.name + id + ".obj", "obj");

        //Stop errors from happening if the user cancels the save process
        if (string.IsNullOrEmpty(path))
        {
            return;
        }

        //Create a file stream that will take the path from the OS and open in create mode
        FileStream fileStream = new FileStream(path, FileMode.Create);

        //The obj data contained resulting from the encode obj function
        OBJData objData = meshFilter.sharedMesh.EncodeOBJ();

        //Calling the export obj function taking the obj data and the file stream and close it
        OBJLoader.ExportOBJ(objData, fileStream);
        fileStream.Close();

        //Display some comfirmation text to the screen then call the ienumerator
        successObj.SetActive(true);
        StartCoroutine(HideTextAfterTime(3.0f));
    }
示例#20
0
    /// <summary>
    ///  Subir obj
    /// </summary>
    /// <param name="ruta"></param>
    /// <returns>Carga un OBJ en la escena</returns>
    IEnumerator obj(string ruta)
    {
        WWW www = new WWW("file:///" + ruta);

        yield return(www);

        if (ruta != null)
        {
            // Destruye cualquier elemento hijo del contenedor de modelos 3d
            if (objeto.transform.childCount >= 1)
            {
                Transform c = objeto.transform.GetChild(0);
                c.parent = c;
                Destroy(c.gameObject);
            }
            // Función encargada decargar el OBJ
            OBJLoader.LoadOBJFile(ruta);
            var rendererComponents = objeto.GetComponentsInChildren <Renderer>(true);
            foreach (var component in rendererComponents)
            {
                component.enabled = false;
            }
            Cambiar_Enlazado.objeto.transform.localPosition = new Vector3(0, 0, 0);
            Cambiar_Enlazado.objeto.transform.localScale    = new Vector3(1, 1, 1);
            Cambiar_Enlazado.objeto.transform.localRotation = Quaternion.Euler(90, 0, 0);
        }
    }
        public static void DumpObj(this Mesh mesh, string name)
        {
            string path = GetFilePath(mesh.name, ".obj");

            using (var fs = new FileStream(path, FileMode.Create))
                OBJLoader.ExportOBJ(mesh.EncodeOBJ(), fs);
        }
示例#22
0
    public void TaskOnClickFile()
    {
        path       = EditorUtility.OpenFilePanel("Choose your .obj file", "", "obj");                     // Opens the dialog window to choose the .obj file
        loadedFile = OBJLoader.LoadOBJFile(path);                                                         // loaded object is stored in loadedfile
        loadedFile.transform.position = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 50.0f)); // it is placed in center of the viewport

//		path_mat = EditorUtility.OpenFilePanel ("Choose the Material (.mtl) file", "", "mtl");
//		loadedFile.GetComponent<Renderer> ().material = fOBJLoader.LoadMTLFile (path_mat) as Material;

        childObj = loadedFile.gameObject.transform.GetChild(0).gameObject;                                         // retrives the childobject (the mesh object) from the parent(empty gameobject) object

        childObj.AddComponent <Rigidbody> ().isKinematic = true;                                                   // Rigidbody is added simulatneously kinematic is set true
        childObj.AddComponent <BoxCollider> ().isTrigger = true;                                                   // BoxCollider is added simulatneously trigger is set true

        if (!listGoName.Contains(loadedFile.name))                                                                 // checks and enters the loop if the list listGoName doesn't contains the loaded file
        {
            namBut   = Instantiate(nameButton, nameContentPanel.transform);                                        // instantiates the nameButton with its corresponding transform
            fileName = loadedFile.name;                                                                            // the loaded file name is stored in fileName variable
            namBut.GetComponentInChildren <Text> ().text = fileName;                                               // this fileName is displayed in text filed of the namBut Button
            namBut.transform.Find("Button_total").gameObject.GetComponentInChildren <Text> ().text = 1.ToString(); // the Button_total text field is set to 1 by default
            listGoName.Add(loadedFile.name);                                                                       // the loadedfile name is added to the list listGoName
            childObj.AddComponent <Manip_Imports> ();                                                              // Manip_Imports is added to the childObject
            childObj.AddComponent <TextureLoader> ();                                                              //TextureLoader script is added to the childObject ***but its not working***
        }

        else if (listGoName.Contains(loadedFile.name)) // checks and enters the loop if the list listGoName contains the loaded file
        {
            Debug.Log("file already exists");          // displays the error
            Destroy(loadedFile);                       // loaded file is destroyed
        }
    }
示例#23
0
        public override void Initialize(int width, int height)
        {
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.Lighting);
            GL.Enable(EnableCap.Light0);
            GL.PointSize(5f);

            GL.Light(LightName.Light0, LightParameter.Position, new float[] { 0.5f, -0.5f, 0.5f, 0.0f });
            GL.Light(LightName.Light0, LightParameter.Ambient, new float[] { 0f, 1f, 0f, 1f });
            GL.Light(LightName.Light0, LightParameter.Diffuse, new float[] { 0f, 1f, 0f, 1f });
            GL.Light(LightName.Light0, LightParameter.Specular, new float[] { 1f, 1f, 1f, 1f });

            scene.Initialize(7f);

            cube = new OBJLoader("Assets/cube.obj");

            // Because the debug AABB we are actually using for picking has no lighting
            // let's actually render an OBJ in the exact position of it!
            scene.RootObject.Children.Add(new OBJ(cube));
            scene.RootObject.Children[0].Parent   = scene.RootObject;
            scene.RootObject.Children[0].Position = new Vector3(3f, -7f, -1f);
            scene.RootObject.Children[0].Scale    = new Vector3(7f, 5f, 4f);

            // Gotta set the World space points of the debug AABB
            // to the same thing as the visual node!
            Matrix4 world = scene.RootObject.Children[0].WorldMatrix;

            debugBox = scene.RootObject.Children[0].BoundingBox; // TEMP
            Vector3 newMin = Matrix4.MultiplyPoint(world, debugBox.Min.ToVector());
            Vector3 newMax = Matrix4.MultiplyPoint(world, debugBox.Max.ToVector());

            // Construct the final collision box
            debugBox = new AABB(new Point(newMin), new Point(newMax));
        }
示例#24
0
    // Load and generate the map model
    void LoadMapModel()
    {
        // Parse de obj model object.
        var mapMeshGameObject = new OBJLoader().Load(_mapModelMeshPath, _mapModelMtlPath);

        var meshRenderer   = mapMeshGameObject.GetComponentInChildren <MeshRenderer>();
        var meshFilter     = mapMeshGameObject.GetComponentInChildren <MeshFilter>();
        var meshGameObject = meshRenderer.gameObject;

        // Extract the texture of the parsed mesh
        var texture = meshRenderer.material.GetTexture("_MainTex");

        // Change the material and set the texture.
        meshRenderer.material = _mapBaseMaterial;
        meshRenderer.sharedMaterial.SetTexture("_BaseMap", texture);

        // Attach the mesh to a know transform.
        mapMeshGameObject.transform.SetParent(_mapRoot.transform);

        // Generate a mesh collider using the same mesh.
        var meshCollider = meshGameObject.AddComponent <MeshCollider>();

        meshCollider.sharedMesh = meshFilter.sharedMesh;

        // Generate the border of this mesh.
        _mapBorderGenerator.GenerateBorderMesh(meshFilter.sharedMesh);
    }
示例#25
0
 void Start()
 {
     GetComponent <Button>().onClick.AddListener(() =>
     {
         string filePath = Application.persistentDataPath + '/' + mdlfilename;
         if (!File.Exists(filePath))
         {
             IIS_Core.DownloadModel(mdlfilename, s =>
             {
                 if (!File.Exists(filePath))
                 {
                     using (FileStream fs = File.Create(filePath))
                     {
                         Byte[] info = new UTF8Encoding(true).GetBytes(s);
                         fs.Write(info, 0, info.Length);
                     }
                 }
                 var obj = OBJLoader.LoadOBJFile(filePath);
                 SetupObject(obj);
             });
         }
         else
         {
             var obj = OBJLoader.LoadOBJFile(filePath);
             SetupObject(obj);
         }
     });
     markerSelectionWindow.SetActive(false);
 }
示例#26
0
    //------------------------------------------------------------------------------------------------------------
    private void Start()
    {
        //	Load the OBJ in
        var lStream     = new FileStream(INPUT_PATH, FileMode.Open);
        var lOBJData    = OBJLoader.LoadOBJ(lStream);
        var lMeshFilter = GetComponent <MeshFilter>();

        lMeshFilter.mesh.LoadOBJ(lOBJData);
        lStream.Close();

        lStream  = null;
        lOBJData = null;

        //	Wiggle Vertices in Mesh
        var lVertices = lMeshFilter.mesh.vertices;

        for (int lCount = 0; lCount < lVertices.Length; ++lCount)
        {
            lVertices[lCount] = lVertices[lCount] + Vector3.up * Mathf.Sin(lVertices[lCount].x) * 4f;
        }
        lMeshFilter.mesh.vertices = lVertices;

        //	Export the new Wiggled Mesh
        if (File.Exists(OUTPUT_PATH))
        {
            File.Delete(OUTPUT_PATH);
        }
        lStream  = new FileStream(OUTPUT_PATH, FileMode.Create);
        lOBJData = lMeshFilter.mesh.EncodeOBJ();
        OBJLoader.ExportOBJ(lOBJData, lStream);
        lStream.Close();
    }
示例#27
0
    public void Export(string meshName = "")
    {
        if (meshName.IsNullOrEmpty())
        {
            meshName = System.DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
        }

        if (!Directory.Exists(DigiClayConstant.CLAY_DATA_PATH))
        {
            Directory.CreateDirectory(DigiClayConstant.CLAY_DATA_PATH);
            Debug.Log("CLAY_DATA_PATH Directory created.");
        }


        var lStream  = new FileStream(DigiClayConstant.CLAY_DATA_PATH + meshName + ".obj", FileMode.Create);
        var lOBJData = Mesh.EncodeOBJ();

        OBJLoader.ExportOBJ(lOBJData, lStream);
        lStream.Close();
        Debug.Log("Mesh Saved.");

        AssetDatabase.Refresh();

        ClayObject co = ScriptableObject.CreateInstance <ClayObject>();

        co.ClayName  = meshName;
        co.ClayMesh  = ClayMesh;
        co.ModelFile = AssetDatabase.LoadMainAssetAtPath(DigiClayConstant.CLAY_DATA_PATH + meshName + ".obj");

        AssetDatabase.CreateAsset(co, DigiClayConstant.CLAY_DATA_PATH + meshName + " ClayData.asset");
        Debug.Log(AssetDatabase.GetAssetPath(co));

        AssetDatabase.SaveAssets();
    }
示例#28
0
    // Update is called once per frame
    void Update()
    {
        // User has picked a case via the UI
#if !UNITY_EDITOR
        if (CaseSelectionID.Length > 0 && !meshSelected)
        {
            //objFiles = CasesCatalog.Cases[0].OBJFiles;
            int idx = CasesCatalog.Cases.FindIndex(item => item.ID == CaseSelectionID);
            if (idx < 0)
            {
                return;
            }
            meshSelected = true;
            objFiles     = CasesCatalog.Cases[idx].OBJFiles;
            meshCount    = objFiles.Count;
            objFiles.ForEach(o =>
            {
                string objURL = serverURL + o.URL;
                //string objPathName = objPath + o.Name + ".obj";
                string objPathName = Path.Combine(ApplicationData.Current.LocalFolder.Path, o.Name + ".obj9");
                setupMeshFileDownload(o.Name + ".obj9", objURL);
                o.filePath = objPathName;
            });
        }


        if (meshSelected && (meshesDownloaded == meshCount) && !meshesLoaded)
        {
            objFiles.ForEach(o =>
            {
                GameObject meshObject = OBJLoader.LoadOBJFile(o.filePath);

                meshObject.transform.parent        = meshParent.transform;
                meshObject.transform.localPosition = new Vector3(0, 0, 0);
                meshObject.transform.localScale    = new Vector3(0.001f, 0.001f, 0.001f);
                string[] col = o.Colour.Split(',');
                Color color;
                if (col.Length > 3)
                {
                    color = new Color(float.Parse(col[0]) / 255, float.Parse(col[1]) / 255, float.Parse(col[2]) / 255, float.Parse(col[3]) / 255);
                }
                else
                {
                    color = new Color(float.Parse(col[0]) / 255, float.Parse(col[1]) / 255, float.Parse(col[2]) / 255);
                }

                GameObject child = meshObject.transform.GetChild(0).gameObject;
                child.GetComponent <Renderer>().material.SetFloat("_UseColor", 1f);
                child.GetComponent <Renderer>().material.SetColor("_Color", color);
                child.GetComponent <Renderer>().material.EnableKeyword("_USECOLOR_ON");
                child.GetComponent <Renderer>().material.DisableKeyword("_USEMAINTEX_ON");
                child.GetComponent <Renderer>().material.DisableKeyword("_USEEMISSIONTEX_ON");
                child.GetComponent <Renderer>().material.SetColor("_Color", color);
                Debug.Log(meshObject.transform.GetChild(0).gameObject.GetComponent <Renderer>().material.GetColor("_Color").ToString());
            });
            meshesLoaded = true;
        }
#endif
    }
示例#29
0
    public static string[] LoadOnlyObj(string filepath, Vector3 targetV)
    {
        GameObject target = OBJLoader.LoadOBJFile(filepath);

        string[] emptyPosIDs = ObjLoadHelper.ShiftPosition(target, targetV);
        Object.Destroy(target);
        return(emptyPosIDs);
    }
示例#30
0
    protected override void ActionResult(string path)
    {
        GameObject obj = OBJLoader.LoadOBJFile(path);

        InitObject(obj);
        Debug.Log("loaded");
//		CreateSpheres(obj);
    }
示例#31
0
        public Dictionary<string, int> GetMaterialsList(string fileName)
        {
            Dictionary<string, ModelBase.MaterialDef> materials = new Dictionary<string, ModelBase.MaterialDef>();
            string modelFormat = fileName.Substring(fileName.Length - 3, 3).ToLower();
            switch (modelFormat)
            {
                case "obj":
                    materials = new OBJLoader(fileName).GetModelMaterials();
                    break;
                case "dae":
                    materials = new DAELoader(fileName).GetModelMaterials();
                    break;
                case "imd":
                    materials = new NITROIntermediateModelDataLoader(fileName).GetModelMaterials();
                    break;
                default:
                    materials = new OBJLoader(fileName).GetModelMaterials();
                    break;
            }

            Dictionary<string, int> matColTypes = new Dictionary<string, int>();

            foreach (string key in materials.Keys)
            {
                matColTypes.Add(key, 0);
            }

            return matColTypes;
        }