コード例 #1
0
    protected override DynamicEntityComponent CreateEntityComponent(VoxelArray voxelArray)
    {
        GameObject playerObject = Resources.Load <GameObject>("ObjectPrefabs/Player");

        playerObject = GameObject.Instantiate(playerObject);
        return(playerObject.AddComponent <PlayerComponent>());
    }
コード例 #2
0
    public List <string> BuildWorld(Transform cameraPivot, VoxelArray voxelArray, bool editor)
    {
        this.editor = editor;

        MessagePackObjectDictionary worldDict = worldObject.AsDictionary();

        CheckWorldValid(worldDict);
        fileWriterVersion = worldDict[FileKeys.WORLD_WRITER_VERSION].AsInt32();

        EntityReference.ResetEntityIds();

        try
        {
            ReadWorld(worldDict, cameraPivot, voxelArray);
        }
        catch (MapReadException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            throw new MapReadException("Error reading world file", e);
        }

        EntityReference.DoneLoadingEntities();
        return(warnings);
    }
コード例 #3
0
ファイル: Substance.cs プロジェクト: VN0/voxel-editor
    public override EntityComponent InitEntityGameObject(VoxelArray voxelArray, bool storeComponent = true)
    {
        GameObject substanceObject = new GameObject();

        substanceObject.name               = "Substance";
        substanceObject.transform.parent   = voxelArray.transform;
        substanceObject.transform.position = PositionInEditor();
        foreach (Voxel voxel in voxels)
        {
            if (storeComponent)
            {
                voxel.transform.parent = substanceObject.transform;
            }
            else
            {
                // clone
                Voxel vClone = voxel.Clone();
                vClone.transform.parent   = substanceObject.transform;
                vClone.transform.position = voxel.transform.position;
                vClone.transform.rotation = voxel.transform.rotation;
            }
        }
        SubstanceComponent component = substanceObject.AddComponent <SubstanceComponent>();

        component.entity    = this;
        component.substance = this;
        component.health    = health;
        if (storeComponent)
        {
            this.component = component;
        }
        return(component);
    }
コード例 #4
0
    public void Write(Transform cameraPivot, VoxelArray voxelArray)
    {
        if (voxelArray.IsEmpty())
        {
            Debug.Log("World is empty! File will not be written.");
            return;
        }

        JSONObject root = new JSONObject();

        root["writerVersion"]    = VERSION;
        root["minReaderVersion"] = FILE_MIN_READER_VERSION;

        JSONObject camera = new JSONObject();

        camera["pan"]    = WriteVector3(cameraPivot.position);
        camera["rotate"] = WriteQuaternion(cameraPivot.rotation);
        camera["scale"]  = cameraPivot.localScale.z;
        root["camera"]   = camera;

        root["world"] = WriteWorld(voxelArray);

        string filePath = WorldFiles.GetFilePath(fileName);

        using (FileStream fileStream = File.Create(filePath))
        {
            using (var sw = new StreamWriter(fileStream))
            {
                sw.Write(root.ToString());
                sw.Flush();
            }
        }
    }
コード例 #5
0
ファイル: Object.cs プロジェクト: JayDown/voxel-editor
    public override EntityComponent InitEntityGameObject(VoxelArray voxelArray, bool storeComponent = true)
    {
        var c = CreateEntityComponent(voxelArray);

        c.transform.parent   = voxelArray.transform;
        c.transform.position = PositionInEditor();
        c.transform.rotation = Quaternion.Euler(new Vector3(0, rotation, 0));
        c.entity             = this;
        c.health             = health;
        if (storeComponent)
        {
            component = c;
        }
        Renderer renderer = c.GetComponent <Renderer>();

        if (renderer != null)
        {
            List <Material> materials = new List <Material>();
            if (paint.material != null)
            {
                materials.Add(paint.material);
            }
            if (paint.overlay != null)
            {
                materials.Add(paint.overlay);
            }
            renderer.materials = materials.ToArray();
        }
        return(c);
    }
コード例 #6
0
ファイル: ReadWorldFile.cs プロジェクト: bmjoy/voxel-editor
    // return warnings
    public static List <string> Read(Stream stream, Transform cameraPivot, VoxelArray voxelArray, bool editor)
    {
        WorldFileReader reader;

        using (stream)
            reader = ReadStream(stream);
        return(BuildWorld(reader, cameraPivot, voxelArray, editor));
    }
