Beispiel #1
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);
    }
Beispiel #2
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);
        }
    }
Beispiel #3
0
    public void ImportObjModel()
    {
        Debug.Log("Initalizing obj model: " + Path);
        GameObject objGameObject = OBJLoader.LoadOBJFile(Path);

        Material[] materials = OBJLoader.LoadMTLFile(Path);
    }
Beispiel #4
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
        }
    }
        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());
        }
Beispiel #6
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);
 }
Beispiel #7
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);
        }
    }
Beispiel #8
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
    }
Beispiel #9
0
    protected override void ActionResult(string path)
    {
        GameObject obj = OBJLoader.LoadOBJFile(path);

        InitObject(obj);
        Debug.Log("loaded");
//		CreateSpheres(obj);
    }
Beispiel #10
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);
    }
Beispiel #11
0
    void Start()
    {
        Screen.orientation          = ScreenOrientation.AutoRotation;
        Application.targetFrameRate = 30;

        OBJ = OBJLoader.LoadOBJFile(Menu.mesh_path);
        MeshRenderer mr = OBJ.transform.GetChild(0).GetComponent <MeshRenderer> ();
        Mesh         M  = OBJ.transform.GetChild(0).GetComponent <MeshFilter> ().mesh;

        M.RecalculateBounds();
        M.RecalculateNormals();
        M.RecalculateTangents();

        target = OBJ.transform;

        boundSize = mr.bounds.size.y;

        if (boundSize > 1)
        {
            boundSize = 1;
        }

        zoomMax = Mathf.Sqrt(mr.bounds.size.x * mr.bounds.size.x + mr.bounds.size.y * mr.bounds.size.y) * 1.5f;
        if (zoomMax < 1 || zoomMax < 10)
        {
            zoomMax = 10;
        }
        l1.intensity = sl.value;


        limit = Mathf.Abs(limit);
        if (limit > 90)
        {
            limit = 90;
        }

        if (mr.bounds.size.y > 1)
        {
            offset = new Vector3(offset.x, offset.y, -Mathf.Abs(mr.bounds.size.y));
        }
        else
        {
            offset = new Vector3(offset.x, offset.y, -Mathf.Abs(mr.bounds.size.y) * 1.5f);
        }

        transform.position = target.position + offset;
        iskomoe_y          = offset.y;
        iskomoe_z          = offset.z;

        target_meshrenderer = target.GetComponentInChildren <MeshRenderer>();
        vctr = new Vector3(0, nn, 0);

        firstClickTime    = 0f;
        timeBetweenClicks = 0.2f;
        clickCounter      = 0;
        coroutinAllowed   = true;
    }
Beispiel #12
0
    /**
     * Loads the object downloaded from the server
     */
    private void LoadDownloadedObj()
    {
        GameObject obj = OBJLoader.LoadOBJFile(Application.persistentDataPath + "/model.obj");

        InitObject(obj);
        SetInsideShader(obj);
        obj.transform.localScale = new Vector3(1f, 1f, 1f);
        Debug.Log("Loaded model from server");
    }
Beispiel #13
0
    IEnumerator OpenSceneCoroutine()
    {
        yield return(FileBrowser.WaitForLoadDialog(false, null, "Load OBJ", "OK"));

        Debug.Log(FileBrowser.Success + " " + FileBrowser.Result);
        if (!FileBrowser.Success)
        {
            yield break;
        }

        GameObject objScene = OBJLoader.LoadOBJFile(FileBrowser.Result);

        InitScene(objScene);
    }
