Exemplo n.º 1
0
    // Update is called once per frame
    void Update()
    {
        DestroySpriteIfNeeded();

        var shape = new Shape();

        var rect1 = new Rect(-radiusX, -radiusY, radiusX + radiusX, radiusY + radiusY);
        var rad1  = new Vector2(radiusX, radiusY);

        var rect2 = new Rect(-maskX, -maskY, maskX + maskX, maskY + maskY);
        var rad2  = new Vector2(maskX, maskY);

        shape.Contours = BuildCircleContourWithMask(rect1, rad1, rect2, rad2);

        shape.IsConvex = true;
        shape.Fill     = new SolidFill()
        {
            Color = color, Mode = FillMode.OddEven
        };

        var options = MakeShapeOptions(stepDistance);
        var geo     = BuildGeometry(shape, options);
        var sprite  = VectorUtils.BuildSprite(
            geo, 100.0f,
            VectorUtils.Alignment.Center,
            Vector2.zero, 128);

        spriteRenderer.sprite = sprite;
    }
Exemplo n.º 2
0
    protected override void SetAppearance()
    {
        string sheepSvg =
            @"<svg xmlns=""http://www.w3.org/2000/svg"" viewBox=""0 0 25.55 15.48"">
	            <g><path id=""Body"" d=""M19.59,9.45A4.27,4.27,0,0,0,19,7.12a2.3,2.3,0,0,0-2.07-1.07A2.47,2.47,0,0,0,15.34,7a7.41,7.41,0,0,0-.94,1.58,6.48,6.48,0,0,1-1.21-1,3.41,3.41,0,0,0-2.62-.83A2.59,2.59,0,0,0,8.48,8.36a.36.36,0,0,1-.11.2c-.08,0-.19,0-.28,0a7.84,7.84,0,0,0-2-.51,1.06,1.06,0,0,0-.47,0,1.15,1.15,0,0,0-.41.35,4.28,4.28,0,0,0-1,2,2,2,0,0,0,.84,2,2.15,2.15,0,0,0,1.34,4,2.36,2.36,0,0,0,.06,1.83,2.12,2.12,0,0,0,1.28.77,9.55,9.55,0,0,0,1.84.3,2.41,2.41,0,0,0,1.3-.21,1,1,0,0,0,.53-1.11,8.92,8.92,0,0,0,3.4,1.59,3.83,3.83,0,0,0,2.07,0,1.84,1.84,0,0,0,1.3-1.49l2.23.35a2.24,2.24,0,0,0,1,0c.76-.23,1.06-1.12,1.16-1.91a1.33,1.33,0,0,0-.35-1.27,3.22,3.22,0,0,0,2.43-1.82,1.3,1.3,0,0,0,.13-.86c-.15-.49-.71-.71-1.19-.87a.55.55,0,0,1-.32-.19.52.52,0,0,1-.05-.28c0-.44.21-.87.19-1.31a1.86,1.86,0,0,0-1.53-1.55,5.19,5.19,0,0,0-2.31.18"" transform=""translate(-3.38 -5.54)"" fill=""#fff"" stroke=""#000"" stroke-miterlimit=""10""/></g>
	            <g><path id=""Head"" d=""M23.53,10.81c.11,0,0,0,.16.06.75.21,1.53.25,2.3.39a4,4,0,0,1,2.1.93.44.44,0,0,1,.12.15.43.43,0,0,1,0,.25,1.92,1.92,0,0,1-.41,1.1,1.72,1.72,0,0,1-1,.41,10,10,0,0,1-1.81.13,4.2,4.2,0,0,0-1,0"" transform=""translate(-3.38 -5.54)"" fill=""#fff"" stroke=""#000"" stroke-miterlimit=""10""/></g>
	            <g><path id=""Mark"" d=""M13.41,12.23a2.84,2.84,0,0,0-.71-.11,3.35,3.35,0,0,0-1.86.81"" transform=""translate(-3.38 -5.54)"" fill=""none"" stroke=""#000"" stroke-miterlimit=""10""/></g>
            </svg>";

        var sceneInfo = SVGParser.ImportSVG(new StringReader(sheepSvg));
        var shape     = sceneInfo.NodeIDs["Body"].Shapes[0];

        shape.Fill = new SolidFill()
        {
            Color = Color.white
        };
        shape      = sceneInfo.NodeIDs["Head"].Shapes[0];
        shape.Fill = new SolidFill()
        {
            Color = Color.black
        };

        var tessOptions = new VectorUtils.TessellationOptions()
        {
            StepDistance         = 100f,
            MaxCordDeviation     = 0.5f,
            MaxTanAngleDeviation = 0.1f,
            SamplingStepSize     = 0.01f
        };

        var geoms  = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);
        var sprite = VectorUtils.BuildSprite(geoms, 26, VectorUtils.Alignment.Center, Vector2.zero, 128, true);

        GetComponent <SpriteRenderer>().sprite = sprite;
    }
Exemplo n.º 3
0
    // Update is called once per frame
    void Update()
    {
        DestroySpriteIfNeeded();

        var lineSegment     = VectorUtils.MakeLine(from, to);
        var lineSegmentPath = VectorUtils.BezierSegmentToPath(lineSegment);

        var path = new Shape()
        {
            Contours = new BezierContour[] { new BezierContour()
                                             {
                                                 Segments = lineSegmentPath
                                             } },
            PathProps = new PathProperties()
            {
                Stroke = new Stroke()
                {
                    Color = pathColor, HalfThickness = pathHalfThickness
                }
            }
        };

        var options = MakeLineOptions(stepDistance);
        var geo     = BuildGeometry(path, options);
        var sprite  = VectorUtils.BuildSprite(
            geo, 1.0f,
            VectorUtils.Alignment.Center,
            Vector2.zero, 128);

        spriteRenderer.sprite = sprite;
    }
