예제 #1
0
    public void LoadScene()
    {
        try
        {
            // Load previously saved file on startup
            // string drawingLocation = Application.dataPath + "/Drawings";
            // DirectoryInfo directory = new DirectoryInfo(drawingLocation);
            // IOrderedEnumerable<FileInfo> drawFiles = directory.GetFiles("*.json")
            //  .OrderByDescending(f => f.LastWriteTime);

            // Maybe check if a save exists first
            string     path      = Application.dataPath + "/Drawings";
            FileInfo[] drawFiles = new DirectoryInfo(path)
                                   .GetDirectories()
                                   .OrderByDescending(d => d.LastWriteTimeUtc)
                                   .First()
                                   .GetFiles("*.json");

            // This doesn't handle for if the parent doesn't exist :/
            foreach (FileInfo file in drawFiles)
            {
                JsonScene scene = ReadFromFile(file.FullName);
                _tubeLoader.ImportDrawing(
                    scene,
                    DrawParents.Find(o => o.name == file.Name.Replace(".json", "")).transform
                    );
            }
        }
        catch (Exception e)
        {
            Debug.Log("!!!!!!!Exception occured!!!!!!!");
            Debug.LogException(e, this);
        }
    }
예제 #2
0
    void Update()
    {
        timer += 1;
        if (_notLoaded && timer > 500)
        {
            _notLoaded = false;
            string folderPath = Path.Combine(Application.streamingAssetsPath, assetFolder);

            if (Directory.Exists(folderPath))
            {
                foreach (string fileName in Directory.GetFiles(folderPath, "*.json"))
                {
                    string    sceneText   = File.ReadAllText(fileName).Replace("object", "sceneObject");
                    JsonScene loadedModel = JsonUtility.FromJson <JsonScene>(sceneText);

                    foreach (DrawingImport target in loadTargets)
                    {
                        string targetId = target.transform.parent.gameObject.GetComponent <TrackerIdGet>().DeviceID;
                        Debug.Log(target.transform.parent.gameObject.name);
                        Debug.Log(targetId + " --- " + loadedModel.metadata.deviceId);

                        if (targetId == loadedModel.metadata.deviceId)
                        {
                            target.LoadMesh(loadedModel);
                        }
                    }
                }
            }
        }
    }
예제 #3
0
        private static void TestCase05()
        {
            Scene s = new JsonScene(@"../scene/group.json");

            Assert.Equal(4, s.World.Lights.Count);

            s.Capture(@"./group.ppm");
        }
예제 #4
0
        public void LoadScene(JsonScene scene)
        {
            currentScene = scene;

            editorObjects.Clear();

            foreach (JsonGeometry geometry in scene.Geometry)
            {
                JsonMaterial material = scene.Materials.SingleOrDefault(m => m.ID == geometry.Material);
                switch (geometry.Type)
                {
                case "plane":
                {
                    editorObjects.Add(new Plane(geometry.Position, geometry.Normal, material));
                    break;
                }

                case "sphere":
                {
                    editorObjects.Add(new Sphere(geometry.Position, geometry.Radius, material));
                    break;
                }

                case "disc":
                {
                    editorObjects.Add(new Disc(geometry.Position, geometry.Normal, geometry.Radius, material));
                    break;
                }
                }
            }

            foreach (JsonLight light in scene.Lights)
            {
                switch (light.Type)
                {
                case "disc":
                {
                    editorObjects.Add(new Disc(light.Position, light.Normal, light.Radius, new JsonMaterial()
                        {
                            Emission = new JsonEmissionSettings()
                            {
                                Color      = light.Color,
                                Brightness = light.Brightness
                            }
                        }));
                    lightPosition  = new Vector4(light.Position.X, light.Position.Y, light.Position.Z, light.Radius);
                    lightDirection = Vector3.Normalize(light.Normal);
                    lightColor     = new Vector4(light.Color.X, light.Color.Y, light.Color.Z, light.Brightness);
                    break;
                }
                }
            }

            if (initialized)
            {
                editorObjects.ForEach(o => o.Initialize());
            }
        }
예제 #5
0
 public void SetGridFromSaved(JsonScene scene)
 {
     foreach (var jvoxel in scene.JsonVoxels)
     {
         var index = jvoxel.Index;
         var voxel = Voxels[index.x, index.y, index.z];
         voxel.IsActive      = jvoxel.IsActive;
         voxel.VoxelFunction = (Function)Enum.Parse(typeof(Function), jvoxel.VoxelFunction);
     }
 }
