public override bool IsPassable()
        {
            AutoTileMap autoTileMap = AutoTileMap.Instance;

            if (autoTileMap.IsValidAutoTilePos(TileX, TileY))
            {
                for (int iLayer = autoTileMap.GetLayerCount() - 1; iLayer >= 0; --iLayer)
                {
                    if (autoTileMap.MapLayers[iLayer].LayerType == eLayerType.Ground)
                    {
                        AutoTile           autoTile = autoTileMap.GetAutoTile(TileX, TileY, iLayer);
                        eTileCollisionType collType = autoTile.Id >= 0 ? autoTileMap.Tileset.AutotileCollType[autoTile.Id] : eTileCollisionType.EMPTY;
                        if (IsEmptyTilePassable && collType == eTileCollisionType.EMPTY ||
                            collType == eTileCollisionType.PASSABLE || collType == eTileCollisionType.WALL)
                        {
                            return(true);
                        }
                        else if (collType == eTileCollisionType.BLOCK || collType == eTileCollisionType.FENCE)
                        {
                            return(false);
                        }
                    }
                }
            }
            return(false);
        }
        // special case for walls
        bool _IsWallPassable(MapTileNode neighNode)
        {
            AutoTileMap        autoTileMap   = AutoTileMap.Instance;
            eTileCollisionType collType      = eTileCollisionType.EMPTY;
            eTileCollisionType collTypeNeigh = eTileCollisionType.EMPTY;

            for (int iLayer = autoTileMap.GetLayerCount() - 1; iLayer >= 0; --iLayer)
            {
                if (autoTileMap.MapLayers[iLayer].LayerType == eLayerType.Ground)
                {
                    AutoTile autoTile      = autoTileMap.GetAutoTile(TileX, TileY, iLayer);
                    AutoTile autoTileNeigh = autoTileMap.GetAutoTile(neighNode.TileX, neighNode.TileY, iLayer);

                    if (autoTile.Id == autoTileNeigh.Id) // you can walk over two wall tiles if they have the same type
                    {
                        if (autoTile.Id >= 0)
                        {
                            return(true);
                        }
                        else
                        {
                            continue;
                        }
                    }
                    else
                    {
                        // collType will keep the first collision type found of type wall or passable
                        if (collType != eTileCollisionType.PASSABLE && collType != eTileCollisionType.WALL)
                        {
                            collType = autoTile.Id >= 0 ? autoTileMap.Tileset.AutotileCollType[autoTile.Id] : eTileCollisionType.EMPTY;
                        }
                        if (collTypeNeigh != eTileCollisionType.PASSABLE && collTypeNeigh != eTileCollisionType.WALL)
                        {
                            collTypeNeigh = autoTileNeigh.Id >= 0 ? autoTileMap.Tileset.AutotileCollType[autoTileNeigh.Id] : eTileCollisionType.EMPTY;
                        }

                        if (collType == eTileCollisionType.PASSABLE && collTypeNeigh == eTileCollisionType.PASSABLE)
                        {
                            return(true);
                        }
                        else if (collType == eTileCollisionType.WALL || collTypeNeigh == eTileCollisionType.WALL)
                        {
                            return(false);
                        }
                    }
                }
            }
            return(true);
        }