Exemplo n.º 4
0
    void Start()
    {
        string svg =
            @"<svg width=""283.9"" height=""283.9"" xmlns=""http://www.w3.org/2000/svg"">
                <line x1=""170.3"" y1=""226.99"" x2=""177.38"" y2=""198.64"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
                <line x1=""205.73"" y1=""198.64"" x2=""212.81"" y2=""226.99"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
                <line x1=""212.81"" y1=""226.99"" x2=""219.9"" y2=""255.33"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
                <line x1=""248.25"" y1=""255.33"" x2=""255.33"" y2=""226.99"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
                <path d=""M170.08,226.77c7.09-28.34,35.43-28.34,42.52,0s35.43,28.35,42.52,0"" transform=""translate(0.22 0.22)"" fill=""none"" stroke=""red"" stroke-width=""1.2""/>
                <circle cx=""170.3"" cy=""226.99"" r=""1.2"" fill=""blue"" stroke-width=""0.6""/>
                <circle cx=""212.81"" cy=""226.99"" r=""1.2"" fill=""blue"" stroke-width=""0.6""/>
                <circle cx=""255.33"" cy=""226.99"" r=""1.2"" fill=""blue"" stroke-width=""0.6""/>
                <circle cx=""177.38"" cy=""198.64"" r=""1"" fill=""black"" />
                <circle cx=""205.73"" cy=""198.64"" r=""1"" fill=""black"" />
                <circle cx=""248.25"" cy=""255.33"" r=""1"" fill=""black"" />
                <circle cx=""219.9"" cy=""255.33"" r=""1"" fill=""black"" />
            </svg>";

        var tessOptions = new VectorUtils.TessellationOptions()
        {
            StepDistance         = 100.0f,
            MaxCordDeviation     = 0.5f,
            MaxTanAngleDeviation = 0.1f,
            SamplingStepSize     = 0.01f
        };

        // Dynamically import the SVG data, and tessellate the resulting vector scene.
        var sceneInfo = SVGParser.ImportSVG(new StringReader(svg));
        var geoms     = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);

        // Build a sprite with the tessellated geometry.
        var sprite = VectorUtils.BuildSprite(geoms, 10.0f, VectorUtils.Alignment.Center, Vector2.zero, 128, true);

        GetComponent <SpriteRenderer>().sprite = sprite;
    }
Exemplo n.º 5
0
    void Hand(int hand)
    {
        string svg =
            @"<svg xmlns=""http://www.w3.org/2000/svg"" viewBox=""0 0 30.11 27.39"">
                <g><circle id=""Hand"" cx=""4.66"" cy=""2.6"" r=""2.11"" fill=""#fff"" stroke=""#000"" stroke-miterlimit=""10"" stroke-width=""0.5""/></g>
            </svg>";

        var sceneInfo = SVGParser.ImportSVG(new StringReader(svg));
        var shape     = sceneInfo.NodeIDs["Hand"].Shapes[0];

        shape.Fill = new SolidFill()
        {
            Color = skinTone
        };

        var tessOptions = new VectorUtils.TessellationOptions()
        {
            StepDistance         = 100f,
            MaxCordDeviation     = 0.5f,
            MaxTanAngleDeviation = 0.1f,
            SamplingStepSize     = 0.01f
        };

        var geoms  = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);
        var sprite = VectorUtils.BuildSprite(geoms, 26, VectorUtils.Alignment.Center, Vector2.zero, 128, true);

        hands[hand].GetComponent <SpriteRenderer>().sprite = sprite;
    }
Exemplo n.º 6
0
    /// <summary>
    /// Create a Sprite icon of a SVG image.
    /// </summary>
    /// <param name="svgContent">String containing svg content.</param>
    /// <remarks>
    /// Standard header and footer will be included if not found in svgContent
    /// </remarks>
    public static Sprite GetSprite(string svgContent)
    {
        string svg;

        if (svgContent.StartsWith("<?xml version = \"1.0\" encoding=\"UTF - 8\"?>"))
        {
            svg = svgContent;
        }
        else
        {
            svg = svgIconHeader + svgContent;
        }

        if (!svg.EndsWith(svgIconFooter))
        {
            svg = svg + svgIconFooter;
        }

        // Parse the SVG
        SVGParser.SceneInfo sceneInfo = SVGParser.ImportSVG(new System.IO.StringReader(svg));
        int width  = Mathf.CeilToInt(sceneInfo.SceneViewport.width);
        int height = Mathf.CeilToInt(sceneInfo.SceneViewport.height);

        if ((width > 64) || (height > 64))
        {
            Debug.LogWarning("SVG icon of unusual size!");
        }

        List <VectorUtils.Geometry> iconGeometry = VectorUtils.TessellateScene(sceneInfo.Scene, tessellationOptions);

        Sprite sprite = VectorUtils.BuildSprite(iconGeometry, 100f, VectorUtils.Alignment.Center, Vector2.zero, 128, true);

        return(sprite);
    }
Exemplo n.º 7
0
    /// <summary>
    /// Create a Texture2D icon of a SVG image.
    /// </summary>
    /// <param name="svg">String containing svg content.</param>
    public static Texture2D GetIcon(string svg)
    {
        // Parse the SVG
        SVGParser.SceneInfo sceneInfo = SVGParser.ImportSVG(new System.IO.StringReader(svg));
        int width  = Mathf.CeilToInt(sceneInfo.SceneViewport.width);
        int height = Mathf.CeilToInt(sceneInfo.SceneViewport.height);

        if ((width > 64) || (height > 64))
        {
            Debug.LogWarning("SVG icon of unusual size!");
        }

        VectorUtils.TessellationOptions tessellationOptions = new VectorUtils.TessellationOptions()
        {
            StepDistance         = 0.05f,
            MaxCordDeviation     = float.MaxValue,
            MaxTanAngleDeviation = Mathf.PI / 2.0f,
            SamplingStepSize     = 0.01f
        };
        List <VectorUtils.Geometry> iconGeometry = VectorUtils.TessellateScene(sceneInfo.Scene, tessellationOptions);

        Sprite    sprite      = VectorUtils.BuildSprite(iconGeometry, 1f, VectorUtils.Alignment.Center, Vector2.zero, 128, true);
        Texture2D iconTexture = VectorUtils.RenderSpriteToTexture2D(sprite, width, height, renderMaterial);

        return(iconTexture);
    }
Exemplo n.º 8
0
        /// <summary>Imports an SVG asset</summary>
        /// <param name="ctx">The asset import context of the scripted importer</param>
        public override void OnImportAsset(AssetImportContext ctx)
        {
            // We're using a hardcoded window size of 100x100. This way, using a pixels per point value of 100
            // results in a sprite of size 1 when the SVG file has a viewbox specified.
            SVGParser.SceneInfo sceneInfo;
            using (var stream = new StreamReader(ctx.assetPath))
                sceneInfo = SVGParser.ImportSVG(stream, 0, 1, 100, 100, PreserveViewport);

            if (sceneInfo.Scene == null || sceneInfo.Scene.Root == null)
            {
                throw new Exception("Wowzers!");
            }

            float stepDist         = StepDistance;
            float samplingStepDist = SamplingStepDistance;
            float maxCord          = MaxCordDeviationEnabled ? MaxCordDeviation : float.MaxValue;
            float maxTangent       = MaxTangentAngleEnabled ? MaxTangentAngle : Mathf.PI * 0.5f;

            if (!AdvancedMode)
            {
                // Automatically compute sensible tessellation options from the
                // vector scene's bouding box and target resolution
                ComputeTessellationOptions(sceneInfo, TargetResolution, ResolutionMultiplier, out stepDist, out maxCord, out maxTangent);
            }

            var tessOptions = new VectorUtils.TessellationOptions();

            tessOptions.MaxCordDeviation     = maxCord;
            tessOptions.MaxTanAngleDeviation = maxTangent;
            tessOptions.SamplingStepSize     = 1.0f / (float)samplingStepDist;
            tessOptions.StepDistance         = stepDist;

            var rect = Rect.zero;

            if (PreserveViewport)
            {
                rect = sceneInfo.SceneViewport;
            }

            var geometry = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions, sceneInfo.NodeOpacity);
            var sprite   = VectorUtils.BuildSprite(geometry, rect, SvgPixelsPerUnit, Alignment, CustomPivot, GradientResolution, true);

            var name = System.IO.Path.GetFileNameWithoutExtension(ctx.assetPath);

            if (SvgType == SVGType.VectorSprite)
            {
                GenerateSpriteAsset(ctx, sprite, name);
            }
            else if (SvgType == SVGType.TexturedSprite)
            {
                GenerateTexturedSpriteAsset(ctx, sprite, name);
            }
            else if (SvgType == SVGType.Texture2D)
            {
                GenerateTexture2DAsset(ctx, sprite, name);
            }
        }