Beispiel #14
0
    private GameObject downloadObj()
    {
        //////////////////////////////
        //// Checks if the object is located on directory
        //// if not downloads from the server
        /////////////////////////////
        string path = Directory.GetCurrentDirectory();
        //string path = System.IO.Path.GetDirectoryName(Application.dataPath);
        bool found  = false;
        bool server = true;

        if (File.Exists(path + "/" + name + ".obj"))
        {
            Debug.Log("OBJ file found");
            if (File.Exists(path + "/" + name + ".mtl"))
            {
                found = true;
                Debug.Log("MTL file found");
            }
        }
        if (!found)
        {
            using (var client = new System.Net.WebClient())
            {
                try {                 // downloads object and mtl files from a HTTP server at address "DownloadLink"
                    Debug.Log("Downloading files");
                    client.DownloadFile("http://" + DownloadLink + ":8000/" + name + ".obj", path + "/" + name + ".obj");
                    client.DownloadFile("http://" + DownloadLink + ":8000/" + name + ".mtl", path + "/" + name + ".mtl");
                } catch (Exception e) {
                    Debug.Log("Problem downloading obj: " + e.ToString());
                    server = false;
                }
            }
        }
        path = System.IO.Path.Combine(@path, name + ".obj");
        if ((found) || (server))           // if the object is either downloaded or already on disk
        {
            GameObject cuube = OBJLoader.LoadOBJFile(path);
            cuube.name = name;             // rename the object
            Debug.Log("Object loaded");
            return(cuube);
        }
        else
        {
            Debug.Log("File not found on disk and download failed");
            GameObject game = null;
            return(game);
        }
    }
Beispiel #15
0
    public void addModel(string modelPath)
    {
        string     fullpath = filepath.Substring(0, filepath.LastIndexOf(ApplicationHelper.slash())) + ApplicationHelper.slash() + modelPath;
        GameObject model    = OBJLoader.LoadOBJFile(fullpath);

        model.name = "Model";
        model.transform.SetParent(robotObject.transform, false);
        model.transform.rotation = Quaternion.Euler(0, 90, 0);

        BoxCollider robCollider = robotObject.AddComponent <BoxCollider>();

        robCollider.center   = new Vector3(0, 0.101f, 0);
        robCollider.size     = new Vector3(0.18f, 0.195f, 0.2f);
        robCollider.material = Resources.Load("nofriction") as PhysicMaterial;
    }
Beispiel #16
0
    private void loadObjects(string[] pathArray, GameObject parentObject)
    {
        foreach (string file in pathArray)
        {
            if (file.EndsWith(".obj"))
            {
                GameObject obj = OBJLoader.LoadOBJFile(file);
                obj.transform.parent        = parentObject.transform;
                obj.transform.localPosition = new Vector3(0.0f, 0.0f, 0.0f);
                obj.transform.localRotation = Quaternion.identity;
                obj.transform.localScale    = new Vector3(1.0f, 1.0f, 1.0f);

                obj.GetComponentInChildren <Renderer>().material = tumourMaterial;
            }
        }
    }
Beispiel #17
0
 void Start()
 {
     args = Environment.GetCommandLineArgs();
     if (args.Length > 1)
     {
         GameObject g = OBJLoader.LoadOBJFile(args[1]);
         g.transform.localScale = new Vector3(0.07f, 0.07f, 0.07f);
         g.transform.SetParent(this.transform);
     }
     else
     {
         GameObject g = OBJLoader.LoadOBJFile("GEO_Trolley0.03.obj");
         g.transform.localScale = new Vector3(0.07f, 0.07f, 0.07f);
         g.transform.SetParent(this.transform);
     }
 }
Beispiel #18
0
    /**
     * Opens a file browser to select the .obj file to load
     */
    IEnumerator OpenBrowserCoroutine()
    {
        yield return(FileBrowser.WaitForLoadDialog(false, null, "Load OBJ", "OK"));

        Debug.Log(FileBrowser.Success + " " + FileBrowser.Result);
        if (!FileBrowser.Success)
        {
            yield break;
        }

        GameObject obj = OBJLoader.LoadOBJFile(FileBrowser.Result);

        InitObject(obj);
        Debug.Log("loaded");

//		CreateSpheres(obj);
    }
Beispiel #19
0
    IEnumerator obj(string ruta, WWW www)
    {
        www = new WWW("file:///" + ruta);
        yield return(www);

        if (ruta != null)
        {
            if (objeto.transform.childCount >= 1)
            {
                Transform c = objeto.transform.GetChild(0);
                c.parent = c;
                Destroy(c.gameObject);
            }
            //Debug.Log (ruta);
            OBJLoader.LoadOBJFile(ruta);
        }
    }