コード例 #7
0
    private GameObject ObjectTemplate(VoxelArray voxelArray)
    {
        GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Sphere);

        obj.name = "Ball";
        obj.GetComponent <MeshRenderer>().materials = new Material[] { material };
        return(obj);
    }
コード例 #8
0
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        VoxelArray obj = (VoxelArray)target;

        if (GUILayout.Button("Refresh Data"))
        {
            obj.refreshData();
        }
    }
コード例 #9
0
ファイル: JSONWorldReader.cs プロジェクト: bmjoy/voxel-editor
 private void ReadMap(JSONObject map, VoxelArray voxelArray,
                      List <Material> materials, List <Substance> substances)
 {
     if (map["voxels"] != null)
     {
         foreach (JSONNode voxelNode in map["voxels"].AsArray)
         {
             JSONObject voxelObject = voxelNode.AsObject;
             ReadVoxel(voxelObject, voxelArray, materials, substances);
         }
     }
 }
コード例 #10
0
ファイル: JSONWorldReader.cs プロジェクト: VN0/voxel-editor
    private void ReadVoxel(JSONObject voxelObject, VoxelArray voxelArray,
                           List <Material> materials, List <Substance> substances)
    {
        if (voxelObject["at"] == null)
        {
            return;
        }
        Vector3 position = ReadVector3(voxelObject["at"].AsArray);
        Voxel   voxel    = null;

        if (!editor)
        {
            // slightly faster -- doesn't add to octree
            voxel = voxelArray.InstantiateVoxel(position);
        }
        else
        {
            voxel = voxelArray.VoxelAt(position, true);
        }

        if (voxelObject["s"] != null)
        {
            voxel.substance = substances[voxelObject["s"].AsInt];
        }

        if (voxelObject["f"] != null)
        {
            foreach (JSONNode faceNode in voxelObject["f"].AsArray)
            {
                JSONObject faceObject = faceNode.AsObject;
                if (fileWriterVersion == 0)
                {
                    // faces were oriented differently. Get voxel for each face
                    int faceI = faceObject["i"].AsInt;
                    voxel = voxelArray.VoxelAt(position + Voxel.DirectionForFaceI(faceI), true);
                }
                ReadFace(faceObject, voxel, materials);
            }
        }

        if (voxelObject["e"] != null)
        {
            foreach (JSONNode edgeNode in voxelObject["e"].AsArray)
            {
                ReadEdge(edgeNode.AsObject, voxel);
            }
        }
        voxel.UpdateVoxel();
    }
コード例 #11
0
ファイル: Object.cs プロジェクト: bmjoy/voxel-editor
    public override EntityComponent InitEntityGameObject(VoxelArray voxelArray, bool storeComponent = true)
    {
        var c = CreateEntityComponent(voxelArray);

        c.transform.parent   = voxelArray.transform;
        c.transform.position = PositionInEditor();
        c.transform.rotation = Quaternion.Euler(new Vector3(0, rotation, 0));
        c.entity             = this;
        c.health             = health;
        if (storeComponent)
        {
            component = c;
        }
        return(c);
    }
コード例 #12
0
 private static List <string> BuildWorld(WorldFileReader reader,
                                         Transform cameraPivot, VoxelArray voxelArray, bool editor)
 {
     try
     {
         return(reader.BuildWorld(cameraPivot, voxelArray, editor));
     }
     catch (MapReadException e)
     {
         throw e;
     }
     catch (Exception e)
     {
         throw new MapReadException("An error occurred while reading the file", e);
     }
 }
コード例 #13
0
    private void ReadVoxel(MessagePackObject voxelObj, VoxelArray voxelArray,
                           List <Material> materials, List <Material> overlays, List <Substance> substances)
    {
        var voxelList = voxelObj.AsList();

        if (voxelList.Count == 0)
        {
            return;
        }

        Vector3 position = ReadVector3(voxelList[0]);
        Voxel   voxel    = null;

        if (!editor)
        {
            // slightly faster -- doesn't add to octree
            voxel = voxelArray.InstantiateVoxel(position);
        }
        else
        {
            voxel = voxelArray.VoxelAt(position, true);
        }

        if (voxelList.Count >= 2)
        {
            foreach (var faceObj in voxelList[1].AsList())
            {
                ReadFace(faceObj, voxel, materials, overlays);
            }
        }

        if (voxelList.Count >= 3 && voxelList[2].AsInt32() != -1)
        {
            voxel.substance = substances[voxelList[2].AsInt32()];
        }

        if (voxelList.Count >= 4)
        {
            foreach (var edgeObj in voxelList[3].AsList())
            {
                ReadEdge(edgeObj, voxel);
            }
        }

        voxel.UpdateVoxel();
    }