Exemplo n.º 9
0
    public void BuildSprite_CreatesFullyConstructedSprite()
    {
        var sprite = VectorUtils.BuildSprite(BuildGeoms(), 100.0f, VectorUtils.Alignment.BottomLeft, Vector2.zero, 128);

        Assert.NotNull(sprite);
        Assert.AreEqual((Vector2)sprite.bounds.min, Vector2.zero);
        Assert.AreEqual((Vector2)sprite.bounds.max, new Vector2(1.0f, 0.5f));
        Assert.AreEqual(5, sprite.vertices.Length);
        Sprite.Destroy(sprite);
    }
Exemplo n.º 10
0
    /// <summary>
    /// Create a Sprite icon out of a VectorShape.
    /// </summary>
    public static Sprite GetSprite(VectorShape shape)
    {
        Rect shapeBounds = shape.ShapeBounds;
        int  width       = Mathf.CeilToInt(shapeBounds.width);
        int  height      = Mathf.CeilToInt(shapeBounds.height);
        List <VectorUtils.Geometry> iconGeometry = shape.ShapeGeometry;

        Sprite sprite = VectorUtils.BuildSprite(iconGeometry, 100f, VectorUtils.Alignment.Center, Vector2.zero, 128, true);

        return(sprite);
    }
Exemplo n.º 11
0
    /// <summary>
    /// Create a Texture2D icon out of a VectorShape.
    /// </summary>
    public static Texture2D GetIcon(VectorShape shape)
    {
        Rect shapeBounds = shape.ShapeBounds;
        int  width       = Mathf.CeilToInt(shapeBounds.width);
        int  height      = Mathf.CeilToInt(shapeBounds.height);
        List <VectorUtils.Geometry> iconGeometry = shape.ShapeGeometry;

        Sprite    sprite      = VectorUtils.BuildSprite(iconGeometry, 1f, VectorUtils.Alignment.Center, Vector2.zero, 128, true);
        Texture2D iconTexture = VectorUtils.RenderSpriteToTexture2D(sprite, width, height, renderMaterial);

        return(iconTexture);
    }
Exemplo n.º 12
0
    public void RenderSpriteToTexture2D_CreatesTexture2DWithProperSize()
    {
        var mat    = new Material(Shader.Find("Unlit/Vector"));
        var sprite = VectorUtils.BuildSprite(BuildGeoms(), 100.0f, VectorUtils.Alignment.BottomLeft, Vector2.zero, 128);
        var tex    = VectorUtils.RenderSpriteToTexture2D(sprite, 100, 50, mat);

        Assert.NotNull(tex);
        Assert.AreEqual(100, tex.width);
        Assert.AreEqual(50, tex.height);
        Sprite.Destroy(sprite);
        Texture2D.Destroy(tex);
    }
    void Start()
    {
        var tessOptions = new VectorUtils.TessellationOptions()
        {
            StepDistance         = 100.0f,
            MaxCordDeviation     = 0.5f,
            MaxTanAngleDeviation = 0.1f,
            SamplingStepSize     = 0.01f
        };

        // Prepare the fill
        var fill = new GradientFill()
        {
            Type  = GradientFillType.Linear,
            Stops = new GradientStop[] {
                new GradientStop()
                {
                    Color = Color.blue, StopPercentage = 0.0f
                },
                new GradientStop()
                {
                    Color = Color.red, StopPercentage = 1.0f
                },
            }
        };

        // Build the scene
        var cornerRad = new Vector2(10, 10);
        var rect      = VectorUtils.BuildRectangleContour(new Rect(0, 0, 100, 100), cornerRad, cornerRad, cornerRad, cornerRad);
        var scene     = new Scene()
        {
            Root = new SceneNode()
            {
                Shapes = new List <Shape> {
                    new Shape()
                    {
                        Contours = new BezierContour[] { rect },
                        Fill     = fill
                    }
                }
            }
        };

        // Dynamically import the SVG data, and tessellate the resulting vector scene.
        var geoms = VectorUtils.TessellateScene(scene, tessOptions);

        // Build a sprite with the tessellated geometry.
        var sprite = VectorUtils.BuildSprite(geoms, 10.0f, VectorUtils.Alignment.Center, Vector2.zero, 16, true);

        GetComponent <SpriteRenderer>().sprite = sprite;
    }
Exemplo n.º 14
0
    public void SetAppearance()
    {
        worldController = WorldController.GetWorldController;
        citizen         = GetComponent <Citizen>();

        skinTone = worldController.skinTones[Random.Range(0, worldController.skinTones.Length)];
        skinTone = ChangeColorBrightness(skinTone);

        string svg =
            @"<svg xmlns=""http://www.w3.org/2000/svg"" viewBox=""0 0 30.11 27.39"">
                <g><path id=""Body"" d=""M30.81,17.36c0,7.43-6.63,13.45-14.81,13.45s-14.81-6-14.81-13.45a12.56,12.56,0,0,1,.36-3C3,8.4,8.94,3.92,16,3.92,24.18,3.92,30.81,9.94,30.81,17.36Z"" transform=""translate(-0.94 -3.67)"" fill=""#fff"" stroke=""#000"" stroke-miterlimit=""10"" stroke-width=""0.5""/></g>";

        Hand(0);
        Hand(1);

        int hairChance = Random.Range(0, citizen.gender ? 100 : 55);

        SVGParser.SceneInfo sceneInfo = default;
        if (hairChance < 70)
        {
            SetHair(ref svg, ref sceneInfo);
        }
        else
        {
            svg += "</svg>";

            sceneInfo = SVGParser.ImportSVG(new StringReader(svg));
        }

        var shape = sceneInfo.NodeIDs["Body"].Shapes[0];

        shape.Fill = new SolidFill()
        {
            Color = skinTone
        };

        var tessOptions = new VectorUtils.TessellationOptions()
        {
            StepDistance         = 100f,
            MaxCordDeviation     = 0.5f,
            MaxTanAngleDeviation = 0.1f,
            SamplingStepSize     = 0.01f
        };

        var geoms  = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);
        var sprite = VectorUtils.BuildSprite(geoms, 26, VectorUtils.Alignment.Center, Vector2.zero, 128, true);

        GetComponent <SpriteRenderer>().sprite = sprite;
    }
