public static void FindHelper(TileMap tileMap, TileData sourceTile, int movement, FindTilesWithinRangeDTO dto)
 {
     if (!dto.TileToMaxMovement.ContainsKey(sourceTile)) {
         dto.TileToMaxMovement[sourceTile] = movement;
     } else {
         int maxMove = dto.TileToMaxMovement[sourceTile];
         if (movement > maxMove) {
             dto.TileToMaxMovement[sourceTile] = movement;
         } else {
             return;
         }
     }
     //if (visited.Contains(sourceTile)) {
     //	return;
     //}
     //visited.Add(sourceTile);
     movement = movement - sourceTile.MovementCost;
     if (movement <= 0) {
         return;
     }
     if (IsTraversable(tileMap.BottomNeighbor(sourceTile), dto)) {
         FindHelper(tileMap, tileMap.BottomNeighbor(sourceTile), movement, dto);
     }
     if (IsTraversable(tileMap.TopNeighbor(sourceTile), dto)) {
         FindHelper(tileMap, tileMap.TopNeighbor(sourceTile), movement, dto);
     }
     if (IsTraversable(tileMap.LeftNeighbor(sourceTile), dto)) {
         FindHelper(tileMap, tileMap.LeftNeighbor(sourceTile), movement, dto);
     }
     if (IsTraversable(tileMap.RightNeighbor(sourceTile), dto)) {
         FindHelper(tileMap, tileMap.RightNeighbor(sourceTile), movement, dto);
     }
 }
Example #2
0
    public void TileToDiscover(string newTileName, int mapPosX, int mapPosY, Transform tileHolder, TileData.Types tileType, int spriteWidth = 0, int spriteHeight = 0)
    {
        // this is called by Resource grid with the proper tile obj
        if (resourceGrid == null)
            resourceGrid = ResourceGrid.Grid;

        tileToSpawn = objPool.GetObjectForType (newTileName, false, Vector3.zero);

        if (tileToSpawn != null) {

            tileToSpawn.transform.position = transform.position;
            tileToSpawn.transform.parent = tileHolder;

            // IF TILE IS NOT EMPTY, IT'S A BUILDING,
            // so it will have a Building Click Handler that needs its pos X and pos Y
            if (tileType != TileData.Types.empty && tileType != TileData.Types.rock)
            {
                Building_Handler bClickHandler = tileToSpawn.GetComponent<Building_Handler> ();
                if (bClickHandler)
                {
                    bClickHandler.mapPosX = mapPosX;
                    bClickHandler.mapPosY = mapPosY;
                    //bClickHandler.resourceGrid = resourceGrid;
                    //bClickHandler.objPool = objPool;
                }

            }

            if (tileType == TileData.Types.capital)
            {
                resourceGrid.transporterGObj = tileToSpawn;
                //// IF IT'S THE TERRAFORMER it will need the master state manager
                //Terraformer_Handler terra = tileToSpawn.GetComponent<Terraformer_Handler>();
        //            if (terra)
                //    terra.master_State = master_state;
            }

            // ADD this tile to the Grid's spawnedTiles array
            if (spriteWidth > 0 && spriteHeight > 0)
            {
                for (int w = -(spriteWidth - 1); w < spriteWidth; w++)
                {
                    for (int h = 0; h < spriteHeight; h++)
                    {
                        if (resourceGrid.spawnedTiles[mapPosX + w, mapPosY + h] == null)
                        {
                            resourceGrid.spawnedTiles[mapPosX + w, mapPosY + h] = tileToSpawn;
                        }

                    }
                }

            }
            else
            {
                resourceGrid.spawnedTiles [mapPosX, mapPosY] = tileToSpawn;
            }

        }
    }
        public object Read(Newtonsoft.Json.JsonReader reader)
        {
            if (reader.TokenType != Newtonsoft.Json.JsonToken.StartObject)
                throw new Exception();

            int w = ReadIntProperty(reader, "Width");
            int h = ReadIntProperty(reader, "Height");
            int d = ReadIntProperty(reader, "Depth");

            var grid = new TileData[d, h, w];

            reader.Read();
            if (reader.TokenType != Newtonsoft.Json.JsonToken.PropertyName || (string)reader.Value != "TileData")
                throw new Exception();

            ReadAndValidate(reader, Newtonsoft.Json.JsonToken.StartArray);

            var queue = new BlockingCollection<Tuple<int, byte[]>>();

            var readerTask = Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < d; ++i)
                {
                    reader.Read();
                    int z = (int)(long)reader.Value;

                    byte[] buf = reader.ReadAsBytes();

                    queue.Add(new Tuple<int, byte[]>(z, buf));
                }

                queue.CompleteAdding();
            });

            Parallel.For(0, d, i =>
            {
                var tuple = queue.Take();

                int z = tuple.Item1;
                byte[] arr = tuple.Item2;

                using (var memStream = new MemoryStream(arr))
                {
                    using (var decompressStream = new DeflateStream(memStream, CompressionMode.Decompress))
                    using (var streamReader = new BinaryReader(decompressStream))
                    {
                        for (int y = 0; y < h; ++y)
                            for (int x = 0; x < w; ++x)
                                grid[z, y, x].Raw = streamReader.ReadUInt64();
                    }
                }
            });

            readerTask.Wait();

            ReadAndValidate(reader, Newtonsoft.Json.JsonToken.EndArray);
            ReadAndValidate(reader, Newtonsoft.Json.JsonToken.EndObject);

            return grid;
        }
    /// <summary>
    /// Determines what type of building player wants to build
    /// by using the tile's type.
    /// </summary>
    /// <param name="_tileType"></param>
    public void GetBuildingFromType(TileData.Types _tileType)
    {
        // TODO: Subtract the nanobot cost of this blueprint
        //Building_UIHandler building_handler = Building_UIHandler.BuildingHandler;
        Build_MainController build_controller = Build_MainController.Instance;
        switch (_tileType)
        {
            case TileData.Types.rock:
                Blueprint extractor = GetAvailableBlueprint(TileData.Types.extractor);
                Build(extractor);
                break;

            case TileData.Types.mineral:
                Blueprint generator = GetAvailableBlueprint(TileData.Types.generator);
                Build(generator);
                break;

            case TileData.Types.empty:
                Debug.Log("NANO B: Building on empty!");
                Build(selectedBluePrint);
                break;

            case TileData.Types.water:
                Blueprint waterPump = GetAvailableBlueprint(TileData.Types.desalt_s);
                Build(waterPump);
                break;

            default:
                Debug.Log("Cant build on that type of tile!");
                break;
        }

           // Debug.Log("Nanobots left: " + nanoBots);
    }
        public void Save(MainViewModel viewModel)
        {
            GestSpaceData space = new GestSpaceData();
            foreach(var tileVm in viewModel.Tiles.Where(t => !t.IsUnused))
            {
                var tile = new TileData();
                space.Tiles.Add(tile);
                if(!tileVm.TakeSuggestedName)
                {
                    tile.ForcedName = tileVm.Description;
                }
                tile.X = (int)tileVm.Position.X;
                tile.Y = (int)tileVm.Position.Y;
                if(tileVm.SelectedPresenterTemplate != null)
                    tile.PresenterTemplate = tileVm.SelectedPresenterTemplate.Description;
                if(tileVm.SelectedGestureTemplate != null)
                    tile.GestureTemplate = tileVm.SelectedGestureTemplate.Name;

                tile.Program = tileVm.FastContext;
                foreach(var evtVm in tileVm.Events)
                {
                    var evt = new EventData();
                    tile.Events.Add(evt);
                    evt.Name = evtVm.Name;
                    if(evtVm.Command != null)
                        evt.Command = evtVm.Command.Script;
                }
            }
            if(viewModel.CurrentTile != null)
            {
                space.LastX = (int)viewModel.CurrentTile.Position.X;
                space.LastY = (int)viewModel.CurrentTile.Position.Y;
            }
            Save(space);
        }
 public void BreakThisBuilding(TileData.Types _type, GameObject building)
 {
     // get me the cost of this building by finding its blueprint
     Blueprint bp = GetAvailableBlueprint(_type);
     Building_Handler b_Handler = building.GetComponent<Building_Handler>();
     if (bp != null)
         b_Handler.BreakBuilding(bp.nanoBotCost);
 }
