示例#1
0
    public Mesh ConvertSprite(SpriteRenderer spriteRenderer)
    {
        Sprite sprite = spriteRenderer.sprite;

        spriteRenderer.transform.position = new Vector3(spriteRenderer.transform.position.x, spriteRenderer.transform.position.y, spriteRenderer.transform.position.z + (spriteRenderer.sortingOrder * sTarget.sortingOrderToZPositionMultiplier + sTarget.sortingOrderToZPositionOffset));
        Mesh newMesh = new Mesh();

        Vector3[] meshVerts = new Vector3[sprite.vertices.Length];
        Color[]   colors    = new Color[sprite.vertices.Length];
        Vector3[] normals   = new Vector3[sprite.vertices.Length];
        for (int i = 0; i < sprite.vertices.Length; i++)
        {
            meshVerts[i] = sprite.vertices[i];
        }
        newMesh.vertices = meshVerts;
        for (int i = 0; i < sprite.vertices.Length; i++)
        {
            colors[i]  = spriteRenderer.color;
            normals[i] = new Vector3(0, 0, -1);
        }
        newMesh.colors  = colors;
        newMesh.normals = normals;
        newMesh.uv      = SpriteUtility.GetSpriteUVs(sprite, false);
        int[] meshIndicies = new int[sprite.triangles.Length];
        for (int i = 0; i < meshIndicies.Length; i++)
        {
            meshIndicies[i] = sprite.triangles[i];
        }
        newMesh.SetIndices(meshIndicies, MeshTopology.Triangles, 0);
        newMesh.hideFlags = HideFlags.HideAndDontSave;
        return(newMesh);
    }
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.ObjectField(position, property);
        Texture2D myText = SpriteUtility.GetSpriteTexture((Sprite)property.objectReferenceValue, false);

        GUI.Label(position, myText);
    }
示例#3
0
        static void showPackInfo_Legacy(Sprite _sprite, GUILayoutOption _option)
        {
            TextureImporter ti = (TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_sprite));

            ti.spritePackingTag = EditorGUILayout.TextField(ti.spritePackingTag, _option);

            EditorGUILayout.LabelField("[Packing Tag]", EditorStyles.boldLabel, _option);
            Texture2D _texture = SpriteUtility.GetSpriteTexture(_sprite, _sprite.packed);

            if (_texture != null)
            {
                if (_sprite.packed)
                {
                    EditorGUI.DrawTextureTransparent(
                        EditorGUILayout.GetControlRect(
                            new GUILayoutOption[] { _option, GUILayout.MaxHeight(150) }),
                        _texture, ScaleMode.ScaleToFit);
                }
                else
                {
                    string _msg = !string.IsNullOrEmpty(ti.spritePackingTag)
                        ? "You have to build to see a Packed Texture."
                        : "If you set the same [Packing Tag] to sprites used in the map, render speed will be faster.";
                    EditorGUI.HelpBox(
                        EditorGUILayout.GetControlRect(
                            new GUILayoutOption[] { _option, GUILayout.MaxHeight(75) }), _msg, MessageType.Info);
                }
            }
        }
示例#4
0
        protected virtual void uploadSpriteTextures()
        {
            using (new ProfilerSample("Upload Sprite Textures"))
            {
                foreach (var spriteFeature in _spriteFeatures)
                {
                    var tex = spriteFeature.featureData.Query().
                              Select(d => d.sprite).
                              Where(s => s != null).
#if UNITY_EDITOR
                              Select(s => SpriteUtility.GetSpriteTexture(s, getAtlasData: true)).
#else
                              Select(s => s.texture).
#endif
                              FirstOrDefault();

                    if (tex != null)
                    {
#if UNITY_EDITOR
                        if (!Application.isPlaying)
                        {
                            _spriteTextureBlock.SetTexture(spriteFeature.propertyName, tex);
                        }
                        else
#endif
                        {
                            _material.SetTexture(spriteFeature.propertyName, tex);
                        }
                    }
                }
            }
        }
示例#5
0
        static void UpdateCachedSpriteMesh(SpriteMesh spriteMesh)
        {
            if (spriteMesh)
            {
                string key = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(spriteMesh));

                if (spriteMesh.sprite)
                {
                    SpriteMesh spriteMeshFromSprite = GetSpriteMeshFromSprite(spriteMesh.sprite);

                    if (!spriteMeshFromSprite || spriteMesh == spriteMeshFromSprite)
                    {
                        string value = AssetDatabase.AssetPathToGUID(
                            AssetDatabase.GetAssetPath(SpriteUtility.GetSpriteTexture(spriteMesh.sprite, false)));

                        s_SpriteMeshToTextureCache[key] = value;
                    }
                    else
                    {
                        Debug.LogWarning("Anima2D: SpriteMesh " + spriteMesh.name + " uses the same Sprite as " +
                                         spriteMeshFromSprite.name + ". Use only one SpriteMesh per Sprite.");
                    }
                }
                else if (s_SpriteMeshToTextureCache.ContainsKey(key))
                {
                    s_SpriteMeshToTextureCache.Remove(key);
                }
            }
        }