Exemplo n.º 15
0
    void sceneDisplay(Scene scene, SpriteRenderer render)
    {
        List <VectorUtils.Geometry> geoms = VectorUtils.TessellateScene(scene, tessellation);

        // Build a sprite with the tessellated geometry.
        Sprite sprite = VectorUtils.BuildSprite(
            geoms,
            10.0f,
            VectorUtils.Alignment.Center,
            Vector2.zero,
            128,
            true);

        render.sprite = sprite;
    }
    private void Start()
    {
        myRenderer = GetComponent <SpriteRenderer>();

        var baseShape = new Shape
        {
            Fill = new SolidFill
            {
                Color   = Color.black,
                Mode    = FillMode.NonZero,
                Opacity = 1f
            },
            PathProps = new PathProperties
            {
                Stroke = new Stroke
                {
                    Color         = Color.red,
                    HalfThickness = thickness / 2,
                },
            }
        };

        //NOTE: Not sure if this a bug, but for some reason the contours CANNOT have negative coordinates when rendering to sprite, even if the sprite rect is set negative.
        //So, make sure your circle stays in positive coordinates.
        VectorUtils.MakeCircleShape(baseShape, Vector2.one * (diameter / 2 + thickness / 2), diameter / 2);

        var scene = new Scene
        {
            Root = new SceneNode
            {
                Shapes = new List <Shape>
                {
                    baseShape,
                },
            }
        };

        var geoms = VectorUtils.TessellateScene(scene, new VectorUtils.TessellationOptions()
        {
            StepDistance         = 10,
            MaxCordDeviation     = 1,
            MaxTanAngleDeviation = 0.1f,
            SamplingStepSize     = 0.01f
        });

        myRenderer.sprite = VectorUtils.BuildSprite(geoms, new Rect(0, 0, diameter + thickness, diameter + thickness), 1, VectorUtils.Alignment.Center, Vector2.zero, 0, false);
    }
Exemplo n.º 17
0
        protected void GenerateBezierCurve(BezierContour[] bezierContours)
        {
            var vectorScene = new Scene
            {
                Root = new SceneNode
                {
                    Shapes = new List <Shape>
                    {
                        new Shape
                        {
                            Contours = bezierContours,
                            IsConvex = false,
                            Fill     = new SolidFill
                            {
                                Mode = FillMode.NonZero
                            }
                        }
                    }
                }
            };

            var tessellationOptions = new VectorUtils.TessellationOptions
            {
                MaxCordDeviation     = float.MaxValue,
                MaxTanAngleDeviation = Mathf.PI / 2.0f,
                SamplingStepSize     = 0.5f,
                StepDistance         = 0.05f
            };

            VectorUtils.TessellateScene(vectorScene, tessellationOptions);
            var geometry = VectorUtils.TessellateScene(vectorScene, tessellationOptions);

            if (spriteRender)
            {
                _sprite = VectorUtils.BuildSprite(geometry, 1, VectorUtils.Alignment.Center, Vector2.zero, 0);

                spriteRenderer.sprite = _sprite;

                transform.position = geometry[0].UnclippedBounds.center;
            }
            else
            {
                VectorUtils.FillMesh(meshFilter.mesh, geometry, 1f);
            }
        }
    // Update is called once per frame
    void Update()
    {
        DestroySpriteIfNeeded();

        var shape = new Shape();

        shape.Contours = BuildRectangleContourWithMask(new Rect(0, 0, width, height), new Rect(width / 2 - maskWidth / 2, height / 2 - maskHeight / 2, maskWidth, maskHeight));
        shape.IsConvex = true;
        shape.Fill     = new SolidFill()
        {
            Color = color, Mode = FillMode.OddEven
        };

        var options = MakeShapeOptions();
        var geo     = BuildGeometry(shape, options);
        var sprite  = VectorUtils.BuildSprite(
            geo, svgPixelsPerUnit,
            VectorUtils.Alignment.Center,
            Vector2.zero, 128);

        spriteRenderer.sprite = sprite;
    }
Exemplo n.º 19
0
    // Update is called once per frame
    void Update()
    {
        DestroySpriteIfNeeded();

        var segments = new BezierPathSegment[segmentInfo.Length];

        for (int i = 0; i < segments.Length; ++i)
        {
            segments[i].P0 = segmentInfo[i].P0;
            segments[i].P1 = segmentInfo[i].P1;
            segments[i].P2 = segmentInfo[i].P2;
        }

        var path = new Shape()
        {
            Contours = new BezierContour[] { new BezierContour()
                                             {
                                                 Segments = segments
                                             } },
            PathProps = new PathProperties()
            {
                Stroke = new Stroke()
                {
                    Color = pathColor, HalfThickness = pathHalfThickness
                }
            }
        };

        var options = MakeLineOptions(stepDistance);
        var geo     = BuildGeometry(path, options);
        var sprite  = VectorUtils.BuildSprite(
            geo, 1.0f,
            VectorUtils.Alignment.Center,
            Vector2.zero, 128);

        spriteRenderer.sprite = sprite;
    }
Exemplo n.º 20
0
    private void GenerateSprite(int dieValue)
    {
        var tessOptions = new VectorUtils.TessellationOptions()
        {
            StepDistance         = 100.0f,
            MaxCordDeviation     = 0.5f,
            MaxTanAngleDeviation = 0.1f,
            SamplingStepSize     = 0.01f
        };

        ColorShape("face", faceColor);
        ColorShape("shadow", shadowColor);
        ColorShape("border", borderColor);

        ColorCircles(dieValue, circlesColor);

        var geoms = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);

        // Build a sprite with the tessellated geometry.
        var sprite = VectorUtils.BuildSprite(geoms, pixelsPerUnit, VectorUtils.Alignment.Center, Vector2.zero, gradientResolution, true);

        GetComponent <SpriteRenderer>().sprite = sprite;
        SaveSprite(sprite, dieValue);
    }