コード例 #14
0
    public List <string> BuildWorld(Transform cameraPivot, VoxelArray voxelArray, bool editor)
    {
        var warnings = ReadWorldFile.Read(Resources.Load <TextAsset>("Templates/indoor"),
                                          cameraPivot, voxelArray, editor);

        foreach (var obj in voxelArray.IterateObjects())
        {
            if (obj is PlayerObject)
            {
                var behavior = new SoundBehavior();
                behavior.SetProperty("dat", data);
                obj.behaviors.Add(behavior);
                break;
            }
        }
        return(warnings);
    }
コード例 #15
0
    private JSONObject WriteMap(VoxelArray voxelArray, List <string> materials, List <Substance> substances)
    {
        JSONObject map    = new JSONObject();
        JSONArray  voxels = new JSONArray();

        foreach (Voxel voxel in voxelArray.IterateVoxels())
        {
            if (voxel.CanBeDeleted())
            {
                Debug.Log("Empty voxel found!");
                voxelArray.VoxelModified(voxel);
                continue;
            }
            voxels[-1] = WriteVoxel(voxel, materials, substances);
        }
        map["voxels"] = voxels;
        return(map);
    }
コード例 #16
0
    private JSONObject WriteWorld(VoxelArray voxelArray)
    {
        JSONObject world = new JSONObject();

        JSONArray materialsArray  = new JSONArray();
        var       foundMaterials  = new List <string>();
        JSONArray substancesArray = new JSONArray();
        var       foundSubstances = new List <Substance>();

        foreach (Voxel voxel in voxelArray.IterateVoxels())
        {
            foreach (VoxelFace face in voxel.faces)
            {
                AddMaterial(face.material, foundMaterials, materialsArray);
                AddMaterial(face.overlay, foundMaterials, materialsArray);
            }
            if (voxel.substance != null && !foundSubstances.Contains(voxel.substance))
            {
                foundSubstances.Add(voxel.substance);
                substancesArray[-1] = WriteEntity(voxel.substance, false);
            }
        }

        world["materials"] = materialsArray;
        if (foundSubstances.Count != 0)
        {
            world["substances"] = substancesArray;
        }
        world["global"] = WritePropertiesObject(voxelArray.world, false);
        world["map"]    = WriteMap(voxelArray, foundMaterials, foundSubstances);

        JSONArray objectsArray = new JSONArray();

        foreach (ObjectEntity obj in voxelArray.IterateObjects())
        {
            objectsArray[-1] = WriteObjectEntity(obj, true);
        }
        if (objectsArray.Count != 0)
        {
            world["objects"] = objectsArray;
        }

        return(world);
    }
コード例 #17
0
    public static void Write(string filePath, Transform cameraPivot, VoxelArray voxelArray)
    {
        if (voxelArray.IsEmpty())
        {
            Debug.Log("World is empty! File will not be written.");
            return;
        }
        Debug.Log("Writing MessagePack file " + filePath);

        var world       = WriteWorld(cameraPivot, voxelArray);
        var worldObject = new MessagePackObject(world);

        using (FileStream fileStream = File.Create(filePath))
        {
            fileStream.WriteByte((byte)'m');
            var packer = Packer.Create(fileStream, PackerCompatibilityOptions.None);
            worldObject.PackToMessage(packer, null);
        }
    }
コード例 #18
0
    private void ReadVoxel(MessagePackObject voxelObj, VoxelArray voxelArray,
                           List <Material> materials, List <Material> overlays, List <Substance> substances)
    {
        var voxelList = voxelObj.AsList();

        if (voxelList.Count == 0)
        {
            return;
        }

        Vector3Int position = ReadVector3Int(voxelList[0]);
        Voxel      voxel    = null;

        voxel = voxelArray.VoxelAt(position, true);

        if (voxelList.Count >= 2)
        {
            foreach (var faceObj in voxelList[1].AsList())
            {
                VoxelFace face = ReadFace(faceObj, out int faceI, materials, overlays);
                if (faceI != -1)
                {
                    voxel.faces[faceI] = face;
                }
            }
        }

        if (voxelList.Count >= 3 && voxelList[2].AsInt32() != -1)
        {
            voxel.substance = substances[voxelList[2].AsInt32()];
        }

        if (voxelList.Count >= 4)
        {
            foreach (var edgeObj in voxelList[3].AsList())
            {
                ReadEdge(edgeObj, voxel);
            }
        }

        voxel.UpdateVoxel();
    }
