protected void ProcessedNodesCB(ForgeLoaderEngine sender, float pct)
 {
     if (ProcessedNodes != null)
     {
         ProcessedNodes.Invoke(pct / 100.0f);
     }
 }
 protected void ProcessingNodesCompletedCB(ForgeLoaderEngine sender, int unprocessedObjects)
 {
     if (ProcessingNodesCompleted != null)
     {
         ProcessingNodesCompleted.Invoke(unprocessedObjects);
     }
     _loader.Sleep();
 }
        public void ProcessingNodesCompleted(ForgeLoaderEngine sender, int unprocessedObjects)
        {
            _loaderActive = false;
            this.Repaint();
            CloseDialog();

            if (this._saveToDisk)
            {
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
            }
        }
Example #4
0
        public static GameObject SetupForSceneOrientationAndUnits(GameObject sceneRoot, JSONNode metadata)
        {
            JSONNode pt  = metadata ["worldBoundingBox"] ["maxXYZ"];
            Vector3  max = new Vector3(pt [0].AsFloat, pt [1].AsFloat, pt [2].AsFloat);

            pt = metadata ["worldBoundingBox"] ["minXYZ"];
            Vector3 min    = new Vector3(pt [0].AsFloat, pt [1].AsFloat, pt [2].AsFloat);
            Vector3 center = (max + min) / 2f;

            //Vector3 size =(max - min) / 2f ;
            //Bounds boundsBubble =new Bounds (center, size) ;
            //Bounds bounds =BoundsExtensions.GameObjectBounds (sceneRoot) ;
            pt = metadata ["refPointLMV"] [1];
            Vector3 pivot = pt.AsArray.Count == 3 ? new Vector3(pt [0].AsFloat, pt [1].AsFloat, pt [2].AsFloat) : Vector3.zero;

            if (sceneRoot.transform.parent == null)
            {
                string     name  = sceneRoot.name + "Pivot";
                GameObject gRoot = new GameObject(name);
                sceneRoot.transform.parent = gRoot.transform;
            }
            Transform root   = sceneRoot.transform.parent;
            JSONNode  marker = metadata ["marker"];

            if (marker != null && marker ["point"] != null)
            {
                pt = marker ["point"];
                Vector3 tr = new Vector3(pt ["x"].AsFloat, pt ["y"].AsFloat, pt ["z"].AsFloat);
                pivot += center + tr;
            }
            root.localPosition = pivot;
            Transform main = sceneRoot.transform;

            main.localPosition = -pivot;
            JSONArray upvector = metadata ["worldUpVector"] [1].AsArray;

            if (upvector [2].AsFloat != 0f)                 // Z axis
            {
                root.Rotate(Vector3.right, -90);
                root.localScale = new Vector3(-1f, 1f, 1f);
            }
            string units        = metadata ["units"];
            float  unitsConvert = ForgeLoaderEngine.convertToMeter(units);

            if (unitsConvert != 1.0f)
            {
                root.localScale = new Vector3(root.localScale.x * unitsConvert, root.localScale.y * unitsConvert, root.localScale.z * unitsConvert);
            }
            // Now move to final position
            root.localPosition = Vector3.zero;

            return(root.gameObject);
        }
 public void ProcessedNodes(ForgeLoaderEngine sender, float pct)
 {
     //EditorUtility.DisplayProgressBar
     if (EditorUtility.DisplayCancelableProgressBar(
             "Importing Scene, please wait...",
             pct.ToString("0.00") + " %",
             pct / 100
             )
         )
     {
         // User pressed cancel
         _loaderActive = false;
         this.Repaint();
         CloseDialog();
     }
 }
