Example #1
0
    void Start()
    {
        // Use Simplex Terrain and our basic Marching Cubes algorithm
        terrGen = new SimplexTerrainGenerator();
        meshGen = new MarchingCubesMeshGenerator();
        world = new WorldData(terrGen, meshGen);

        // Grab the meshfilter from our current object
        // Replace the mesh data with calculated mesh data from WorldData
        var meshfilter = GetComponent<MeshFilter>();
        Mesh mesh = new Mesh();
        Chunk testChunk = world.chunks[0,0];
        mesh.vertices = testChunk.vertices;
        mesh.uv = testChunk.uvRays;
        mesh.triangles = testChunk.triangles;
        meshfilter.mesh = mesh;
        //meshfilter.mesh.vertices = world.vertices;
        //meshfilter.mesh.uv = world.uvRays;
        //meshfilter.mesh.triangles = world.triangles;

        // Update the mesh collider to use the graphical mesh for the physics engine
        mesh.RecalculateNormals();
        var meshcollider = GetComponent<MeshCollider>();
        meshcollider.sharedMesh = mesh;
    }
Example #2
0
    void Start()
    {
        // Use Simplex Terrain and our basic Marching Cubes algorithm
        terrGen = new SimplexTerrainGenerator ();

        // Generate the lookup table for the 256 first pass smoothed surface net possibilities
        SurfaceNetLookupTable.GenerateSmoothedPointLocations(Smoothing);

        // Set the MeshGenerator of your choice
        //meshGen = new RegularCubeMeshGenerator ();
        //meshGen = new MarchingCubesMeshGenerator();
        meshGen = new SurfaceNetsMeshGenerator();

        world = new WorldData (terrGen, meshGen, ChunkXSize, ChunkYSize);

        // Add chunks to the list of nearby chunks for instantiation during runtime
        // Reduces black screen load time
        nearbyChunks = new List<Chunk> ();
        for (int i=0; i<world.chunks.GetLength(0); i++) {
            for (int j=0; j<i+1 && j<world.chunks.GetLength(1); j++) {
                nearbyChunks.Add (world.chunks [i, j]);
            }
            for (int k=0; k<i; k++)
            {
                nearbyChunks.Add (world.chunks[k,i]);
            }
        }
    }
Example #3
0
	public void SaveWorld() {
		WorldData worldData = new WorldData (worldX, worldY, worldZ, chunkSize, data);
		BinaryFormatter bf = new BinaryFormatter ();
		FileStream file = new FileStream (Application.dataPath + "/Resources/" + worldName + "/" + worldName + ".dat", FileMode.Create, FileAccess.Write);
		bf.Serialize (file, worldData);
		file.Close ();
	}
 public TerrainGenerator(WorldData worldData,IChunkProcessor chunkProcessor, IBatchProcessor<Chunk> batchProcessor, ITerrainGenerationMethod terrainGenerationMethod)
 {
     m_WorldData = worldData;
     m_ChunkProcessor = chunkProcessor;
     m_BatchProcessor = batchProcessor;
     m_TerrainGenerationMethod = terrainGenerationMethod;
 }
    public override void parse()
    {
        status = DataReader.ReadShort(dataStream);

        if (status == 0) {
            short size = DataReader.ReadShort(dataStream);

            for (int i = 0; i < size; i++) {
                int world_id = DataReader.ReadInt(dataStream);

                WorldData world = new WorldData(world_id);
                world.name = DataReader.ReadString(dataStream);
                world.type = DataReader.ReadShort(dataStream);
                world.credits = DataReader.ReadInt(dataStream);

                world.isNew = DataReader.ReadBool(dataStream);

                if (!world.isNew) {
                    world.year = DataReader.ReadShort(dataStream);
                    world.month = DataReader.ReadShort(dataStream);
                    world.play_time = DataReader.ReadInt(dataStream);
                    world.score = DataReader.ReadInt(dataStream);
                }

                worldList.Add(world_id, world);
            }
        }
    }
Example #6
0
 /// <summary>
 /// This only exists for testing, not to be called directly by production code.
 /// </summary>
 public WorldDecorator(WorldData worldData, IBatchProcessor<Chunk> batchProcessor, List<IDecoration> decorations,
     IChunkProcessor chunkProcessor)
 {
     m_WorldData = worldData;
     m_BatchProcessor = batchProcessor;
     m_ChunkProcessor = chunkProcessor;
     m_Decorations = decorations;
 }
 public GameObjectCreationData(string name, Vector3 position, Vector3 rotation, WorldData worldData )
 {
     m_Name = name;
     m_Position = position;
     m_Rotation = rotation;
     m_WorldData = worldData;
     GlobalUnityPosition = new Vector3(position.x + worldData.MapBlockOffset.X,position.z + worldData.MapBlockOffset.Z, position.y + worldData.MapBlockOffset.Y);
 }
Example #8
0
 public Chunk(int arrayX, int arrayY, int arrayZ, WorldData worldData)
 {
     m_WorldData = worldData;
     ArrayX = arrayX;
     ArrayY = arrayY;
     ArrayZ = arrayZ;
     m_Id++;
     Id = m_Id;
 }
 // Use this for initialization
 public void Awake()
 {
     if(world == null){
         Debug.Log("Heightmap has no WorldData component, assigning default world data");
         world = GameObject.Find("World").GetComponent<WorldData>();
     }
     size = world.GetWorldSize();
     Generate();
 }