示例#6
0
        public override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height)
        {
            SpriteAtlas spriteAtlas = AssetDatabase.LoadMainAssetAtPath(assetPath) as SpriteAtlas;
            Texture2D   result;

            if (spriteAtlas == null)
            {
                result = null;
            }
            else
            {
                Texture2D[] previewTextures = spriteAtlas.GetPreviewTextures();
                if (previewTextures == null || previewTextures.Length == 0)
                {
                    result = null;
                }
                else
                {
                    Texture2D texture2D = previewTextures[0];
                    PreviewHelpers.AdjustWidthAndHeightForStaticPreview(texture2D.width, texture2D.height, ref width, ref height);
                    result = SpriteUtility.CreateTemporaryDuplicate(texture2D, width, height);
                }
            }
            return(result);
        }
示例#7
0
    static Rect GetAltasTextureRect(Sprite sp, Texture2D atlasTexture)
    {
        Rect textureRect = new Rect();

        Vector2[] uvs      = SpriteUtility.GetSpriteUVs(sp, false);
        Vector2[] altasUvs = SpriteUtility.GetSpriteUVs(sp, true);
        int       count    = uvs.Length;
        int       compare  = 0;

        for (int i = 1; i < count; i++)
        {
            if (uvs[i].x != uvs[0].x && uvs[i].y != uvs[0].y)
            {
                compare = i;
                break;
            }
        }
        textureRect.width   = (altasUvs[0].x - altasUvs[compare].x) / (uvs[0].x - uvs[compare].x);
        textureRect.height  = (altasUvs[0].y - altasUvs[compare].y) / (uvs[0].y - uvs[compare].y);
        textureRect.x       = altasUvs[0].x - textureRect.width * uvs[0].x;
        textureRect.y       = altasUvs[0].y - textureRect.height * uvs[0].y;
        textureRect.x      *= atlasTexture.width;
        textureRect.y      *= atlasTexture.height;
        textureRect.width  *= atlasTexture.width;
        textureRect.height *= atlasTexture.height;
        return(textureRect);
    }
示例#8
0
        public void InitFromOutline(float detail, float alphaTolerance, bool holeDetection, float tessellation, string undoName)
        {
            Clear(undoName);

            float   pixelsPerUnit = SpriteMeshUtils.GetSpritePixelsPerUnit(spriteMesh.sprite);
            float   factor        = pixelsPerUnit / spriteMesh.sprite.pixelsPerUnit;
            Vector2 position      = rect.position / factor;
            Vector2 size          = rect.size / factor;

            Rect l_rect = new Rect(position.x, position.y, size.x, size.y);

            Texture2D texture     = SpriteUtility.GetSpriteTexture(spriteMesh.sprite, false);
            Rect      clampedRect = MathUtils.ClampRect(MathUtils.OrderMinMax(l_rect), new Rect(0f, 0f, texture.width, texture.height));

            List <Vector2>     l_texcoords;
            List <IndexedEdge> l_indexedEdges;
            List <int>         l_indices;

            SpriteMeshUtils.InitFromOutline(texture, clampedRect, detail, alphaTolerance, holeDetection, out l_texcoords, out l_indexedEdges, out l_indices);
            SpriteMeshUtils.Tessellate(l_texcoords, l_indexedEdges, holes, l_indices, tessellation * 10f);

            nodes         = l_texcoords.ConvertAll(v => Node.Create(l_texcoords.IndexOf(v)));
            edges         = l_indexedEdges.ConvertAll(e => Edge.Create(nodes[e.index1], nodes[e.index2]));
            m_TexVertices = l_texcoords.ConvertAll(v => v * factor);
            boneWeights   = l_texcoords.ConvertAll(v => BoneWeight.Create());
            indices       = l_indices;

            isDirty = true;

            m_DirtyVertices = true;
        }
        /// <summary>
        /// <para>Draws a sprite graphic at a specified <see cref="Rect"/>.</para>
        /// </summary>
        /// <param name="rect">The <see cref="Rect"/> in which the item is drawn.</param>
        /// <param name="sprite">The graphic to draw.</param>
        /// <param name="style">A style used to modify the appearance of a graphic.</param>
        /// <param name="selected">Whether the graphic should be rendered with a selection tint.</param>
        /// <remarks>
        /// <para>This implementation draws a <see cref="Texture2D"/> and crops the boundaries. This may result in
        /// sprites that are tightly packed to draw artifacts.</para>
        /// </remarks>
        public static void DrawSprite(Rect rect, Sprite sprite,
                                      CompiledStyleDefinition style = null, bool selected = false)
        {
            if (sprite == null || sprite.Equals(null) || Event.current.type != EventType.Repaint)
            {
                return;
            }

            Texture2D textureIcon = null;
            Rect      textureRect;

            if (sprite.packed)
            {
                textureIcon = SpriteUtility.GetSpriteTexture(sprite, false);
            }

            if (textureIcon == null)
            {
                textureIcon = sprite.texture;
            }

            textureRect = sprite.rect;

            DrawTexWithCoords(rect, textureIcon, textureRect, style, selected);
        }