Exemplo n.º 21
0
    void SetCrisps()
    {
        string crisp =
            @"<svg xmlns=""http://www.w3.org/2000/svg"" viewBox=""0 0 11.44 13.95"">
                <g><path id=""Packet"" d=""M13.13,13.9H3.39a5.9,5.9,0,0,1-.81-3.15c0-1.51.75-2.34.63-4.08a16.67,16.67,0,0,0-.39-1.79A5.66,5.66,0,0,1,3.21,1L12.6,1a15.62,15.62,0,0,1,.33,5c-.19,1.94-.78,2.25-.56,3.63.2,1.21.79,2.12.53,3.63a4.26,4.26,0,0,1-.27.93"" transform=""translate(-2.07 -0.47)"" fill=""none"" stroke=""#000"" stroke-miterlimit=""10""/></g>
                <g><text transform=""translate(2.33 5.11) rotate(-7.27)"" font-size=""2.5"">B</text></g>
                <g><text transform=""translate(3.66 5) rotate(-2.06)"" font-size=""2.5"" font-family=""ArialNarrow-Italic, Arial"">I</text></g>
                <g><text transform=""translate(4.23 5.03) rotate(0.56)"" font-size=""2.5"" font-family=""ArialNarrow-Italic, Arial"">T</text></g>
                <g><text transform=""translate(5.45 5.07) rotate(2.51)"" font-size=""2.5"" font-family=""ArialNarrow-Italic, Arial"">E</text></g>
                <g><text transform=""translate(6.66 5.17) rotate(3.93)"" font-size=""2.5"" font-family=""ArialNarrow-Italic, Arial"">R</text></g>
                <g><text transform=""translate(8.07 5.27) rotate(0.35)"" font-size=""2.5"" font-family=""ArialNarrow-Italic, Arial"">S</text></g>
                <g><ellipse id=""Crisp1"" cx=""8.34"" cy=""9.75"" rx=""2.04"" ry=""1.5"" transform=""translate(-5.83 5) rotate(-30)"" fill=""#ffdc7f"" stroke=""#000"" stroke-miterlimit=""10"" stroke-width=""0.15""/></g>
                <g><ellipse id=""Crisp0"" cx=""6.77"" cy=""8.95"" rx=""2.04"" ry=""1.5"" transform=""translate(-6.44 9.86) rotate(-60)"" fill=""#ffdc7f"" stroke=""#000"" stroke-miterlimit=""10"" stroke-width=""0.15""/></g>
            </svg>";

        var sceneInfo = SVGParser.ImportSVG(new StringReader(crisp));
        var shape     = sceneInfo.NodeIDs["Packet"].Shapes[0];

        shape.Fill = new SolidFill()
        {
            Color = Color.red
        };

        var tessOptions = new VectorUtils.TessellationOptions()
        {
            StepDistance         = 100f,
            MaxCordDeviation     = 0.5f,
            MaxTanAngleDeviation = 0.1f,
            SamplingStepSize     = 0.01f
        };

        var geoms  = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);
        var sprite = VectorUtils.BuildSprite(geoms, 26, VectorUtils.Alignment.Center, Vector2.zero, 128, true);

        GetComponent <SpriteRenderer>().sprite = sprite;
    }
Exemplo n.º 22
0
 private Sprite BuildSpriteFromGeometry(List <VectorUtils.Geometry> geometry, Rect rect)
 {
     return(VectorUtils.BuildSprite(geometry, rect, SvgPixelsPerUnit, Alignment, CustomPivot, GradientResolution, true));
 }
Exemplo n.º 23
0
        /// <summary>
        /// Imports a vector texture
        /// </summary>
        /// <param name="file">The file to import from</param>
        /// <param name="size">The size of the texture</param>
        /// <param name="type"></param>
        /// <returns>The vector texture imported as a Sprite</returns>
        public static Sprite ImportVector(FileInfo file, int size, SpriteImportType type)
        {
            StreamReader reader = null;
            StringReader sr     = null;

            try
            {
                reader = new StreamReader(file.OpenRead());
                sr     = new StringReader(reader.ReadToEnd());
                SVGParser.SceneInfo scene = SVGParser.ImportSVG(sr);

                VectorUtils.TessellationOptions tessOptions = new VectorUtils.TessellationOptions()
                {
                    StepDistance         = 100.0f,
                    MaxCordDeviation     = 0.5f,
                    MaxTanAngleDeviation = 0.1f,
                    SamplingStepSize     = 0.01f
                };

                List <VectorUtils.Geometry> geoms = VectorUtils.TessellateScene(scene.Scene, tessOptions);
                Sprite tempSprite = VectorUtils.BuildSprite(geoms, size, VectorUtils.Alignment.Center, Vector2.zero, 64, false);

                Shader shader = null;
                switch (type)
                {
                case SpriteImportType.svggradient:
                    shader = Shader.Find("Unlit/VectorGradient");
                    break;

                case SpriteImportType.svg:
                default:
                    shader = Shader.Find("Unlit/Vector");
                    break;
                }

                Texture2D tex = VectorUtils.RenderSpriteToTexture2D(tempSprite, size, size, new Material(shader));
                //tex.alphaIsTransparency = true;
                Sprite sprite = Sprite.Create(tex, new Rect(Vector2.zero, new Vector2(tex.width, tex.height)), new Vector2(0.5f, 0.5f), size * 2);

                return(sprite);
            }

            catch (Exception e)
            {
                MonoBehaviour.print(e.Message + "\nFile: " + file.Name + "\n" + e.StackTrace);
            }

            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (sr != null)
                {
                    sr.Close();
                }
            }

            return(null);
        }