Example #10
0
	public World(string worldName, int seed) {
		this.name = worldName;
		chunks = new Dictionary<Vector3, Chunk> ();

		// load WorldData
		worldData = Serialization.LoadWorldData(this);
		if (worldData == null) {
			worldData = new WorldData (seed);
		}
	}
Example #11
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!this.IsPostBack)
     {
         var data = new WorldData();
         var continents = data.Continents.All().Select(c => c.Name).ToList();
         this.ListBoxContinents.DataSource = continents;
         this.ListBoxContinents.DataBind();
     }
 }
Example #12
0
    // Use this for initialization
    void Start()
    {
        // get the data class
        GameObject scripts = GameObject.Find ("Scripts");
        data = scripts.GetComponent<WorldData> ();

        // start loading the rest
        baseCity = GameObject.FindGameObjectWithTag("BaseCity");
        earth = GameObject.FindGameObjectWithTag("Earth");
        LoadCities();
    }
Example #13
0
 public World(WorldData worldData, ITerrainGenerator terrainGenerator, ILightProcessor lightProcessor,
              IMeshDataGenerator meshDataGenerator, IWorldDecorator worldDecorator, IChunkProcessor chunkProcessor)
 {
     m_WorldData = worldData;
     m_LightProcessor = lightProcessor;
     m_MeshDataGenerator = meshDataGenerator;
     m_WorldDecorator = worldDecorator;
     m_ChunkProcessor = chunkProcessor;
     m_TerrainGenerator = terrainGenerator;
     ContinueProcessingChunks = true;
 }
Example #14
0
        protected void BindCountries(object sender, EventArgs e)
        {
            var selectedContinent = this.ListBoxContinents.SelectedValue;

            var data = new WorldData();

            var coutries = data.Countries.All()
                .Where(c => c.Continent.Name == selectedContinent)
                .ToList();

            this.GridViewCoutries.DataSource = coutries;
            this.GridViewCoutries.DataBind();
        }
Example #15
0
	public string GetCurrentWorldData () {

		WorldData data = new WorldData ();
		data.itemDataList = new List<KeyValuePair<string, string>> ();

		foreach (EditorItem item in this.GetComponentsInChildren<EditorItem>()) {
			EditorItemData itemData = item.GetData();
			string itemDataString = JsonConvert.SerializeObject(itemData);
			data.itemDataList.Add (new KeyValuePair<string, string>(itemData.itemName, itemDataString));
		}

		string worldDataString = JsonConvert.SerializeObject (data);
		return worldDataString;
	}
Example #16
0
        protected void GridViewCoutries_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var gridView = (GridView)sender;
            int countryId = int.Parse(gridView.DataKeys[e.RowIndex].Value.ToString());

            var data = new WorldData();

            var country = data.Countries.Find(countryId);
            data.Countries.Delete(country);

            data.SaveChanges();
            gridView.EditIndex = -1;
            this.BindCountries(null, null);
        }
Example #17
0
    /// <summary>
    /// Finds all decorations in this assembly, creates instances of each in memory,
    /// and adds them to the list.
    /// </summary>
    public static List<IDecoration> LoadDecorators(WorldData worldData)
    {
        List<IDecoration> decorations = new List<IDecoration>();
        foreach (Type type in typeof (IDecoration).Assembly.GetTypes())
        {
            if (typeof(IDecoration).IsAssignableFrom(type) && type.IsClass && !type.IsAbstract)
            {
                IDecoration decoration =
                    Activator.CreateInstance(type, new object[] {worldData}) as IDecoration;
                decorations.Add(decoration);
            }
        }

        return decorations;
    }
Example #18
0
        /// <summary>
        /// Generates a game entity from a world data.
        /// </summary>
        /// <param name="data">
        /// The data to generate from.
        /// </param>
        /// <returns>
        /// A game entity.
        /// </returns>
        public GameEntityBase Create(WorldData data)
        {
            // TODO better conversion
            switch (data.Type)
            {
                case EntityType.TerrainSurface:
                    return TerrainEntity.CreateSurface(this.contentProvider.GetTerrainTexture(data.Subtype), data.Position);
                case EntityType.TerrainObstacle:
                    return TerrainEntity.CreateObstacle(this.contentProvider.GetTerrainTexture(data.Subtype), data.Position, data.Size);
                case EntityType.Ant:
                    return YellowAntEntity.Create(this.contentProvider, data.Position);
            }

            return null;
        }
        public Material getMaterialForSubset(int subset)
        {
            Material mat = null;

            string[] matIds = this.MaterialIDs;
            if (matIds != null)
            {
                try { mat = WorldData.GetObject(materialIDs[subset]) as Material; }
                catch { }
            }
            if (mat == null)
            {
                mat = WorldData.GetObject("DefaultMaterial") as Material;
            }

            return(mat);
        }
Example #20
0
    public void GenerateCanyons(WorldData worldData)
    {
        int distanceFromLast = 0;

        for (int x = 0; x < worldData.Width; x++)
        {
            if (distanceFromLast > minimumCanyonDistance && Random.value < canyonChance)
            {
                distanceFromLast = 0;
                GenerateCanyon(x, worldData);
            }
            else
            {
                distanceFromLast++;
            }
        }
    }
Example #21
0
    public void Generate(WorldData worldData)
    {
        int distanceFromLast = 0;

        for (int x = 0; x < worldData.Width; x++)
        {
            if (distanceFromLast > minimumDistanceBetween && Random.value < chance)
            {
                distanceFromLast = 0;
                GeneratePrairie(x, worldData);
            }
            else
            {
                distanceFromLast++;
            }
        }
    }