Exemple #3
0
        /// <summary>
        /// Save the map configuration
        /// </summary>
        /// <param name="_autoTileMap"></param>
        /// <returns></returns>
        public bool SaveData(AutoTileMap _autoTileMap, int width = -1, int height = -1)
        {
            if (width < 0)
            {
                width = TileMapWidth;
            }
            if (height < 0)
            {
                height = TileMapHeight;
            }
            // avoid clear map data when auto tile map is not initialized
            if (!_autoTileMap.IsInitialized)
            {
                //Debug.LogError(" Error saving data. Autotilemap is not initialized! Map will not be saved. ");
                return(false);
            }

            Metadata.version = k_version;

            TileData.Clear();
            for (int iLayer = 0; iLayer < _autoTileMap.GetLayerCount(); ++iLayer)
            {
                AutoTileMap.MapLayer mapLayer = _autoTileMap.MapLayers[iLayer];
                List <int>           tileData = new List <int>(width * height);
                int iTileRepetition           = 0;
                int savedTileId = 0;

                int mapWidth  = _autoTileMap.MapTileWidth;
                int mapHeight = _autoTileMap.MapTileHeight;
                for (int tile_y = 0; tile_y < height; ++tile_y)
                {
                    for (int tile_x = 0; tile_x < width; ++tile_x)
                    {
                        int iType = -1;
                        if (tile_x < mapWidth && tile_y < mapHeight)
                        {
                            AutoTile autoTile = _autoTileMap.TileLayers[_autoTileMap.MapLayers[iLayer].TileLayerIdx][tile_x + tile_y * mapWidth];
                            iType = autoTile != null? autoTile.Id : -1;
                        }

                        //+++fix: FogOfWar tiles could be < -1, and this is not good for compress system, excepting ids >= -1
                        if (mapLayer.LayerType == eLayerType.FogOfWar)
                        {
                            iType = ((iType >> 1) & 0x7FFFFFFF); // remove the last bit of the last byte. Will be << 1 later when loading
                        }
                        //---

                        if (iTileRepetition == 0)
                        {
                            savedTileId     = iType;
                            iTileRepetition = 1;
                        }
                        else
                        {
                            // compression data. All tiles of the same type are store with number of repetitions ( negative number ) and type
                            // ex: 5|5|5|5 --> |-4|5| (4 times 5) ex: -1|-1|-1 --> |-3|-1| ( 3 times -1 )
                            if (iType == savedTileId)
                            {
                                ++iTileRepetition;
                            }
                            else
                            {
                                if (iTileRepetition > 1)
                                {
                                    tileData.Add(-iTileRepetition);                                       // save number of repetition with negative sign
                                }
                                if (savedTileId < -1)
                                {
                                    Debug.LogError(" Wrong tile id found when compressing the tile layer " + mapLayer.Name);
                                    savedTileId = -1;
                                }
                                tileData.Add(savedTileId);
                                savedTileId     = iType;
                                iTileRepetition = 1;
                            }
                        }
                    }
                }
                // save last tile type found
                if (iTileRepetition > 1)
                {
                    tileData.Add(-iTileRepetition);
                }
                tileData.Add(savedTileId);

                //
                TileData.Add(new TileLayer()
                {
                    Tiles        = tileData,
                    Depth        = mapLayer.Depth,
                    LayerType    = mapLayer.LayerType,
                    SortingLayer = mapLayer.SortingLayer,
                    SortingOrder = mapLayer.SortingOrder,
                    Name         = mapLayer.Name,
                    Visible      = mapLayer.Visible
                });
            }
            TileMapWidth  = width;
            TileMapHeight = height;
            return(true);
        }
        /// <summary>
        /// Copy a section of the map and use it as drawing template
        /// </summary>
        /// <param name="tile_start_x"></param>
        /// <param name="tile_start_y"></param>
        /// <param name="tile_end_x"></param>
        /// <param name="tile_end_y"></param>
        /// <param name="_dragEndTileX"></param>
        /// <param name="_dragEndTileY"></param>
        /// <param name="isCtrlKeyHold"></param>
        public void RefreshBrushGizmo(int tile_start_x, int tile_start_y, int tile_end_x, int tile_end_y, int _dragEndTileX, int _dragEndTileY, bool isCtrlKeyHold)
        {
            Vector2 pivot = new Vector2(0f, 1f);

            SpriteRenderer[] aSprites = GetComponentsInChildren <SpriteRenderer>();

            int sprIdx = 0;

            for (int tile_x = tile_start_x; tile_x <= tile_end_x; ++tile_x)
            {
                for (int tile_y = tile_start_y; tile_y <= tile_end_y; ++tile_y)
                {
                    for (int tile_layer = 0; tile_layer < MyAutoTileMap.GetLayerCount(); ++tile_layer)
                    {
                        if (
                            (isCtrlKeyHold && tile_layer == SelectedLayer) || //copy all layers over the SelectedLayer
                            !MyAutoTileMap.MapLayers[tile_layer].Visible      // skip invisible layers
                            )
                        {
                            continue;
                        }

                        AutoTileMap.AutoTile autoTile = MyAutoTileMap.GetAutoTile(tile_x, tile_y, tile_layer);
                        if (autoTile != null && autoTile.TilePartsIdx != null && autoTile.Id >= 0)
                        {
                            for (int partIdx = 0; partIdx < autoTile.TilePartsLength; ++partIdx, ++sprIdx)
                            {
                                SpriteRenderer spriteRender = sprIdx < aSprites.Length? aSprites[sprIdx] : null;
                                if (spriteRender == null)
                                {
                                    GameObject spriteObj = new GameObject();
                                    spriteObj.transform.parent = transform;
                                    spriteRender = spriteObj.AddComponent <SpriteRenderer>();
                                }
                                spriteRender.transform.gameObject.name = "BrushGizmoPart" + sprIdx;
                                spriteRender.sprite       = Sprite.Create(MyAutoTileMap.Tileset.AtlasTexture, MyAutoTileMap.Tileset.AutoTileRects[autoTile.TilePartsIdx[partIdx]], pivot, AutoTileset.PixelToUnits);
                                spriteRender.sortingOrder = 50;                                 //TODO: +50 temporal? see for a const number later
                                spriteRender.color        = new Color32(192, 192, 192, 192);

                                // get last tile as relative position
                                int tilePart_x = (tile_x - _dragEndTileX) * 2 + partIdx % 2;
                                int tilePart_y = (tile_y - _dragEndTileY) * 2 + partIdx / 2;

                                float xFactor = MyAutoTileMap.Tileset.TilePartWidth / AutoTileset.PixelToUnits;
                                float yFactor = MyAutoTileMap.Tileset.TilePartHeight / AutoTileset.PixelToUnits;
                                spriteRender.transform.localPosition = new Vector3(tilePart_x * xFactor, -tilePart_y * yFactor, spriteRender.transform.position.z);
                            }
                        }
                    }
                }
            }
            // clean unused sprite objects
            while (sprIdx < aSprites.Length)
            {
                if (Application.isEditor)
                {
                    DestroyImmediate(aSprites[sprIdx].transform.gameObject);
                }
                else
                {
                    Destroy(aSprites[sprIdx].transform.gameObject);
                }
                ++sprIdx;
            }
        }
        /// <summary>
        /// Save the map configuration
        /// </summary>
        /// <param name="_autoTileMap"></param>
        /// <returns></returns>
        public bool SaveData(AutoTileMap _autoTileMap)
        {
            int width  = TileMapWidth;
            int height = TileMapHeight;

            // avoid clear map data when auto tile map is not initialized
            if (!_autoTileMap.IsInitialized)
            {
                //Debug.LogError(" Error saving data. Autotilemap is not initialized! Map will not be saved. ");
                return(false);
            }

            Metadata.version = MetadataChunk.k_version;

            TileData.Clear();
            // TriggerLink.Clear();
            // WarpsData.Clear();
            // SignpostsData.Clear();
            // ScriptData.Clear();

            bool isEnableCompression = true;

            for (int iLayer = 0; iLayer < _autoTileMap.GetLayerCount(); ++iLayer)
            {
                AutoTileMap.MapLayer mapLayer = _autoTileMap.MapLayers[iLayer];
                List <int>           tileData = new List <int>(width * height);
                int iTileRepetition           = 0;
                int savedTileId = 0;
                int mapWidth    = _autoTileMap.MapTileWidth;
                int mapHeight   = _autoTileMap.MapTileHeight;
                for (int tile_y = 0; tile_y < height; ++tile_y)
                {
                    for (int tile_x = 0; tile_x < width; ++tile_x)
                    {
                        int iType = -1;
                        if (tile_x < mapWidth && tile_y < mapHeight)
                        {
                            // AutoTile autoTile = _autoTileMap.TileLayers[_autoTileMap.MapLayers[iLayer].TileLayerIdx][tile_x + tile_y * mapWidth];
                            AutoTile autoTile = _autoTileMap.TileLayers[iLayer][tile_x, tile_y];
                            iType = autoTile != null? autoTile.Id : -1;
                        }

                        if (isEnableCompression)
                        {
                            if (iTileRepetition == 0)
                            {
                                savedTileId     = iType;
                                iTileRepetition = 1;
                            }
                            else
                            {
                                // compression data. All tiles of the same type are store with number of repetitions ( negative number ) and type
                                // ex: 5|5|5|5 --> |-4|5| (4 times 5) ex: -1|-1|-1 --> |-3|-1| ( 3 times -1 )
                                if (iType == savedTileId)
                                {
                                    ++iTileRepetition;
                                }
                                else
                                {
                                    if (iTileRepetition > 1)
                                    {
                                        tileData.Add(-iTileRepetition);   // save number of repetition with negative sign
                                    }
                                    if (savedTileId < -1)
                                    {
                                        Debug.LogError(" Wrong tile id found when compressing the tile layer " + mapLayer.Name);
                                        savedTileId = -1;
                                    }
                                    tileData.Add(savedTileId);
                                    savedTileId     = iType;
                                    iTileRepetition = 1;
                                }
                            }
                        }
                        else
                        {
                            tileData.Add(iType);   // save number of repetition with negative sign
                        }
                    }
                }
                if (isEnableCompression)
                {
                    // save last tile type found
                    if (iTileRepetition > 1)
                    {
                        tileData.Add(-iTileRepetition);
                    }
                    tileData.Add(savedTileId);
                }
                //
                TileData.Add(new TileLayer()
                {
                    Tiles        = tileData,
                    Depth        = mapLayer.Depth,
                    LayerType    = mapLayer.LayerType,
                    SortingLayer = mapLayer.SortingLayer,
                    SortingOrder = mapLayer.SortingOrder,
                    Name         = mapLayer.Name,
                    Visible      = mapLayer.Visible
                });
            }
            TileMapWidth  = width;
            TileMapHeight = height;

            //Compression Data
            OverlayLink_C   = CreateCompressionArray(OverlayLink);
            TriggerLink_C   = CreateCompressionArray(TriggerLink);
            High_C          = CreateCompressionArray(High);
            OverlayRotate_C = CreateCompressionArray(OverlayRotate);
            // RawFlagMap.Data = FlagMap;
            RawFlagAction = new List <FlagAction.SerializableFlagAction>(ListFlagAction.Count);
            for (int i = 0; i < ListFlagAction.Count; i++)
            {
                var r = new FlagAction.SerializableFlagAction();
                r.FlagAction = ListFlagAction[i];
                RawFlagAction.Add(r);
            }
            Debug.Log("Save with Compression");
            return(true);
        }
        void Update()
        {
            if (!m_isInitialized)
            {
                Init();
                return;
            }

            #region Draw Collisions
            // Generate texture again in case window has been resized
            Vector2 screenSize = new Vector2(Screen.width, Screen.height);
            if (m_prevScreenSize != screenSize)
            {
                _GenerateCollisionTexture();
            }
            m_prevScreenSize = screenSize;

            m_spriteCollLayer.SetActive(m_showCollisions);
            if (m_showCollisions && (int)(Time.timeSinceLevelLoad * 4) % 2 == 0)
            {
                SpriteRenderer sprRender = m_spriteCollLayer.GetComponent <SpriteRenderer>();
                Vector3        vPos      = m_camera2D.transform.position;
                vPos.x -= (vPos.x % (m_autoTileMap.Tileset.TileWorldWidth / 4));
                vPos.y -= (vPos.y % (m_autoTileMap.Tileset.TileWorldHeight / 4));
                vPos.z += 1f;

                // Collision texture position snap to a quarter of tile part
                sprRender.transform.position = vPos;

                // Collision texture pixel scaled to a quarter of tile part
                sprRender.transform.localScale = new Vector3((m_autoTileMap.Tileset.TilePartWidth / 2), (m_autoTileMap.Tileset.TilePartHeight / 2), 1f);

                vPos = m_camera2D.Camera.WorldToScreenPoint(sprRender.transform.position);                   // vPos = center of collision texture in screen coords
                Vector3 vTopLeftOff = new Vector3(sprRender.sprite.texture.width * (m_autoTileMap.Tileset.TilePartWidth / 2) / 2, -sprRender.sprite.texture.height * (m_autoTileMap.Tileset.TilePartHeight / 2) / 2) * m_camera2D.Zoom;
                vPos -= vTopLeftOff;
                vPos  = m_camera2D.Camera.ScreenToWorldPoint(vPos); // vPos is now the top left corner of the collison texture in world coordinates

                Color32[] colors  = sprRender.sprite.texture.GetPixels32();
                float     factorX = m_autoTileMap.Tileset.TileWorldWidth / 4; //smallest collision part has a size of a quarter of tile part
                float     factorY = m_autoTileMap.Tileset.TileWorldHeight / 4;
                for (int y = 0; y < sprRender.sprite.texture.height; ++y)
                {
                    for (int x = 0; x < sprRender.sprite.texture.width; ++x)
                    {
                        Vector3 vCheckPos = vPos;
                        vCheckPos.x += (x + 0.5f) * factorX;
                        vCheckPos.y -= (y + 0.5f) * factorY;
                        AutoTileMap.eTileCollisionType collType = m_autoTileMap.GetAutotileCollisionAtPosition(vCheckPos);
                        //Color32 color = (x+y)%2 == 0? new Color32(0, 0, 64, 128) : new Color32(64, 0, 0, 128) ;
                        Color32 color = new Color32(0, 0, 0, 0);
                        colors[(sprRender.sprite.texture.height - 1 - y) * sprRender.sprite.texture.width + x] = (collType != AutoTileMap.eTileCollisionType.PASSABLE)? new Color32(255, 0, 0, 128) : color;
                    }
                }
                sprRender.sprite.texture.SetPixels32(colors);
                sprRender.sprite.texture.Apply();
            }
            #endregion

            if (Input.GetKeyDown(KeyCode.Delete))  //TODO: only delete the tiles in ground layer, fix this
            {
                // select delete tile
                m_selectedTileIdx = -1;

                // Remove Brush
                m_autoTileMap.BrushGizmo.Clear();
                m_tilesetSelStart = m_tilesetSelEnd = -1;
            }

            #region Undo / Redo
            if (m_isCtrlKeyHold)
            {
                if (Input.GetKeyDown(KeyCode.Z))
                {
                    m_autoTileMap.BrushGizmo.UndoAction();
                }
                else if (Input.GetKeyDown(KeyCode.Y))
                {
                    m_autoTileMap.BrushGizmo.RedoAction();
                }

                //+++ Key Repetition Implementation
                if (Input.GetKey(KeyCode.Z))
                {
                    m_keyPressTimer += Time.deltaTime;
                    if (m_keyPressTimer >= k_timeBeforeKeyRepeat)
                    {
                        m_keyPressTimer -= k_timeBetweenKeyRepeat;
                        m_autoTileMap.BrushGizmo.UndoAction();
                    }
                }
                else if (Input.GetKey(KeyCode.Y))
                {
                    m_keyPressTimer += Time.deltaTime;
                    if (m_keyPressTimer >= k_timeBeforeKeyRepeat)
                    {
                        m_keyPressTimer -= k_timeBetweenKeyRepeat;
                        m_autoTileMap.BrushGizmo.RedoAction();
                    }
                }
                else
                {
                    m_keyPressTimer = 0f;
                }
                //---
            }
            #endregion

            if (Input.GetKeyDown(KeyCode.M))
            {
                m_showMinimap = !m_showMinimap;
            }
            if (Input.GetKeyDown(KeyCode.C))
            {
                m_showCollisions = !m_showCollisions;
            }

            bool isMouseLeft      = Input.GetMouseButton(0);
            bool isMouseRight     = Input.GetMouseButton(1);
            bool isMouseMiddle    = Input.GetMouseButton(2);
            bool isMouseLeftDown  = Input.GetMouseButtonDown(0);
            bool isMouseRightDown = Input.GetMouseButtonDown(1);

            m_drawSelectionRect = false;

            Vector3 vGuiMouse      = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
            Vector3 vGuiMouseDelta = vGuiMouse - m_mousePrevPos;
            m_mousePrevPos = vGuiMouse;

            //+++ Set window with focus
            if (!isMouseLeft)
            {
                if (m_rEditorRect.Contains(vGuiMouse))
                {
                    m_focusWindow = eEditorWindow.TOOLS;
                }
                else if (m_rMinimapRect.Contains(vGuiMouse) && m_showMinimap)
                {
                    m_focusWindow = eEditorWindow.MINIMAP;
                }
                // Added an extra padding to avoid drawing tiles when resizing window
                else if (new Rect(m_rEditorRect.x + m_rEditorRect.width + 10f, 10f, Screen.width - 20f - (m_rEditorRect.x + m_rEditorRect.width), Screen.height - 20f).Contains(vGuiMouse))
                {
                    m_focusWindow = eEditorWindow.MAPVIEW;
                }
                else
                {
                    m_focusWindow = eEditorWindow.NONE;
                }
            }
            //---

            // drag and move over the map
            if (isMouseMiddle)
            {
                if (m_camera2DFollowBehaviour)
                {
                    m_camera2DFollowBehaviour.Target = null;
                }
                Vector3 vTemp = vGuiMouseDelta; vTemp.y = -vTemp.y;
                m_camera2D.transform.position -= (vTemp / 100) / m_camera2D.Zoom;
            }

            //
            // Inputs inside Editor Rect
            //
            if (m_rEditorRect.Contains(vGuiMouse))
            {
                if (m_rTilesetRect.Contains(vGuiMouse))
                {
                    vGuiMouse += new Vector3(m_scrollPos.x, m_scrollPos.y);
                    Vector3 vOff        = new Vector2(vGuiMouse.x, vGuiMouse.y) - m_rTilesetRect.position;
                    int     tileX       = (int)(vOff.x / k_visualTileWidth);
                    int     tileY       = (int)(vOff.y / k_visualTileHeight);
                    int     autotileIdx = tileY * m_autoTileMap.Tileset.AutoTilesPerRow + tileX + (m_subTilesetIdx * 256);

                    if (isMouseLeftDown || isMouseRightDown && m_isCtrlKeyHold)
                    {
                        if (m_isCtrlKeyHold)
                        {
                            // cycle pressed tile collision type
                            int collType = (int)m_autoTileMap.Tileset.AutotileCollType[autotileIdx];
                            collType += isMouseLeftDown? 1 : (int)AutoTileMap.eTileCollisionType._SIZE - 1;
                            collType %= (int)AutoTileMap.eTileCollisionType._SIZE;
                            m_autoTileMap.Tileset.AutotileCollType[autotileIdx] = (AutoTileMap.eTileCollisionType)(collType);
                        }
                        else
                        {
                            // select pressed tile
                            m_selectedTileIdx = autotileIdx;

                            // Remove Brush
                            m_autoTileMap.BrushGizmo.Clear();
                            m_tilesetSelStart = m_tilesetSelEnd = -1;
                        }
                    }
                    else if (isMouseRightDown)
                    {
                        m_tilesetSelStart = m_tilesetSelEnd = autotileIdx;
                    }
                    else if (isMouseRight)
                    {
                        m_tilesetSelEnd = autotileIdx;
                    }
                    else if (m_tilesetSelStart >= 0 && m_tilesetSelEnd >= 0)
                    {
                        m_autoTileMap.BrushGizmo.RefreshBrushGizmoFromTileset(m_tilesetSelStart, m_tilesetSelEnd);
                        m_tilesetSelStart = m_tilesetSelEnd = -1;
                    }
                }
            }
            //
            // Inputs inside Minimap Rect
            //
            else if (m_showMinimap && m_rMinimapRect.Contains(vGuiMouse) && m_focusWindow == eEditorWindow.MINIMAP)
            {
                if (isMouseLeft)
                {
                    float   minimapScale = m_rMinimapRect.width / m_autoTileMap.MinimapTexture.width;
                    Vector3 vPos         = vGuiMouse - new Vector3(m_rMinimapRect.position.x, m_rMinimapRect.position.y);
                    vPos.y  = -vPos.y;
                    vPos.x *= m_autoTileMap.Tileset.TileWidth / (AutoTileset.PixelToUnits * minimapScale);
                    vPos.y *= m_autoTileMap.Tileset.TileHeight / (AutoTileset.PixelToUnits * minimapScale);
                    vPos.z  = m_camera2D.transform.position.z;
                    m_camera2D.transform.position = vPos;
                    if (m_camera2DFollowBehaviour)
                    {
                        m_camera2DFollowBehaviour.Target = null;
                    }
                }
            }
            //
            // Insputs inside map view
            //
            else if (m_focusWindow == eEditorWindow.MAPVIEW)
            {
                Vector3 vWorldMousePos = m_autoTileMap.ViewCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y));
                m_autoTileMap.BrushGizmo.UpdateBrushGizmo(vWorldMousePos);

                if (isMouseRight || isMouseLeft)
                {
                    m_drawSelectionRect = isMouseRight;

                    //+++ Move camera automatically when near bounds
                    if (isMouseLeft)
                    {
                        float fAutoDragDistX = m_rMapViewRect.width / 15;
                        float fAutoDragDistY = m_rMapViewRect.height / 15;
                        float fHDist         = m_rMapViewRect.center.x - vGuiMouse.x;
                        float fVDist         = m_rMapViewRect.center.y - vGuiMouse.y;
                        float fHSpeed        = Mathf.Lerp(0f, -Mathf.Sign(fHDist), Mathf.Abs(fHDist) < (m_rMapViewRect.width / 2 - fAutoDragDistX)? 0 : 1f - (m_rMapViewRect.width / 2 - Mathf.Abs(fHDist)) / fAutoDragDistX);
                        float fVSpeed        = Mathf.Lerp(0f, Mathf.Sign(fVDist), Mathf.Abs(fVDist) < (m_rMapViewRect.height / 2 - fAutoDragDistY)? 0 : 1f - (m_rMapViewRect.height / 2 - Mathf.Abs(fVDist)) / fAutoDragDistY);
                        if (fVSpeed != 0f || fHSpeed != 0f)
                        {
                            if (m_camera2DFollowBehaviour)
                            {
                                m_camera2DFollowBehaviour.Target = null;
                            }
                            m_camera2D.transform.position += (new Vector3(fHSpeed, fVSpeed, 0f) / 30) / m_camera2D.Zoom;
                        }
                    }
                    //---

                    Ray   ray      = Camera.main.ScreenPointToRay(Input.mousePosition);
                    Plane hPlane   = new Plane(Vector3.forward, Vector3.zero);
                    float distance = 0;
                    if (hPlane.Raycast(ray, out distance))
                    {
                        // get the hit point:
                        Vector3 vPos   = ray.GetPoint(distance);
                        int     tile_x = (int)(vPos.x / m_autoTileMap.Tileset.TileWorldWidth);
                        int     tile_y = (int)(-vPos.y / m_autoTileMap.Tileset.TileWorldHeight);

                        // for optimization, is true when mouse is over a diffent tile during the first update
                        bool isMouseTileChanged = (tile_x != m_prevMouseTileX) || (tile_y != m_prevMouseTileY);

                        //if ( m_autoTileMap.IsValidAutoTilePos(tile_x, tile_y)) // commented to allow drawing outside map, useful when brush has a lot of copied tiles
                        {
                            int gndTileType        = m_autoTileMap.GetAutoTile(tile_x, tile_y, m_autoTileMap.BrushGizmo.SelectedLayer).Id;
                            int gndOverlayTileType = m_autoTileMap.GetAutoTile(tile_x, tile_y, m_autoTileMap.BrushGizmo.SelectedLayer + 1).Id;

                            // mouse right for tile selection
                            if (isMouseRightDown || isMouseRight && isMouseTileChanged)
                            {
                                if (isMouseRightDown)
                                {
                                    m_startDragTileX = tile_x;
                                    m_startDragTileY = tile_y;

                                    // copy tile
                                    if (m_isCtrlKeyHold)
                                    {
                                        m_selectedTileIdx = -2;                                         //NOTE: -2 means, ignore this tile when painting
                                    }
                                    else
                                    {
                                        m_selectedTileIdx = gndTileType >= 0? gndTileType : gndOverlayTileType;
                                    }
                                }
                                m_dragTileX = tile_x;
                                m_dragTileY = tile_y;

                                // Remove Brush
                                m_autoTileMap.BrushGizmo.Clear();
                                m_tilesetSelStart = m_tilesetSelEnd = -1;
                            }
                            // isMouseLeft
                            else if (isMouseLeftDown || isMouseTileChanged)                              // avoid Push the same action twice during mouse drag
                            {
                                AutoTileBrush.TileAction action = new AutoTileBrush.TileAction();
                                if (m_autoTileMap.BrushGizmo.BrushAction != null)
                                {
                                    //+++ case of multiple tiles painting
                                    action.CopyRelative(m_autoTileMap, m_autoTileMap.BrushGizmo.BrushAction, tile_x, tile_y);
                                    if (m_isCtrlKeyHold && (m_autoTileMap.BrushGizmo.SelectedLayer + 1) < m_autoTileMap.GetLayerCount())
                                    {
                                        // old functionality: ground tiles become ground overlay, ground overlay are removed, overlay tiles remains
                                        // Tiles in SelectedLayer are moved to next layer
                                        action.BecomeOverlay(m_autoTileMap.BrushGizmo.SelectedLayer);
                                    }
                                }
                                else
                                {
                                    //+++ case of single tile painting
                                    // If smart brush is enabled, the tiles with collision type Overlay will be placed directly in the first overlay layer found over current SelectedLayer
                                    int overlayLayer = m_autoTileMap.FindFirstLayerIdx(AutoTileMap.eLayerType.Overlay, m_autoTileMap.BrushGizmo.SelectedLayer);
                                    if (m_autoTileMap.BrushGizmo.SmartBrushEnabled && overlayLayer >= 0 && m_selectedTileIdx >= 0 && m_autoTileMap.Tileset.AutotileCollType[m_selectedTileIdx] == AutoTileMap.eTileCollisionType.OVERLAY)
                                    {
                                        action.Push(m_autoTileMap, tile_x, tile_y, m_selectedTileIdx, overlayLayer);
                                    }
                                    else
                                    {
                                        if (m_isCtrlKeyHold || m_autoTileMap.IsAutoTileHasAlpha(m_selectedTileIdx) && m_autoTileMap.BrushGizmo.SmartBrushEnabled)
                                        {
                                            // Put tiles with alpha in the layer over Selected Layer
                                            action.Push(m_autoTileMap, tile_x, tile_y, m_selectedTileIdx, m_autoTileMap.BrushGizmo.SelectedLayer + 1);
                                        }
                                        else if (m_selectedTileIdx >= 0)
                                        {
                                            // Paint the selected tile
                                            action.Push(m_autoTileMap, tile_x, tile_y, m_selectedTileIdx, m_autoTileMap.BrushGizmo.SelectedLayer);
                                        }
                                        else //if (m_selectedTileIdx < 0)
                                        {
                                            // Delete all tiles of all layers
                                            for (int i = 0; i < m_autoTileMap.GetLayerCount(); ++i)
                                            {
                                                if (
                                                    m_autoTileMap.MapLayers[i].LayerType == AutoTileMap.eLayerType.Ground ||
                                                    m_autoTileMap.MapLayers[i].LayerType == AutoTileMap.eLayerType.Overlay ||
                                                    m_autoTileMap.MapLayers[i].LayerType == AutoTileMap.eLayerType.FogOfWar
                                                    )
                                                {
                                                    action.Push(m_autoTileMap, tile_x, tile_y, -1, i);
                                                }
                                            }
                                        }
                                    }
                                }

                                m_autoTileMap.BrushGizmo.PerformAction(action);
                            }
                        }

                        m_prevMouseTileX = tile_x;
                        m_prevMouseTileY = tile_y;
                    }
                }
                else
                {
                    // Copy selected tiles
                    if (m_dragTileX != -1 && m_dragTileY != -1)
                    {
                        m_autoTileMap.BrushGizmo.BrushAction = new AutoTileBrush.TileAction();
                        int startTileX = Mathf.Min(m_startDragTileX, m_dragTileX);
                        int startTileY = Mathf.Min(m_startDragTileY, m_dragTileY);
                        int endTileX   = Mathf.Max(m_startDragTileX, m_dragTileX);
                        int endTileY   = Mathf.Max(m_startDragTileY, m_dragTileY);

                        for (int tile_x = startTileX; tile_x <= endTileX; ++tile_x)
                        {
                            for (int tile_y = startTileY; tile_y <= endTileY; ++tile_y)
                            {
                                // Tile position is relative to last released position ( m_dragTile )
                                if (m_isCtrlKeyHold)
                                {
                                    // Copy overlay only
                                    for (int i = m_autoTileMap.BrushGizmo.SelectedLayer + 1; i < m_autoTileMap.GetLayerCount(); ++i)
                                    {
                                        int tileType = m_autoTileMap.GetAutoTile(tile_x, tile_y, i).Id;
                                        if (
                                            (m_autoTileMap.MapLayers[i].LayerType != AutoTileMap.eLayerType.Ground) ||
                                            (tileType >= 0) // this allow paste overlay tiles without removing ground or ground overlay
                                            )
                                        {
                                            m_autoTileMap.BrushGizmo.BrushAction.Push(m_autoTileMap, tile_x - m_dragTileX, tile_y - m_dragTileY, tileType, i);
                                        }
                                    }
                                }
                                else
                                {
                                    for (int i = 0; i < m_autoTileMap.GetLayerCount(); ++i)
                                    {
                                        int tileType = m_autoTileMap.GetAutoTile(tile_x, tile_y, i).Id;
                                        m_autoTileMap.BrushGizmo.BrushAction.Push(m_autoTileMap, tile_x - m_dragTileX, tile_y - m_dragTileY, tileType, i);
                                    }
                                }
                            }
                        }

                        m_autoTileMap.BrushGizmo.RefreshBrushGizmo(startTileX, startTileY, endTileX, endTileY, m_dragTileX, m_dragTileY, m_isCtrlKeyHold);

                        m_dragTileX = m_dragTileY = -1;
                    }

                    if (Input.GetAxis("Mouse ScrollWheel") < 0)                     // back
                    {
                        if (m_camera2D.Zoom > 1f)
                        {
                            m_camera2D.Zoom = Mathf.Max(m_camera2D.Zoom - 1, 1);
                        }
                        else
                        {
                            m_camera2D.Zoom = Mathf.Max(m_camera2D.Zoom / 2f, 0.05f);
                        }
                    }
                    else if (Input.GetAxis("Mouse ScrollWheel") > 0)                     // forward
                    {
                        if (m_camera2D.Zoom >= 1f)
                        {
                            m_camera2D.Zoom = Mathf.Min(m_camera2D.Zoom + 1, 10);
                        }
                        else
                        {
                            m_camera2D.Zoom *= 2f;
                        }
                    }
                }
            }
        }