예제 #6
0
        private static void TestCase04()
        {
            Scene s = new JsonScene(@"../scene/cone.json");

            Shape cone = s.World.Shapes[1];

            Assert.True(cone is Cone);
            Assert.Equal(0, (cone as Cone)?.Minimum);

            s.Capture(@"./cone.ppm");
        }
예제 #7
0
        private static void TestCase01()
        {
            // Parse reflect-refract scene
            Scene s = new JsonScene(@"../scene/reflect-refract.json");

            // Camera
            Assert.Equal(400, s.Camera.HSize);
            Assert.Equal(200, s.Camera.VSize);
            Assert.Equal(1.152f, s.Camera.FieldOfView, 5);
            Matrix cameraTransform = Transformation.LookAt(Tuple.Point(-2.6f, 1.5f, -3.9f),
                                                           Tuple.Point(-0.6f, 1, -0.8f),
                                                           Tuple.Vector(0, 1, 0));

            Assert.Equal(cameraTransform, s.Camera.Transform);

            // Light
            Assert.Single(s.World.Lights);
            Assert.Equal(Tuple.Point(-4.9f, 4.9f, -1), s.World.Lights[0].Position);
            Assert.Equal(Tuple.Color(1, 1, 1), s.World.Lights[0].Intensity);

            // Shapes
            Shape floor = s.World.Shapes[0];

            Assert.Equal(Transformation.RotationY(0.31415f), floor.Transform);
            Assert.Equal(0, floor.Material.Specular);
            Assert.Equal(0.4f, floor.Material.Reflective);

            Shape ceiling = s.World.Shapes[1];

            Assert.Equal(Tuple.Color(0.8f, 0.8f, 0.8f), ceiling.Material.Color);

            Shape westWall = s.World.Shapes[2];

            Assert.Equal(Transformation.Translation(-5, 0, 0) *
                         Transformation.RotationZ(1.5708f) *
                         Transformation.RotationY(1.5708f), westWall.Transform);
            Assert.True(westWall.Material.Pattern is StripePattern);

            Shape redSphere = s.World.Shapes[10];

            Assert.True(redSphere is Sphere);

            Material blueGassMaterial = s.World.Shapes[11].Material;

            Assert.Equal(0, blueGassMaterial.Ambient, 5);
            Assert.Equal(0.4f, blueGassMaterial.Diffuse, 5);
            Assert.Equal(300, blueGassMaterial.Shininess, 5);
            Assert.Equal(0.9, blueGassMaterial.Reflective, 5);
            Assert.Equal(0.9, blueGassMaterial.Transparency, 5);
            Assert.Equal(1.5, blueGassMaterial.RefractiveIndex, 5);

            s.Capture(@"./reflectRefract.ppm");
        }
예제 #8
0
 // I should move some of this to the TubeDraw script probably
 public void ImportDrawing(JsonScene drawing, Transform parent)
 {
     foreach (Geometry geo in drawing.geometries)
     {
         GameObject newTube = (GameObject)Instantiate(_tube);
         newTube.transform.SetParent(parent, false);
         // Some ugly long way to load a material
         newTube.GetComponent <Renderer>().material = _tools.GetLoadedMat(geo.metadata.mat);
         _allTubes.Add(newTube);
         _allTubes.Last().GetComponent <TubeDraw>().LoadMesh(geo);
     }
 }
예제 #9
0
    public static void AddScene(JsonScene scene)
    {
        if (CreatedScenes.ContainsKey(CurrentLevel))
        {
            CreatedScenes[CurrentLevel] = scene;
        }

        else
        {
            CreatedScenes.Add(CurrentLevel, scene);
        }
    }
예제 #10
0
        private static void TestCase03()
        {
            Scene s = new JsonScene(@"../scene/cylinder.json");

            Shape cyl = s.World.Shapes[1];

            Assert.True(cyl is Cylinder);
            Assert.Equal(0, (cyl as Cylinder)?.Minimum);
            Assert.Equal(0.75f, (cyl as Cylinder)?.Maximum);
            Assert.True((cyl as Cylinder)?.Closed);


            s.Capture(@"./cylinder.ppm");
        }
예제 #11
0
    public List <Room> SetRoomsFromSaved(JsonScene scene)
    {
        // Get the voxels indexes from the saved scene
        // set the according voxels to be part of a room
        List <Room> result = new List <Room>();

        foreach (var jvoxel in scene.JsonVoxels)
        {
            var index = jvoxel.Index;
            var voxel = Voxels[index.x, index.y, index.z];
            voxel.IsActive = jvoxel.IsActive;
            var room = (Room)Enum.Parse(typeof(Room), jvoxel.VoxelFunction);
            voxel.InRoom = room;
            result.Add(room);
        }
        return(result);
    }