Example #22
0
    void Create()
    {
        WorldData data = ScriptableObject.CreateInstance <WorldData>();

        data.fileName    = fileName;
        data.worldID     = worldID;
        data.worldName   = worldName;
        data.description = description;

        data.unlockRequirement = unlockRequirement;
        data.totalLevels       = totalLevels;
        data.totalSecrets      = totalSecrets;

        data.unlockOverride = unlockOverride;
        AssetDatabase.CreateAsset(data, "Assets/Resources/" + fileName + ".asset");
        this.Close();
    }
Example #23
0
    public static void SaveChunks(WorldData world)
    {
        return;

        List <ChunkData> chunks = new List <ChunkData>(world.modifiedChunks);

        world.modifiedChunks.Clear();
        int count = 0;

        foreach (var chunk in chunks)
        {
            SaveChunk(chunk, world.worldName);
            count++;
        }

        Debug.Log($"SaveSystem - {world.worldName} SAVED ! ({count} Chunks");
    }
Example #24
0
    private static void GenerateValleys(WorldData worldData)
    {
        int distanceFromLast = 0;

        for (int x = 0; x < worldData.Width; x++)
        {
            if (distanceFromLast > minimumValleyDistance && Random.value < valleyChance)
            {
                distanceFromLast = 0;
                GenerateValley(x, worldData);
            }
            else
            {
                distanceFromLast++;
            }
        }
    }
        public void MapWorld(World world, WorldData worldData)
        {
            var gridDataDictionary = worldData.Grids.ToDictionary(gridData => gridData.Id);

            foreach (var grid in world.Grids)
            {
                if (gridDataDictionary.TryGetValue(grid.Id, out var gridData))
                {
                    MapGrid(grid, gridData);
                }
            }

            foreach (var entityData in worldData.Entities)
            {
                world.Entities.Add(MapEntity(entityData));
            }
        }
Example #26
0
        public static BlockPosition GetTopSolidBlock(Vector2Int worldPositon, out Chunk chunk)
        {
            chunk = GetChunk(worldPositon.x, worldPositon.y);
            BlockPosition blockPosition = new BlockPosition(new int3(worldPositon.x, 0, worldPositon.y));

            for (int y = ChunkSizeY - 1; y >= 0; y--)
            {
                blockPosition.y = y;
                int index = Utils.BlockPosition3DtoIndex(blockPosition);
                if (WorldData.GetBlockState(chunk.blocks[index]) == BlockState.SOLID)
                {
                    return(blockPosition);
                }
            }

            return(new BlockPosition());
        }
        public static void DrawInstancedSpheres(GraphicsDeviceManager gdm, List <Matrix> instances)
        {
            Model sphere = WorldData.GetObject("sphereInstanced.mesh") as Model;

            D3D10.Buffer    indexBuffer   = sphere.MeshObj.GetDeviceIndexBuffer();
            D3D10.Buffer    vertextBuffer = sphere.MeshObj.GetDeviceVertexBuffer(0);
            Shader          e             = WorldData.GetObject("Instanced.fx") as Shader;
            EffectTechnique t             = e.EffectObj.GetTechniqueByName("RenderInstanced");

            InputLayout l = ShaderHelper.ConstructInputLayout(MeshInputElements10.PositionOnlyInstanced, t.GetPassByIndex(0).Description.Signature);



            BufferDescription bd = new BufferDescription();

            bd.SizeInBytes    = System.Runtime.InteropServices.Marshal.SizeOf(instances[0]) * instances.Count;
            bd.Usage          = ResourceUsage.Dynamic;
            bd.CpuAccessFlags = CpuAccessFlags.Write;
            bd.BindFlags      = BindFlags.VertexBuffer;

            D3D10.Buffer instanceData = new D3D10.Buffer(gdm.Direct3D10.Device, bd);

            DataStream ds = instanceData.Map(MapMode.WriteDiscard, SlimDX.Direct3D10.MapFlags.None);

            ds.Position = 0;
            ds.WriteRange(instances.ToArray());
            instanceData.Unmap();



            Game.Device.InputAssembler.SetInputLayout(l);
            Game.Device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertextBuffer, 16, 0), new VertexBufferBinding(instanceData, System.Runtime.InteropServices.Marshal.SizeOf(instances[0]), 0));
            Game.Device.InputAssembler.SetIndexBuffer(indexBuffer, Format.R16_UInt, 0);
            Game.Device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList);

            e.GetVar("WorldViewProj").AsMatrix().SetMatrix(Camera.ViewMatrix * Camera.ProjectionMatrix);

            t.GetPassByIndex(0).Apply();
            Game.Device.DrawIndexedInstanced((sphere.Mesh3d.attrTable[0].FaceCount * 3), instances.Count, 0, 0, 0);
            //Game.Device.DrawIndexed((sphere.attrTable[0].FaceCount * 3) * 2, 0, 0);

            indexBuffer.Dispose();
            vertextBuffer.Dispose();
            sphere.Dispose();
        }
        private void SetActiveControl(bool active)
        {
            Input       instance = Singleton <Input> .Instance;
            IEnumerator coroutine;

            if (active)
            {
                Time.set_timeScale(0.0f);
                this._lcw.useDownload = true;
                List <string> stringList = ListPool <string> .Get();

                WorldData autoData = Singleton <Game> .Instance.Data.AutoData;
                if (autoData != null)
                {
                    stringList.Add(autoData.PlayerData.CharaFileName);
                    foreach (KeyValuePair <int, AgentData> keyValuePair in autoData.AgentTable)
                    {
                        stringList.Add(keyValuePair.Value.CharaFileName);
                    }
                }
                foreach (KeyValuePair <int, WorldData> world in Singleton <Game> .Instance.Data.WorldList)
                {
                    stringList.Add(world.Value.PlayerData.CharaFileName);
                    foreach (KeyValuePair <int, AgentData> keyValuePair in world.Value.AgentTable)
                    {
                        stringList.Add(keyValuePair.Value.CharaFileName);
                    }
                }
                this._lcw.ReCreateList(true, false);
                instance.FocusLevel   = 0;
                instance.MenuElements = this.MenuUIList;
                coroutine             = this.OpenCoroutine();
            }
            else
            {
                instance.ClearMenuElements();
                instance.FocusLevel = -1;
                coroutine           = this.CloseCoroutine();
            }
            if (this._fadeDisposable != null)
            {
                this._fadeDisposable.Dispose();
            }
            this._fadeDisposable = ObservableExtensions.Subscribe <Unit>((IObservable <M0>)Observable.FromCoroutine((Func <IEnumerator>)(() => coroutine), false), (Action <M0>)(_ => {}), (Action <Exception>)(ex => Debug.LogException(ex)));
        }