Exemplo n.º 24
0
    static void SvgLayerImporterModified(string assetPath)
    {
        var originalSvgPathFull = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("/") + 1) + assetPath;

        var sceneInfo = SVGParser.ImportSVG(File.OpenText(originalSvgPathFull));

        if (null == sceneInfo.Scene)
        {
            Debug.LogError("Could not parse SVG at " + originalSvgPathFull + "!");
        }
        else
        {
            Debug.Log("Custom import: " + originalSvgPathFull);

            var tessOptions = new VectorUtils.TessellationOptions()
            {
                StepDistance         = 100.0f,
                MaxCordDeviation     = 0.5f,
                MaxTanAngleDeviation = 0.1f,
                SamplingStepSize     = 0.01f
            };

            var newPrefabLocation = assetPath.Replace(".svg", "_Split.prefab");
            var parentObj         = new GameObject("testObject");

            int numOriginalLayers = sceneInfo.Scene.Root.Children.Count;

            var objs    = new GameObject[numOriginalLayers];
            var sprites = new Sprite[numOriginalLayers];

            //for (int i = 0; i < numOriginalLayers; i++)
            //{
            //    objs[i] = new GameObject(numOriginalLayers.ToString());

            //}

            for (int i = 0; i < numOriginalLayers; i++)
            {
                var newSceneInfo = sceneInfo;
                int removed      = 0;
                var layerName    = "";

                for (int c = 0; c < numOriginalLayers; c++)
                {
                    if (c == i)
                    {
                        layerName = "Layer " + c;
                    }
                    else
                    {
                        if (c - removed >= 0 && c - removed < newSceneInfo.Scene.Root.Children.Count)
                        {
                            newSceneInfo.Scene.Root.Children.Remove(newSceneInfo.Scene.Root.Children[c - removed]);
                        }

                        ++removed;
                    }
                }

                // instantiate the current layer as a new sprite in the scene, and attach it to our new prefab which will soon be saved to disk
                var geom = VectorUtils.TessellateScene(newSceneInfo.Scene, tessOptions);
                sprites[i]      = VectorUtils.BuildSprite(geom, 10.0f, VectorUtils.Alignment.SVGOrigin, Vector2.zero, 128, true);
                sprites[i].name = layerName;

                // each SVG layer will have a corresponding GameObject that's part of the new prefab
                //GameObject go = new GameObject(layerName);
                objs[i] = new GameObject(layerName);
                SpriteRenderer s = objs[i].AddComponent <SpriteRenderer>();
                s.sprite = sprites[i];
                objs[i].transform.SetParent(parentObj.transform);
                Debug.Log(objs[i].GetComponent <SpriteRenderer>().sprite.bounds);
                Debug.Log(sprites[i].name + sprites[i].bounds);

                //AssetDatabase.AddObjectToAsset(sprites[i].texture, objs[i]);
                var tempPath = assetPath.Replace(".svg", "_" + i.ToString() + ".prefab");
                PrefabUtility.SaveAsPrefabAsset(objs[i], tempPath);

                AssetDatabase.ImportAsset(tempPath);
                AssetDatabase.AddObjectToAsset(sprites[i], objs[i]);
                AssetDatabase.SaveAssets();
            }

            // now apply the changes from the instantiated prefab to the saved prefab on disk, and destroy the instance
            Debug.Log(parentObj.transform.childCount);


            PrefabUtility.SaveAsPrefabAsset(parentObj, newPrefabLocation);
            //PrefabUtility.SaveAsPrefabAsset(instPrefab, newPrefabLocation);

            for (int i = 0; i < objs.Length; i++)
            {
                Debug.Log(objs[i].name);
                Debug.Log(objs[i].GetComponent <SpriteRenderer>().sprite.bounds);
            }

            Object.DestroyImmediate(parentObj);
        }

        return;
    }
Exemplo n.º 25
0
        static public Sprite CreateBorderSpriteVector(int tl, int tr, int bl, int br)
        {
            tl = Mathf.Max(tl, 0);
            tr = Mathf.Max(tr, 0);
            bl = Mathf.Max(bl, 0);
            br = Mathf.Max(br, 0);

            var key = GetKey(tl, tr, bl, br);

            if (SpriteCache.ContainsKey(key))
            {
                return(SpriteCache[key]);
            }
            if (tl == 0 && tr == 0 && bl == 0 && br == 0)
            {
                return(CreateFlatBorder());
            }
            var(width, height) = GetSize(tl, tr, bl, br);

            if (!FeatureGuards.VectorGraphics && Application.isPlaying)
            {
                return(null);
            }

#if !REACT_VECTOR_GRAPHICS || UNITY_WEBGL
            return(null);
#else
            var svg = new Scene()
            {
                Root = new SceneNode()
                {
                    Shapes = new List <Shape>()
                }
            };

            // For some reason, the svg is inverted so I am inverting the corners
            var contour = VectorUtils.BuildRectangleContour(new Rect(0, 0, width, height),
                                                            Vector2.one * bl, Vector2.one * br, Vector2.one * tr, Vector2.one * tl);

            var roundedRect = new Shape()
            {
                Contours = new BezierContour[] { contour },
                Fill     = new SolidFill()
                {
                    Color = Color.white, Opacity = 1
                },
                PathProps = new PathProperties()
                {
                    Corners = PathCorner.Round
                },
                IsConvex = true,
            };
            svg.Root.Shapes.Add(roundedRect);

            var geo = VectorUtils.TessellateScene(svg, new VectorUtils.TessellationOptions()
            {
                StepDistance = 1, SamplingStepSize = 1
            });
            var sprite = VectorUtils.BuildSprite(geo, 1, VectorUtils.Alignment.Center, Vector2.one / 2, 100);

            var mat       = new Material(Shader.Find("Unlit/Vector"));
            var texture   = VectorUtils.RenderSpriteToTexture2D(sprite, width, height, mat);
            var newSprite = Sprite.Create(texture, new Rect(0, 0, width, height), Vector2.one / 2, 1, 0, SpriteMeshType.FullRect, GetBorder(tl, tr, bl, br));


            Object.DestroyImmediate(sprite);
            SpriteCache[key] = newSprite;
            return(newSprite);
#endif
        }