示例#10
0
 private static bool tryGetAtlasedUvsEditor(Sprite sprite, out Vector2[] uvs)
 {
     try {
         uvs = SpriteUtility.GetSpriteUVs(sprite, getAtlasData: true);
         return(true);
     } catch (Exception) {
         uvs = null;
         return(false);
     }
 }
    static void SaveSubTextureInfo()
    {
        Texture2D altasTexture = SpriteUtility.GetSpriteTexture(spriteList[0], true);

        string filename = Application.dataPath + "/Resources/" + MapPrefabDef.MapTerrainSprData + ".txt";

        StreamWriter sw;
        FileInfo     t = new FileInfo(filename);

        if (!t.Exists)
        {
            //如果此文件不存在则创建
            sw = t.CreateText();
        }
        else
        {
            //如果此文件存在则打开
            t.Delete();
            sw = t.CreateText();
        }

        byte[] altasdata             = altasTexture.GetRawTextureData();
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendFormat(" {0}", altasTexture.name);
        sb.AppendFormat(" {0}", altasTexture.width);
        sb.AppendFormat(" {0}", altasTexture.height);
        sb.AppendFormat(" {0}", (int)altasTexture.format);
        sb.AppendFormat(" {0}", altasdata.Length);
        sb.AppendFormat(" {0}", altasTexture.mipmapCount);
        sb.Remove(0, 1);
        sw.WriteLine(sb.ToString());
        List <Vector4> TArray = new List <Vector4>();

        for (int i = 0; i < spriteList.Count; i++)
        {
            Vector2[] data = SpriteUtility.GetSpriteUVs(spriteList[i], true);
            Vector2   ms   = new Vector2(altasTexture.width, altasTexture.height);
            //左上
            Vector2 p0 = new Vector2(data[0].x * ms.x, data[0].y * ms.y);
            //右下
            Vector2 p1 = new Vector2(data[1].x * ms.x, data[1].y * ms.y);
            //右上
            Vector2 p2 = new Vector2(data[2].x * ms.x, data[2].y * ms.y);
            //左下
            Vector2 p3  = new Vector2(data[3].x * ms.x, data[3].y * ms.y);
            var     sp  = p3;
            var     ss  = new Vector2(p1.x - p3.x, p0.y - p3.y);
            Vector4 pos = new Vector4(sp.x / ms.x, sp.y / ms.y, ss.x / ms.x, ss.y / ms.y);
            sw.WriteLine(spriteList[i].name + " " + pos.x + " " + pos.y + " " + pos.z + " " + pos.w + "\n");
        }
        sw.Close();
        //销毁流
        sw.Dispose();
        AssetDatabase.Refresh();
    }
示例#12
0
        public static void GetSpriteTextureSize(Sprite sprite, ref int width, ref int height)
        {
            if (sprite)
            {
                Texture2D texture = SpriteUtility.GetSpriteTexture(sprite, false);

                TextureImporter textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)) as TextureImporter;

                GetWidthAndHeight(textureImporter, ref width, ref height);
            }
        }
示例#13
0
    public static void WritePrefabPathToCSharp()
    {
        Debug.Log(string.Join(",", Packer.atlasNames));
        Texture2D[] texts   = Packer.GetTexturesForAtlas("1");
        Sprite      sprite0 = Resources.Load <Sprite>("Sprites/car02");
        Sprite      sprite1 = Resources.Load <Sprite>("Sprites/car0_scaled");

        Vector2[] points0 = SpriteUtility.GetSpriteUVs(sprite0, true);
        Vector2[] points1 = SpriteUtility.GetSpriteUVs(sprite1, true);

        Debug.Log("tEXT");
    }