Example #29
0
 override public bool Match(WorldData worldState)
 {
     rulePriority = RuleFrameWork.RulePriorityType.PRIORITY1;
     if (worldState.LeftFree && !worldState.LeftVisited)
     {
         //food before empty space
         if (worldState.LeftFood)
         {
             rulePriority = RuleFrameWork.RulePriorityType.PRIORITY2;
         }
         if (worldState.LeftPowerUp)//powwr up FIRST
         {
             rulePriority = RuleFrameWork.RulePriorityType.PRIORITY3;
         }
         return(true);
     }
     return(false);
 }
        private void ddlUpdateScript_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 0)
            {
                return;
            }
            ComboBoxItem c = (ComboBoxItem)e.AddedItems[0];

            if (c != null)
            {
                ComboBoxItem ci     = ddlUpdateScript.SelectedItem as ComboBoxItem;
                Script       script = WorldData.GetObject(ci.Name) as Script;
                if (script != null)
                {
                    lblArgsDesc.Content = "Args: " + script.ScriptArgsDesc;
                }
            }
        }
Example #31
0
    public static void SaveChunks(WorldData world)
    {
        //Copy modified chunks into a new list and clear the old one to prevent
        //chunks being added to list while it is saving.
        List <ChunkData> chunks = new List <ChunkData>(world.modifiedChunks);

        world.modifiedChunks.Clear();

        int count = 0;

        foreach (ChunkData chunk in chunks)
        {
            SaveSystem.SaveChunk(chunk, world.worldName);
            count++;
        }
        Debug.Log(count + " chunks saved.");
        DebugScreen.consoleText = count + " chunks saved.";
    }
Example #32
0
    private Vector2i ChoosePlayerSpawnLocation()
    {
        int x         = Mathf.RoundToInt((Width - 1) / 2.0f * Chunk.Size);
        int positionY = 0;

        for (int y = WorldData.Height; y >= 0; --y)
        {
            if (WorldData.GetTileTypeAt(x, y) == TileType.Empty)
            {
                continue;
            }

            positionY = y + 6;
            break;
        }

        return(new Vector2i(x, positionY));
    }
Example #33
0
    private static void GenerateCanyon(int startX, WorldData worldData)
    {
        int steps    = Random.Range(minimumCanyonSteps, maximumCanyonSteps);
        int currentX = startX;

        for (int i = 0; i < steps; i++)
        {
            int radius = Random.Range(minimumCanyonSize, maximumCanyonSize);

            int pivot = Random.Range(-radius, radius);
            int x     = currentX + pivot;

            Vector2i spot = TerrainUtilities.FindUpperMostTile(x, worldData, type => type != TileType.Empty);
            TerrainUtilities.GenerateFuzzyCircle(minimumCanyonSize, maximumCanyonSize, worldData, spot, TileType.Empty);

            currentX = x;
        }
    }
Example #34
0
    public Node(int _x, int _y)
    {
        x = _x;
        y = _y;

        if (!WorldData.ContainsTile(x, y))
        {
            intraversable = true;
        }
        else
        {
            Tile tile = WorldData.GetTile(x, y);
            if (tile != null && tile.type != 0)
            {
                intraversable = true;
            }
        }
    }
    private void initBlocks(WorldData worldData)
    {
        WorldBlock[,] worldBlocks = new WorldBlock[config.worldWidth, config.worldHeight];
        int   initialX    = config.initialX;
        int   initialY    = config.initialY;
        float worldWidth  = config.worldWidth;
        float worldHeight = config.worldHeight;

        //generate solid blocks
        for (var i = initialY; i < worldHeight; i++)
        {
            for (var j = initialX; j < worldWidth; j++)
            {
                worldBlocks[j, i] = WorldBlockUtils.getRandomWorldBlock();
            }
        }
        worldData.Blocks = worldBlocks;
    }
Example #36
0
 void Start()
 {
     GameCanvs = GetComponent <CanvasUpdater>().GameCanvas.gameObject;
     PopText   = GameCanvs.transform.Find("PopText").GetComponent <Text>();
     WorldName = GameCanvs.transform.Find("WorldName").GetComponent <Text>();
     DegreeT   = GameCanvs.transform.Find("DegreeT").GetComponent <Text>();
     DateText  = GameCanvs.transform.Find("DateText").GetComponent <Text>();
     SpeedText = GameCanvs.transform.Find("SpeedText").GetComponent <Text>();
     if (SaveLoadSystem.HasSaved())
     {
         gameData = SaveLoadSystem.LoadPlayer();
     }
     else
     {
         gameData = new GameData().GameDataNew(GetComponent <SelectButtons>().worldNum);
     }
     worldData = new Finder().WorldFinder(gameData.worldnum);
 }