Example #7
0
 public bool CheckForBlueprint(TileData.Types bpType)
 {
     if (blueprintsMap.ContainsKey(bpType))
     {
         return true;
     }
     else
         return false;
 }
Example #8
0
 public void SetColumnAndRow(int column, int row)
 {
     if (this.TileData == null) {
         this.TileData = new TileData();
         this.TileData.Tile = this;
     }
     this.TileData.Column = column;
     this.TileData.Row = row;
 }
 public void GetExtractorStats(string id, Transform objTransform, ExtractionBuilding extractor, TileData.Types resourceType)
 {
     if (extractorsMap.ContainsKey(id))
     {
        // Debug.Log("BP Database: Found stats for " + id);
         extractor.Init(resourceType, extractorsMap[id].extractorStats.extractRate, extractorsMap[id].extractorStats.extractPower,
             extractorsMap[id].extractorStats.extractAmmount, extractorsMap[id].extractorStats.personalStorageCapacity, objTransform);
     }
 }
Example #10
0
 // Survival Mission:
 public Mission(string name, MissionType mType, Blueprint requiredBP, TileData.Types reqResource, int reqAmnt, string desc = "Unknown Signal")
 {
     missionName = name;
     missionType = mType;
     requiredBlueprint = requiredBP;
     description = desc;
     objectiveResource = reqResource;
     objectiveAmnt = reqAmnt;
 }
Example #11
0
 public void AddConnectedTile(TileData t)
 {
     if (ConnectedTiles == null) {
         ConnectedTiles = new List<TileData>();
         ConnectedTiles.Add(t);
     }
     else if (!ConnectedTiles.Contains (t)) {
         ConnectedTiles.Add(t);
     }
 }
Example #12
0
    public void UnsetDefenderForTile(TileData t)
    {
        DefenderData defenderData;
        defenderLookup.TryGetValue (t, out defenderData);

        if (defenderData != null) {
            Destroy (defenderData.CurrentDefender.gameObject);
            defenderData.CurrentDefender = null;
        }
    }
Example #13
0
    public void UnsetPrisonerForTile(TileData t)
    {
        PrisonerData prisonerData;
        prisonerLookup.TryGetValue(t, out prisonerData);

        if (prisonerData != null) {
            Destroy(prisonerData.CurrentPrisoner.gameObject);
            prisonerData.CurrentPrisoner = null;
        }
    }
Example #14
0
    // For a Required Blueprint (like Terraformer, Generator, etc)
    public Blueprint(string Name, TileData.Types _type, BuildingType tType)
    {
        buildingName = Name;
        memoryCost = 0;
        nanoBotCost = 0;
        tileType = _type;
        description = " ";

        buildingType = tType;
    }
Example #15
0
 void OnTerrainOrInteriorChanged(IntVector3 p, TileData oldData, TileData newData)
 {
     if (oldData.HasTree != newData.HasTree)
     {
         if (newData.HasTree)
             AddTree();
         else
             RemoveTree();
     }
 }
Example #16
0
	GameObject GetNewTile(TileData tileData, float width, float height)
	{
		var tile = GameObject.Instantiate(tilePrefab);
		var tileLayoutElement = tile.GetComponent<LayoutElement>();
		tileLayoutElement.preferredWidth = width;
		tileLayoutElement.preferredHeight = height;

		tile.GetComponent<MapTileView>().SetObject(tileData.objectOnTile);
		return tile;
	}
Example #17
0
        /**
         *
         */
        public override bool GetTileData(Vector3Int location, ITileMap tileMap, ref TileData tileData)
        {
            base.GetTileData(location, tileMap, ref tileData);

            int mask = GetMask(location, tileMap, ref tileData);
            int index = GetIndex(mask);

            tileData.sprite = GetTileSprite(index);
            tileData.gameobject = GetTileGameObject(index);

            return true;
        }
Example #18
0
    public void AddBluePrint(TileData.Types bpType, Blueprint bp)
    {
        blueprintsMap.Add(bpType, bp);

        if (bpType != TileData.Types.terraformer)
        {
            cur_memory -= bp.memoryCost;
        }

        if (!bpTypes.Contains(bpType))
            bpTypes.Add(bpType);
    }
 private void SetupTags(TileData wall, Point textTagTilePosition)
 {
     foreach (var textTag in wall.TextTags.Where(x => !x.Processed && x.GetParentPosition(textTagTilePosition) == CurrentTile.GridPosition))
     {
         textTag.Processed = true;
         var tag = new TextTag(builder.GetWallPosition(textTag.TilePosition, CurrentTile), textTag.IsVisible,
             textTag.TilePosition == TilePosition.East_TopRight || textTag.TilePosition == TilePosition.West_BottomRight, textTag.Text.Replace("|", Environment.NewLine))
         {
             AcceptMessages = textTag.HasTargetingActuator
         };
         CurrentTile.SubItems.Add(tag);
     }
 }
 public static bool IsTraversable(TileData tileData, FindTilesWithinRangeDTO dto)
 {
     if (tileData == null) {
         return false;
     }
     if (tileData.OccupiedTeam == dto.MoveThroughMask) {
         return false;
     }
     if (dto.MoveThroughMask == TeamId.MOVE_THROUGH_NONE && tileData.OccupiedTeam != -1) {
         return false;
     }
     return true;
 }
	void InitAlgorithm (MapData mapData)
	{
		source = mapData.PlayerTile;
		finish = mapData.FinishTile;

		foreach(var row in mapData)
		{
			foreach(var tile in row)
			{
				distancesToCheck.Add(tile, tile == mapData.PlayerTile ? 0 : int.MaxValue);
				predecessors.Add(tile, null);
			}
		}
	}
    public static List<TileData> Find(TileMap tileMap, TileData sourceTile, int movement, int jumpHeight, int moveThroughMask)
    {
        FindTilesWithinRangeDTO dto = new FindTilesWithinRangeDTO();
        dto.JumpHeight = jumpHeight;
        dto.MoveThroughMask = moveThroughMask;
        movement = movement + 1;

        List<TileData> visited = new List<TileData>();
        FindHelper(tileMap, sourceTile, movement, dto);
        foreach(TileData t in dto.TileToMaxMovement.Keys) {
            visited.Add(t);
        }
        return visited;
    }