示例#14
0
    public static void PackAlphaAltasToAssetBoundles()
    {
        EditorSettings.spritePackerMode   = SpritePackerMode.AlwaysOn;
        Packer.SelectedPolicy             = typeof(CustomPackerPolicy).Name;
        CustomPackerPolicy.forceIOSOpaque = true;
        Packer.RebuildAtlasCacheIfNeeded(BuildTarget.iOS, true, Packer.Execution.ForceRegroup);

        List <UnityEngine.Object> objects = new List <UnityEngine.Object>();

        foreach (string path in AssetDatabase.FindAssets("t:sprite"))
        {
            objects.AddRange(AssetDatabase.LoadAllAssetRepresentationsAtPath(AssetDatabase.GUIDToAssetPath(path)));
        }

        Sprite[] sprites = objects.Distinct()
                           .Select(x => x as Sprite)
                           .Where(x => x != null && x.packed)
                           .ToArray();

        List <SerializedObject> sos = new List <SerializedObject>();

        foreach (Sprite sprite in sprites)
        {
            Texture2D atlasTexture;
            string    atlasName;
            Packer.GetAtlasDataForSprite(sprite, out atlasName, out atlasTexture);
            if (atlasTexture != null)
            {
                SerializedObject so = new SerializedObject(sprite);
                so.FindProperty("m_RD.textureRect").rectValue        = GetAltasTextureRect(sprite, atlasTexture);
                so.FindProperty("m_RD.texture").objectReferenceValue = atlasTexture;
                Texture2D alphaTexture = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets/" + AlphaAtlasManager.TEXTURE_ALPHA_ATLAS_PATH + atlasTexture.name + "_alpha.png");
                so.FindProperty("m_RD.alphaTexture").objectReferenceValue = alphaTexture;
                so.ApplyModifiedProperties();

                sos.Add(so);
            }
        }

        EditorSettings.spritePackerMode = SpritePackerMode.Disabled;
        BuildPipeline.BuildAssetBundles(Application.dataPath + "/AssetBundles", BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.iOS);
        EditorSettings.spritePackerMode = SpritePackerMode.AlwaysOn;

        foreach (SerializedObject so in sos)
        {
            Sprite sprite = so.targetObject as Sprite;
            so.FindProperty("m_RD.textureRect").rectValue             = sprite.textureRect;
            so.FindProperty("m_RD.texture").objectReferenceValue      = SpriteUtility.GetSpriteTexture(sprite, false);
            so.FindProperty("m_RD.alphaTexture").objectReferenceValue = null;
            so.ApplyModifiedProperties();
        }
        AssetDatabase.Refresh();
    }
    static void SaveAltasTexture()
    {
        Texture2D altasTexture = SpriteUtility.GetSpriteTexture(spriteList[0], true);

        byte[] data     = altasTexture.GetRawTextureData();
        string filename = Application.dataPath + "/Resources/" + MapPrefabDef.MapAtlas + ".bytes";

        FileStream file = new FileStream(filename, FileMode.Create);

        file.Write(data, 0, data.Length);
        file.Close();
    }
        private void TestMosaics()
        {
            Vector2   size   = SpriteUtility.GetRealSize(output);
            Texture2D sTex   = source.sprite.texture;
            var       outTex = new Texture2D(sTex.width, sTex.height, format, sTex.mipmapCount > 0);

            GraphicUtility.Mosaics(sTex, ref outTex, mosaicSize);

            Vector2 pivot = new Vector2(0.5f, 0.5f);

            output.sprite = Sprite.Create(outTex, new Rect(0f, 0f, outTex.width, outTex.height), pivot);
            output.color  = Color.white;
            SpriteUtility.SetRealSize(output, size.x, size.y);
        }
示例#17
0
        private void LoadSprites()
        {
            if (IsAtlasLoaded)
            {
                return;
            }

            var modPath = PluginManager.instance.FindPluginInfo(Assembly.GetExecutingAssembly()).modPath;

            if (SpriteUtility.InitialiseAtlas(Path.Combine(modPath, "Resources/Icon.png"), AtlasName))
            {
                SpriteUtility.AddSpriteToAtlas(new Rect(new Vector2(66, 2), new Vector2(30, 30)), RoundButton.NormalBgSprite, AtlasName);
                SpriteUtility.AddSpriteToAtlas(new Rect(new Vector2(98, 2), new Vector2(30, 30)), RoundButton.HoveredBgSprite, AtlasName);
            }
        }
        public override void Action(int instanceId, string pathName, string resourceFile)
        {
            bool flag = false;

            if (this.sides < 0)
            {
                this.sides = 5;
                flag       = true;
            }
            SpriteUtility.CreateSpritePolygonAssetAtPath(pathName, this.sides);
            if (flag)
            {
                Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(pathName);
                SpriteEditorWindow.GetWindow();
            }
        }