コード例 #19
0
ファイル: Substance.cs プロジェクト: bmjoy/voxel-editor
    public override EntityComponent InitEntityGameObject(VoxelArray voxelArray, bool storeComponent = true)
    {
        GameObject substanceObject = new GameObject();

        substanceObject.name               = "Substance";
        substanceObject.transform.parent   = voxelArray.transform;
        substanceObject.transform.position = PositionInEditor();

        var voxelComponents = new HashSet <VoxelComponent>();

        foreach (Voxel v in voxels)
        {
            voxelComponents.Add(v.voxelComponent);
        }
        foreach (VoxelComponent vc in voxelComponents)
        {
            // TODO: need to update this!
            if (storeComponent)
            {
                vc.transform.parent = substanceObject.transform;
            }
            else
            {
                // clone
                VoxelComponent vClone = vc.Clone();
                vClone.transform.parent   = substanceObject.transform;
                vClone.transform.position = vc.transform.position;
                vClone.transform.rotation = vc.transform.rotation;
            }
        }
        SubstanceComponent component = substanceObject.AddComponent <SubstanceComponent>();

        component.entity    = this;
        component.substance = this;
        component.health    = health;
        if (storeComponent)
        {
            this.component = component;
        }
        return(component);
    }
コード例 #20
0
    // return false if object could not be placed
    public bool PlaceObject(ObjectEntity obj)
    {
        Vector3 createPosition  = selectionBounds.center;
        int     faceNormal      = GetSelectedFaceNormal();
        Vector3 createDirection = Voxel.DirectionForFaceI(faceNormal);

        if (faceNormal != -1)
        {
            createPosition += createDirection / 2;
        }
        else
        {
            faceNormal      = 3;
            createDirection = Vector3.up;
        }
        createPosition -= new Vector3(0.5f, 0.5f, 0.5f);

        // don't create the object at the same location of an existing object
        // keep moving in the direction of the face normal until an empty space is found
        while (true)
        {
            Voxel voxel = VoxelAt(createPosition, false);
            if (voxel != null && voxel.substance == null && !voxel.faces[Voxel.OppositeFaceI(faceNormal)].IsEmpty())
            {
                return(false); // blocked by wall. no room to create object
            }
            if (voxel == null || voxel.objectEntity == null)
            {
                break;
            }
            createPosition += createDirection;
        }
        obj.position = VoxelArray.Vector3ToInt(createPosition);

        obj.InitObjectMarker(this);
        AddObject(obj);
        unsavedChanges = true;
        // select the object. Wait one frame so the position is correct
        StartCoroutine(SelectNewObjectCoroutine(obj));
        return(true);
    }
コード例 #21
0
ファイル: JSONWorldReader.cs プロジェクト: bmjoy/voxel-editor
    public List <string> BuildWorld(Transform cameraPivot, VoxelArray voxelArray, bool editor)
    {
        this.editor = editor;

        JSONObject root = rootNode.AsObject;

        if (root == null || root["writerVersion"] == null || root["minReaderVersion"] == null)
        {
            throw new MapReadException("Invalid world file");
        }
        if (root["minReaderVersion"].AsInt > VERSION)
        {
            throw new MapReadException("This world file requires a newer version of the app");
        }
        fileWriterVersion = root["writerVersion"].AsInt;

        EntityReference.ResetEntityIds();

        try
        {
            if (editor && cameraPivot != null && root["camera"] != null)
            {
                ReadCamera(root["camera"].AsObject, cameraPivot);
            }
            if (root["world"] != null)
            {
                ReadWorld(root["world"].AsObject, voxelArray);
            }
        }
        catch (MapReadException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            throw new MapReadException("Error reading world file", e);
        }

        EntityReference.DoneLoadingEntities();
        return(warnings);
    }