Example #23
0
    // Constructor for Raw Resources Trade Order:
    public TradeOrder(TradeClient client, string name, int comp, TileData.Types rawResource, int ammnt, int days)
    {
        tradeClient = client;

        orderName = name;

        compensation = comp;

        tradeResource = new TradeResource(rawResource);
        tradeQuota = ammnt;

        timeLimit = days;

        tradeOrderStatus = TradeOrderStatus.Pending;
    }
Example #24
0
    public void SetFlagForTile(TileData t)
    {
        FlagData flagData;
        flagLookup.TryGetValue(t, out flagData);
        if (flagData == null) {
            flagData = new FlagData();
            flagData.Marker = Utils.GetFirstChildWithTag("MarkerFlag", t.TileObject);
            flagLookup.Add(t, flagData);
        }

        if (flagData.Marker) {
            flagData.CurrentFlag = setFlagObject(t, flagData);
            flagData.CurrentType = t.Owner;
        }
    }
    void FullMeshUpdate(TileData tileData)
    {
        filter.mesh.Clear();
        filter.mesh.SetVertices(tileData.vertices);
        filter.mesh.SetUVs(0,tileData.uv);
        filter.mesh.SetTriangles(tileData.triangles, 0);
        filter.mesh.RecalculateNormals();

        coll.sharedMesh = null;
        Mesh mesh = new Mesh();
        mesh.vertices = tileData.colVertices.ToArray();
        mesh.triangles = tileData.colTriangles.ToArray();
        mesh.RecalculateNormals();

        coll.sharedMesh = mesh;
    }
    public void LoadSprites()
    {
        //Load the sprites from the resources folder
        foreach(var t in tileSets){
            Sprite[] sprites = Resources.LoadAll<Sprite>(t.Name);
            for (int i = 0; i < sprites.Length; i++) {
                if(i >= t.tileData.Count){
                    TileData td = new TileData(){sprite = sprites[i]};
                    t.tileData.Add(td);
                }else{
                    t.tileData[i].sprite = sprites[i];
                }

            }
        }
    }
Example #27
0
    public void SetDefenderForTile(TileData t)
    {
        DefenderData defenderData;
        defenderLookup.TryGetValue(t, out defenderData);

        if (defenderData == null) {
            defenderData = new DefenderData();
            defenderData.Marker = Utils.GetFirstChildWithTag("MarkerDefending", t.TileObject);
            defenderLookup.Add(t, defenderData);
        }

        if (defenderData.Marker) {
            defenderData.CurrentDefender = setDefenderObject(t, defenderData);
            defenderData.CurrentType = t.Owner;
        }
    }
Example #28
0
    public void SetPrisonerForTile(TileData t)
    {
        PrisonerData prisonerData;
        prisonerLookup.TryGetValue(t, out prisonerData);

        if (prisonerData == null ) {
            prisonerData = new PrisonerData();
            prisonerData.Marker = Utils.GetFirstChildWithTag("MarkerJail", t.TileObject);
            prisonerLookup.Add(t, prisonerData);
        }

        if (prisonerData.Marker) {
            prisonerData.CurrentPrisoner = setPrisonerObject(t, prisonerData);
            prisonerData.CurrentType = t.Owner;
        }
    }
    public static List<TileData> Find(TileMap tileMap, TileData sourceTile, TileData destinationTile, int moveThroughMask)
    {
        List<TileData> shortestPath = new List<TileData>();
        List<TileData> unvisited = new List<TileData>(tileMap.TileDataList);

        FindShorestPathDTO dto = new FindShorestPathDTO();
        dto.Destination = destinationTile;
        dto.MoveThroughMask = moveThroughMask;
        if (moveThroughMask != TeamId.MOVE_THROUGH_ALL) {
            unvisited = TileUtility.FilterOutOccupiedTiles(unvisited, moveThroughMask); // TODO support enemyteam
            unvisited.Add(sourceTile);
        }

        dto.TileToDistance.Add(sourceTile, 0);
        TileData currentTile = null;
        int count = 0;
        while (unvisited.Count > 0 && count < 100) {
            count++;
            currentTile = TileWithMinDistance(dto.TileToDistance, unvisited);
            unvisited.Remove(currentTile);
            CalculateDistanceAndUpdatePath(currentTile, tileMap.TopNeighbor(currentTile), dto);
            CalculateDistanceAndUpdatePath(currentTile, tileMap.BottomNeighbor(currentTile), dto);
            CalculateDistanceAndUpdatePath(currentTile, tileMap.LeftNeighbor(currentTile), dto);
            CalculateDistanceAndUpdatePath(currentTile, tileMap.RightNeighbor(currentTile), dto);
        }

        Debug.Log("starting return path - " + count);

        TileData returnTile = destinationTile;
        shortestPath.Add(returnTile);
        count = 0;
        while (returnTile != sourceTile && count < 100) {
            count++;
            Debug.Log("finding last hop for " + returnTile.ToString());
            try {
            returnTile = dto.TileToOptimalPrevious[returnTile];
            } catch (Exception ex) {
                Debug.LogError(ex);
                Debug.LogError("oh shit error couldn't find " + returnTile.ToString());
            }
            Debug.Log("found " + returnTile);
            shortestPath.Add(returnTile);
        }
        Debug.Log("finish return path - TILEDATA");
        shortestPath.Reverse();
        return shortestPath;
    }
 //public void InitShipInventory(int _food, int _water, int _ore)
 //{
 //    oreText.text = _ore.ToString();
 //    foodText.text = _food.ToString();
 //    waterText.text = _water.ToString();
 //    // Reset the temporary inventory
 //}
 //public void DisplayShipInventoryText(TileData.Types statThatChanges, int ammnt)
 //{
 //    // This method will only be called when a stat is changing. This will update the text.
 //    switch (statThatChanges)
 //    {
 //        case TileData.Types.rock:
 //            oreText.text = ammnt.ToString();
 //            break;
 //        case TileData.Types.food:
 //            foodText.text = ammnt.ToString();
 //            break;
 //        case TileData.Types.water:
 //            waterText.text = ammnt.ToString();
 //            break;
 //        default:
 //            // do nothing
 //            break;
 //    }
 //}
 public void DisplayTransporterStorage(TileData.Types statThatChanges, int ammnt)
 {
     // This method will only be called when a stat is changing. This will update the text.
     switch (statThatChanges)
     {
         case TileData.Types.rock:
             tempOreTxt.text = ammnt.ToString();
             break;
         case TileData.Types.food:
             tempFoodTxt.text = ammnt.ToString();
             break;
         case TileData.Types.water:
             tempWaterTxt.text = ammnt.ToString();
             break;
         default:
             // do nothing
             break;
     }
 }