Exemple #7
0
        public void OnSceneGUI()
        {
            #region Undo / Redo
            if (Event.current.isKey && Event.current.shift && Event.current.type == EventType.KeyUp)
            {
                if (Event.current.keyCode == KeyCode.Z)
                {
                    m_autoTileMap.BrushGizmo.UndoAction();
                }
                if (Event.current.keyCode == KeyCode.Y)
                {
                    m_autoTileMap.BrushGizmo.RedoAction();
                }
            }
            #endregion

            Rect rSceneView = new Rect(0, 0, Screen.width, Screen.height);
            if (rSceneView.Contains(Event.current.mousePosition))
            {
                UpdateMouseInputs();

                Ray   ray      = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
                Plane hPlane   = new Plane(Vector3.forward, Vector3.zero);
                float distance = 0;
                if (hPlane.Raycast(ray, out distance))
                {
                    // get the hit point:
                    Vector3 vPos = ray.GetPoint(distance);
                    m_autoTileMap.BrushGizmo.UpdateBrushGizmo(vPos);

                    if (m_isMouseRight || m_isMouseLeft)
                    {
                        int tile_x = (int)(vPos.x / m_autoTileMap.Tileset.TileWorldWidth);
                        int tile_y = (int)(-vPos.y / m_autoTileMap.Tileset.TileWorldHeight);

                        // for optimization, is true when mouse is over a diffent tile during the first update
                        bool isMouseTileChanged = (tile_x != m_prevMouseTileX) || (tile_y != m_prevMouseTileY);

                        //if ( m_autoTileMap.IsValidAutoTilePos(tile_x, tile_y)) // commented to allow drawing outside map, useful when brush has a lot of copied tiles
                        {
                            int gndTileType        = m_autoTileMap.GetAutoTile(tile_x, tile_y, m_autoTileMap.BrushGizmo.SelectedLayer).Id;
                            int gndOverlayTileType = m_autoTileMap.GetAutoTile(tile_x, tile_y, m_autoTileMap.BrushGizmo.SelectedLayer + 1).Id;

                            // mouse right for tile selection
                            if (m_isMouseRightDown || m_isMouseRight && isMouseTileChanged)
                            {
                                if (m_isMouseRightDown)
                                {
                                    m_startDragTileX = tile_x;
                                    m_startDragTileY = tile_y;

                                    // Remove Brush
                                    m_autoTileMap.BrushGizmo.Clear();
                                    m_tilesetSelStart = m_tilesetSelEnd = -1;

                                    // copy tile
                                    if (Event.current.shift)
                                    {
                                        m_selectedTileId = -2;                                         //NOTE: -2 means, ignore this tile when painting
                                    }
                                    else
                                    {
                                        m_selectedTileId = gndTileType >= 0? gndTileType : gndOverlayTileType;
                                    }
                                }
                                m_dragTileX = tile_x;
                                m_dragTileY = tile_y;
                            }
                            // isMouseLeft
                            else if (m_isMouseLeftDown || isMouseTileChanged)                              // avoid Push the same action twice during mouse drag
                            {
                                AutoTileBrush.TileAction action = new AutoTileBrush.TileAction();
                                if (m_autoTileMap.BrushGizmo.BrushAction != null)
                                {
                                    //+++ case of multiple tiles painting
                                    action.CopyRelative(m_autoTileMap, m_autoTileMap.BrushGizmo.BrushAction, tile_x, tile_y);
                                    if (Event.current.shift && (m_autoTileMap.BrushGizmo.SelectedLayer + 1) < m_autoTileMap.GetLayerCount())
                                    {
                                        // old functionality: ground tiles become ground overlay, ground overlay are removed, overlay tiles remains
                                        // Tiles in SelectedLayer are moved to next layer
                                        action.BecomeOverlay(m_autoTileMap.BrushGizmo.SelectedLayer);
                                    }
                                }
                                else
                                {
                                    //+++ case of single tile painting
                                    // If smart brush is enabled, the tiles with collision type Overlay will be placed directly in the first overlay layer found over current SelectedLayer
                                    int overlayLayer = m_autoTileMap.FindFirstLayerIdx(eLayerType.Overlay, m_autoTileMap.BrushGizmo.SelectedLayer);
                                    if (m_autoTileMap.BrushGizmo.SmartBrushEnabled && overlayLayer >= 0 && m_selectedTileId >= 0 && m_autoTileMap.Tileset.AutotileCollType[m_selectedTileId] == eTileCollisionType.OVERLAY)
                                    {
                                        action.Push(m_autoTileMap, tile_x, tile_y, m_selectedTileId, overlayLayer);
                                    }
                                    else
                                    {
                                        if (Event.current.shift || m_autoTileMap.IsAutoTileHasAlpha(m_selectedTileId) && m_autoTileMap.BrushGizmo.SmartBrushEnabled)
                                        {
                                            // Put tiles with alpha in the layer over Selected Layer
                                            action.Push(m_autoTileMap, tile_x, tile_y, m_selectedTileId, m_autoTileMap.BrushGizmo.SelectedLayer + 1);
                                        }
                                        else
                                        {
                                            action.Push(m_autoTileMap, tile_x, tile_y, m_selectedTileId, m_autoTileMap.BrushGizmo.SelectedLayer);
                                        }
                                    }
                                }

                                m_autoTileMap.BrushGizmo.PerformAction(action);
                                EditorUtility.SetDirty(m_autoTileMap);
                            }
                        }

                        m_prevMouseTileX = tile_x;
                        m_prevMouseTileY = tile_y;
                    }
                    else
                    {
                        // Copy selected tiles
                        if (m_dragTileX != -1 && m_dragTileY != -1)
                        {
                            m_autoTileMap.BrushGizmo.BrushAction = new AutoTileBrush.TileAction();
                            int startTileX = Mathf.Min(m_startDragTileX, m_dragTileX);
                            int startTileY = Mathf.Min(m_startDragTileY, m_dragTileY);
                            int endTileX   = Mathf.Max(m_startDragTileX, m_dragTileX);
                            int endTileY   = Mathf.Max(m_startDragTileY, m_dragTileY);

                            for (int tile_x = startTileX; tile_x <= endTileX; ++tile_x)
                            {
                                for (int tile_y = startTileY; tile_y <= endTileY; ++tile_y)
                                {
                                    // Tile position is relative to last released position ( m_dragTile )
                                    if (Event.current.shift)
                                    {
                                        // Copy overlay only
                                        for (int i = m_autoTileMap.BrushGizmo.SelectedLayer + 1; i < m_autoTileMap.GetLayerCount(); ++i)
                                        {
                                            int tileType = m_autoTileMap.GetAutoTile(tile_x, tile_y, i).Id;
                                            if (
                                                (m_autoTileMap.MapLayers[i].LayerType != eLayerType.Ground) ||
                                                (tileType >= 0) // this allow paste overlay tiles without removing ground or ground overlay
                                                )
                                            {
                                                m_autoTileMap.BrushGizmo.BrushAction.Push(m_autoTileMap, tile_x - m_dragTileX, tile_y - m_dragTileY, tileType, i);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        for (int i = 0; i < m_autoTileMap.GetLayerCount(); ++i)
                                        {
                                            int tileType = m_autoTileMap.GetAutoTile(tile_x, tile_y, i).Id;
                                            m_autoTileMap.BrushGizmo.BrushAction.Push(m_autoTileMap, tile_x - m_dragTileX, tile_y - m_dragTileY, tileType, i);
                                        }
                                    }
                                }
                            }

                            m_autoTileMap.BrushGizmo.RefreshBrushGizmo(startTileX, startTileY, endTileX, endTileY, m_dragTileX, m_dragTileY, Event.current.shift);

                            m_dragTileX = m_dragTileY = -1;
                        }
                    }
                }

                // Draw selection rect
                if (m_isMouseRight)
                {
                    float rX         = m_autoTileMap.transform.position.x + Mathf.Min(m_startDragTileX, m_dragTileX) * m_autoTileMap.Tileset.TileWorldWidth;
                    float rY         = m_autoTileMap.transform.position.y + Mathf.Min(m_startDragTileY, m_dragTileY) * m_autoTileMap.Tileset.TileWorldHeight;
                    float rWidth     = (Mathf.Abs(m_dragTileX - m_startDragTileX) + 1) * m_autoTileMap.Tileset.TileWorldWidth;
                    float rHeight    = (Mathf.Abs(m_dragTileY - m_startDragTileY) + 1) * m_autoTileMap.Tileset.TileWorldHeight;
                    Rect  rSelection = new Rect(rX, -rY, rWidth, -rHeight);
                    UtilsGuiDrawing.DrawRectWithOutline(rSelection, new Color(0f, 1f, 0f, 0.2f), new Color(0f, 1f, 0f, 1f));
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// Copy a section of the map and use it as drawing template
        /// </summary>
        /// <param name="tile_start_x"></param>
        /// <param name="tile_start_y"></param>
        /// <param name="tile_end_x"></param>
        /// <param name="tile_end_y"></param>
        /// <param name="_dragEndTileX"></param>
        /// <param name="_dragEndTileY"></param>
        /// <param name="isCtrlKeyHold"></param>
        public void RefreshBrushGizmo(int tile_start_x, int tile_start_y, int tile_end_x, int tile_end_y, int _dragEndTileX, int _dragEndTileY, bool isCtrlKeyHold)
        {
            Vector2 pivot = new Vector2(0f, 1f);

            SpriteRenderer[] aSprites = GetComponentsInChildren <SpriteRenderer>();

            int sprIdx = 0;

            for (int tile_x = tile_start_x; tile_x <= tile_end_x; ++tile_x)
            {
                for (int tile_y = tile_start_y; tile_y <= tile_end_y; ++tile_y)
                {
                    for (int tile_layer = 0; tile_layer < MyAutoTileMap.GetLayerCount(); ++tile_layer)
                    {
                        // if(
                        //     (isCtrlKeyHold && tile_layer == SelectedLayer) || //copy all layers over the SelectedLayer
                        //     !MyAutoTileMap.MapLayers[tile_layer].Visible // skip invisible layers
                        // )
                        // {
                        //  continue;
                        // }

                        AutoTile autoTile = MyAutoTileMap.GetAutoTile(tile_x, tile_y, tile_layer);
                        if (autoTile != null && autoTile.Id >= 0)
                        {
                            // for( int partIdx = 0; partIdx < autoTile.TilePartsLength; ++partIdx, ++sprIdx )
                            // {
                            int idSlot = autoTile.Id;
                            if (!MyAutoTileMap.Tileset.IsExitSlot(idSlot))
                            {
                                continue;
                            }
                            var slot = MyAutoTileMap.Tileset.GetSlot(idSlot);
                            if (!slot.IsCanCopyWhenDraw)
                            {
                                continue;
                            }

                            SpriteRenderer spriteRender = GetSpriteRenderer(aSprites, ref sprIdx);

                            SetSpriteRendererSlot(spriteRender, slot, pivot);
                            spriteRender.sortingOrder = 50; //TODO: +50 temporal? see for a const number later

                            // get last tile as relative position
                            int tilePart_x = (tile_x - _dragEndTileX) * 2;
                            int tilePart_y = (tile_y - _dragEndTileY) * 2;

                            float xFactor = MyAutoTileMap.CellSize.x / 2f;
                            float yFactor = MyAutoTileMap.CellSize.y / 2f;
                            spriteRender.transform.localPosition = new Vector3(tilePart_x * xFactor, -tilePart_y * yFactor, spriteRender.transform.position.z);
                            spriteRender.transform.localScale    = new Vector3(MyAutoTileMap.CellSize.x * AutoTileset.PixelToUnits / MyAutoTileMap.Tileset.TileWidth, MyAutoTileMap.CellSize.y * AutoTileset.PixelToUnits / MyAutoTileMap.Tileset.TileHeight, 1f);
                            // }
                        }
                    }
                }
            }
            // clean unused sprite objects
            while (sprIdx < aSprites.Length)
            {
                if (Application.isEditor)
                {
                    DestroyImmediate(aSprites[sprIdx].transform.gameObject);
                }
                else
                {
                    Destroy(aSprites[sprIdx].transform.gameObject);
                }
                ++sprIdx;
            }
        }