コード例 #22
0
ファイル: Clone.cs プロジェクト: JayDown/voxel-editor
    public override void BehaviorEnabled()
    {
        EntityComponent entityComponent = GetComponent <EntityComponent>();
        VoxelArray      voxelArray      = transform.parent.GetComponent <VoxelArray>();
        EntityComponent entityClone     = entityComponent.entity.InitEntityGameObject(voxelArray, storeComponent: false);

        // based on TeleportComponent
        entityClone.transform.position = transform.position;
        if (dest.component != null)
        {
            Vector3 originPos;
            if (origin.component != null)
            {
                originPos = origin.component.transform.position;
            }
            else
            {
                originPos = transform.position;
            }
            entityClone.transform.position += dest.component.transform.position - originPos;
        }
    }
コード例 #23
0
ファイル: ReadWorldFile.cs プロジェクト: bmjoy/voxel-editor
    private static List <string> BuildWorld(WorldFileReader reader,
                                            Transform cameraPivot, VoxelArray voxelArray, bool editor)
    {
        if (missingMaterial == null)
        {
            // allowTransparency is true in case the material is used for an overlay, so the alpha value can be adjusted
            missingMaterial       = ResourcesDirectory.MakeCustomMaterial(ColorMode.UNLIT, true);
            missingMaterial.color = Color.magenta;
        }

        try
        {
            return(reader.BuildWorld(cameraPivot, voxelArray, editor));
        }
        catch (MapReadException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            throw new MapReadException("An error occurred while reading the file", e);
        }
    }
コード例 #24
0
    private void ReadWorld(MessagePackObjectDictionary world, Transform cameraPivot, VoxelArray voxelArray)
    {
        if (editor && cameraPivot != null && world.ContainsKey(FileKeys.WORLD_CAMERA))
        {
            ReadCamera(world[FileKeys.WORLD_CAMERA].AsDictionary(), cameraPivot);
        }

        var materials = new List <Material>();

        if (world.ContainsKey(FileKeys.WORLD_MATERIALS))
        {
            foreach (var matObj in world[FileKeys.WORLD_MATERIALS].AsList())
            {
                materials.Add(ReadMaterial(matObj.AsDictionary(), false));
            }
        }

        var overlays = new List <Material>();

        if (world.ContainsKey(FileKeys.WORLD_OVERLAYS))
        {
            foreach (var matObj in world[FileKeys.WORLD_OVERLAYS].AsList())
            {
                overlays.Add(ReadMaterial(matObj.AsDictionary(), true));
            }
        }

        var substances = new List <Substance>();

        if (world.ContainsKey(FileKeys.WORLD_SUBSTANCES))
        {
            foreach (var subObj in world[FileKeys.WORLD_SUBSTANCES].AsList())
            {
                Substance s = new Substance();
                ReadEntity(subObj.AsDictionary(), s);
                substances.Add(s);
            }
        }

        if (world.ContainsKey(FileKeys.WORLD_GLOBAL))
        {
            ReadPropertiesObject(world[FileKeys.WORLD_GLOBAL].AsDictionary(), voxelArray.world);
        }

        if (world.ContainsKey(FileKeys.WORLD_VOXELS))
        {
            foreach (var voxelObj in world[FileKeys.WORLD_VOXELS].AsList())
            {
                ReadVoxel(voxelObj, voxelArray, materials, overlays, substances);
            }
        }

        if (world.ContainsKey(FileKeys.WORLD_OBJECTS))
        {
            foreach (var objObj in world[FileKeys.WORLD_OBJECTS].AsList())
            {
                var    objDict  = objObj.AsDictionary();
                string typeName = objDict[FileKeys.PROPOBJ_NAME].AsString();
                var    objType  = GameScripts.FindTypeWithName(GameScripts.objects, typeName);
                if (objType == null)
                {
                    warnings.Add("Unrecognized object type: " + typeName);
                    continue;
                }
                ObjectEntity obj = (ObjectEntity)objType.Create();
                ReadObjectEntity(objDict, obj);
                voxelArray.AddObject(obj);
            }
        }

        if (!editor)
        {
            // start the game
            foreach (Substance s in substances)
            {
                s.InitEntityGameObject(voxelArray);
            }
            foreach (ObjectEntity obj in voxelArray.IterateObjects())
            {
                obj.InitEntityGameObject(voxelArray);
            }
        }
        else // editor
        {
            foreach (ObjectEntity obj in voxelArray.IterateObjects())
            {
                obj.InitObjectMarker((VoxelArrayEditor)voxelArray);
            }
        }
    }