Exemplo n.º 26
0
    void Start()
    {
        //string svg =
        //    @"<svg width=""283.9"" height=""283.9"" xmlns=""http://www.w3.org/2000/svg"">
        //        <line x1=""170.3"" y1=""226.99"" x2=""177.38"" y2=""198.64"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
        //        <line x1=""205.73"" y1=""198.64"" x2=""212.81"" y2=""226.99"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
        //        <line x1=""212.81"" y1=""226.99"" x2=""219.9"" y2=""255.33"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
        //        <line x1=""248.25"" y1=""255.33"" x2=""255.33"" y2=""226.99"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
        //        <path d=""M170.08,226.77c7.09-28.34,35.43-28.34,42.52,0s35.43,28.35,42.52,0"" transform=""translate(0.22 0.22)"" fill=""none"" stroke=""red"" stroke-width=""1.2""/>
        //        <circle cx=""170.3"" cy=""226.99"" r=""1.2"" fill=""blue"" stroke-width=""0.6""/>
        //        <circle cx=""212.81"" cy=""226.99"" r=""1.2"" fill=""blue"" stroke-width=""0.6""/>
        //        <circle cx=""255.33"" cy=""226.99"" r=""1.2"" fill=""blue"" stroke-width=""0.6""/>
        //        <circle cx=""177.38"" cy=""198.64"" r=""1"" fill=""black"" />
        //        <circle cx=""205.73"" cy=""198.64"" r=""1"" fill=""black"" />
        //        <circle cx=""248.25"" cy=""255.33"" r=""1"" fill=""black"" />
        //        <circle cx=""219.9"" cy=""255.33"" r=""1"" fill=""black"" />
        //    </svg>";



        var tessOptions = new VectorUtils.TessellationOptions()
        {
            StepDistance         = 100.0f,
            MaxCordDeviation     = 0.5f,
            MaxTanAngleDeviation = 0.1f,
            SamplingStepSize     = 0.01f
        };

        //Pfad zur Datei
        string svgFilePath = Application.dataPath + "/Resources/testObject_layerTest-10-10.svg";

        StreamReader sr      = new StreamReader(svgFilePath);
        string       svgText = sr.ReadToEnd();

        print(svgText);
        sr.Close();
        sr.Dispose();

        var sceneInfo = SVGParser.ImportSVG(new StringReader(svgText));

        int NrOfLayers = sceneInfo.Scene.Root.Children.Count;

        m_Sprites = new Sprite[NrOfLayers];
        SVGParser.SceneInfo[]         m_SIArray = new SVGParser.SceneInfo[NrOfLayers];
        List <VectorUtils.Geometry>[] m_Geoms   = new List <VectorUtils.Geometry> [NrOfLayers];

        for (int i = 0; i < NrOfLayers; i++)
        {
            m_SIArray[i] = SVGParser.ImportSVG(new StringReader(svgText));
            int removed = 0;
            for (int c = 0; c < NrOfLayers; c++)
            {
                if (c != i)
                {
                    //print("at " + i + " removing index " + c);
                    m_SIArray[i].Scene.Root.Children.Remove(m_SIArray[i].Scene.Root.Children[c - removed]);
                    removed++;
                }
            }

            var fullBounds  = VectorUtils.SceneNodeBounds(sceneInfo.Scene.Root);
            var localBounds = VectorUtils.SceneNodeBounds(sceneInfo.Scene.Root.Children[i]);
            var pivot       = localBounds.position - fullBounds.position;

            var localSceneBounds = VectorUtils.SceneNodeBounds(m_SIArray[i].Scene.Root);

            Vector2 position = new Vector2(fullBounds.position.x, fullBounds.position.y);
            // position = new Vector2(fullBounds.center.x / fullBounds.width - (localBounds.position.x) / fullBounds.width, fullBounds.center.y / fullBounds.height - localBounds.position.y / fullBounds.height);
            //position = new Vector2((fullBounds.center.x - localBounds.position.x )/ fullBounds.width, 0);
            //position = new Vector2((fullBounds.position.x-localBounds.position.x-pivot.x) / fullBounds.width , 0);
            position = new Vector2(0, 0);

            print("FullBounds: " + fullBounds + " localBounds:" + localBounds);// + " localSceneBounds:"+ localSceneBounds);
            //print(i + ": " + position+" / pivot: "+pivot);

            //print(position.x * fullBounds.width + " , " + position.y * fullBounds.height);

            m_Geoms[i]   = VectorUtils.TessellateScene(m_SIArray[i].Scene, tessOptions);
            m_Sprites[i] = VectorUtils.BuildSprite(m_Geoms[i], 1000.0f, VectorUtils.Alignment.TopLeft, position, 128, true);

            GameObject     go = new GameObject();
            SpriteRenderer s  = go.AddComponent <SpriteRenderer>();
            go.transform.parent = transform;
            // go.transform.position = new Vector3((localSceneBounds.x - fullBounds.width/2f)/1000f, (fullBounds.y + fullBounds.height/2f - localSceneBounds.y) /1000f , 0);
            go.transform.position = new Vector3((localBounds.x) / 1000f, (fullBounds.y - localBounds.y) / 1000f, 0);
            s.sprite = m_Sprites[i];

            //var test = typeof(VectorUtils.TessellateScene);
            //var methods = test.GetMethods();

            //// test code: generate better shape
            //bool m_BetterGeneratePhysicsShape = true;
            //if (m_BetterGeneratePhysicsShape)
            //{
            //    var test = typeof(VectorUtils);
            //    var methods = test.GetMethods();
            //    foreach (MethodInfo mf in methods)
            //    {
            //        Debug.Log(mf.Name);
            //    }

            //    var physicsShapes = VectorUtils.TraceNodeHierarchyShapes(sceneInfo.Scene.Root, tessOptions);

            //    var rect = sceneInfo.SceneViewport;

            //    foreach (var vertices in physicsShapes)
            //    {
            //        if (rect == Rect.zero)
            //        {
            //            rect = VectorUtils.Bounds(vertices);
            //            VectorUtils.RealignVerticesInBounds(vertices, rect, flip: true);
            //        }
            //        else
            //        {
            //            VectorUtils.FlipVerticesInBounds(vertices, rect);
            //            VectorUtils.ClampVerticesInBounds(vertices, rect);
            //        }
            //    }

            //    m_Sprites[i].OverridePhysicsShape(physicsShapes);
            //}
            //// test code end

            go.AddComponent <PolygonCollider2D>();

            //PrefabUtility.SaveAsPrefabAsset(go, svgFilePath.Replace(".svg", "_2" + i.ToString() + ".prefab"));
        }



        //AssetImportContext ctx;

        //ctx.AddObjectToAsset();

        //var geoms = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);

        //// Build a sprite with the tessellated geometry.
        //var sprite = VectorUtils.BuildSprite(geoms, 1000.0f, VectorUtils.Alignment.TopLeft, Vector2.zero, 128, true);
        //GetComponent<SpriteRenderer>().sprite = sprite;

        //GenerateSpriteAsset(ctx, sprite, name);
    }