Example #31
0
        static void HandleTree(VertexList <SceneryVertex> sceneryVertexList, TileData td, ref IntVector3 pos)
        {
            SymbolID symbol;
            Color    color;

            switch (td.ID)
            {
            case TileID.Tree:
                switch (td.MaterialID)
                {
                case MaterialID.Fir:
                    symbol = SymbolID.ConiferousTree;
                    break;

                case MaterialID.Pine:
                    symbol = SymbolID.ConiferousTree2;
                    break;

                case MaterialID.Birch:
                    symbol = SymbolID.DeciduousTree;
                    break;

                case MaterialID.Oak:
                    symbol = SymbolID.DeciduousTree2;
                    break;

                default:
                    throw new Exception();
                }
                break;

            case TileID.Sapling:
                switch (td.MaterialID)
                {
                case MaterialID.Fir:
                    symbol = SymbolID.ConiferousSapling;
                    break;

                case MaterialID.Pine:
                    symbol = SymbolID.ConiferousSapling2;
                    break;

                case MaterialID.Birch:
                    symbol = SymbolID.DeciduousSapling;
                    break;

                case MaterialID.Oak:
                    symbol = SymbolID.DeciduousSapling2;
                    break;

                default:
                    throw new Exception();
                }
                break;

            case TileID.DeadTree:
                symbol = SymbolID.DeadTree;
                break;

            default:
                throw new Exception();
            }

            color = Color.ForestGreen;

            sceneryVertexList.Add(new SceneryVertex(pos.ToVector3(), Color.LightGreen, (uint)symbol));
        }
Example #32
0
 // Set sprite and/or gameobject for rendering, this method is useful as context can be used to determine the desired sprite/gameobject
 public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
 {
     tileData.gameObject = Resources.Load <GameObject>("Prefabs/Buildings/Solarpower");
 }
    public TileData GenerateTile(float centerVertexZ, float maxDistanceZ)
    {
        // calculate tile depth and width based on the mesh vertices
        Vector3[] meshVertices = this.meshFilter.mesh.vertices;
        int       tileDepth    = (int)Mathf.Sqrt(meshVertices.Length); // sqr of 121  = 11
        int       tileWidth    = tileDepth;


        size_checker = (int)Mathf.Sqrt(meshVertices.Length);
        // print(size_checker);

        // calculate the offsets based on the tile position
        float offsetX = -this.gameObject.transform.position.x;
        float offsetZ = -this.gameObject.transform.position.z;

        // generate a heightMap using Perlin Noise **********
        float[,] heightMap = this.noiseMapGeneration.GeneratePerlinNoiseMap(tileDepth, tileWidth, this.levelScale, offsetX, offsetZ, this.heightWaves);

        // calculate vertex offset based on the Tile position and the distance between vertices
        Vector3 tileDimensions          = this.meshFilter.mesh.bounds.size;
        float   distanceBetweenVertices = tileDimensions.z / (float)tileDepth;
        float   vertexOffsetZ           = this.gameObject.transform.position.z / distanceBetweenVertices;

        // generate a heatMap using uniform noise ********
        float[,] uniformHeatMap = this.noiseMapGeneration.GenerateUniformNoiseMap(tileDepth, tileWidth, centerVertexZ, maxDistanceZ, vertexOffsetZ);

        // generate a heatMap using Perlin Noise********
        float[,] randomHeatMap = this.noiseMapGeneration.GeneratePerlinNoiseMap(tileDepth, tileWidth, this.levelScale, offsetX, offsetZ, this.heatWaves);
        float[,] heatMap       = new float[tileDepth, tileWidth];
        for (int zIndex = 0; zIndex < tileDepth; zIndex++)
        {
            for (int xIndex = 0; xIndex < tileWidth; xIndex++)
            {
                // mix both heat maps together by multiplying their values **** randomize heat reigons
                heatMap[zIndex, xIndex] = uniformHeatMap[zIndex, xIndex] * randomHeatMap[zIndex, xIndex];
                // makes higher regions colder, by adding the height value to the heat map
                heatMap[zIndex, xIndex] += this.heatCurve.Evaluate(heightMap[zIndex, xIndex]) * heightMap[zIndex, xIndex];   // adding height values , to make colder in heier reigons
            }
        }

        // generate a moistureMap using Perlin Noise ***
        float[,] moistureMap = this.noiseMapGeneration.GeneratePerlinNoiseMap(tileDepth, tileWidth, this.levelScale, offsetX, offsetZ, this.moistureWaves);
        for (int zIndex = 0; zIndex < tileDepth; zIndex++)
        {
            for (int xIndex = 0; xIndex < tileWidth; xIndex++)
            {
                // makes higher regions dryer, by reducing the height value from the heat map
                moistureMap[zIndex, xIndex] -= this.moistureCurve.Evaluate(heightMap[zIndex, xIndex]) * heightMap[zIndex, xIndex];
            }
        }

        // build a Texture2D from the height map ********  use build texture

        TerrainType[,] chosenHeightTerrainTypes = new TerrainType[tileDepth, tileWidth];

        Texture2D heightTexture = BuildTexture(heightMap, this.heightTerrainTypes, chosenHeightTerrainTypes);

        // build a Texture2D from the heat map
        TerrainType[,] chosenHeatTerrainTypes = new TerrainType[tileDepth, tileWidth];
        Texture2D heatTexture = BuildTexture(heatMap, this.heatTerrainTypes, chosenHeatTerrainTypes);

        // build a Texture2D from the moisture map
        TerrainType[,] chosenMoistureTerrainTypes = new TerrainType[tileDepth, tileWidth];
        Texture2D moistureTexture = BuildTexture(moistureMap, this.moistureTerrainTypes, chosenMoistureTerrainTypes);

        // build a biomes Texture2D from the three other noise variables*************************height,heat and moisture heat values are used
        Biome[,] chosenBiomes = new Biome[tileDepth, tileWidth];
        Texture2D biomeTexture = BuildBiomeTexture(chosenHeightTerrainTypes, chosenHeatTerrainTypes, chosenMoistureTerrainTypes, chosenBiomes);

        switch (this.visualizationMode)
        {
        case VisualizationMode.Height:
            // assign material texture to be the heightTexture
            this.tileRenderer.material.mainTexture = heightTexture;
            break;

        case VisualizationMode.Heat:
            // assign material texture to be the heatTexture
            this.tileRenderer.material.mainTexture = heatTexture;
            break;

        case VisualizationMode.Moisture:
            // assign material texture to be the moistureTexture
            this.tileRenderer.material.mainTexture = moistureTexture;
            break;

        case VisualizationMode.Biome:
            // assign material texture to be the moistureTexture
            this.tileRenderer.material.mainTexture = biomeTexture;
            break;
        }

        // update the tile mesh vertices according to the height map********************update vertices
        UpdateMeshVertices(heightMap);

        TileData tileData = new TileData(heightMap, heatMap, moistureMap,
                                         chosenHeightTerrainTypes, chosenHeatTerrainTypes, chosenMoistureTerrainTypes, chosenBiomes,
                                         this.meshFilter.mesh, (Texture2D)this.tileRenderer.material.mainTexture);

        return(tileData);
    }