コード例 #25
0
    private static MessagePackObjectDictionary WriteWorld(Transform cameraPivot, VoxelArray voxelArray)
    {
        var world = new MessagePackObjectDictionary();

        world[FileKeys.WORLD_WRITER_VERSION]     = VERSION;
        world[FileKeys.WORLD_MIN_READER_VERSION] = FILE_MIN_READER_VERSION;

        world[FileKeys.WORLD_TYPE] = (int)voxelArray.type;

        world[FileKeys.WORLD_CAMERA] = new MessagePackObject(WriteCamera(cameraPivot));

        var materialsList   = new List <MessagePackObject>();
        var foundMaterials  = new List <string>();
        var overlaysList    = new List <MessagePackObject>();
        var foundOverlays   = new List <string>();
        var substancesList  = new List <MessagePackObject>();
        var foundSubstances = new List <Substance>();

        foreach (Voxel voxel in voxelArray.IterateVoxels())
        {
            foreach (VoxelFace face in voxel.faces)
            {
                AddMaterial(face.material, foundMaterials, materialsList);
                AddMaterial(face.overlay, foundOverlays, overlaysList);
            }
            if (voxel.substance != null && !foundSubstances.Contains(voxel.substance))
            {
                foundSubstances.Add(voxel.substance);
                substancesList.Add(new MessagePackObject(WriteEntity(voxel.substance, false)));
            }
        }

        world[FileKeys.WORLD_MATERIALS] = new MessagePackObject(materialsList);
        world[FileKeys.WORLD_OVERLAYS]  = new MessagePackObject(overlaysList);
        if (foundSubstances.Count != 0)
        {
            world[FileKeys.WORLD_SUBSTANCES] = new MessagePackObject(substancesList);
        }
        world[FileKeys.WORLD_GLOBAL] = new MessagePackObject(WritePropertiesObject(voxelArray.world, false));

        var voxelsList = new List <MessagePackObject>();

        foreach (Voxel voxel in voxelArray.IterateVoxels())
        {
            if (voxel.CanBeDeleted())
            {
                Debug.Log("Empty voxel found!");
                continue;
            }
            voxelsList.Add(WriteVoxel(voxel, foundMaterials, foundOverlays, foundSubstances));
        }
        world[FileKeys.WORLD_VOXELS] = new MessagePackObject(voxelsList);

        var objectsList = new List <MessagePackObject>();

        foreach (ObjectEntity obj in voxelArray.IterateObjects())
        {
            objectsList.Add(new MessagePackObject(WriteObjectEntity(obj, true)));
        }
        if (objectsList.Count != 0)
        {
            world[FileKeys.WORLD_OBJECTS] = new MessagePackObject(objectsList);
        }

        return(world);
    }