Example #37
0
        private void BlockstateSolidHalf(NativeArray <bool> sides, int x, int y, int z, int3 rotation)
        {
            int eulerY = rotation.y / 90;

            int frontIndex = 2 + eulerY > 5 ? 2 + eulerY - 4 : 2 + eulerY;
            int rightIndex = 5 + eulerY > 5 ? 3 + eulerY - 4 : 5 + eulerY;
            int backIndex  = 3 + eulerY > 5 ? 4 + eulerY - 4 : 3 + eulerY;
            int leftIndex  = 4 + eulerY > 5 ? 5 + eulerY - 4 : 4 + eulerY;

            sides[0] = y < WorldSettings.ChunkSizeY - 1 &&
                       WorldData.GetBlockState(blocks[Utils.BlockPosition3DtoIndex(x, y + 1, z)]) != BlockState.SOLID;
            sides[1] = y > 0 &&
                       WorldData.GetBlockState(blocks[Utils.BlockPosition3DtoIndex(x, y - 1, z)]) != BlockState.SOLID;
            sides[frontIndex] = WorldData.GetBlockState(blocks[Utils.BlockPosition3DtoIndex(x, y, z - 1)]) != BlockState.SOLID;
            sides[rightIndex] = WorldData.GetBlockState(blocks[Utils.BlockPosition3DtoIndex(x + 1, y, z)]) != BlockState.SOLID;
            sides[backIndex]  = WorldData.GetBlockState(blocks[Utils.BlockPosition3DtoIndex(x, y, z + 1)]) != BlockState.SOLID;
            sides[leftIndex]  = WorldData.GetBlockState(blocks[Utils.BlockPosition3DtoIndex(x - 1, y, z)]) != BlockState.SOLID;
        }
Example #38
0
    private bool ValidateStage(WorldStage worldStage)
    {
        if (worldStage.IsLast)
        {
            return(false);
        }
        WorldData worldData = FindWorldData(worldStage.World);

        if (worldData == null)
        {
            return(false);
        }
        if (worldData.levelsNames.Length <= worldStage.Id + 1)
        {
            return(false);
        }
        return(true);
    }
Example #39
0
    public void OpenLevel(WorldData worldData, string _levelPath)
    {
        levelPath = _levelPath;

        WorldManager.current.GenerateMaterials();

        LoadLevel(levelPath);

        CameraManager.current.onClick      += MainVineControlHelper;
        CameraManager.current.onClick      += PreTraceVine;
        CameraManager.current.onReleaseAny += delegate { CameraManager.current.onHover -= TraceVine; };

        brambleInput = StartCoroutine(BrambleInput());
        GenerateAvailableVinesUI();

        GameObject.Find("LevelAnchor/CameraAnchor/Camera").GetComponent <Camera>().backgroundColor = WorldManager.current.palette[0];
        CameraManager.current.CalibrateCamera(WorldManager.current.board);
    }
    public void GenerateTerrain(WorldData world)
    {
        for(int x=0; x<world.points.GetLength(0); x++)
        {
            for(int y=0; y<world.points.GetLength(1); y++)
            {
                int height = (int)Mathf.Clamp((5*world.points.GetLength(2)*(SimplexNoise.noise(x/50f, y/50f, 0)) + 0.35f), 1f, 5f);

                for (int z=0; z<world.points.GetLength(2); z++)
                {
                    //world.points[x,y,z] = false;
                    //if (z<3) world.points[x,y,z] = true;
                    //if (x==4 && y==4 && z==3) world.points[x,y,z] = true;
                    world.points[x,y,z] = z > height;
                }
            }
        }
    }
        public WorldData Decode(EngineVersion engineVersion, WorldTexFile texFile, ILogger log, byte[] data, int startOffset, int length)
        {
            var worldData = new WorldData();

            var reader = new DataReader(data, startOffset, length);

            var numElements = reader.ReadInt32();       // 0

            reader.Skip(12);                            // Skipping 3 ints

            var numCols = reader.ReadInt32();           // x10
            var numRows = reader.ReadInt32();           // x14

            reader.Skip(12);                            // Skipping 3 ints         // x18 x1c x20
            var elementArrayStart = reader.ReadInt32(); // x24

            reader.Skip(8);                             // Skipping 2 ints
            var off38Cols = reader.ReadInt32();
            var off38Rows = reader.ReadInt32();
            var off38     = reader.ReadInt32();

            reader.Skip(28);
            var texll = reader.ReadInt32();
            var texur = reader.ReadInt32();
            var texX0 = texll % 100;
            var texY0 = texll / 100;
            var texX1 = texur % 100;
            var texY1 = texur / 100;

            reader.Skip(4);
            var worldTexOffsetsOffset = reader.ReadInt32();

            worldData.textureChunkOffsets = readTextureChunkOffsets(engineVersion, data, startOffset + worldTexOffsetsOffset, texX0, texY0, texX1 + 1, texY1);
            worldData.worldElements       = new List <WorldElement>(numElements);

            for (var elementIdx = 0; elementIdx < numElements; ++elementIdx)
            {
                var element = ReadWorldElement(engineVersion, texFile, log, data, startOffset, worldData, reader, elementArrayStart, texX0, texY0, elementIdx);

                worldData.worldElements.Add(element);
            }

            return(worldData);
        }