Example #34
0
 public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
 {
     tileData.sprite = ReferenceTile.PreviewSprite;
 }
        private static void CheckIfUnderEntity(out int maxItemZ, out bool drawTerrain, out bool underSurface)
        {
            maxItemZ     = 255;
            drawTerrain  = true;
            underSurface = false;
            Tile tile = World.Map.GetTile(World.Map.Center.X, World.Map.Center.Y);

            if (tile != null && tile.IsZUnderObjectOrGround(World.Player.Position.Z, out GameObject underObject, out GameObject underGround))
            {
                drawTerrain = underGround == null;

                if (underObject != null)
                {
                    if (underObject is IDynamicItem item)
                    {
                        if (TileData.IsRoof((long)item.ItemData.Flags))
                        {
                            maxItemZ = World.Player.Position.Z - World.Player.Position.Z % 20 + 20;
                        }
                        else if (TileData.IsSurface((long)item.ItemData.Flags) || TileData.IsWall((long)item.ItemData.Flags) && !TileData.IsDoor((long)item.ItemData.Flags))
                        {
                            maxItemZ = item.Position.Z;
                        }
                        else
                        {
                            int z = World.Player.Position.Z + (item.ItemData.Height > 20 ? item.ItemData.Height : 20);
                            maxItemZ = z;
                        }
                    }

                    if (underObject is IDynamicItem sta && TileData.IsRoof((long)sta.ItemData.Flags))
                    {
                        bool isRoofSouthEast = true;

                        if ((tile = World.Map.GetTile(World.Map.Center.X + 1, World.Map.Center.Y)) != null)
                        {
                            tile.IsZUnderObjectOrGround(World.Player.Position.Z, out underObject, out underGround);
                            isRoofSouthEast = underObject != null;
                        }

                        if (!isRoofSouthEast)
                        {
                            maxItemZ = 255;
                        }
                    }

                    underSurface = maxItemZ != 255;
                }
            }
        }
Example #36
0
 public override void ClearApplied(TileData data, Terrain terrain)
 {
     // Might need to do something in here...
 }
Example #37
0
 public void UnsetTilePrisoner(TileData t)
 {
     _DefendingUnitManager.UnsetPrisonerForTile(t);
 }
Example #38
0
        public static async Task InspectObjectAsync()
        {
            (TargetType targetType, TargetFlags _, int serial, int x, int y, int z, int itemID) =
                await GetTargetInfoAsync(Strings.Target_object___);

            if (targetType == TargetType.Object && serial != 0)
            {
                Entity entity = UOMath.IsMobile(serial)
                    ? (Entity)Engine.Mobiles.GetMobile(serial)
                    : Engine.Items.GetItem(serial);

                if (entity == null)
                {
                    return;
                }

                Thread t = new Thread(() =>
                {
                    ObjectInspectorWindow window =
                        new ObjectInspectorWindow {
                        DataContext = new ObjectInspectorViewModel(entity)
                    };

                    window.ShowDialog();
                })
                {
                    IsBackground = true
                };

                t.SetApartmentState(ApartmentState.STA);
                t.Start();
            }
            else
            {
                if (itemID == 0)
                {
                    if (x == 65535 && y == 65535)
                    {
                        return;
                    }

                    LandTile landTile = MapInfo.GetLandTile((int)Engine.Player.Map, x, y);
                    Thread   t        = new Thread(() =>
                    {
                        ObjectInspectorWindow window = new ObjectInspectorWindow
                        {
                            DataContext = new ObjectInspectorViewModel(landTile)
                        };

                        window.ShowDialog();
                    })
                    {
                        IsBackground = true
                    };

                    t.SetApartmentState(ApartmentState.STA);
                    t.Start();
                }
                else
                {
                    StaticTile[] statics = Statics.GetStatics((int)Engine.Player.Map, x, y);

                    if (statics == null)
                    {
                        return;
                    }

                    StaticTile selectedStatic = statics.FirstOrDefault(i => i.ID == itemID);

                    if (selectedStatic.ID == 0)
                    {
                        selectedStatic   = TileData.GetStaticTile(itemID);
                        selectedStatic.X = x;
                        selectedStatic.Y = y;
                        selectedStatic.Z = z;
                    }

                    Thread t = new Thread(() =>
                    {
                        ObjectInspectorWindow window = new ObjectInspectorWindow
                        {
                            DataContext = new ObjectInspectorViewModel(selectedStatic)
                        };

                        window.ShowDialog();
                    })
                    {
                        IsBackground = true
                    };

                    t.SetApartmentState(ApartmentState.STA);
                    t.Start();
                }
            }
        }
Example #39
0
 public override void GetTileData(Vector3Int location, ITilemap tileMap, ref TileData tileData)
 {
     UpdateTile(location, tileMap, ref tileData);
 }
Example #40
0
 public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
 {
     tileData.sprite = m_movingSideWalk.GetComponent <MovingSidewalk>().Sprite;
     tileData.flags  = TileFlags.LockAll;
 }
 public override void Generate(TileData data, StopToken stop)
 {
 }
Example #42
0
        public void RegenerateMesh(TileData data)
        {
            Mesh mesh = GetGenerator().GenerateMesh(data);

            MeshFilter.mesh = mesh;
        }
        public void SetTileAt(int x, int y, TileData data)
        {
            var idx = Change(x, y);

            tiles[idx] = data;
        }
Example #44
0
    public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
    {
        int ix_tile = ResourceManager.map[position.x + ResourceManager.yui.x, position.y + ResourceManager.yui.y];

        tileData.sprite = sprites[ix_tile];
    }
Example #45
0
 public void UnsetTileDefence(TileData t)
 {
     _DefendingUnitManager.UnsetDefenderForTile(t);
 }
Example #46
0
 public IslandTile(GameObject worldObject, HexPoint point, TileData data) : base(worldObject, point, data)
 {
     tileType = TileType.Island;
 }