コード例 #26
0
ファイル: SingularMesh.cs プロジェクト: DaviesCooper/AMish
        /// <summary>
        /// Given a filename and a resolution, creates a point cloud array from
        /// the locations found in the file
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="resolution"></param>
        /// <returns></returns>
        public VoxelArray createPointCloud(string filename, int resolution, string xaxis, string yaxis, string zaxis, float[] minMaxArray)
        {
            //how to output the file based on input
            string filePath  = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(filename)));
            string attribute = Path.GetFileName(Path.GetDirectoryName(filename));
            string divider   = Path.GetFileNameWithoutExtension(filename);

            Directory.CreateDirectory(filePath + "\\meshes\\" + attribute + "\\" + resolution + "\\");
            outputPath = filePath + "\\meshes\\" + attribute + "\\" + resolution + "\\" + divider;

            List <FieldCell> cells = FieldCell.ReadCells(filename);

            //sort based on cell number
            cells.Sort(delegate(FieldCell c1, FieldCell c2) { return(c1.cellNum.CompareTo(c2.cellNum)); });
            //Now we need to create a list of ATTRPoint by pulling necessarry parts from
            //other files

            //TODO make this so that it checks if the axis exist in the cache
            string xFPath = Path.Combine(filePath, "fields", xaxis, "full.BNF");
            string yFPath = Path.Combine(filePath, "fields", yaxis, "full.BNF");
            string zFPath = Path.Combine(filePath, "fields", zaxis, "full.BNF");

            //Set up xcoord, ycoord, zcoord readers
            FileStream[] streams = new FileStream[3];
            streams[0] = File.OpenRead(xFPath);
            streams[1] = File.OpenRead(yFPath);
            streams[2] = File.OpenRead(zFPath);
            BinaryReader[] readers = new BinaryReader[3];
            readers[0] = new BinaryReader(streams[0]);
            readers[1] = new BinaryReader(streams[1]);
            readers[2] = new BinaryReader(streams[2]);

            int numToRead = 1;
            int bIndex    = 0;
            List <AttCoordCell> points = new List <AttCoordCell>();
            int count = 0;

            for (int i = 0; i < cells.Count; i++)
            {
                //The number of floats to read from each file is:
                //numToRead = cells[i].cellnumber - bIndex
                //The next bytes will be the values associated with the
                //desired cell
                //Then set bIndex = cells[i].cellnumber so that our bIndex
                //is updated
                numToRead = (cells[i].cellNum - bIndex) - 1;
                //incrementing our readers to the correct index

                if (numToRead > 0)
                {
                    int bytes = numToRead * 4;
                    readers[0].ReadBytes(bytes);
                    readers[1].ReadBytes(bytes);
                    readers[2].ReadBytes(bytes);
                }

                float xc = readers[0].ReadSingle();
                float yc = readers[1].ReadSingle();
                float zc = readers[2].ReadSingle();
                bIndex = cells[i].cellNum;
                AttCoordCell toAdd = new AttCoordCell(cells[i].cellNum, xc, yc, zc, cells[i].field);
                points.Add(toAdd);
                count++;
                //if (count % 50000 == 0)
                //{
                //    double perc = ((double)count / (double)cells.Count) * 100;
                //    PercentageClass.UpdatePercentage("Creating Point Cloud Array", perc);
                //    DebugLog.logConsole("Attribute Coordcell Reading: "+perc.ToString("#.##") + "%");
                //}
            }

            foreach (BinaryReader r in readers)
            {
                r.Close();
            }
            foreach (Stream s in streams)
            {
                s.Close();
            }
            if (points.Count < 3)
            {
                throw new InvalidOperationException();
            }
            if (minMaxArray == null)
            {
                List <float> newMinMax = new List <float>();
                string[]     axises    = new string[] { xaxis, yaxis, zaxis };
                foreach (string a in axises)
                {
                    string axisPath = Path.Combine(filePath, "fields", xaxis, "mmAray.bin");

                    float[] minMax = AllMeshes.minMaxOfFile(axisPath);
                    newMinMax.Add(minMax[0]);
                    newMinMax.Add(minMax[1]);
                }

                VoxelArray array = new VoxelArray(resolution, newMinMax.ToArray());
                //inserting all the points into the array
                array.insertPoints(points);

                return(array);
            }
            else
            {
                VoxelArray array = new VoxelArray(resolution, minMaxArray);
                //inserting all the points into the array
                array.insertPoints(points);

                return(array);
            }
        }
コード例 #27
0
ファイル: SingularMesh.cs プロジェクト: DaviesCooper/AMish
        //args0 - filepath
        //args1 - resolution
        //args2 - xaxis
        //args3 - yaxis
        //args4 - zaxis
        //args5 - isoLevel
        public static void Main(string[] args)
        {
            DebugLog.resetLog();
            DebugLog.setDebug(true);
            int   resolution;
            float isoLevel;

            #region cmd args handling
            if (args.Length > 6 || args.Length < 1)
            {
                Console.Out.WriteLine(numArgs);
                Console.In.ReadLine();
                return;
            }
            if (args.Length == 1 && (args[0].ToLower() == "--help" || args[0].ToLower() == "help" || args[0].ToLower() == "?" || args[0].ToLower() == "h"))
            {
                Console.Out.WriteLine(help);
                Console.In.ReadLine();
                return;
            }

            if (!File.Exists(args[0]))
            {
                DebugLog.logConsole("Could not find file. Are you sure you are passing in the right string?");
                throw new Exception("Could not find file. Are you sure you are passing in the right string?");
            }
            try
            {
                resolution = Int32.Parse(args[1]);
            }
            catch
            {
                DebugLog.logConsole("Resolution not a number");
                throw new Exception("Resolution not a number");
            }
            try
            {
                isoLevel = float.Parse(args[5]);
            }
            catch
            {
                DebugLog.logConsole("IsoLevel is not a float");
                throw new Exception("IsoLevel is not a float");
            }
            if (resolution < 1)
            {
                DebugLog.logConsole("Resolution cannot be less than 1");
                throw new Exception("Resolution cannot be less than 1");
            }
            #endregion
            SingularMesh mcAlg       = new SingularMesh();
            string       dir         = Directory.GetParent(Directory.GetParent(Directory.GetParent(args[0]).FullName).FullName).Name;
            List <float> minMaxArray = generateMinMaxArray(new string[] { args[2], args[3], args[4] }, dir);


            VoxelArray array = mcAlg.createPointCloud(args[0], resolution, args[2], args[3], args[4], minMaxArray.ToArray());
            //VoxelArray.WriteFloatArray(mcAlg.outputPath + ".FARA", array);
            MarchingCubes test = new MarchingCubes();
            test.SetTarget(isoLevel);
            IM intermediate = test.CreateMesh(array.toFloatArray());
            if (intermediate.verts.Count > 64999)
            {
                IM[] divs = intermediate.divideIntoSmall();
                for (int i = 0; i < divs.Length; i++)
                {
                    divs[i].WriteIntermediateToFile(mcAlg.outputPath + "_" + i + ".IMF");
                }
            }
            else
            {
                intermediate.WriteIntermediateToFile(mcAlg.outputPath + ".IMF");
            }
        }