Example #42
0
        protected override async Task OnActionAsync(JoinResponse value)
        {
            _trackingController.SetNewCluster(value.MapType, value.DungeonGuid, value.MapIndex, value.MainMapIndex);

            _trackingController.DungeonController.LocalUserData = new LocalUserData
            {
                UserObjectId      = value.UserObjectId,
                Guid              = value.Guid,
                InteractGuid      = value.InteractGuid,
                Username          = value.Username,
                LearningPoints    = value.LearningPoints,
                Reputation        = value.Reputation,
                ReSpecPoints      = value.ReSpecPoints,
                Silver            = value.Silver,
                Gold              = value.Gold,
                GuildName         = value.GuildName,
                MainMapIndex      = value.MainMapIndex,
                PlayTimeInSeconds = value.PlayTimeInSeconds,
                AllianceName      = value.AllianceName,
            };

            _mainWindowViewModel.TrackingUsername       = value.Username;
            _mainWindowViewModel.TrackingGuildName      = value.GuildName;
            _mainWindowViewModel.TrackingAllianceName   = value.AllianceName;
            _mainWindowViewModel.TrackingCurrentMapName = WorldData.GetUniqueNameOrDefault(value.MapIndex);

            _mainWindowViewModel.DungeonCloseTimer = new DungeonCloseTimer
            {
                IsVisible = Visibility.Hidden
            };

            if (value.Guid != null && value.InteractGuid != null && value.UserObjectId != null)
            {
                _trackingController.EntityController.AddEntity((long)value.UserObjectId, (Guid)value.Guid, (Guid)value.InteractGuid, value.Username, GameObjectType.Player, GameObjectSubType.LocalPlayer);
                _trackingController.EntityController.AddToParty((Guid)value.Guid, value.Username);
            }

            _trackingController.DungeonController?.AddDungeon(value.MapType, value.DungeonGuid, value.MainMapIndex);

            ResetFameCounterByMapChangeIfActive();
            SetTrackingIconColor();

            await Task.CompletedTask;
        }
Example #43
0
    private void Start()
    {
        lightIntensity      = lightMinIntensity;
        lightTransitionTime = float.Parse("0.0" + (dayLength / 2).ToString());

        if (!mainMenu.newWorld)
        {
            worldData = SaveSystem.LoadWorld(worldData.worldName);
        }
        else
        {
            worldData = SaveSystem.LoadWorld(mainMenu.worldNameInput.text, mainMenu.seed);
        }

        Random.InitState(seed);

        Shader.SetGlobalFloat("minGlobalLightLevel", VoxelData.minLightLevel);
        Shader.SetGlobalFloat("maxGlobalLightLevel", VoxelData.maxLightLevel);

        if (enableThreading)
        {
            ChunkUpdateThread = new Thread(new ThreadStart(ThreadedUpdate));
            ChunkUpdateThread.Start();
        }

        try
        {
            float[] light = SaveSystem.LoadDayData(worldData.worldName);
            time           = light[0];
            lightIntensity = light[1];
        }
        catch
        {
            time           = 0;
            lightIntensity = lightMinIntensity;
        }

        mainMenu.generatingWait.SetActive(true);
        lightStyle             = Instance.mainMenu.settingsMenu.GetComponent <Settings>().lightStyle;
        spawnPosition          = new Vector3((VoxelData.WorldSizeInChunks * VoxelData.ChunkWidth) / 2f, VoxelData.ChunkHeight - 50f, (VoxelData.WorldSizeInChunks * VoxelData.ChunkWidth) / 2f);
        sun.transform.position = new Vector3(((VoxelData.WorldSizeInChunks * VoxelData.ChunkWidth) / 2f), 150, ((VoxelData.WorldSizeInChunks * VoxelData.ChunkWidth) / 2f));
        GenerateWorld();
        playerLastChunkCoord = GetChunkCoordFromVector3(player.position);
    }
Example #44
0
    public void ResponseWorldMenuAction(ExtendedEventArgs eventArgs)
    {
        ResponseWorldMenuActionEventArgs args = eventArgs as ResponseWorldMenuActionEventArgs;

        switch (args.action)
        {
        case 1:                 // Create
            if (args.status == 0)
            {
                WorldData world = new WorldData(args.world_id);
                world.name    = args.name;
                world.credits = args.credits;
                world.month   = args.month;

                worldList.Add(args.world_id, world);
            }
            break;

        case 2:                 // Join
            if (args.status == 0)
            {
                WorldData world = new WorldData(args.world_id);
                world.name    = args.name;
                world.credits = args.credits;
                world.month   = args.month;

                GameState.world = world;
                Application.LoadLevel("World");
            }
            break;

        case 3:                 // Delete
            worldList.Remove(args.world_id);

            if (worldList.Count > 0)
            {
                worldSelected = new List <WorldData>(worldList.Values)[0];
            }
            break;

        default:
            break;
        }
    }
Example #45
0
    public Heightmap(HeightmapParams vars)
    {
        worldData = GameObject.Find("World").GetComponent<WorldData>();

        form = vars.form;
        formArg = vars.formArg;
        mapSize = worldData.GetWorldSize();
        featureSizePower = vars.featureSizePower;
        heightScale = vars.heightScale;
        heightStepped = vars.heightStepped;
        heightStep = Mathf.Max(vars.heightStep, 0.00001f);

        floatMap = new float[mapSize*mapSize];
        featureSize = (int)Mathf.Pow(2.0f, (float)featureSizePower);

        diamondSquared = vars.diamondSquared;
        diamondRange = vars.diamondRange;
        squareRange = vars.squareRange;
    }