示例#19
0
        private Mesh SpriteToMesh(SpriteRenderer spriteRenderer)
        {
            var sprite = spriteRenderer.sprite;

            Mesh result = new Mesh();

            result.hideFlags = HideFlags.HideAndDontSave;
            result.Clear();

            //verts
            var verts   = sprite.vertices;
            var verts3d = new Vector3[verts.Length];

            for (int i = 0; i < verts.Length; i++)
            {
                verts3d [i] = verts [i];
            }
            result.vertices = verts3d;

            // uvs
            result.uv = SpriteUtility.GetSpriteUVs(sprite, false);

            // colors and normals
            var colors  = new Color[result.vertices.Length];
            var normals = new Vector3[result.vertices.Length];

            for (int i = 0; i < colors.Length; i++)
            {
                colors [i]  = spriteRenderer.color;
                normals [i] = Vector3.back;
            }
            result.colors  = colors;
            result.normals = normals;

            // indicies
            var indicies2d = sprite.triangles;
            var indicies   = new int[indicies2d.Length];

            for (int i = 0; i < indicies.Length; i++)
            {
                indicies [i] = indicies2d [i];
            }

            // finish it up
            result.SetIndices(indicies, MeshTopology.Triangles, 0);
            return(result);
        }
示例#20
0
    public static Mesh CreateSpriteMesh(Transform owner, Sprite sprite)
    {
        if (owner != null && sprite != null)
        {
            // Unparent the skin temporarily before adding the mesh
            Transform parent = owner.parent;
            owner.parent = null;

            // Reset the rotation before creating the mesh so the UV's will align properly
            Quaternion localRotation = owner.localRotation;
            owner.localRotation = Quaternion.identity;

            // Reset the scale before creating the mesh so the UV's will align properly
            Vector3 localScale = owner.localScale;
            owner.localScale = Vector3.one;

            Vector2[] vertices2D = SpriteUtility.GetSpriteMesh(sprite, false);
            int[]     indices    = SpriteUtility.GetSpriteIndices(sprite, false).Select(element => (int)element).ToArray();

            // Create the Vector3 vertices
            Vector3[] vertices = new Vector3[vertices2D.Length];
            for (int i = 0; i < vertices.Length; i++)
            {
                vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0);
            }

            Mesh mesh = new Mesh();
            mesh.vertices  = vertices;
            mesh.triangles = indices;
            Vector2[] uvs = SpriteUtility.GetSpriteUVs(sprite, false);
            mesh.uv = uvs;
            mesh.RecalculateNormals();
            mesh.RecalculateBounds();

            // Reset the rotations of the object
            owner.localRotation = localRotation;
            owner.localScale    = localScale;
            owner.parent        = parent;

            return(mesh);
        }

        return(null);
    }
示例#21
0
        public override void Start()
        {
            name            = nameof(RoundButton);
            normalBgSprite  = NormalBgSprite;
            hoveredBgSprite = HoveredBgSprite;

            Vector2 resolution = UIView.GetAView().GetScreenResolution();
            var     pos        = new Vector2((145f), (resolution.y * 4 / 5) - 50);
            Rect    rect       = new Rect(pos.x, pos.y, 30, 30);

            SpriteUtility.ClampRectToScreen(ref rect, resolution);

            absolutePosition = rect.position;
            size             = new Vector2(30f, 30f);

            atlas  = SpriteUtility.GetAtlas(Loader.AtlasName);
            zOrder = 11;

            eventClick += RoundButtonClick;
        }
 public override void OnGUI(Rect position,
                            SerializedProperty property,
                            GUIContent label)
 {
     EditorGUI.PropertyField(position, property, label, true);
     if (property.objectReferenceValue != null)
     {
         var rect = new Rect(position.width - Attribute.width, position.y, Attribute.width, Attribute.height);
         using (new ZeroIndent())
         {
             if (property.objectReferenceValue as Sprite)
             {
                 EditorGUI.DrawPreviewTexture(rect, SpriteUtility.GetSpriteTexture((Sprite)property.objectReferenceValue, false));
             }
             else if (property.objectReferenceValue as Texture)
             {
                 EditorGUI.DrawPreviewTexture(rect, (Texture)property.objectReferenceValue);
             }
         }
     }
 }
        public override Texture2D RenderStaticPreview(string assetPath, Object[] subAssets, int width, int height)
        {
            var spriteAtlas = AssetDatabase.LoadMainAssetAtPath(assetPath) as SpriteAtlas;

            if (spriteAtlas == null)
            {
                return(null);
            }

            var previewTextures = spriteAtlas.GetPreviewTextures();

            if (previewTextures == null || previewTextures.Length == 0)
            {
                return(null);
            }

            var texture = previewTextures[0];

            PreviewHelpers.AdjustWidthAndHeightForStaticPreview(texture.width, texture.height, ref width, ref height);

            return(SpriteUtility.CreateTemporaryDuplicate(texture, width, height));
        }