コード例 #28
0
    protected override DynamicEntityComponent CreateEntityComponent(VoxelArray voxelArray)
    {
        GameObject obj = ObjectTemplate(voxelArray);

        return(obj.AddComponent <BallComponent>());
    }
コード例 #29
0
ファイル: JSONWorldReader.cs プロジェクト: bmjoy/voxel-editor
    private void ReadWorld(JSONObject world, VoxelArray voxelArray)
    {
        var materials = new List <Material>();

        if (world["materials"] != null)
        {
            foreach (JSONNode matNode in world["materials"].AsArray)
            {
                JSONObject matObject = matNode.AsObject;
                materials.Add(ReadMaterial(matObject));
            }
        }

        var substances = new List <Substance>();

        if (world["substances"] != null)
        {
            foreach (JSONNode subNode in world["substances"].AsArray)
            {
                Substance s = new Substance();
                ReadEntity(subNode.AsObject, s);
                substances.Add(s);
            }
        }

        if (world["global"] != null)
        {
            ReadPropertiesObject(world["global"].AsObject, voxelArray.world);
        }
        if (fileWriterVersion <= 2 && world["sky"] != null)
        {
            Material sky = materials[world["sky"].AsInt];
            if (sky != ReadWorldFile.missingMaterial) // default skybox is null
            {
                voxelArray.world.SetSky(sky);
            }
        }
        if (world["map"] != null)
        {
            ReadMap(world["map"].AsObject, voxelArray, materials, substances);
        }
        if (fileWriterVersion <= 2 && world["player"] != null)
        {
            PlayerObject player = new PlayerObject();
            ReadObjectEntity(world["player"].AsObject, player);
            voxelArray.AddObject(player);
        }
        if (world["objects"] != null)
        {
            foreach (JSONNode objNode in world["objects"].AsArray)
            {
                JSONObject objObject = objNode.AsObject;
                string     typeName  = objObject["name"];
                var        objType   = GameScripts.FindTypeWithName(GameScripts.objects, typeName);
                if (objType == null)
                {
                    warnings.Add("Unrecognized object type: " + typeName);
                    continue;
                }
                ObjectEntity obj = (ObjectEntity)objType.Create();
                ReadObjectEntity(objObject, obj);
                voxelArray.AddObject(obj);
            }
        }

        if (!editor)
        {
            // start the game
            foreach (Substance s in substances)
            {
                s.InitEntityGameObject(voxelArray);
            }
            foreach (ObjectEntity obj in voxelArray.IterateObjects())
            {
                obj.InitEntityGameObject(voxelArray);
            }
        }
        else // editor
        {
            foreach (ObjectEntity obj in voxelArray.IterateObjects())
            {
                obj.InitObjectMarker((VoxelArrayEditor)voxelArray);
            }
        }
    }
コード例 #30
0
ファイル: ReadWorldFile.cs プロジェクト: bmjoy/voxel-editor
 public static List <string> Read(TextAsset asset, Transform cameraPivot, VoxelArray voxelArray, bool editor)
 {
     return(Read(new MemoryStream(asset.bytes), cameraPivot, voxelArray, editor));
 }