Exemplo n.º 27
0
    static void SvgLayerImporter(string assetPath)
    {
        var originalSvgPathFull = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("/") + 1) + assetPath;

        var sceneInfo = SVGParser.ImportSVG(File.OpenText(originalSvgPathFull));

        if (null == sceneInfo.Scene)
        {
            Debug.LogError("Could not parse SVG at " + originalSvgPathFull + "!");
        }
        else
        {
            Debug.Log("Custom import: " + originalSvgPathFull);

            // this could probably stand to be specified elsewhere
            var tessOptions = new VectorUtils.TessellationOptions()
            {
                StepDistance         = 100.0f,
                MaxCordDeviation     = 0.5f,
                MaxTanAngleDeviation = 0.1f,
                SamplingStepSize     = 0.01f
            };

            // duplicate the original SVG prefab and create a GameObject that will serve as a pretend "instance" of that prefab
            var newPrefabLocation = assetPath.Replace(".svg", "_Split.prefab");
            //var ob = new GameObject("111");
            //PrefabUtility.SaveAsPrefabAsset(ob, newPrefabLocation);

            var newSceneInfo = SVGParser.ImportSVG(File.OpenText(originalSvgPathFull));
            var geom         = VectorUtils.TessellateScene(newSceneInfo.Scene, tessOptions);
            var newSprite    = VectorUtils.BuildSprite(geom, 10.0f, VectorUtils.Alignment.SVGOrigin, Vector2.zero, 128, true);

            var            ob             = new GameObject("111");
            SpriteRenderer spriteRenderer = ob.AddComponent <SpriteRenderer>();
            spriteRenderer.sprite = newSprite;

            //PrefabUtility.CreatePrefab(newPrefabLocation, ob);
            //PrefabUtility.SaveAsPrefabAsset(ob, newPrefabLocation);
            //AssetDatabase.ImportAsset(newPrefabLocation);
            //AssetDatabase.
            //Debug.Log(newSprite.bounds);
            //AssetDatabase.AddObjectToAsset(newSprite, newPrefabLocation);
            //AssetDatabase.SaveAssets();

            //AssetDatabase.CreateAsset(newSprite, assetPath.Replace(".svg", "_test.prefab"));
            //AssetDatabase.SaveAssets();

            //PrefabUtility.CreatePrefab(assetPath.Replace(".svg", "_test.prefab"), ob);
            ////AssetDatabase.CreateAsset(ob, assetPath.Replace(".svg", "_test.prefab"));
            //AssetDatabase.AddObjectToAsset(newSprite, assetPath.Replace(".svg", "_test.prefab"));
            //AssetDatabase.SaveAssets();
            //Sprite t = (Sprite)AssetDatabase.LoadAssetAtPath(assetPath.Replace(".svg", "_test.prefab"), typeof(Sprite));
            //Debug.Log(t.bounds);

            //AssetDatabase.AddObjectToAsset(newSprite, ob);
            //PrefabUtility.SaveAsPrefabAsset(ob, newPrefabLocation);

            //PrefabUtility.CreateEmptyPrefab(newPrefabLocation);
            //var newPrefab = AssetDatabase.LoadAssetAtPath<GameObject>(newPrefabLocation);
            //Debug.Log(newPrefab);
            //var instPrefab = new GameObject();

            /*
             * // go through each layer of the SVG, and in each layer, remove SVG info nodes that are *not* in that layer
             * int numOriginalLayers = sceneInfo.Scene.Root.Children.Count;
             * for (int i = 0; i < numOriginalLayers; ++i)
             * {
             *  var newSceneInfo = SVGParser.ImportSVG(File.OpenText(originalSvgPathFull));
             *  int removed = 0;
             *  var layerName = "";
             *  for (int c = 0; c < numOriginalLayers; ++c)
             *  {
             *      if (c == i)
             *      {
             *          layerName = "Layer " + c;
             *      }
             *      else
             *      {
             *          newSceneInfo.Scene.Root.Children.Remove(newSceneInfo.Scene.Root.Children[c - removed]);
             ++removed;
             *      }
             *  }
             *
             *  // instantiate the current layer as a new sprite in the scene, and attach it to our new prefab which will soon be saved to disk
             *  var geom = VectorUtils.TessellateScene(newSceneInfo.Scene, tessOptions);
             *  var newSprite = VectorUtils.BuildSprite(geom, 10.0f, VectorUtils.Alignment.SVGOrigin, Vector2.zero, 128, true);
             *  newSprite.name = layerName;
             *
             *  // each SVG layer will have a corresponding GameObject that's part of the new prefab
             *  GameObject go = new GameObject(layerName);
             *  SpriteRenderer s = go.AddComponent<SpriteRenderer>();
             *  s.sprite = newSprite;
             *  go.transform.SetParent(instPrefab.transform);
             *
             *  // bundle the new sprite (for this layer) in with the new SVG prefab
             *  AssetDatabase.AddObjectToAsset(newSprite, newPrefab);
             * }
             *
             * // now apply the changes from the instantiated prefab to the saved prefab on disk, and destroy the instance
             * PrefabUtility.ReplacePrefab(instPrefab, newPrefab, ReplacePrefabOptions.ReplaceNameBased);
             * Object.DestroyImmediate(instPrefab);
             */
        }

        return;
    }
Exemplo n.º 28
0
 public Sprite BuildSprite(float svgPixelsPerUnit, Alignment alignment, Vector2 customPivot, ushort gradientResolution, bool flipYAxis = false)
 {
     return(VectorUtils.BuildSprite(_geoms, svgPixelsPerUnit, alignment, customPivot, gradientResolution, flipYAxis));
 }
Exemplo n.º 29
0
        static public Sprite CreateBorderSprite(int borderRadius)
        {
            borderRadius = Mathf.Max(borderRadius, 0);
            if (SpriteCache.ContainsKey(borderRadius))
            {
                return(SpriteCache[borderRadius]);
            }

            if (borderRadius == 0)
            {
                var smallTexture = new Texture2D(4, 4);
                var colors       = new Color[16];
                for (int i = 0; i < 16; i++)
                {
                    colors[i] = Color.white;
                }
                smallTexture.SetPixels(colors);
                smallTexture.Apply();
                return(SpriteCache[borderRadius] =
                           Sprite.Create(smallTexture, new Rect(0, 0, 4, 4), Vector2.one / 2, 1, 0, SpriteMeshType.FullRect, Vector4.one));
            }


#if !REACT_VECTOR_GRAPHICS
            if (ShowVectorGraphicsMessage)
            {
                Debug.LogError("To use the 'borderRadius' feeature, 'Unity.VectorGraphics' package must be installed.");
                ShowVectorGraphicsMessage = false;
            }
            return(null);
#else
            var svg = new Scene()
            {
                Root = new SceneNode()
                {
                    Shapes = new List <Shape>()
                }
            };

            var totalSize = borderRadius * 2 + 2;

            var rad = Vector2.one * borderRadius;

            var contour     = VectorUtils.BuildRectangleContour(new Rect(0, 0, totalSize, totalSize), rad, rad, rad, rad);
            var roundedRect = new Shape()
            {
                Contours = new BezierContour[] { contour },
                Fill     = new SolidFill()
                {
                    Color = Color.white, Opacity = 1
                },
                PathProps = new PathProperties()
                {
                    Corners = PathCorner.Round
                },
                IsConvex = true,
            };
            svg.Root.Shapes.Add(roundedRect);

            var geo = VectorUtils.TessellateScene(svg, new VectorUtils.TessellationOptions()
            {
                StepDistance = 1, SamplingStepSize = 1
            });
            var sprite = VectorUtils.BuildSprite(geo, 1, VectorUtils.Alignment.Center, Vector2.one / 2, 100);

            var size       = Mathf.CeilToInt(totalSize);
            var spriteRect = new Vector4(borderRadius, borderRadius, borderRadius, borderRadius);
            var mat        = new Material(Shader.Find("Unlit/Vector"));
            var texture    = VectorUtils.RenderSpriteToTexture2D(sprite, size, size, mat);
            var newSprite  = Sprite.Create(texture, new Rect(0, 0, size, size), Vector2.one / 2, 1, 0, SpriteMeshType.FullRect, spriteRect);


            Object.DestroyImmediate(sprite);
            SpriteCache[borderRadius] = newSprite;
            return(newSprite);
#endif
        }