示例#24
0
    public override void OnInspectorGUI()
    {
        GUI.enabled = false;
        EditorGUILayout.TextField("Type", typeof(T).Name);
        GUI.enabled = true;

        Rect totalPosition = EditorGUILayout.GetControlRect(false, 32, new GUILayoutOption[0]);

        totalPosition = EditorGUI.PrefixLabel(totalPosition, new GUIContent("Preview"));
        Rect position  = new Rect(totalPosition.xMin, totalPosition.yMin, 32, 32);
        Rect position2 = new Rect(totalPosition.xMin - 1, totalPosition.yMin - 1, 34, 34);

        if (Event.current.type == EventType.Repaint)
        {
            EditorStyles.textField.Draw(position2, false, false, false, false);
        }
        Sprite sprite = this.tile.sprite;

        if (sprite != null)
        {
            Texture2D image = SpriteUtility.RenderStaticPreview(sprite, this.tile.color, 32, 32, this.tile.transform);
            EditorGUI.DrawTextureTransparent(position, image, ScaleMode.StretchToFill);
        }
        EditorGUI.BeginChangeCheck();
        EditorGUI.BeginChangeCheck();
        Object obj = EditorGUILayout.ObjectField("Sprite", this.tile.sprite, typeof(Sprite), false, new GUILayoutOption[] {
            GUILayout.Height(16)
        });

        if (EditorGUI.EndChangeCheck())
        {
            this.tile.sprite = (Sprite)obj;
        }
        if (EditorGUI.EndChangeCheck())
        {
            EditorUtility.SetDirty(this.tile);
        }
    }
示例#25
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            ArchetypeChunkSharedComponentType <SpriteAsset> assetType      = GetArchetypeChunkSharedComponentType <SpriteAsset>();
            ArchetypeChunkComponentType <SpriteVertexData>  spriteDataType = GetArchetypeChunkComponentType <SpriteVertexData>();

            using (var chunkArray = m_SpriteAssetGroup.CreateArchetypeChunkArray(Unity.Collections.Allocator.TempJob))
            {
                foreach (var chunk in chunkArray)
                {
                    var spriteDataArray = chunk.GetNativeArray(spriteDataType);
                    var asset           = chunk.GetSharedComponentData(assetType, EntityManager);
                    var spriteData      = SpriteUtility.GetSpriteVertexData(asset.Value);
                    spriteData.NativeMaterialId = chunk.GetSharedComponentIndex(assetType);
                    for (int i = 0; i < chunk.Count; i++)
                    {
                        spriteDataArray[i] = spriteData;
                    }
                    //chunk.SetChunkComponentData(spriteDataType, spriteData);
                }
            }
            EntityManager.AddComponent(m_SpriteAssetGroup, typeof(SpriteAssetInitialized));
            return(inputDeps);
        }
示例#26
0
 private static Vector2[] getAtlasedUvsEditor(Sprite sprite)
 {
     return(SpriteUtility.GetSpriteUVs(sprite, getAtlasData: true));
 }
示例#27
0
 public static void GenerateOutline(Texture2D texture, Rect rect, float detail, byte alphaTolerance, bool holeDetection, out Vector2[][] paths)
 {
     SpriteUtility.GenerateOutline(texture, rect, detail, alphaTolerance, holeDetection, out paths);
 }