Example #46
0
    private Room.DoorDirection CheckFreeConnections(ref WorldData world, out int count, WorldData.RoomCell cell)
    {
        Room.DoorDirection result = Room.DoorDirection.None;
        count = 0;

        foreach (Room.DoorDirection dir in Room.AllDirs)
        {
            var room = cell.Reference.GetGlobalRoomCell(world, dir);

            if (room.Type == Room.RoomType.Empty &&
                !cell.Reference.HasEdge(world, dir))
            {
                result |= dir;
                count++;
            }
        }

        return(result);
    }
    /// <summary>
    /// Creates a fuzzy circle with radius between <paramref name="minRadius"/> and <paramref name="maxRadius"/>
    /// around a given <paramref name="tilePosition"/> with <paramref name="type"/>.
    /// Use this for terrain generation.
    /// </summary>
    /// <param name="minRadius"></param>
    /// <param name="maxRadius"></param>
    /// <param name="worldData"></param>
    /// <param name="tilePosition"></param>
    /// <param name="type"></param>
    public static void GenerateFuzzyCircle(float minRadius, float maxRadius, WorldData worldData, Vector2i tilePosition, TileType type)
    {
        int range = (int)Math.Ceiling(maxRadius);

        for (int x = -range; x <= range; x++)
        {
            for (int y = -range; y <= range; y++)
            {
                double fuzzyRadius = Random.Range(minRadius, maxRadius);
                double distance    = Math.Sqrt(x * x + y * y);
                if (!(distance <= fuzzyRadius))
                {
                    continue;
                }

                worldData.SetTileTypeAt(tilePosition.X + x, tilePosition.Y + y, type);
            }
        }
    }
Example #48
0
    public WorldData LoadData(string savePath)
    {
        WorldData data = null;

        if (File.Exists(savePath))
        {
            using (FileStream stream = new FileStream(savePath, FileMode.Open))
            {
                XmlSerializer binaryFormatter = new XmlSerializer(typeof(WorldData));
                data = (WorldData)binaryFormatter.Deserialize(stream);
            }
        }
        else
        {
            Debug.LogError("Save file not fount in " + savePath);
        }

        return(data);
    }
            public static void GameDataSaveHook(AIProject.SaveData.SaveData saveData, BinaryWriter bw)
            {
                Logger.Log(BepInEx.Logging.LogLevel.Debug, "Save Game Data Hook!");

                MainGameSaveWriteEvent(saveData);
                bw.Write(Marker);
                bw.Write(DataVersion);

                // AI's GameSave contains multiple world data.
                // unfortunately it will try to save all the world data so we need to fix it.
                WorldData autoSaveData = saveData.AutoData;

                WriteWorldData(-1, saveData.AutoData, bw);
                foreach (var kv in saveData.WorldList)
                {
                    WriteWorldData(kv.Key, kv.Value, bw);
                    Logger.LogMessage($"Saved world data for {kv.Key}");
                }
            }
        internal static void PaintGrid(Graphics grfx, int[] boardSize, WorldData world)
        {
            float width    = world.Width;
            float height   = world.Height;
            float w        = boardSize[0] / width;
            float h        = boardSize[1] / height;
            float boxSizeX = w * world.TileDimensions.X;
            float boxSizeY = h * world.TileDimensions.Y;

            for (float y = boxSizeY; y < boardSize[1] - 1; y += boxSizeY)
            {
                grfx.DrawLine(LinePen, new Point(0, (int)y), new Point(boardSize[0], (int)y));
            }

            for (float x = boxSizeX; x < boardSize[0] - 1; x += boxSizeX)
            {
                grfx.DrawLine(LinePen, new Point((int)x, 0), new Point((int)x, boardSize[1]));
            }
        }
    void Start()
    {
        terrGen = new SimplexTerrainGenerator();
        meshGen = new MarchingCubesMeshGenerator();
        world = new WorldData(terrGen, meshGen);
        transform.Rotate(new Vector3(2, 2, 2));
        var meshfilter = GetComponent<MeshFilter>();
        Mesh mesh = new Mesh();
        mesh.vertices = world.vertices;
        mesh.uv = world.uvRays;
        mesh.triangles = world.triangles;
        //meshfilter.mesh.vertices = world.vertices;
        //meshfilter.mesh.uv = world.uvRays;
        //meshfilter.mesh.triangles = world.triangles;
        meshfilter.mesh = mesh;

        mesh.RecalculateNormals();
        var meshcollider = GetComponent<MeshCollider>();
        meshcollider.sharedMesh = mesh;
        //var thing = GetComponent<MeshRenderer>();
    }
Example #52
0
        protected void ButtonInsert_OnClick(object o, EventArgs e)
        {
            var data = new WorldData();

            var name = this.GridViewCoutries.FooterRow.FindControl("TextBoxCountryName") as TextBox;
            var language = this.GridViewCoutries.FooterRow.FindControl("TextBoxCountryLanguage") as TextBox;
            var population = this.GridViewCoutries.FooterRow.FindControl("TextBoxCountryPopulation") as TextBox;

            var continentName = this.ListBoxContinents.SelectedValue;
            var continent = data.Continents.All().First(c => c.Name == continentName);

            var country = new Country
                              {
                                  Name = name.Text,
                                  Population = decimal.Parse(population.Text),
                                  Language = language.Text,
                              };
            continent.Countries.Add(country);
            data.Continents.Update(continent);
            data.SaveChanges();

            this.BindCountries(null, null);
        }