Beispiel #20
0
    // Use this for initialization
    void Start()
    {
        MachineQrCommunication machineQrCommunication = new MachineQrCommunication();
        string ServerResponse = machineQrCommunication.ReceiveDataFromServer();

        //Receive the CAD file and save to Resources or local of the client machine
        MachineEntity machine = JsonUtility.FromJson <MachineEntity>(ServerResponse);

        instructionsEntity.operationId = machine.operationToDo;
        instructionsEntity.operationInstructionListId = machine.operationInstructionListId;
        instructionsEntity.operationInstructionList   = machine.operationInstructionList;

        //Iterprete CAD Filename
        string CadFilenameAbsolute = machine.machineCADFile;

        string[] file        = CadFilenameAbsolute.Split('/');
        int      counter     = file.Length;
        string   CadFilename = file[counter - 1]; //Exact Filename => example.obj

        //string CadFilename = "gokart_main_assy.obj";
        //This filepath can be changed according to device
        string FilePath = "C:/ARClient/ARTeamcenterClient/Assets/Resources/" + CadFilename;

        byte[] FileBuffer = machineQrCommunication.ReceiveCADFileFromServer();

        // create a file in local and write to file
        BinaryWriter bWrite = new System.IO.BinaryWriter(File.Open(FilePath, FileMode.Create));

        bWrite.Write(FileBuffer);
        bWrite.Flush();
        bWrite.Close();

        //Load CAD model to the scene
        CADImage = OBJLoader.LoadOBJFile(FilePath); //I hope this will work


        //Display first step of the operation on the screen
        InstructionList = machine.operationInstructionList;
        size            = InstructionList.Count;
        NextInformationButton.GetComponentInChildren <Text>().text = "Start";
        InformationText.text = "You will see the instructions here!" +
                               "If you feel you need more information, click the button below!";

        //Highlight the part which will be changed
    }
        public GameObject[] LoadSemanticColliderObjs(string dirPath)
        {
            // reset
            isAllColliderReady = false;
            totalObjNumber     = loadedObjNumber = 0;
            StopAllCoroutines();

            ViveSR_SceneUnderstanding.ImportSceneObjects(dirPath); // read data from xml

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

            if (!dir.Exists)
            {
                Debug.Log(dirPath + " does not exist.");
            }
            else
            {
                string[] fileNames = ViveSR_SceneUnderstanding.GetColliderFileNames();
                totalObjNumber = fileNames.Length;
                for (int i = 0; i < fileNames.Length; i++)
                {
                    FileInfo file = new FileInfo(dirPath + "/" + fileNames[i]);
                    //Debug.Log(file.FullName);
                    if (!file.Exists)
                    {
                        Debug.Log(file.FullName + " does not exist.");
                        if (i == fileNames.Length - 1)
                        {
                            isAllColliderReady = true;
                            return(outputObjs.ToArray());
                        }
                        else
                        {
                            continue;
                        }
                    }

                    GameObject go = OBJLoader.LoadOBJFile(file.FullName, LoadColliderDoneCallBack, file.Name);
                    go.SetActive(false);
                    outputObjs.Add(go);
                }
            }
            return(outputObjs.ToArray());
        }
Beispiel #22
0
        public static void BuildPlayerPrefab()
        {
            OBJLoader.OBJFile file = new OBJLoader.OBJFile
            {
                ObjData   = Properties.Resources.patrick,
                MtlData   = Properties.Resources.patrick_mtl,
                MtlImages = new Dictionary <string, byte[]>()
                {
                    ["Image_2D_0001_0008.png"] = Properties.Resources.Image_2D_0001_0008,
                    ["Image_2D_0002_0009.png"] = Properties.Resources.Image_2D_0002_0009,
                    ["Image_2D_0003_0010.png"] = Properties.Resources.Image_2D_0003_0010,
                }
            };

            PlayerModelPrefab = OBJLoader.LoadOBJFile("Patrick", file);
            PlayerModelPrefab.transform.position   = new Vector3(-1000, -1000, -1000);
            PlayerModelPrefab.transform.localScale = new Vector3(.025f, .025f, .025f);
        }