示例#28
0
        public static void GetSpriteData(Sprite sprite, out Vector2[] vertices, out IndexedEdge[] edges, out int[] indices, out Vector2 pivotPoint)
        {
            int width  = 0;
            int height = 0;

            GetSpriteTextureSize(sprite, ref width, ref height);

            pivotPoint = Vector2.zero;

            Vector2[] uvs = SpriteUtility.GetSpriteUVs(sprite, false);

            vertices = new Vector2[uvs.Length];

            for (int i = 0; i < uvs.Length; ++i)
            {
                vertices[i] = new Vector2(uvs[i].x * width, uvs[i].y * height);
            }

            ushort[] l_indices = sprite.triangles;

            indices = new int[l_indices.Length];

            for (int i = 0; i < l_indices.Length; ++i)
            {
                indices[i] = (int)l_indices[i];
            }

            HashSet <IndexedEdge> edgesSet = new HashSet <IndexedEdge>();

            for (int i = 0; i < indices.Length; i += 3)
            {
                int index1 = indices[i];
                int index2 = indices[i + 1];
                int index3 = indices[i + 2];

                IndexedEdge edge1 = new IndexedEdge(index1, index2);
                IndexedEdge edge2 = new IndexedEdge(index2, index3);
                IndexedEdge edge3 = new IndexedEdge(index1, index3);

                if (edgesSet.Contains(edge1))
                {
                    edgesSet.Remove(edge1);
                }
                else
                {
                    edgesSet.Add(edge1);
                }

                if (edgesSet.Contains(edge2))
                {
                    edgesSet.Remove(edge2);
                }
                else
                {
                    edgesSet.Add(edge2);
                }

                if (edgesSet.Contains(edge3))
                {
                    edgesSet.Remove(edge3);
                }
                else
                {
                    edgesSet.Add(edge3);
                }
            }

            edges = new IndexedEdge[edgesSet.Count];
            int edgeIndex = 0;

            foreach (IndexedEdge edge in edgesSet)
            {
                edges[edgeIndex] = edge;
                ++edgeIndex;
            }

            pivotPoint = GetPivotPoint(sprite);
        }
示例#29
0
        public void OnGUI()
        {
            var style = new GUIStyle(GUI.skin.button);

            if (headObject == null)
            {
                CreateNewObject();
            }

            if (spriteArray == null)
            {
                return;
            }

            int columnCount = Mathf.RoundToInt((position.width) / 70) - 2;
            int x           = 0;
            int y           = 0;
            int current     = 0;

            GUILayout.Label("2D Tile Placer", EditorStyles.boldLabel);

            if (GUILayout.Button("New sprite list"))
            {
                CreateNewObject();
            }

            GUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Current tool state", GUILayout.Width(150));
            GUILayout.BeginVertical(EditorStyles.helpBox);

            if (isActive)
            {
                style.normal.textColor = Color.black;
                GUI.backgroundColor    = new Color32(180, 255, 180, 255);

                if (GUILayout.Button("Active", style))
                {
                    isActive = false;
                }
            }
            else
            {
                style.normal.textColor = Color.red;

                if (GUILayout.Button("De-active", style))
                {
                    isActive = true;
                }
            }
            GUILayout.EndVertical();
            GUILayout.EndHorizontal();

            EditorGUILayout.Space();

            tag   = EditorGUILayout.TagField("Change tags to: ", tag);
            layer = EditorGUILayout.LayerField("Change layers to: ", layer);

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Paint With Collider", GUILayout.Width(150));
            makeCollider = EditorGUILayout.Toggle(makeCollider);
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            orderInLayer = EditorGUILayout.IntField("Order in layer: ", orderInLayer);
            EditorGUILayout.EndHorizontal();

            string[] tools = { "Draw", "Erase" };
            selectedTool = GUILayout.Toolbar(selectedTool, tools);
            Debug.Log(selectedTool);
            tileScrollPosition = EditorGUILayout.BeginScrollView(tileScrollPosition, false, true, GUILayout.Width(position.width));
            GUILayout.BeginHorizontal();

            for (int i = 0; i < spriteArray.Length; i++)
            {
                child   = spriteArray[i];
                newRect = new Rect(child.rect.x / child.texture.width,
                                   child.rect.y / child.texture.height,
                                   child.rect.width / child.texture.width,
                                   child.rect.height / child.texture.height);

                aTexture = SpriteUtility.GetSpriteTexture(child, false);

                if (GUILayout.Button("", GUILayout.Width(spriteUnit + 1 + (spriteUnit * (1 / 16))), GUILayout.Height(spriteUnit + 1 + (spriteUnit * (1 / 16)))))
                {
                    //draw a clickable button
                    if (cmSelectedTile != null && !Event.current.control)
                    {
                        //empty the selected tile list if control isn't held. Allows multiselect of tiles.
                        cmSelectedTile.Clear();
                        cmCurSprite.Clear();
                    }
                    cmSelectedTile.Add(current); //Adds clicked on tile to list of selected tiles.
                    clickedTile = true;
                    cmCurSprite.Add(child);
                }

                //Displaying the sprite size inside the tool
                if (spriteUnit < 40)
                {
                    spriteUnit = 40;
                }
                else if (spriteUnit > 80)
                {
                    spriteUnit = 80;
                }
                //Draws the sprites
                GUI.DrawTextureWithTexCoords(new Rect(5 + (x * spriteUnit * 1.06f), 4 + (y * spriteUnit * 1.05f), spriteUnit, spriteUnit), child.texture, newRect, true);

                if (x < columnCount)
                {
                    x++;
                }
                else
                {
                    // if we have enough columns to fill the scroll area, reset the column count and start a new line of buttons
                    x = 0;
                    y++;
                    GUILayout.EndHorizontal();
                    GUILayout.BeginHorizontal();
                }

                //For selected tiles
                if (cmSelectedTile != null && cmSelectedTile.Contains(current))
                {
                    if (cmSelectedColor == null)
                    {
                        cmSelectedColor = new Texture2D(1, 1);
                        cmSelectedColor.alphaIsTransparency = true;
                        cmSelectedColor.filterMode          = FilterMode.Point;
                        cmSelectedColor.SetPixel(0, 0, new Color(.5f, .5f, 1f, .5f));
                        cmSelectedColor.Apply();
                    }
                    GUI.DrawTexture(new Rect(5 + (x * spriteUnit * 1.06f), 4 + (y * spriteUnit * 1.05f), spriteUnit, spriteUnit), cmSelectedColor, ScaleMode.ScaleToFit, true);
                }
            }

            EditorGUILayout.EndScrollView();
        }