예제 #12
0
    public void LoadMesh(JsonScene drawing)
    {
        try
        {
            foreach (Geometry geo in drawing.geometries)
            {
                GameObject newTube = (GameObject)Instantiate(_meshPrefab);
                newTube.transform.SetParent(transform.parent, false);
                // Some ugly long way to load a material
                newTube.GetComponent <Renderer>().material = GetLoadedMat(geo.metadata.mat);
                _allTubes.Add(newTube);
                _allTubes.Last().GetComponent <TubeDraw>().LoadMesh(geo);
            }
        }

        catch (Exception e)
        {
            Debug.Log("!!!!!!!Exception occured in DrawingImport LoadMesh!!!!!!!");
            Debug.LogException(e, this);
        }
    }
예제 #13
0
        private static void TestCase02()
        {
            // Parse table scene
            Scene s = new JsonScene(@"../scene/table.json");

            Shape glassCube = s.World.Shapes[7];

            Assert.True(glassCube is Cube);
            Assert.Equal(Transformation.Translation(0, 3.45001f, 0) *
                         Transformation.RotationY(0.2f) *
                         Transformation.Scaling(0.25f, 0.25f, 0.25f), glassCube.Transform);
            Assert.Equal(Tuple.Color(1, 1, 0.8f), glassCube.Material.Color);
            Assert.Equal(0, glassCube.Material.Ambient, 5);
            Assert.Equal(0.3f, glassCube.Material.Diffuse, 5);
            Assert.Equal(0.9f, glassCube.Material.Specular, 5);
            Assert.Equal(300, glassCube.Material.Shininess, 5);
            Assert.Equal(0.7f, glassCube.Material.Reflective, 5);
            Assert.Equal(0.7f, glassCube.Material.Transparency, 5);
            Assert.Equal(1.5f, glassCube.Material.RefractiveIndex, 5);

            s.Capture(@"./table.ppm");
        }
예제 #14
0
    // Attach this to a button that represents the user is done
    public static void SaveScenes()
    {
        foreach (var level in CreatedScenes.Keys)
        {
            JsonScene jsonScene = CreatedScenes[level];
            string    json      = JsonUtility.ToJson(jsonScene);
            string    filename  = $"Level{level}.json";

            try
            {
                if (!Directory.Exists(_path))
                {
                    Directory.CreateDirectory(_path);                                                                     // changed in technical tutorial
                }
                System.IO.File.WriteAllText(_path + filename, json);
            }
            catch (Exception e)
            {
                Debug.LogWarning(e);
            }
        }
    }
예제 #15
0
    public static void SaveScene(VoxelGrid grid, List <Room> rooms)
    {
        JsonScene jsonScene = ConvertToJsonScene(grid, rooms);
        string    json      = JsonUtility.ToJson(jsonScene);
        string    filename  = $"Level1.json";

        try
        {
            if (!Directory.Exists(_path))
            {
                Directory.CreateDirectory(_path);
            }
            //if (!File.Exists(_path + filename)) System.IO.File.WriteAllText(_path + filename, json);     // changed in technical tutorial
            //else Debug.LogWarning("File allready exists");                                               // changed in technical tutorial

            System.IO.File.WriteAllText(_path + filename, json);
        }
        catch (Exception e)
        {
            Debug.LogWarning(e);
        }
    }
예제 #16
0
    public void ExportMeshes(List <GameObject> objects, string filename, string trackerId)
    {
        try
        {
            // string fileName = EditorUtility.SaveFilePanel("Export .obj file", "", meshName, "obj");
            // string fileName = Application.dataPath + "/" + gameObject.name + ".obj"; // you can also use: "/storage/sdcard1/" +gameObject.

            JsonScene currentScene = new JsonScene(trackerId);
            foreach (GameObject geo in objects)
            {
                currentScene.AddGeometry(geo.transform);
            }

            string json = JsonUtility.ToJson(currentScene);
            WriteToFile(json, filename);
            Debug.Log("Exported Mesh: " + filename);
        }

        catch (Exception e)
        {
            Debug.Log("!!!!!!!Exception occured!!!!!!!");
            Debug.LogException(e, this);
        }
    }