Example #47
0
        public static FinalizeAction finalizeAction = Finalize; //class identified for FinalizeData
        public static void Finalize(TileData data, StopToken stop)
        {
            if (stop != null && stop.stop)
            {
                return;
            }

            int upscale   = 1;
            int margins   = data.area.Margins;
            int matrixRes = (data.heights.rect.size.x - margins * 2 - 1) * upscale + margins * 2 * upscale + 1;


            if (stop != null && stop.stop)
            {
                return;
            }
            Matrix matrix = data.heights;

            //clamping heights to 0-1 (otherwise culing issues can occur)
            matrix.Clamp01();

            //2Darray resolution (this should still match our 69x69 size input as well)
            int arrRes = matrix.rect.size.x - margins * upscale * 2;

            //splits number (used for SetHeightsDelayLOD and Texture)
            int splitSize = SplitSizeRef = data.globals.heightSplit;
            int numSplits = arrRes / splitSize;

            if (arrRes % splitSize != 0)
            {
                numSplits++;
            }

            IApplyData applyData;

            // we do some comparisons on this
            float[,] heights2Dfull = new float[arrRes, arrRes];
            // we do some our data operation on this
            bool[,] bool2Dfull = new bool[arrRes - 1, arrRes - 1];


            // We need to honour multiple outputs  // sigh.  the horror story negative logic.
            // Why did unity make FALSE = hole is TRUE.  //And, yes, I know why, but still.

            bool firstPass = true;

            foreach ((HoleOutMark1 output, MatrixWorld product, MatrixWorld biomeMask)
                     in data.Outputs <HoleOutMark1, MatrixWorld, MatrixWorld>(typeof(HoleOutMark1), inSubs: true))
            {
                Matrix othermatrix = product;

                // This is our holes then
                // product.


                Coord  heightsOffset = othermatrix.rect.offset + margins * upscale;
                Matrix matrixbool    = othermatrix;

                matrix.ExportHeights(heights2Dfull, matrix.rect.offset + margins * upscale);

                Coord     heightsSize = new Coord(heights2Dfull.GetLength(1), heights2Dfull.GetLength(0)); //x and z swapped
                CoordRect heightsRect = new CoordRect(heightsOffset, heightsSize);

                CoordRect intersection = CoordRect.Intersected(matrixbool.rect, heightsRect);
                Coord     min = intersection.Min; Coord max = intersection.Max;

                for (int x = min.x; x < max.x - 1; x++)
                {
                    for (int z = min.z; z < max.z - 1; z++)
                    {
                        int matrixPos   = (z - matrixbool.rect.offset.z) * matrixbool.rect.size.x + x - matrixbool.rect.offset.x;
                        int heightsPosX = x - heightsRect.offset.x;
                        int heightsPosZ = z - heightsRect.offset.z;

                        float val = matrixbool.arr[matrixPos];

                        bool result = true;  // TERRAIN

                        // The samples are represented as bool values: true for surface and false for hole

                        bool test1 = bool2Dfull[heightsPosZ, heightsPosX];
                        bool test2 = val < float.Epsilon;

                        // It is already true
                        if (test1 || firstPass)
                        // just slap in the value
                        {
                            result = test2;
                        }
                        else // Last time it was false or we didn't set it.   and FALSE means ADD A HOLE
                        {
                            result = test1 && test2;
                        }

                        bool2Dfull[heightsPosZ, heightsPosX] = result;
                    }
                }
                firstPass = false;
            }

            applyData = new ApplySetData()
            {
                heights2D = heights2Dfull, height = data.globals.height, bools2D = bool2Dfull
            };

            //pushing to apply
            if (stop != null && stop.stop)
            {
                return;
            }
            Graph.OnOutputFinalized?.Invoke(typeof(HoleOutMark1), data, applyData, stop);
            data.MarkApply(applyData);

#if MM_DEBUG
            Log.Add("HOLEOut Finalized");
#endif
        }