示例#30
0
    public void OnGUI()
    {
        if (spriteArray == null)
        {
            return;
        }

        int columnCount = Mathf.RoundToInt((position.width) / 70) - 2;
        int x           = 0;
        int y           = 0;
        int current     = 0;

        GUILayout.Label("2D Tile Placer", EditorStyles.boldLabel);

        EditorGUILayout.BeginHorizontal();
        spriteUnit = EditorGUILayout.IntField("Sprite units: ", spriteUnit);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Paint With Collider", GUILayout.Width(150));
        makeCollider = EditorGUILayout.Toggle(makeCollider);
        EditorGUILayout.EndHorizontal();

        //GUILayout.BeginVertical(EditorStyles.helpBox);

        string[] tools = { "Draw", "Erase" };
        selectedTool = GUILayout.Toolbar(selectedTool, tools);

        tileScrollPosition = EditorGUILayout.BeginScrollView(tileScrollPosition, false, true, GUILayout.Width(position.width));
        GUILayout.BeginHorizontal();

        for (int i = 0; i < spriteArray.Length; i++)
        {
            Sprite child   = spriteArray[i];
            Rect   newRect = new Rect(child.rect.x / child.texture.width,
                                      child.rect.y / child.texture.height,
                                      child.rect.width / child.texture.width,
                                      child.rect.height / child.texture.height);

            aTexture = SpriteUtility.GetSpriteTexture(child, false);
            //

            if (GUILayout.Button("", GUILayout.Width(spriteUnit + (spriteUnit * (1 / 16))), GUILayout.Height(spriteUnit + (spriteUnit * (1 / 16)))))
            {
                //draw a clickable button
                if (cmSelectedTile != null && !Event.current.control)
                {
                    //empty the selected tile list if control isn't held. Allows multiselect of tiles.
                    cmSelectedTile.Clear();
                    cmCurSprite.Clear();
                }
                cmSelectedTile.Add(current); //Adds clicked on tile to list of selected tiles.
                cmCurSprite.Add(child);
            }

            GUI.DrawTextureWithTexCoords(new Rect(5 + (x * spriteUnit * 1.06f), 4 + (y * spriteUnit * 1.05f), spriteUnit, spriteUnit), child.texture, newRect, true);
            //GUI.DrawTexture(newRect, spriteArray[i].texture, ScaleMode.StretchToFill, GUILayout.Width(32.0f), GUILayout.Height(32));
            //GUILayout.Label(aTexture);
            if (x < columnCount)
            {
                x++;
            }
            else
            {
                // if we have enough columns to fill the scroll area, reset the column count and start a new line of buttons
                x = 0;
                y++;
                GUILayout.EndHorizontal();
                GUILayout.BeginHorizontal();
            }
        }

        EditorGUILayout.EndScrollView();
        //GUILayout.EndVertical();
    }