Beispiel #23
0
    public static string[] LoadObj(string[] filepaths, Vector3 targetV, bool isTest = true)
    {
        GameObject target = OBJLoader.LoadOBJFile(filepaths[0]);

        string[] emptyPosIDs = ObjLoadHelper.ShiftPosition(target, targetV);

        if (target.transform.childCount > 0)
        {
            Texture2D texture = TextureLoader.LoadTexture(filepaths[1]);
            foreach (Transform child in target.transform)
            {
                child.gameObject.AddComponent <MeshCollider> ();
                child.gameObject.GetComponent <Renderer> ().material             = new Material(Const.DIFFUSE_SHADER);
                child.gameObject.GetComponent <Renderer> ().material.mainTexture = texture;
            }
        }
        return(emptyPosIDs);
        //return target;
    }
Beispiel #24
0
    public void getObj()
    {
        GameObject arrow;

        // Use this for initialization
        //WWW www = new WWW(url);
        //yield return www;
        Debug.Log("Downloading files");
        try {
            using (var client = new System.Net.WebClient())
            {
                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) {
            Debug.Log(e);
        }
        arrow = OBJLoader.LoadOBJFile(@"C:\Users\kone6\Documents\Office\Assets\arrow_color.obj");
    }
Beispiel #25
0
    public void TaskOnClickFile()
    {
        path       = EditorUtility.OpenFilePanel("Choose your .obj file", "", "obj");
        loadedFile = OBJLoader.LoadOBJFile(path);

        if (!listGoName.Contains(loadedFile.name))
        {
            namBut   = Instantiate(nameButton, nameContentPanel.transform);
            fileName = loadedFile.name;
            namBut.GetComponentInChildren <Text> ().text = fileName;
            namBut.transform.Find("Button_total").gameObject.GetComponentInChildren <Text> ().text = 1.ToString();
            listGoName.Add(loadedFile.name);
        }

        else if (listGoName.Contains(loadedFile.name))
        {
            Debug.Log("file already exists");
            Destroy(loadedFile);
        }
    }
Beispiel #26
0
    public override void OnPress()
    {
        string fileName = transform.Find("Text").GetComponent <TextMesh>().text;

        Vector3    pos       = Hands.Left.PalmPosition.ToVector3();
        GameObject loadedObj = OBJLoader.LoadOBJFile("Assets/Resources/Imports/Meshes/" + fileName);

        this.prefab = loadedObj;
        loadedObj.transform.position   = transform.position = new Vector3(pos.x, pos.y, pos.z) + new Vector3(0.00f, 0.00f, 0.25f);
        loadedObj.transform.localScale = new Vector3(.02f, .02f, .02f);
        this.prefab = Instantiate(loadedObj);


        this.prefab.transform.position = new Vector3(pos.x, pos.y, pos.z) + new Vector3(0.00f, 0.00f, 0.25f); //+ new Vector3(Hands.Left.Rotation.x, Hands.Left.Rotation.y, Hands.Left.Rotation.z);
        //LeapHandController.transform.rotation * (new Vector3(0.0f, 0.00f, 0.04f));
        this.prefab.transform.localScale = new Vector3(.02f, .02f, .02f);
        this.prefab.gameObject.name      = fileName;

        new Solid(this.prefab.GetComponent <MeshFilter>().mesh, Matrix4x4.TRS(prefab.transform.position, prefab.transform.rotation, prefab.transform.localScale), prefab.transform.position);

        base.OnPress();
    }
Beispiel #27
0
    /// <summary>
    /// Searches the data folder for
    /// </summary>
    /// <param name="name"></param>
    public StarpointModel(string name)
    {
        string        albedoTransparency = "";
        string        metallicSmoothness = "";
        string        normal             = "";
        string        obj          = "";
        List <string> relatedFiles = GetRelatedFiles(data, Path.GetFileNameWithoutExtension(name));

        foreach (string file in relatedFiles)
        {
            switch (Path.GetExtension(file))
            {
            case ".obj":
                obj = file;
                break;

            case ".png":
                if (file.IndexOf("AlbedoTransparency") != -1)
                {
                    albedoTransparency = file;
                }
                if (file.IndexOf("MetallicSmoothness") != -1)
                {
                    metallicSmoothness = file;
                }
                if (file.IndexOf("Normal") != -1)
                {
                    normal = file;
                }
                break;
            }
        }
        GameObject go = OBJLoader.LoadOBJFile(obj);

        mesh = go.GetComponentInChildren <MeshFilter>().mesh;
        GameObject.Destroy(go);
        //Mesh m = ReadObjFile(obj);
    }
Beispiel #28
0
    // Imports game object.
    GameObject ImportObject(Vector3 position, int viewID)
    {
        GameObject imported = OBJLoader.LoadOBJFile("Models/F-14A_Tomcat/F-14A_Tomcat.obj");

        imported.transform.position   = position;
        imported.transform.localScale = Vector3.one * 0.1f;

        // Name and tag the object
        imported.name = viewID.ToString();
        imported.tag  = "imported";

        // Add the photon view and set it up.
        imported.AddComponent <PhotonView>();
        imported.AddComponent <OnClickRequestOwnership>();
        imported.GetComponent <PhotonView>().viewID             = viewID;
        imported.GetComponent <PhotonView>().ObservedComponents = new List <Component>();
        imported.GetComponent <PhotonView>().ownershipTransfer  = OwnershipOption.Takeover;
        imported.GetComponent <PhotonView>().ObservedComponents.Add(imported.transform);
        imported.GetComponent <PhotonView>().onSerializeTransformOption = OnSerializeTransform.All;
        imported.GetComponent <PhotonView>().synchronization            = ViewSynchronization.UnreliableOnChange;

        return(imported);
    }
Beispiel #29
0
    IEnumerator LoadAssetCoroutine()
    {
        if (!string.IsNullOrEmpty(OBJUrl))
        {
            Destroy(loadedOBJGameObject);

            UnityWebRequest webRequest = UnityWebRequest.Get(OBJUrl);

            yield return(webRequest.SendWebRequest());

            if (webRequest.isNetworkError || webRequest.isHttpError)
            {
                Debug.Log("Couldn't get OBJ, error: " + webRequest.error + " ... " + OBJUrl);
            }
            else
            {
                loadedOBJGameObject      = OBJLoader.LoadOBJFile(webRequest.downloadHandler.text, true);
                loadedOBJGameObject.name = "LoadedOBJ";
                loadedOBJGameObject.transform.SetParent(transform);
                loadedOBJGameObject.transform.localPosition = Vector3.zero;

                OnFinishedLoadingAsset?.Invoke();
                alreadyLoadedAsset = true;
            }
        }
        else
        {
            Debug.Log("couldn't load OBJ because url is empty");
        }

        if (loadingPlaceholder != null)
        {
            loadingPlaceholder.SetActive(false);
        }

        loadingRoutine = null;
    }
    public GameObject BuildObjectFromFile(string filepath)
    {
        IO         io        = new IO("#;");
        GameObject customObj = null;

        EyesimLogger.instance.Log("Building object: " + filepath);

        if (!io.Load(filepath))
        {
            Debug.Log("Couldn't load file");
            EyesimLogger.instance.Log("Error loading file");
            return(null);
        }

        if (io.extension(filepath) != ".esObj")
        {
            Debug.Log("Invalid input to Object Loader");
            return(null);
        }

        string[] args;
        // Read each line
        while ((args = io.ReadNextArguments())[0] != "ENDOFFILE")
        {
            switch (args[0])
            {
            // Read the .obj file and construct a new gameObject (MUST BE FIRST NONCOMMENT)
            case "obj":
                Debug.Log(args[1]);
                string objPath = io.SearchForFile(args[1], "");
                if (objPath == "")
                {
                    EyesimLogger.instance.Log("Failed to find .obj file for " + Path.GetFileName(filepath));
                    return(null);
                }
                customObj = OBJLoader.LoadOBJFile(objPath);
                customObj.transform.position = new Vector3(0f, -20f, 0f);
                customObj.name = Path.GetFileNameWithoutExtension(filepath);
                customObj.AddComponent <Rigidbody>().isKinematic = true;
                break;

            case "scale":
                if (customObj == null)
                {
                    Debug.Log("obj must be first input in .esObj file");
                    EyesimLogger.instance.Log("First input in .esObj file must be path to .obj");
                    return(null);
                }
                try
                {
                    customObj.transform.localScale = new Vector3(float.Parse(args[1]), float.Parse(args[1]), float.Parse(args[1]));
                }
                catch
                {
                    Debug.Log("Error in scale: Invalid argument");
                    EyesimLogger.instance.Log("Error parsing scale argument");
                    return(null);
                }
                break;

            // Configure mass properties
            case "mass":
                if (customObj == null)
                {
                    Debug.Log("obj must be first input in .esObj file");
                    EyesimLogger.instance.Log("First input in .esObj file must be path to .obj");
                    return(null);
                }
                try
                {
                    Rigidbody rb = customObj.GetComponent <Rigidbody>();
                    rb.mass         = float.Parse(args[1]);
                    rb.centerOfMass = new Vector3(float.Parse(args[2]), float.Parse(args[3]), float.Parse(args[4]));
                }
                catch
                {
                    Debug.Log("Error in mass: Invalid argument");
                    EyesimLogger.instance.Log("Error parsing mass argument");
                    Destroy(customObj);
                    return(null);
                }
                break;

            // Add colliders
            // Capsule
            case "capsule":
            {
                if (customObj == null)
                {
                    Debug.Log("obj must be first input in .esObj file");
                    EyesimLogger.instance.Log("First input in .esObj file must be path to .obj");
                    return(null);
                }
                CapsuleCollider col = customObj.AddComponent <CapsuleCollider>();
                try
                {
                    col.center = new Vector3(float.Parse(args[1]), float.Parse(args[2]), float.Parse(args[3]));
                    col.radius = float.Parse(args[4]);
                    col.height = float.Parse(args[5]);
                    if (args[6] == "x")
                    {
                        col.direction = 0;
                    }
                    else if (args[6] == "y")
                    {
                        col.direction = 1;
                    }
                    else if (args[6] == "z")
                    {
                        col.direction = 2;
                    }
                    else
                    {
                        throw new FormatException();
                    }
                }
                catch
                {
                    Debug.Log("Error in capsule: Invalid arguments");
                    EyesimLogger.instance.Log("Error parsing capsule arguments");
                    Destroy(customObj);
                    return(null);
                }
                break;
            }

            // Sphere
            case "sphere":
            {
                if (customObj == null)
                {
                    Debug.Log("obj must be first input in .esObj file");
                    EyesimLogger.instance.Log("First input in .esObj file must be path to .obj");
                    return(null);
                }
                SphereCollider col = customObj.AddComponent <SphereCollider>();
                try
                {
                    col.center = new Vector3(float.Parse(args[1]), float.Parse(args[2]), float.Parse(args[3]));
                    col.radius = float.Parse(args[4]);
                }
                catch
                {
                    Debug.Log("Error in sphere: Invalid arguments");
                    EyesimLogger.instance.Log("Error parsing sphere arguments");
                    Destroy(customObj);
                    return(null);
                }
                break;
            }

            // Box
            case "box":
            {
                if (customObj == null)
                {
                    Debug.Log("obj must be first input in .esObj file");
                    EyesimLogger.instance.Log("First input in .esObj file must be path to .obj");
                    return(null);
                }
                BoxCollider col = customObj.AddComponent <BoxCollider>();
                try
                {
                    col.center = new Vector3(float.Parse(args[1]), float.Parse(args[2]), float.Parse(args[3]));
                    col.size   = new Vector3(float.Parse(args[4]), float.Parse(args[5]), float.Parse(args[6]));
                }
                catch
                {
                    Debug.Log("Error in box: Invalid arguments");
                    EyesimLogger.instance.Log("Error box capsule arguments");
                    Destroy(customObj);
                    return(null);
                }
                break;
            }

            default:
            {
                Debug.Log("Unknown input: " + args[0]);
                EyesimLogger.instance.Log("Unknown input type: " + args[0]);
                break;
            }
            }
        }
        // Add the WorldObject component, and calculate vertical offset
        WorldObject wObj = customObj.AddComponent <WorldObject>();

        wObj.defaultVerticalOffset = -customObj.GetComponent <Collider>().bounds.min.y - 20f;
        wObj.type = customObj.name;
        customObj.SetActive(false);
        return(customObj);
    }