Example #48
0
        public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
        {
            var spriteArray = RandomTiles.ToArray();

            tileData.sprite = spriteArray[Random.Range(0, spriteArray.Length)];
        }
        private void AddTileToRenderList(IReadOnlyList <GameObject> objList, int worldX, int worldY, bool useObjectHandles, int maxZ)
        {
            for (int i = 0; i < objList.Count; i++)
            {
                GameObject obj = objList[i];

                if (obj.CurrentRenderIndex == _renderIndex || obj.IsDisposed)
                {
                    continue;
                }

                if (_updateDrawPosition && obj.CurrentRenderIndex != _renderIndex || obj.IsPositionChanged)
                {
                    obj.UpdateRealScreenPosition(_offset);
                }
                obj.UseInRender = 0xFF;
                int drawX = (int)obj.RealScreenPosition.X;
                int drawY = (int)obj.RealScreenPosition.Y;

                if (drawX < _minPixel.X || drawX > _maxPixel.X)
                {
                    break;
                }
                int z          = obj.Position.Z;
                int maxObjectZ = obj.PriorityZ;

                switch (obj)
                {
                case Mobile _:
                    maxObjectZ += 16;

                    break;

                case IDynamicItem dyn:
                    maxObjectZ += dyn.ItemData.Height;

                    break;
                }

                if (maxObjectZ > maxZ)
                {
                    break;
                }
                obj.CurrentRenderIndex = _renderIndex;

                if (!(obj is Tile) && (z >= _maxZ || obj is IDynamicItem dyn2 && (TileData.IsInternal((long)dyn2.ItemData.Flags) || _maxZ != 255 && TileData.IsRoof((long)dyn2.ItemData.Flags))))
                {
                    continue;
                }
                int testMinZ = drawY + z * 4;
                int testMaxZ = drawY;

                if (obj is Tile t && t.IsStretched)
                {
                    testMinZ -= t.MinZ * 4;
                }
Example #50
0
        public void WontLootDisabledInGuardzone()
        {
            const string localPath = @"C:\Users\johns\Desktop\KvG Client 2.0";

            if (!Directory.Exists(localPath))
            {
                Debug.WriteLine("Not running test, requires Cliloc.enu");
                return;
            }

            TileData.Initialize(localPath);

            Engine.Player = new PlayerMobile(0x01)
            {
                X = 652, Y = 869
            };
            Item backpack = new Item(0x40000001, 0x01)
            {
                Container = new ItemCollection(0x40000001)
            };

            Engine.Player.SetLayer(Layer.Backpack, backpack.Serial);
            Engine.Items.Add(backpack);

            Item corpse = new Item(0x40000000)
            {
                ID = 0x2006
            };

            Engine.Items.Add(corpse);

            IncomingPacketHandlers.Initialize();
            AutolootViewModel vm = new AutolootViewModel {
                Enabled = true, DisableInGuardzone = true
            };

            AutolootEntry lootEntry = new AutolootEntry
            {
                Rehue       = false,
                Autoloot    = true,
                Constraints = new ObservableCollection <AutolootConstraintEntry>(),
                ID          = 0x108a
            };

            AutolootConstraintEntry autolootConstraint = new AutolootConstraintEntry
            {
                Property = vm.Constraints.FirstOrDefault(c => c.Name == "Hue"),
                Operator = AutolootOperator.Equal,
                Value    = 0
            };

            lootEntry.Constraints.Add(autolootConstraint);

            vm.Items.Add(lootEntry);

            Engine.PacketWaitEntries = new PacketWaitEntries();

            void OnPacketSentEvent(byte[] data, int length)
            {
                if (data[0] == 0xD6 || data[0] == 0x06)
                {
                    return;
                }

                Assert.Fail();
            }

            Engine.InternalPacketSentEvent += OnPacketSentEvent;

            Engine.PacketWaitEntries.WaitEntryAddedEvent += entry =>
            {
                byte[] containerContentsPacket =
                {
                    0x3C, 0x00, 0x19, 0x00, 0x01, 0x43, 0x13, 0xFC, 0x5E, 0x10, 0x8A, 0x00, 0x00, 0x01, 0x00, 0x13,
                    0x00, 0x82, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00
                };

                PacketHandler handler = IncomingPacketHandlers.GetHandler(0x3C);

                handler.OnReceive(new PacketReader(containerContentsPacket, containerContentsPacket.Length, false));
                entry.Packet = containerContentsPacket;
                entry.Lock.Set();
            };

            vm.OnCorpseEvent(corpse.Serial);

            Engine.Items.Clear();
            Engine.PacketWaitEntries        = null;
            Engine.InternalPacketSentEvent -= OnPacketSentEvent;
            Engine.Player = null;
        }
Example #51
0
    public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
    {
        var iden = Matrix4x4.identity;

        tileData.sprite       = possibleSprites[(int)tileSpritePositions.def];
        tileData.gameObject   = null;
        tileData.flags        = TileFlags.LockTransform;
        tileData.transform    = iden;
        tileData.colliderType = Tile.ColliderType.Sprite;
        Vector3Int up                = position + new Vector3Int(0, 1, 0);
        Vector3Int down              = position + new Vector3Int(0, -1, 0);
        Vector3Int left              = position + new Vector3Int(-1, 0, 0);
        Vector3Int right             = position + new Vector3Int(1, 0, 0);
        Vector3Int topLeft           = position + new Vector3Int(-1, 1, 0);
        Vector3Int topRight          = position + new Vector3Int(1, 1, 0);
        Vector3Int bottomLeft        = position + new Vector3Int(-1, -1, 0);
        Vector3Int bottomRight       = position + new Vector3Int(1, -1, 0);
        Sprite     upSprite          = tilemap.GetSprite(up);
        Sprite     downSprite        = tilemap.GetSprite(down);
        Sprite     leftSprite        = tilemap.GetSprite(left);
        Sprite     rightSprite       = tilemap.GetSprite(right);
        Sprite     bottomLeftSprite  = tilemap.GetSprite(bottomLeft);
        Sprite     bottomRightSprite = tilemap.GetSprite(bottomRight);
        Sprite     topLeftSprite     = tilemap.GetSprite(topLeft);
        Sprite     topRightSprite    = tilemap.GetSprite(topRight);

        if (!rightSprite && !upSprite && leftSprite && downSprite)
        {
            tileData.sprite = possibleSprites[(int)tileSpritePositions.tRight];
        }
        else if (rightSprite && downSprite && !upSprite && !leftSprite)
        {
            tileData.sprite = possibleSprites[(int)tileSpritePositions.tLeft];
        }
        else if (rightSprite && upSprite && !downSprite && !leftSprite)//right == possibleSprites[(int)tileSpritePositions.bottom] || right == possibleSprites[(int)tileSpritePositions.def]) && (up == possibleSprites[(int)tileSpritePositions.left] || up == possibleSprites[(int)tileSpritePositions.def]))
        {
            tileData.sprite = possibleSprites[(int)tileSpritePositions.bLeft];
        }
        else if (leftSprite && upSprite && !downSprite && !rightSprite)//(left == possibleSprites[(int)tileSpritePositions.bottom] || left == possibleSprites[(int)tileSpritePositions.def]) && (up == possibleSprites[(int)tileSpritePositions.right] || up == possibleSprites[(int)tileSpritePositions.def]))
        {
            tileData.sprite = possibleSprites[(int)tileSpritePositions.bRight];
        }

        else if (!leftSprite && !rightSprite)
        {
            if (
                (upSprite == possibleSprites[(int)tileSpritePositions.right]) ||
                (downSprite == possibleSprites[(int)tileSpritePositions.right]) ||
                (upSprite == possibleSprites[(int)tileSpritePositions.tRight] && topLeftSprite) ||
                (downSprite == possibleSprites[(int)tileSpritePositions.bRight] && bottomLeftSprite)
                )
            {
                tileData.sprite = possibleSprites[(int)tileSpritePositions.right];
            }
            else if (upSprite || downSprite)
            {
                tileData.sprite = possibleSprites[(int)tileSpritePositions.left];
            }
        }
        else
        {
            if (
                (leftSprite == possibleSprites[(int)tileSpritePositions.top]) ||
                (rightSprite == possibleSprites[(int)tileSpritePositions.top]) ||
                (leftSprite == possibleSprites[(int)tileSpritePositions.tLeft] && bottomLeftSprite) ||
                (rightSprite == possibleSprites[(int)tileSpritePositions.tRight] && bottomRightSprite)
                )
            {
                tileData.sprite = possibleSprites[(int)tileSpritePositions.top];
            }
            else if (leftSprite || rightSprite)
            {
                tileData.sprite = possibleSprites[(int)tileSpritePositions.bottom];
            }
        }
        //base.GetTileData(position, tilemap, ref tileData);
    }
Example #52
0
 public static TerrainData GenerateCoasts(TerrainData data, TerrainSettings settings)
 {
     // first get rid of islands/peninsulas
     data = RemoveIsolatedOceanTiles(data, settings);
     data = RemoveIslandsAndPeninsulas(data, settings);
     for (int x = 0; x < data.xSize; x++)
     {
         for (int z = 0; z < data.zSize; z++)
         {
             List <TileData> edgeAdjacentOcean = data.GetEdgeAdjacentTilesOfType(x, z, TileType.OceanFloor);
             if (!data.IsOceanTile(x, z) && edgeAdjacentOcean.Count > 0)
             {
                 if (edgeAdjacentOcean.Count == 1) // coastal straight
                 {
                     Vector3 direction = edgeAdjacentOcean[0].Position - data.GetTileAtCoordinates(x, z).Position;
                     direction = direction.normalized;
                     Vector3  position = new Vector3(x * settings.tileSize, 0, z * settings.tileSize);
                     TileData tile     = data.GetTileAtCoordinates(x, z);
                     tile.ReplaceTile(TileType.CoastStraight, position, Vector3.zero);
                     if (direction == -Vector3.forward)
                     {
                         tile.Rotate(0, 180, 0);
                         tile.AddPosition(new Vector3(settings.tileSize, 0, settings.tileSize));
                     }
                     else if (direction == Vector3.right)
                     {
                         tile.Rotate(0, 90, 0);
                         tile.AddPosition(new Vector3(0, 0, settings.tileSize));
                     }
                     else if (direction == -Vector3.right)
                     {
                         tile.Rotate(0, 270, 0);
                         tile.AddPosition(new Vector3(settings.tileSize, 0, 0));
                     }
                 }
                 else if (edgeAdjacentOcean.Count == 2)
                 {
                     Vector3 directionOne = edgeAdjacentOcean[0].Position - data.GetTileAtCoordinates(x, z).Position;
                     directionOne = directionOne.normalized;
                     Vector3 directionTwo = edgeAdjacentOcean[1].Position - data.GetTileAtCoordinates(x, z).Position;
                     directionTwo = directionTwo.normalized;
                     if (Vector3.Angle(directionOne, directionTwo) <= 90) // coastal outer corner
                     {
                         Vector3  position = new Vector3(x * settings.tileSize, 0, z * settings.tileSize);
                         TileData tile     = data.GetTileAtCoordinates(x, z);
                         tile.ReplaceTile(TileType.CoastOuterCorner, position, Vector3.zero);
                         if (directionOne == Vector3.forward && directionTwo == -Vector3.right || directionTwo == Vector3.forward && directionOne == -Vector3.right)
                         {
                             tile.Rotate(0, -90, 0);
                             tile.AddPosition(new Vector3(settings.tileSize, 0, 0));
                         }
                         else if (directionOne == Vector3.right && directionTwo == -Vector3.forward || directionTwo == Vector3.right && directionOne == -Vector3.forward)
                         {
                             tile.Rotate(0, 90, 0);
                             tile.AddPosition(new Vector3(0, 0, settings.tileSize));
                         }
                         else if (directionOne == -Vector3.forward && directionTwo == -Vector3.right || directionTwo == -Vector3.forward && directionOne == -Vector3.right)
                         {
                             tile.Rotate(0, 180, 0);
                             tile.AddPosition(new Vector3(settings.tileSize, 0, settings.tileSize));
                         }
                     }
                 }
             }
             List <TileData> cornerAdjacentOcean = data.GetCornerAdjacentTilesOfType(x, z, TileType.OceanFloor);
             if (cornerAdjacentOcean.Count == 1 && edgeAdjacentOcean.Count == 0) // coastal inner corner
             {
                 Vector3 direction = cornerAdjacentOcean[0].Position - data.GetTileAtCoordinates(x, z).Position;
                 direction = direction.normalized;
                 Vector3  position = new Vector3(x * settings.tileSize, 0, z * settings.tileSize);
                 TileData tile     = data.GetTileAtCoordinates(x, z);
                 tile.ReplaceTile(TileType.CoastInnerCorner, position, Vector3.zero);
                 float angle = Vector3.SignedAngle(direction, Vector3.forward, Vector3.up);
                 if (angle > 90 && angle <= 180)
                 {
                     tile.Rotate(0, -90, 0);
                     tile.AddPosition(new Vector3(settings.tileSize, 0, 0));
                 }
                 else if (angle < -90 && angle >= -180)
                 {
                     tile.Rotate(0, 180, 0);
                     tile.AddPosition(new Vector3(settings.tileSize, 0, settings.tileSize));
                 }
                 else if (angle < 0 && angle >= -90)
                 {
                     tile.Rotate(0, 90, 0);
                     tile.AddPosition(new Vector3(0, 0, settings.tileSize));
                 }
             }
         }
     }
     // do a final check for islands and peninsulas
     data = RemoveIslandsAndPeninsulas(data, settings);
     return(data);
 }
Example #53
0
 /// <summary>
 /// 타일을 사용 가능한 상태로 세팅합니다.
 /// </summary>
 public void Initialize(TileData tileData)
 {
     coordinate         = new Vector2Int(tileData.posX, tileData.posY);
     transform.position = new Vector3(tileData.posX, 0, tileData.posY) * TilePositionSetting.Instance.tileInterval;
 }
Example #54
0
        private IEnumerator generateGrid(Level data)
        {
            activeGoals = new List <Tile>();

            var rectTransform = transform as RectTransform;

            if (data != null)
            {
                SetupData = data;
            }

            var width  = SetupData.Width;
            var height = SetupData.Height;

            //container.sizeDelta = new Vector2(rectTransform.rect.width, rectTransform.rect.width * ((float) height / width));
            //orphanTileContainer.sizeDelta = container.sizeDelta;

            float cellSize = ((RectTransform)cellPrefab.transform).rect.width;

            float wouldBeCellSize = rectTransform.rect.width / width;
            float scaleFactor     = wouldBeCellSize / cellSize;

            transform.localScale           = new Vector3(scaleFactor, scaleFactor, scaleFactor);
            container.localScale           = new Vector3(scaleFactor, scaleFactor, scaleFactor);
            orphanTileContainer.localScale = new Vector3(scaleFactor, scaleFactor, scaleFactor);

            float startX = ((-rectTransform.rect.width / 2) / scaleFactor) + (cellSize / 2);
            float startY = ((-rectTransform.rect.height / 2) / scaleFactor) + (cellSize / 2);

            // Fill grid with new cells.
            cells = new TileGridCell[width, height];
            var predefinedTiles = new TileData[width, height];

            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    cells[i, j]      = Instantiate(cellPrefab, container).GetComponent <TileGridCell>();
                    cells[i, j].Grid = this;
                    ((RectTransform)cells[i, j].transform).sizeDelta        = new Vector2(cellSize, cellSize);
                    ((RectTransform)cells[i, j].transform).anchoredPosition =
                        new Vector2(startX + (cellSize * i), startY + (cellSize * j));

                    predefinedTiles[i, j] = null;
                }
            }

            // Populate defined cells.
            foreach (var cellData in SetupData.GetCells())
            {
                if (cellData.x < width && cellData.y < height)
                {
                    cells[cellData.x, cellData.y].Data = new TileGridCellData()
                    {
                        x = cellData.x,
                        y = cellData.y
                    };

                    predefinedTiles[cellData.x, cellData.y] = cellData.tileData;
                }
            }

            // Fill the undefined cells with random tiles
            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    var cell = cells[i, j];
                    if (cell.Data == null || predefinedTiles[i, j] == null)
                    {
                        cell.Data = new TileGridCellData()
                        {
                            x = i,
                            y = j
                        };
                        predefinedTiles[i, j] = setupData.GetRandomTileData();
                    }
                }
            }

            // Actually build the tiles for all this data!
            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    var cell = cells[i, j];
                    cell.GenerateTile(predefinedTiles[i, j]);
                }
            }

            //swapper.SetSideSize(cellSize);
            swapper.transform.localScale = new Vector3(scaleFactor, scaleFactor, scaleFactor);
            swapper.HideSides();

            transform.localScale = new Vector3(1, 1, 1);

            yield break;
        }
 public override bool GetTileData(Vector3Int location, ITileMap tileMap, ref TileData tileData)
 {
     UpdateTile(location, tileMap, ref tileData);
     return(true);
 }