Example #6
0
        public override GameObject BuildScene(string name, bool saveToDisk = false)
        {
            try {
                if (_vertices.Length == 0 || _triangles.Length == 0)
                {
                    state = SceneLoadingStatus.eCancelled;
                    return(gameObject);
                }
                Mesh mesh = new Mesh();
                mesh.vertices  = _vertices;
                mesh.triangles = _triangles;
                if (_uvs != null && _uvs.Length != 0)
                {
                    mesh.uv = _uvs;
                }
                mesh.RecalculateNormals();
                mesh.RecalculateBounds();

                MeshFilter filter = gameObject.AddComponent <MeshFilter> ();
                filter.sharedMesh = mesh;
                MeshRenderer renderer = gameObject.AddComponent <MeshRenderer> ();
                renderer.sharedMaterial = ForgeLoaderEngine.GetDefaultMaterial();
                if (createCollider)
                {
                    MeshCollider collider = gameObject.AddComponent <MeshCollider>();
                    collider.sharedMesh = mesh;
                }
#if UNITY_EDITOR
                if (saveToDisk)
                {
                    AssetDatabase.CreateAsset(mesh, ForgeConstants._resourcesPath + this.loader.PROJECTID + "/" + name + ".asset");
                    //AssetDatabase.SaveAssets () ;
                    //AssetDatabase.Refresh () ;
                    //mesh =AssetDatabase.LoadAssetAtPath<Mesh> (ForgeConstants._resourcesPath + this.loader.PROJECTID + "/" + name + ".asset") ;
                }
#endif

                base.BuildScene(name, saveToDisk);
                state = SceneLoadingStatus.eWaitingMaterial;
            } catch (Exception ex) {
                Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
                state = SceneLoadingStatus.eError;
            }
            return(gameObject);
        }