Example #53
0
 public Chunk(int xPos, int yPos, int xySize, int zSize, IGenerateTerrain terrGen, IMeshGenerator meshGen, WorldData world)
 {
     TerrainGenerator = terrGen;
     MeshGenerator = meshGen;
     XYSize = xySize;
     ZSize = zSize;
     XPosition = xPos;
     YPosition = yPos;
     upperLimit = new int[XYSize+2, XYSize+2];
     lowerLimit = new int[XYSize+2, XYSize+2];
     blocks = new Block[xySize+2, xySize+2, zSize];
     for(int i=0; i<blocks.GetLength(0); i++)
     {
         for (int j=0; j<blocks.GetLength(1); j++)
         {
             for (int k=0; k<blocks.GetLength(2); k++)
             {
                 blocks[i,j,k] = new Block();
             }
         }
     }
     this.world = world;
 }
Example #54
0
    //Deserialize a file, load into world_data object, then load into actual world
    public void Load_World(string a_world_name)
    {
        BinaryFormatter bf = new BinaryFormatter();
        //MainGUI already checks if the file exists and will dispaly an error message in that case
        FileStream file = File.Open(Application.persistentDataPath + "/" + a_world_name + ".dat", FileMode.Open);

        WorldData world_data = new WorldData();
        Debug.Log("Attempting to deserialize . . .");
        world_data = (WorldData)bf.Deserialize(file); //Transfer file data into world_data object

        Debug.Log("Success! Loading World Data. . .");
        world_name = world_data.name;
        size = world_data.size; //Again, some world's may be bigger/smaller than others for performance preferences.
        Region.RegionData region_to_load;
        Vector3 location = new Vector3();
        Quaternion rotation = new Quaternion();
        for(int current_row = 0; current_row < size; current_row++)
        {
            for(int current_col = 0; current_col < size; current_col++)
            {
                region_to_load = world_data.regions[size*current_row + current_col];
                location.x = -size + 2*region_to_load.column; //Each region has dimension 2x2
                location.z = size - 2*region_to_load.row;
                rotation = Quaternion.Euler(new Vector3(0,region_to_load.y_rotation,0)); //Will be 0, 90, 180, or 270

                //Load prefab from resources based on terrain_type and instantiate a gameObject for the Region
                regions.Add(Resources.Load<GameObject>("Prefabs/Regions/"  + region_to_load.terrain_type));
                regions[size*current_row + current_col] = Instantiate(regions[size*current_row + current_col], location, rotation) as GameObject;

                //Prefabbed GameObject already has Region component, load its RegionData object with serialized values
                regions[size*current_row + current_col].GetComponent<Region>().region_data = world_data.regions[size*current_row + current_col];
                //world_regions[current_row, current_col].GetComponent<Region>().load_data();
                //world_regions[current_row, current_col].GetComponent<Region>().new_Region(terrain_type[current_row,current_col], current_row, current_col, region_name);
            }
        }
        file.Close(); Debug.Log("Data has been loaded. World's name from data is: " + world_name);
    }
Example #55
0
    /// <summary>
    /// Finds all decorations in this assembly, creates instances of each in memory,
    /// and adds them to the list.
    /// </summary>
    public static List<IDecoration> LoadDecorators(WorldData worldData)
    {
        List<IDecoration> decorations = new List<IDecoration>();

        // Go through each type in this assembly.
        // /TODO: It might be better to just have each 'world' or scene know about the available decorations,
        // that way only certain decorations would be applied to certain scenes.
        // These would be selected for each scene, in the inspector.
        foreach (Type type in typeof (IDecoration).Assembly.GetTypes())
        {
            // Has to implement IDecoration, must be a class and can't be abstract
            if (typeof(IDecoration).IsAssignableFrom(type) && type.IsClass && !type.IsAbstract)
            {
                // Create an instance of the decoration in memory, and pass worldData in its constructor
                IDecoration decoration =
                    Activator.CreateInstance(type, new object[] {worldData}) as IDecoration;

                // Add it to our know list of decorations
                decorations.Add(decoration);
            }
        }

        return decorations;
    }
Example #56
0
    void serializeWorldData()
    {
        List<WorldChunk> loadedChunks = World.GetAllLoadedChunks ();
        wdata = new WorldData ();

        for (int i = 0; i < loadedChunks.Count; ++i) {
            wdata.chunks.Add(new SerializableChunk());
            serializeChunkData(wdata.chunks[i], loadedChunks[i]);
        }
    }
Example #57
0
 public ChunkMover(WorldData worldData, ChunkProcessor chunkProcessor)
 {
     m_WorldData = worldData;
     m_ChunkProcessor = chunkProcessor;
 }
Example #58
0
 public static Chunk CreateChunk(Vector3i location, WorldData worldData)
 {
     Chunk chunk = new Chunk(location.X, location.Y, location.Z, worldData);
     worldData.Chunks[location.X, location.Y, location.Z] = chunk;
     chunk.InitializeBlocks();
     return chunk;
 }
Example #59
0
	static IEnumerator PutWorldData(WorldData data, AWebCoroutine handler)
	{
		string json = "{\"world\":{\"timber_count\":"+data.timber_count+"}";
		handler.Request = new HTTP.Request( "Put", WWWX.AppendParametersToUrl(WebRequests.urlGetWorld, WebRequests.authenticatedGodModeParameters) );
		handler.Request.SetText( json );
		handler.Request.Send();
		
		while(!handler.IsDone) {
			yield return 0;
		}
		Debug.Log(handler.ResponseText);
	}
Example #60
0
 public void Initialize(WorldData world)
 {
     this.worldData = world;
     this.Initialized = true;
 }