Example #56
0
    void DigTile(Vector3Int position)
    {
        mUsingStamina = true;

        if (mStamina <= 0)
        {
            return; // TODO: communicate somehow
        }

        TileData tileData = tileManager.GetTileData(position);

        if (tileData != null)
        {
            mIsTryingToDig = true;
            float digSkill = SaveData.Get().digSkill;
            if (tileData.requiredDigSkill >= 0 && tileData.requiredDigSkill <= digSkill)
            {
                mIsDigging = true;

                float digSpeed = (digSkill - tileData.requiredDigSkill) * 0.1f + 1.2f + (digSkill / 10f);
                float progress;
                if (mDigProgress.TryGetValue(position, out progress))
                {
                    mDigSoundTimer -= Time.deltaTime;
                    if (mDigSoundTimer <= 0f)
                    {
                        PlayDigSound();
                        mDigSoundTimer = 0.4f;
                    }

                    progress += Time.deltaTime * digSpeed;
                    if (progress < 1f)
                    {
                        mDigProgress[position] = progress;
                    }
                    else
                    {
                        tileManager.DestroyTile(position);
                        mDigProgress.Remove(position);
                        --mStamina;
                    }
                }
                else
                {
                    mDigProgress[position] = 0f;
                }
            }
            else
            {
                if (tileData.requiredDigSkill >= 0)
                {
                    // mark that we should receive an email advertising the item that digs through this
                    if (SaveData.Get().activeShopItem == -1)
                    {
                        SaveData.Get().activeShopItem = 0;
                    }
                }

                mDigSoundTimer -= Time.deltaTime;
                if (mDigSoundTimer <= 0f)
                {
                    PlayClankSound();
                    mDigSoundTimer = 0.4f;
                }
            }
        }
    }
Example #57
0
        public static TileData CreateTestTileData()
        {
            TileData tileData = Resources.Load <TileData>(ENV.DEFAULT_TILE_RESOURCE_PATH);

            return(tileData);
        }
Example #58
0
 public void SetTileOwner(TileData t, PlayerType p)
 {
     t.Owner = p;
     _FlagManager.SetFlagForTile(t);
 }
 internal ChangedTile(uint coords, TileData tile)
 {
     this.Coords = new TileCoords(coords);
     this.Tile   = tile;
 }
Example #60
0
 public TileData(TileData tileData)
 {
     type      = tileData.type;
     amount    = tileData.amount;
     endurance = tileData.endurance;
 }