예제 #17
0
파일: Statistics.cs 프로젝트: ZengHuiAn/sgk
    void ConvertToJson(string url, bool limit)
    {
#if UNITY_EDITOR
        if (!enable)
        {
            return;
        }

        JsonData data = new JsonData();
        data.datas = new JsonScene[StatCount.Count];

        int i = 0, k = 0;
        foreach (var itc in StatCount)
        {
            Dictionary <string, int> assets = itc.Value;
            JsonScene scene = new JsonScene();
            data.datas[i++] = scene;
            scene.name      = itc.Key;
            scene.count     = ScenesLoadedCount[itc.Key];

            List <string> l = new List <string>();
            foreach (var it in assets)
            {
                if (it.Value > 1 || !limit)
                {
                    l.Add(it.Key);
                }
            }

            l.Sort((a, b) => {
                if (assets[a] > assets[b])
                {
                    return(-1);
                }
                else
                {
                    return(1);
                }
            });

            int c = l.Count;
            if (limit)
            {
                c = l.Count > StatisticsCount ? StatisticsCount : l.Count;
            }
            scene.objects = new JsonObject[c];

            for (k = 0; k < c; ++k)
            {
                JsonObject obj = new JsonObject();
                obj.asset        = l[k];
                obj.count        = assets[obj.asset];
                scene.objects[k] = obj;
            }
        }

        string str = JsonUtility.ToJson(data);
        Debug.Log(str);

        WebRequest myRequest = WebRequest.Create(url);
        myRequest.Method      = "POST";
        myRequest.ContentType = "application/x-www-form-urlencoded";

        Stream reqs = myRequest.GetRequestStream();
        byte[] ds   = System.Text.Encoding.UTF8.GetBytes("data=" + str);
        reqs.Write(ds, 0, ds.Length);
        reqs.Close();

        HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
        if (myResponse.StatusCode != HttpStatusCode.OK)
        {
            Debug.LogErrorFormat("send statistics failed", myResponse.StatusDescription);
            return;
        }

        Stream       myStream = myResponse.GetResponseStream();
        StreamReader myReader = new StreamReader(myStream);

        string s = myReader.ReadToEnd();
        Debug.Log(s);
#endif
    }
예제 #18
0
    //Used to create a JsonScene from a JSON string
    public static JsonScene CreateFromJSON(string jString)
    {
        JsonScene jScene = JsonUtility.FromJson <JsonScene>(jString);

        return(jScene);
    }
예제 #19
0
        private void LoadScene(string filename)
        {
            JsonScene jsonScene = JsonScene.FromFile(filename);

            sceneNameLabel.Content = $"Scene: {jsonScene.Name}";

            editorViewport.LoadScene(jsonScene);

            Dictionary <string, Material> materials = jsonScene.Materials.ToDictionary(material => material.ID, material =>
            {
                Material mat = new Material().Create();
                if (material.Diffuse != null)
                {
                    mat.SetDiffuse(material.Diffuse.Color, material.Diffuse.Albedo);
                }
                if (material.Emission != null)
                {
                    mat.SetEmission(material.Emission.Color, material.Emission.Brightness);
                }
                if (material.Reflection != null)
                {
                    mat.SetReflection(material.Reflection.Color, material.Reflection.Reflectivity, material.Reflection.IOR);
                }
                return(mat);
            });

            sceneGeometry = jsonScene.Geometry.Select(j =>
            {
                switch (j.Type)
                {
                case "sphere": return(Geometry.CreateSphere(j.Position, j.Radius, materials[j.Material]));

                case "disc": return(Geometry.CreateDisc(j.Position, j.Normal, j.Radius, materials[j.Material]));

                case "plane": return(Geometry.CreatePlane(j.Position, j.Normal, materials[j.Material]));

                case "cylinder": return(Geometry.CreateCylinder(j.Position, j.Normal, j.Radius, j.Height, materials[j.Material]));

                default: return(new Geometry());
                }
            }).ToArray();
            if (jsonScene.Lights.Length > 0)
            {
                sceneLights = jsonScene.Lights.Select(j =>
                {
                    switch (j.Type)
                    {
                    case "disc": return(Light.CreateDisc(j.Position, j.Normal, j.Radius, j.Color, j.Brightness));

                    default: return(new Light());
                    }
                }).ToArray();
            }
            else
            {
                sceneLights = new Light[] { new Light() };
            }

            scene = new Scene()
            {
                Camera             = new Camera(jsonScene.Camera.Position, jsonScene.Camera.LookAt, jsonScene.Camera.FocalLength, RenderWidth, RenderHeight),
                SkylightColor      = jsonScene.Skylight.Color,
                SkylightBrightness = jsonScene.Skylight.Brightness
            };
            SetResolution();
        }