Example #7
0
        public static Matrix4x4 fromUnityMatrix(GameObject sceneRoot, JSONNode metadata = null)
        {
            if (metadata == null)
            {
                metadata = sceneRoot.GetComponent <ForgeProperties> ().Properties;
            }

            Vector3 center = GetSceneBoundingBox(sceneRoot, metadata).center;
            Vector3 pivot  = GetSceneOrigin(sceneRoot, metadata);

            if (IsMarkerDefined(sceneRoot, metadata))
            {
                pivot += /*center +*/ GetMarkerPoint(sceneRoot, metadata);
            }
            Vector3 upvector = GetSceneUpVector(sceneRoot, metadata);
            string  units    = GetSceneUnit(sceneRoot, metadata);

            Transform tr = new GameObject().transform;

            if (upvector [2] != 0f)                 // Z axis
            {
                tr.Rotate(Vector3.right, -90);
                tr.localScale = new Vector3(-1f, 1f, 1f);
            }
            float unitsConvert = ForgeLoaderEngine.convertToMeter(units);

            if (unitsConvert != 1.0f)
            {
                tr.localScale = new Vector3(tr.localScale.x * unitsConvert, tr.localScale.y * unitsConvert, tr.localScale.z * unitsConvert);
            }
            //tr.localPosition =-pivot ;

            Matrix4x4 mat = Matrix4x4.identity;

            mat = tr.worldToLocalMatrix;

            Matrix4x4 mTR = Matrix4x4.identity;

            mTR.m03 = pivot.x;
            mTR.m13 = pivot.y;
            mTR.m23 = pivot.z;
            mat     = mTR * mat;
            GameObject.DestroyImmediate(tr.gameObject);
            return(mat);
        }
        public override GameObject BuildScene(string name, bool saveToDisk = false)
        {
            Clear();
            GameObject pivot = null;

            try {
                gameObject = new GameObject(name);
                if (lmvtkDef == null)
                {
                    return(null);
                }
                ForgeProperties properties = gameObject.AddComponent <ForgeProperties> ();
                properties.Properties = lmvtkDef ["metadata"];

                foreach (JSONNode child in lmvtkDef["childs"].AsArray)
                {
                    IteratorNodes(child, gameObject);
                }
                base.BuildScene(name, saveToDisk);

                pivot = ForgeLoaderEngine.SetupForSceneOrientationAndUnits(gameObject, properties.Properties);

                // Create as much Meshes requests we need to load chunks of 0.5Mb-0.7Mb pack files
                // 1-499 polys = factor of 25
                // >500 poly = factor of 17
                int compSize = 0;
                List <Eppy.Tuple <int, int> > components = new List <Eppy.Tuple <int, int> > ();
                List <Eppy.Tuple <int, int, GameObject, JSONNode> > fragments = new List <Eppy.Tuple <int, int, GameObject, JSONNode> > ();
                foreach (KeyValuePair <int, InstanceTreeData> data in _components)
                {
                    //if ( data.Value.fragments.Count == 0 )
                    //continue;
                    foreach (Eppy.Tuple <int, int, GameObject, JSONNode> frag in data.Value.fragments)
                    {
                        JSONArray json  = frag.Item4 ["fragments"].AsArray;
                        JSONArray json2 = frag.Item4 ["fragPolys"].AsArray;
                        int       index = 0;
                        for ( ; index < json.Count && json [index].AsInt != frag.Item1; index++)
                        {
                        }
                        if (index >= json2.Count)
                        {
                            continue;
                        }
                        compSize += json2 [index].AsInt;
                        //Debug.Log (data.Key + "-" + frag.Item1 + " " + json2 [index].AsInt);
                        components.Add(new Eppy.Tuple <int, int> (data.Key, frag.Item1));
                        fragments.Add(frag);
                    }

                    if (compSize > 29411 /* 29411 * 17 = 500kb */)
                    {
                        MeshesRequest reqMeshes = new MeshesRequest(loader, null, bearer, components, fragments, null);
                        reqMeshes.gameObject = null;
                        if (fireRequestCallback != null)
                        {
                            fireRequestCallback(this, reqMeshes);
                        }
                        compSize   = 0;
                        components = new List <Eppy.Tuple <int, int> > ();
                        fragments  = new List <Eppy.Tuple <int, int, GameObject, JSONNode> > ();
                    }
                }
                if (components.Count > 0)
                {
                    MeshesRequest reqMeshes = new MeshesRequest(loader, null, bearer, components, fragments, null);
                    reqMeshes.gameObject = null;
                    if (fireRequestCallback != null)
                    {
                        fireRequestCallback(this, reqMeshes);
                    }
                }

                if (loader.GetMgr()._materials.Count > 0)
                {
                    MaterialsRequest reqMaterials = new MaterialsRequest(loader, null, bearer, loader.GetMgr()._materials, lmvtkDef);
                    reqMaterials.gameObject = null;
                    if (fireRequestCallback != null)
                    {
                        fireRequestCallback(this, reqMaterials);
                    }
                }                 // Textures will be requested by the material request (one by one)

                // Now Properties
                int []    dbIds  = _components.Keys.ToArray();
                int [] [] chunks = dbIds
                                   .Select((s, i) => new { Value = s, Index = i })
                                   .GroupBy(x => x.Index / 100)
                                   .Select(grp => grp.Select(x => x.Value).ToArray())
                                   .ToArray();
                for (int i = 0; i < chunks.Length; i++)
                {
                    List <Eppy.Tuple <int, GameObject> > dbIdsTuple = new List <Eppy.Tuple <int, GameObject> > ();
                    foreach (int dbId in chunks[i])
                    {
                        dbIdsTuple.Add(new Eppy.Tuple <int, GameObject> (dbId, _components [dbId].obj));
                    }
                    PropertiesRequest2 reqProps = new PropertiesRequest2(loader, null, bearer, dbIdsTuple);
                    reqProps.gameObject = null;
                    if (fireRequestCallback != null)
                    {
                        fireRequestCallback(this, reqProps);
                    }
                }

                Clear();
            } catch (Exception ex) {
                if (gameObject)
                {
                    GameObject.DestroyImmediate(gameObject);
                }
                gameObject = null;
                pivot      = null;
            }
            return(pivot);
        }
        protected Material CreateMaterial(StandardMaterial lmvMat)
        {
            // https://docs.unity3d.com/Manual/StandardShaderMetallicVsSpecular.html
            // Standard: The shader exposes a “metallic” value that states whether the material is metallic or not.
            // Standard (Specular setup): Choose this shader for the classic approach.
            bool     isMetal = lmvMat.isMetal;
            Material mat     = new Material(isMetal ? Shader.Find("Standard") : Shader.Find("Standard (Specular setup)"));

            try {
                // Color properties
                Color color    = Color.clear;
                Color diffuse  = lmvMat.diffuse;
                Color ambient  = lmvMat.ambient;
                Color specular = lmvMat.specular;

                color = diffuse != Color.clear ? diffuse : ambient;

                if (color == Color.clear && isMetal)
                {
                    color = specular;
                }

                mat.SetColor("_Color", color);

                // Metallic properties
                if (isMetal)
                {
                    mat.SetFloat("_Metallic", 1);
                }

                //This glossines code is an arbitrary placeholder until the proper
                //material properties are added
                float glossiness = Mathf.Clamp(lmvMat.glossiness / 2000f, .01f, .99f);
                mat.SetFloat("_Glossiness", glossiness);
                mat.SetFloat("_Shininess", glossiness);

                if (specular != Color.white)
                {
                    mat.SetColor("_SpecColor", color);
                }

                var specularTexture = lmvMat.specular_tex;
                if (specularTexture != null)
                {
                    mat.EnableKeyword("_SPECULARHIGHLIGHTS_OFF");
                    mat.SetFloat("_SpecularHighlights", 0f);
                    mat.EnableKeyword("_GLOSSYREFLECTIONS_OFF");
                    mat.SetFloat("_GlossyReflections", 0f);
                }
                else
                {
                    mat.DisableKeyword("_SPECULARHIGHLIGHTS_OFF");
                    mat.SetFloat("_SpecularHighlights", 1f);
                    mat.DisableKeyword("_GLOSSYREFLECTIONS_OFF");
                    mat.SetFloat("_GlossyReflections", 1f);
                }

                // Emissive properties
                var emissive = lmvMat.emissive;
                if (emissive != Color.clear)
                {
                    mat.SetColor("_EmissionColor", emissive);
                }

                //var specular = lmvMat.specular;
                //if ( specular != Color.clear
                //	&& (
                //		   lmvMat.isMetal == true // In Unity3d, the texture would not show
                //		&& lmvMat.diffuse_tex != null
                //		&& specular != Color.white
                //	)
                //)
                //	mat.SetColor ("_SpecColor", specular);

                // Transparent properties
                var transparent = lmvMat.transparent;
                if (transparent)
                {
                    mat.SetFloat("_Mode", (float)BlendMode.Transparent);
                    mat.EnableKeyword("_ALPHABLEND_ON");
                    color.a = lmvMat.transparency;
                    mat.SetColor("_Color", color);
                }

                // Create a new request to get the Textures
                if (lmvMat.diffuse_tex != null)
                {
                    //TextureRequest req =new TextureRequest (loader, null, mat, Texture.TextureType.Diffuse, lmvMat.material) ;
                    TextureRequest req = new TextureRequest(loader, null, bearer, mat, lmvMat.diffuse_tex, lmvMat.material);
                    if (fireRequestCallback != null)
                    {
                        fireRequestCallback(this, req);
                    }
                }
                if (lmvMat.specular_tex != null)
                {
                    TextureRequest req = new TextureRequest(loader, null, bearer, mat, lmvMat.specular_tex, lmvMat.material);
                    if (fireRequestCallback != null)
                    {
                        fireRequestCallback(this, req);
                    }
                }
                if (lmvMat.bump_tex != null)
                {
                    TextureRequest req = new TextureRequest(loader, null, bearer, mat, lmvMat.bump_tex, lmvMat.material);
                    if (fireRequestCallback != null)
                    {
                        fireRequestCallback(this, req);
                    }
                }
            } catch (System.Exception e) {
                Debug.Log("exception " + e.Message);
                mat = ForgeLoaderEngine.GetDefaultMaterial();
            }
            return(mat);
        }
        protected Material CreateMaterialV1(StandardMaterial lmvMat)
        {
            // https://docs.unity3d.com/Manual/StandardShaderMetallicVsSpecular.html
            // Standard: The shader exposes a “metallic” value that states whether the material is metallic or not.
            // Standard (Specular setup): Choose this shader for the classic approach.
            Material mat = new Material(
                lmvMat.isMetal == true ?
                Shader.Find("Standard")
                                : Shader.Find("Standard (Specular setup)")
                );

            try {
                if (lmvMat.specular_tex != null)
                {
                    mat.EnableKeyword("_SPECULARHIGHLIGHTS_OFF");
                    mat.SetFloat("_SpecularHighlights", 0f);
                }
                //mat.DisableKeyword ("_SPECULARHIGHLIGHTS_OFF") ;
                //mat.SetFloat ("_SpecularHighlights", 1f) ;
                mat.EnableKeyword("_GLOSSYREFLECTIONS_OFF");
                mat.SetFloat("_GlossyReflections", 0f);

                var ambiant = lmvMat.ambient;
                if (ambiant != Color.clear)
                {
                    mat.SetColor("_Color", ambiant);
                }

                var diffuse = lmvMat.diffuse;
                if (diffuse != Color.clear)
                {
                    mat.SetColor("_Color", diffuse);
                }

                var emissive = lmvMat.emissive;
                if (emissive != Color.clear)
                {
                    mat.SetColor("_EmissionColor", emissive);
                }

                var specular = lmvMat.specular;
                if (specular != Color.clear &&
                    (
                        lmvMat.isMetal == true &&                         // In Unity3d, the texture would not show
                        lmvMat.diffuse_tex != null &&
                        specular != Color.white
                    )
                    )
                {
                    mat.SetColor("_SpecColor", specular);
                }

                var transparent = lmvMat.transparent;
                if (transparent)
                {
                    mat.SetFloat("_Mode", (float)BlendMode.Transparent);
                    mat.EnableKeyword("_ALPHABLEND_ON");
                    Color color = mat.GetColor("_Color");
                    color.a = lmvMat.transparency;
                    mat.SetColor("_Color", color);
                }

                // Create a new request to get the Textures
                if (lmvMat.diffuse_tex != null)
                {
                    //TextureRequest req =new TextureRequest (loader, null, mat, Texture.TextureType.Diffuse, lmvMat.material) ;
                    TextureRequest req = new TextureRequest(loader, null, bearer, mat, lmvMat.diffuse_tex, lmvMat.material);
                    if (fireRequestCallback != null)
                    {
                        fireRequestCallback(this, req);
                    }
                }
                if (lmvMat.specular_tex != null)
                {
                    TextureRequest req = new TextureRequest(loader, null, bearer, mat, lmvMat.specular_tex, lmvMat.material);
                    if (fireRequestCallback != null)
                    {
                        fireRequestCallback(this, req);
                    }
                }
                if (lmvMat.bump_tex != null)
                {
                    TextureRequest req = new TextureRequest(loader, null, bearer, mat, lmvMat.bump_tex, lmvMat.material);
                    if (fireRequestCallback != null)
                    {
                        fireRequestCallback(this, req);
                    }
                }
            } catch (System.Exception e) {
                Debug.Log("exception " + e.Message);
                mat = ForgeLoaderEngine.GetDefaultMaterial();
            }
            return(mat);
        }
        public override GameObject BuildScene(string name, bool saveToDisk = false)
        {
            try {
                foreach (Eppy.Tuple <int, OpenCTM.Mesh> openctm in _openctm)
                {
                    OpenCTM.Mesh ctmMesh = openctm.Item2;
                    if (ctmMesh == null || ctmMesh.getVertexCount() == 0 || ctmMesh.getTriangleCount() == 0)
                    {
                        state = SceneLoadingStatus.eCancelled;
                        return(gameObject);
                    }

                    Eppy.Tuple <int, int, GameObject, JSONNode> item = fragments.Single(x => x.Item1 == openctm.Item1);
                    GameObject meshObject = item.Item3;

                    Mesh       mesh     = new Mesh();
                    Vector3 [] vertices = MeshRequest2.getAsVector3(ctmMesh.vertices);
                    mesh.vertices  = vertices;
                    mesh.triangles = ctmMesh.indices;
                    if (ctmMesh.hasNormals())
                    {
                        mesh.normals = MeshRequest2.getAsVector3(ctmMesh.normals);
                    }
                    for (int i = 0; i < ctmMesh.getUVCount(); i++)
                    {
                        mesh.SetUVs(i, MeshRequest2.getAsVector2List(ctmMesh.texcoordinates [i].values));
                    }

                    mesh.RecalculateNormals();
                    mesh.RecalculateBounds();

                    MeshFilter filter = meshObject.AddComponent <MeshFilter> ();
                    filter.sharedMesh = mesh;
                    MeshRenderer renderer = meshObject.AddComponent <MeshRenderer> ();
                    renderer.sharedMaterial = ForgeLoaderEngine.GetDefaultMaterial();
                    if (createCollider)
                    {
                        MeshCollider collider = meshObject.AddComponent <MeshCollider> ();
                        collider.sharedMesh = mesh;
                    }
#if UNITY_EDITOR
                    if (saveToDisk)
                    {
                        AssetDatabase.CreateAsset(mesh, ForgeConstants._resourcesPath + this.loader.PROJECTID + "/" + GetName(item.Item1) + ".asset");
                        //AssetDatabase.SaveAssets () ;
                        //AssetDatabase.Refresh () ;
                        //mesh =AssetDatabase.LoadAssetAtPath<Mesh> (ForgeConstants._resourcesPath + this.loader.PROJECTID + "/" + name + ".asset") ;
                    }
#endif

                    // Add our material to the queue
                    loader.GetMgr()._materials.Add(item.Item2);
                    //if ( loader.GetMgr ()._materials.Add (item.Item2) ) {
                    //	MaterialRequest req = new MaterialRequest (loader, null, bearer, item.Item2, item.Item4);
                    //	req.gameObject = meshObject;
                    //	if ( fireRequestCallback != null )
                    //		fireRequestCallback (this, req);
                    //}
                }
                base.BuildScene(name, saveToDisk);
                state = SceneLoadingStatus.eWaitingMaterial;
            } catch (Exception ex) {
                Debug.Log(ForgeLoader.GetCurrentMethod() + " " + ex.Message);
                state = SceneLoadingStatus.eError;
            }
            return(gameObject);
        }