GithubHelp home page GithubHelp logo

starlinggraphics / starling-extension-graphics Goto Github PK

View Code? Open in Web Editor NEW
283.0 283.0 89.0 8.68 MB

flash.display.Graphics style extension for the Starling Flash GPU rendering framework

Home Page: https://github.com/StarlingGraphics/Starling-Extension-Graphics/wiki

License: MIT License

ActionScript 100.00%

starling-extension-graphics's People

Contributors

albirdie avatar chamberlainpi avatar cykoder avatar drumsoft avatar ionswitz avatar jarrodmoldrich avatar jonathanrpace avatar leethomason avatar robsilv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

starling-extension-graphics's Issues

Too many stroke objects

Hi, it's me again:) I've noticed, that when I call just:

g.lineStyle(20, 0xFF0000)
g.lineTo(100, 0);
g.moveTo(0, 100);
g.lineTo(100, 100);

in the g's container I will have 2 stroke objects. Woudn't it be better to have just one in such a case?

Context lost throws null pointer exception on windows 7

Hi im running into the issue that on context lost(via strg+alt+del) following null pointer exception gets thrown: at starling.display.materials::StandardMaterial/drawTriangles() ... StandardMaterial.as:135

Thats the code inside of StatusBar.as

var bgRect : Shape = new Shape();
bgRect.graphics.clear();
bgRect.graphics.lineStyle(1, 0x000000, 0.5);
bgRect.graphics.beginFill(0xFFFFFF, 1);
bgRect.graphics.drawRoundRect(0, 0, 155, 55, 12);
// borderCorner);
bgRect.graphics.endFill();
this.addChild(bgRect);

native drawRoundRect

Hello, can you add an drawRoundRect method ?

It will be cool :)

Thanks for this lib !

Lost context on android

Seems to lose context on Android (tested on galaxy nexus and nexus 7 both running 4.2.1). When the screen rotates the "context" is lost. The drawing/line disappears every time

memory leak found in Graphics

whenever it goes _currentFill=null; it causes the memory leak
because the _currentFill is not disposed.

It can be reproduced by calling shape.graphics.beginFill() shape.graphics.endFill()
in an onEnterFrame function.

my current fix is to remove _currentFill=null in the endFill function
and do if(_currentFill) { _currentFill.dispose(); _currentFill = null} before every _currentFill = new FIll(). and _currentFill = null;

Anti-aliasing?

What would be the best approach to anti-aliasing? Rotated rectangle look quite aliased.

Drawing natural cubic splines

The curveTo() function of the graphics extension is a great feature but the use of control points make it pretty complicated to manage.

I found few AS3 scripts that allows you to draw a smooth line through a series of points on a map without having to deal with control points. You can see some pratical examples like the green line in here and here.

The first example has been made by Nicoptere on this page

The second one has been ported in AS3 by Daniel McLaren here

There are as well some alternative methods on this thread.

I've ported Nicoptere's class to Starling:
Example
Source code
A glowing river

Would it be complicated to add this to the graphics extension?

Graphics on mobile works strange

Hi, I`m working on some drawing app and use graphics extension. It works pretty fine on desktop, but not on mobile. Here 2 screenshots of my Acer Iconia Tab A100:
droid screen-1
droid screen-2

I have Shape and drawing white line by finger. If I move finger slow it draws like [1], if fast - like [2].
I have fixed it by adding myShape.graphics.moveTo(prevPoint.x, prevPoint.y) before myShape.graphics.lineTo(currentPoint.x, currentPoint.y)
But I think it is dirty hack and problem appears only on mobile.
PS. It`s a repost of http://forum.starling-framework.org/topic/graphics-on-mobile-works-strange

beginTextureFill() from atlas texture behaves wierd

When I do this:

var texture:Texture = Assets.atlas.getTexture( "SimpleCrate" );

displayObject.graphics.beginTextureFill( texture );
displayObject.graphics.moveTo( 0, 0 );

displayObject.graphics.lineTo( 150, 0 );
displayObject.graphics.lineTo( 150, 150 );
displayObject.graphics.lineTo( 0, 150 );
displayObject.graphics.endFill();

And that draws fine except that it draws entire game atlas png scaled into 150x150 pixel box instead of just normal crate image texture.

Thanks,
Caslav

[Enhancement] Remove ternary operators

Hi there, this is probably a very(!) small performance enhancement, but since I stumbled across it, I figured why not improve it anyways?

Based on Jackson Dunstan's latest article about conditionals (http://jacksondunstan.com/articles/2178), Fill.addVertex() might actually be a tad faster when setting the min- and maxBounds like this:

if(x < minBounds.x)
minBounds.x = x;

if(y < minBounds.y)
minBounds.y = y;

if(x > maxBounds.x)
maxBounds.y = x;

if(y > maxBounds.y)
maxBounds.y = y;

, instead of using the ternary operator (whose else case isn't actually required anyway, is it?);

minBounds.x = x < minBounds.x ? x : minBounds.x;
minBounds.y = y < minBounds.y ? y : minBounds.y;
maxBounds.x = x > maxBounds.x ? x : maxBounds.x;
maxBounds.y = y > maxBounds.y ? y : maxBounds.y;

Ellipse stroke bug

not correct:
var x:Number = s * width;
var y:Number = -c * height;
if ( i == 0 )
{
moveTo(x,y);
}
else
{
lineTo(x,y);
}

correct:
var sx:Number = s * width + x;
var sy:Number = -c * height + y;
if ( i == 0 )
{
moveTo(sx,sy);
}
else
{
lineTo(sx,sy);
}

new class based on plane

Hi Jonathan,

here's a new class based on the plane:

package starling.display.graphics
{
import flash.geom.Rectangle;

import starling.core.RenderSupport;
import starling.core.Starling;
import starling.display.DisplayObject;



public class Ball extends Graphic
{
    private static const VERTEX_STRIDE:int = 9;

    private var vertices:Vector.<Number>;
    public var _Speed:Number
    private var indices:Vector.<uint>;
    public var _width:Number;
    public var _height:Number;
    private var _numVerticesX:uint;
    private var _numVerticesY:uint;
    public var offset:Number = 0
    public var _Shading:Number = 0



    private var isInvalid:Boolean;

    public function Ball( radius:Number = 100, numVerticesX:uint = 2, numVerticesY:uint = 2 ,Speed:Number = 0.005,Shading:Number=0.7)
    {
        _width = radius;
        _height = radius;
        _numVerticesX = numVerticesX+1;
        _numVerticesY = numVerticesY;
        _Speed = Speed
        _Shading = Shading
        isInvalid = true;
        validate()
        isInvalid = false;


    }

    public function validate():void
    {

        if (vertexBuffer)
        {
            vertexBuffer.dispose();
            if(isInvalid){indexBuffer.dispose();}
        }

        // Generate vertices
        var numVertices:int = _numVerticesX * (_numVerticesY-1)+1
        vertices = new Vector.<Number>();

        for (var j:int=1; j < _numVerticesY; j++){

            const temp:Number =  Math.sin(Math.PI*((j)/(_numVerticesY))/2)

            for (var i:int = 0; i < _numVerticesX; i++){

                var u:Number = Math.cos(i*Math.PI*2 / (_numVerticesX - 1))*(j/ (_numVerticesY - 1))/4 + offset
                var v:Number = Math.sin(i*Math.PI*2 / (_numVerticesX - 1))*(j/ (_numVerticesY - 1))/2 +0.5
                var x:Number = (_width+(_width*Math.cos(i*Math.PI*2 / (_numVerticesX - 1)))*(temp))/2
                var y:Number = (_height+(_height*Math.sin(i*Math.PI*2 / (_numVerticesX - 1)))*(temp))/2
                const shading = Math.pow(1-temp,_Shading)
                vertices.push( x, y, 0,shading, shading, shading, 1, u, v );
        }
        }

        vertices.push( _width/2,_height/2 , 0,1, 1, 1, 1, 0+offset, 0.5 );

        if(isInvalid){
            // Generate indices
            indices = new Vector.<uint>();
            var qn:int = 0; //quad number
            for (var m:int = 0; m <_numVerticesY-1; m++) //create quads out of the vertices
            {               
                for (var n:int = 0; n <_numVerticesX - 1; n++)
                {

                  if(m<_numVerticesY - 2){
                  indices.push(qn, qn + 1, qn + _numVerticesX ); //upper face
                  indices.push(qn + _numVerticesX, qn + _numVerticesX  + 1, qn+1); //lower face
                  }else{

                  indices.push(n, n +  1, numVertices-1) 
                  }

                  qn++; //jumps to next quad
                }
                qn++; // jumps to next row
            }
        }
        // Upload vertex/index buffers.
        vertexBuffer = Starling.context.createVertexBuffer(numVertices,VERTEX_STRIDE);
        vertexBuffer.uploadFromVector( vertices, 0, numVertices );

        if(isInvalid){
            indexBuffer = Starling.context.createIndexBuffer(indices.length);
            indexBuffer.uploadFromVector( indices, 0, indices.length );
        }
        offset += _Speed

    }

    public override function getBounds(targetSpace:DisplayObject, resultRect:Rectangle=null):Rectangle
    {
        minBounds.x = 0;
        minBounds.y = 0;
        maxBounds.x = _width;
        maxBounds.y = _height;
        return super.getBounds(targetSpace, resultRect);
    }

    override public function render( renderSupport:RenderSupport, alpha:Number ):void
    {
        if(isInvalid || _Speed != 0){
        validate()}

        super.render( renderSupport, alpha );
    }
}

}

greetings Rogier

PS, funny if you replace the uv's with:

var u:Number = Math.cos(i_Math.PI_2 / (numVerticesX - 1)+0.4_j_Math.sin(offset_10))(j/ (_numVerticesY - 1))/4 + offset;
var v:Number = Math.sin(i_Math.PI_2 / (numVerticesX - 1)+0.4_j_Math.sin(offset_10))(j/ (_numVerticesY - 1))/2 +0.5;

Hard to override classes - Making privates protected?

Just a small question here:

Is there a reason for most of the classes to have "private" rather than "protected" members? Such as the Stroke class, for example? Or the Graphics class?

The code base is magnificent, but with the private member variables, it's kind of hard to extend without basically copying the existing classes, renaming them and making the member variables "protected".

I wouldn't mind doing the work to change them to "protected", but I won't do it if there's a decision or a reason not to open them up for extension...

Let me know what you think, @robsilv and you others.

Handling LostContext

Hi im trying to implement the context loose in Starling. I´m using your great library to draw curves and stuff.

var s:Shape = new Shape();
s.graphics.beginFill(0xFFFFFF);
s.graphics.lineStyle(2);
s.graphics.drawCircle(0, 0, 250);
s.graphics.endFill();

addChild(s);

After setting Starling.handleLostContext = true; i get a null pointer exception for the context:

at starling.display.materials::StandardMaterial/drawTriangles()[C:\Andoria\gitHub\Starling-Extension-Graphics\extension\src\starling\display\materials\StandardMaterial.as:135]
at starling.display.materials::StandardMaterial/drawTriangles()

Edit: i´m using the githubs last version and windows 7 DirectX9 (Baseline Constrained)

Fill and Stroke cause objects drawn before them to vanish

I'm getting a weird issue with the Fill and Stroke objects. When used in combination with other starling sprites some of the other sprites will stop rendering.

As an example I have this code, which is based on the Fill_Stroke example:

grassLayer = new Sprite();
addChild(grassLayer);
// .... add sprites to grassLayer

mountainLayer = new Sprite();
addChild(mountainLayer);
mountain = new Sprite();
mountainLayer.addChild(mountain);
var landStroke:Stroke = new Stroke();
landStroke.material.fragmentShader = new TextureVertexColorFragmentShader();
landStroke.material.textures[0] = grassTexture;
landStroke.addVertex( 100, 100, 3  );
landStroke.addVertex( 130, 130, 3  );
mountain.addChild(landStroke);

treeLayer = new Sprite();
addChild(treeLayer );

What I find is that the sprites in the grass layer won't draw, but the mountain and tree will. If I remove the mountain.addChild(landStroke) line the grass draws correctly. I also tried doing landStroke.visible = false, and this causes the grass to draw.
If I move the mountain after the tree, then the tree will not draw but the grass will.

It seems that the only hack I've found is to add another image just before the mountain layer so that it gets ignored instead of the ones I want.

How to cache vertex data

Hi, doing more tests I found, that on mobile devices the shape creation is too slow (running my shape animation on iPad with 2fps where on PC I have 60fps still with hight AS peaks)... My original idea was using pools for once created shapes, but using it I hit vertext buffer limit. When I clear the shape, I will not hit the buffer limit, but it require re-tessellation of the shape when added to stage again.

So I just would like to know, if it would be possible to precompute the shape data and just initiate and reuse them when needed. Any idea? (I hope you understand what I'm trying to describe:-)

Maybe storing renderVertices and indices and not to need recreate them durring the render even when vertexBuffer and indexBuffer are disposed.

Allowing Graphic.validateNow to work as a pre-cacher of StrokeVertices?

As I was checking through the Stroke code tonight, I saw that calling validateNow
will calculate the vertex data etc for the Graphic, BUT it will run twice in a frame.

As a frame rate fiend, I like to be able to pre-calculate everything in a shape, before it renders. The way validateNow , and the building of vertices is run today, there is no way to do that, since validateNow will run within the render method, and re-generate the vertices even if no change has occured since the last time validateNow was run.

So I would suggest adding a member variable, something like:

protected var hasBeenValidatedButNeedsRender:Boolean = false;

that gets set to true after running through validateNow, regardless of where it is called from.

and, in render, we would check this flag, before running into validateNow.

override public function render( renderSupport:RenderSupport, parentAlpha:Number ):void
{
if ( hasBeenValidatedButNeedsRender == false )
validateNow();

This would allow us to precalculate everything in a Graphic class, and the only thing render would actually do would be to push the triangles to the hardware.

Doesn't that sound like a very pleasant option?

Example returns weird error

Running the provided example files (after incorporating Feathers-maste, Starling framework and given SWC), running in simulator displays only one line "This application is not correctly embedded (wrong wmode value)". Any idea what I did wrong (?) Thanks.

[Enhancement] Interrupt Stroke

I'm not sure if this isn't already supported, let me first explain what I'm trying to do ([pseudo]code says more than a thousand words here);

var stroke:Stroke = new Stroke();
addChild(stroke);
for(i=0; i<10;i++) {
stroke.addVertex(0, i_10, 1);
stroke.addVertex(100, i_10, 1);
}

As you can see, basically I just wanna add 10 lines to the screen by using a single Stroke. Naturally, the stroke connects the line(s), so draws a line from the previous line's end position to the current line's start position.

Thus, I'm somehow looking for a means to avoid this connection and get separate lines with just a single Stroke.
I'm aware of moveTo and lineTo using a Shape, but that isn't an option for our use case as it is way too slow. Using multiple Strokes would work, but using a single one is about 25% faster and since I'm targeting mobile devices, that is a huge difference.

I'd highly appreciate it if you could help me out here Jonathan.

BTW: More performance improvements are on the way, although performance gains are minimal this time. Gonna make a new pull request this weekend.

Stroke error with latest Starling build

Hello,

Just switched from SWC to the latest source for the Starling Graphics Extension and I keep getting this error :

The index 4294967295 is out of range 0.
at starling.display.graphics::Stroke$/fixUpPolyLine()[----\src\starling\display\graphics\Stroke.as:422].

I'm using the latest Starling source.

starling\display\materials\graphics\plane

Hi there,

first of all: I just love this graphics extention!
i'm trying to use the extension called "plane"
i think it has nice posibilities for warping images by transforming its uvcoordinates
But... I cant get it to work. i tried adding it to stage like this:

        grid = new Plane(1,1,10,10);
        grid.material = new StandardMaterial( new StandardVertexShader(), new TextureVertexColorFragmentShader() );
        grid.material.textures[0] = Texture.fromBitmap( new CheckerBMP(), false );
        addChild(grid);

can you please help me out?

greetings,

Rogier de Leeuw

Stroke fixUpPolyLine bug

This line idx would be a big int while vertices.length==0
var idx:uint = vertices.length - 1;
while ( idx > 0 && vertices[idx].degenerate > 0 )

Graphic.bounds issue when rotated

The following code:

package
{
    import starling.display.Image;
    import starling.display.Sprite;
    import starling.textures.Texture;

    public class GetBoundsStarling extends Sprite
    {
        [Embed( source = '/assets/crate1_80x80.png' )] 
        private var Crate:Class;

        public var image:Image;

        public function GetBoundsStarling()
        {
            var texture:Texture = Texture.fromBitmap( new Crate() );

            image = new Image(texture);
            addChild(image);

            image.x = 100;
            image.y = 100;

            image.rotation = 30 * Math.PI/180;

            trace(image.bounds);
        }
    }
}

Traces out

(x=60.00000000000001, y=100, w=109.28203230275511, h=109.28203230275508)

Whereas

package
{
    import starling.display.Shape;
    import starling.display.Sprite;

    public class GetBoundsStarling2 extends Sprite
    {
        public function GetBoundsStarling2()
        {
            var sprite:Shape = new Shape();
            addChild(sprite);

            sprite.graphics.beginFill(0xFF0000);
            sprite.graphics.drawRect(0, 0, 80, 80);

            sprite.x = 100;
            sprite.y = 100;

            sprite.rotation = 30 * Math.PI/180;

            trace(sprite.bounds);
        }
    }
}

Traces out

(x=100, y=100, w=29.282032302755113, h=109.28203230275508)

Note the x and w values are wrong, but the y and h values are correct.

Both versions trace out the following when rotation is zero:

(x=100, y=100, w=80, h=80)

The problem seems to be here. Any thoughts?

Ta
Rob

Fill colour+alpha issue with drawRect

Hi,

I happened to notice a little problem when using the latest version of starling from the github repo. If you call beginFill, then use drawRect, the fill colour and alpha isn't assigned to the fill material on the rect, so you get a white fill at 100% alpha.
To fix it I just assigned the fill alpha and colour to the fill material inside drawRect function before assigning the material.

Hope that helps and good work on the library.

Matt Murton

SWF metadata tag mobile

If I don't set SWF metadata tag
[SWF( width="480", height="800", backgroundColor="#FFFFFF", frameRate="60" )]

I cannot draw under y = 600.

If I set metadata I can't configure multiresolution for diferent devices.

Any solution?

render problem with curveTo()

Hello everyone,

First thank for this very usefull extension to starling you are currently implementing.

I face a problem of rendering when i try to make a shape with curveTo(), i try to make a square with a quarter of circle to render the exterior of a curve.

if you add a new shape with this code:

var s:Shape = new Shape();
var g:Graphics = s.graphics;

g.lineStyle(3, 0xFF0000);
g.beginFill(0xFF0000, 0.2);
g.lineTo(0, 350);
g.curveTo(0, 0, 350, 0);
g.lineTo(0, 0);
g.endFill();

s.x = 10;
s.y = 10;

addChild(s);

you will get the line rendering ok but the fill is not correct.

i use flash builder 4.6
air SDK 3.5
Flash plugin 11.5.31.5

on a actionscript mobile project.

Hope i send enough details for this issue :)

addEventlistener ?

Great extension :)
I only have some troubles adding an eventlistener to a Shape.
it does noet seem to work.
Any ideas why?

        var shape:Shape= new Shape();
        _dragger.addChild(shape);   
        shape.graphics.beginFill(vendor.color);
        shape.graphics.moveTo(vendor.points[0].x, vendor.points[0].y);
        for each(var p:Point in vendor.points){
            shape.graphics.lineTo(p.x, p.y);
        }
        shape.addEventListener(TouchEvent.TOUCH, onClickShape)

Extension project is missing .flexLibProperties file

The library project in the extension folder does not have the .flexLibProperties file generated by Flash Builder 4.7, can it be included so that developers who are importing this project in Flash Builder 4.7 do not face any issues. Currently without this file, Flash Builder 4.7 gives an error that the project might be corrupted.

RenderTexture as drawn including unused pixels.

Thx alot. Great lib and keep forward.
Issue
Example:

var gradientQuad:Quad = new Quad(100, 100);
gradientQuad.setVertexColor(0, 0xFF00FF);
gradientQuad.setVertexColor(1, 0x0000FF);
gradientQuad.setVertexColor(2, 0xFFFF00);
gradientQuad.setVertexColor(3, 0xF0F0FF);
addChild(gradientQuad);

        var renderTexture:RenderTexture = new RenderTexture(100, 100);
        //var renderTexture:RenderTexture = new RenderTexture(128, 128);<--solution

        renderTexture.draw(gradientQuad);



        shape.graphics.beginTextureFill(renderTexture);


        shape.graphics.drawRect(0, 0, 100, 100);


        shape.graphics.endFill();

Texture is drawn with unused pixels.

If for example we use bigger rect and we expect to scale texture to fit new size
Matrix m=new Matrix();
m.scale(4,3);

shape.graphics.beginTextureFill(renderTexture,m);
shape.graphics.drawRect(0, 0, 400, 300);

the same effect would be visible. Using first nearest texture size of power of 2 would solve the problem.

Without matrix scaling(if we want tilling) gaps between tiles can be seen.

Silly class for performance measurement

One thing that has bothered me is how hard it can be to do speed comparisons in Release builds. trace-output wont work for me in FlashDevelop Release builds, for some reason, in spite of the flag saying allow trace output.

So I decided to do this piece of madness. A class to output the numbers 0,1,2,3,4,5,6,7,8 and 9 through the Graphics package, using only lineTo, moveTo, curveTo, etc.

If anyone finds any use what so ever for this, I'm happy to have helped. To me, it just gives me an easy way to compare performance runs of the type: Adding 5000 vertexes, is Method A faster than Method B?

What REALLY should be done, ofcourse, is to import SVG graphics through this Graphics API... But, well, it seems like an amazingly daunting task. ;)

The only "API" is

public function drawNumber(value:uint) : void

var debug:DebugNumbers = new DebugNumbers();
debug.x = 100;
debug.y = 100;
addChild(debug);
debug.drawNumber(1234); // etc

You can set the public properties:

public var _characterHeight:Number = 20;
public var _characterWidth:Number = 10;
public var _lineWidth:Number = 2;
public var _lineColor:Number = 0xFFFFFF;

from the outside of the class, if that makes you happy. :)

Massive performance decrease with AIR 3.7

Not sure if this issue is known already, but AIR 3.7 heavily reduced the performance of the graphics API.
I've deployed the exact same application to identical iPads and put them side by side.
The 3.6 application runs at 60fps, the 3.7 compiled one at less than 20.

Not sure what exactly causes this behaviour as the rest of the Starling app doesn't show this drop in performance.

context.createProgram(); -> Error #3691: Resource limit for this resource type exceeded

Hi, I'm playing with your extension a little bit, but probably reached its current limits.

I'm getting Error #3691: Resource limit for this resource type exceeded
at this line https://github.com/unwrong/Starling-Extension-Graphics/blob/master/extension/src/starling/display/materials/StandardMaterial.as#L111

I'm having quite a lot shapes used as a complex animation (extracted from SWF file)... maybe if I will not store them in a pool and release the shapes immediately will help in my case, but maybe there is even better way. I'm just a Stage3D newbie.

Btw.. thank you very much for your valuable afford!

API doc

Hi there!
You don't happen to have some documentation for this api, do you?
It's quite hard getting used to this mighty API without even a bit of documentation.

Memory Leaking with latest release and dynamically filled shapes

Firstly, thanks for the extension.
Secondly, I've got a problem - I'm guessing it's my problem because I'm always doing things wrong. The thing is my little app has started to get rather greedy with the memory.
For example – when dragging the points of a triangle the triangle is filled with a texture. The lines, points and texture that make up the triangle are cleared and updated as the points are moved. This was working correctly now it’s out of control. As you move the points the memory increases, it used to reach a max and the garbage would be collected – now it happens once if I am lucky and then the memory then just keeps on rising.

If I revert to an older swc the problem disappears. (How do I identify the version?)

The code below is a simple demo which exhibits this behaviour when using the latest swc. Perhaps someone could take a look and see if I’ve done anything wrong or see if it can be replicated.
Many Thanks

import flash.geom.Point;
import starling.display.Image;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.events.TouchPhase;

import starling.display.Shape;
import starling.display.Sprite;
import starling.events.Event;
import starling.textures.Texture;

public class GraphicsAPIExample_Dynamic extends Sprite
{

    [Embed( source = "../assets/Checker.png" )]
    private var CheckerBMP      :Class;
    [Embed(source = "../assets/marble_80x80.png")]
    private var PinBMP          :Class;

    private var totalpins:int;
    private var pinArray:Array;
    private var pin:Image;
    private var pinRadius:int = 30;
    private var shapeDrawnWithLines:Shape;
    private var posX:int;
    private var posY:int;
    private var CheckerTexture:Texture;

    public function GraphicsAPIExample_Dynamic()
    {
        addEventListener(Event.ADDED_TO_STAGE, onAdded);
    }

    private function onAdded ( e:Event ):void
    {
        trace("touchHandler");
        pinArray = new Array();
        totalpins = 3;  
        var radius:int = 200;
        var location:Point = new Point(200, 200);
        var pinTexture:Texture = Texture.fromBitmap( new PinBMP(), false );
        CheckerTexture = Texture.fromBitmap( new CheckerBMP, false, false, 2 ); 
        for (var i:int = 0; i < totalpins; i++) 
        {   
            pin = new Image(pinTexture);
            addChild(pin);                              
            pinArray.push(pin);                     
            var angle:int = angle+(360/totalpins);
            pinArray[i].x = location.x + (Math.sin(angle*(Math.PI/180))*radius)/2;;
            pinArray[i].y = location.y + (Math.cos(angle*(Math.PI/180))*radius)/2;
            pinArray[i].addEventListener(TouchEvent.TOUCH, touchHandler);   
        }
        beginMaterialFill();
    }

    private function touchHandler(e:TouchEvent):void
    {   
        trace("touchHandler");
            var target:Image = e.target as Image;
            var touch:Touch = e.getTouch(parent);       
        if ( e.getTouch(parent, TouchPhase.BEGAN))
                {                                       
                    position = touch.getLocation(parent);
                    var posT:Point = touch.getLocation(target.parent.parent);
                    posX = target.x - position.x;
                    posY = target.y - position.y;
                }


        if ( e.getTouch(parent, TouchPhase.MOVED))
        {   
            var pin:Image = e.target as Image;
            touch = e.getTouch(parent);
            var position:Point = touch.getLocation(parent);
            pin.x = position.x - pinRadius ;
            pin.y = position.y - pinRadius ;    
            movin();
        }           
        if ( e.getTouch(parent, TouchPhase.ENDED))
        {                   
            position = touch.getLocation(parent);                                               
        }
    }


    private function beginMaterialFill():void //innitially fill the shape
    {   
        shapeDrawnWithLines = new Shape();
        shapeDrawnWithLines.graphics.lineStyle(4, 0xFF0000, 1);
        shapeDrawnWithLines.graphics.beginTextureFill(CheckerTexture);
        shapeDrawnWithLines.graphics.moveTo(pinArray[0].x + pinRadius, pinArray[0].y + pinRadius);
        for (var i:int = 1; i <= totalpins; i++)
        {
            if (i < totalpins)
            {
                shapeDrawnWithLines.graphics.lineTo(pinArray[i].x + pinRadius, pinArray[i].y + pinRadius);
            } else {
                shapeDrawnWithLines.graphics.lineTo(pinArray[0].x + pinRadius, pinArray[0].y + pinRadius);
                shapeDrawnWithLines.graphics.endFill();
            }
        }
            addChild(shapeDrawnWithLines);

    }
    private function movin():void 
    {           
        shapeDrawnWithLines.graphics.clear();
        shapeDrawnWithLines.graphics.lineStyle(4, 0xFF8040, 1);
        shapeDrawnWithLines.graphics.beginTextureFill(CheckerTexture);
        shapeDrawnWithLines.graphics.moveTo(pinArray[0].x + pinRadius, pinArray[0].y + pinRadius);
        for (var i:int = 1; i <= pinArray.length; i++)
        {       
        if (i <= pinArray.length-1)
        {                   
            shapeDrawnWithLines.graphics.lineTo(pinArray[i].x+pinRadius, pinArray[i].y+pinRadius);      
        }
        else    
        {                       
            shapeDrawnWithLines.graphics.lineTo(pinArray[0].x + pinRadius, pinArray[0].y + pinRadius);
            shapeDrawnWithLines.graphics.endFill(); 
        }
    }
    }
}

affect other DisplayObject render

After the fill or stroke is added, some other display are weird.

  1. the background of starling state disappear.
  2. Some starling DisplayObject will disappear briefly(the object is still here and touchable, but could not be rendered).

I have fixed the second issue by add renderSupport.finishQuadBatch(); to the beginning of the Graphic class render function and "var context:Context3D = Starling.context;
if (context == null) throw new MissingContextError();
context.setVertexBufferAt(0, null);
context.setVertexBufferAt(1, null);" to the end of it.

Can't compile with ASC 2.0 preview 2

Hi guys,

I'm trying to compile an AIR 3.4 app under FlashDevelop but as soon as I instanciate a Shape I get this error:
as3[Fault] exception, information=TypeError: Error #1034: Type Coercion failed: cannot convert to starling.display.shaders.IShader.

Do you think it can be fixed?

Thank yo for your great work. It helps a lot!

Regards

Interpolating thickness for lineTo/curveTo?

Hey.

I've been coding graphics for two decades, but this is my first time developing in Starling and while digging around, I found this fantastic Graphics extension. Outstanding job, everyone!

However, as I try to use lineTo and curveTo, etc, I run into a problem. The thickness of the stroke is only controlled in the start point. Hence you get a line or curve with constant thickness between the control points.

I hacked some stuff into the code directly, to enable the use of an interpolating thickness ( allowing, for example, thickness 5 at the start and thickness 20 at the end), but my hack solution wasn't pretty. If I get a "Go Ahead" from anyone on here, I will clean up the code and submit a backwards compatible solution. What do you all say?

The solution would probably be along the line of adding a Function property to the Graphics class, with a signature like:

function thicknessFunction(startThickness:Number, endThickness:Number, lerp:Number) : Number

this would allow a user to add any kind of interpolating method (linear, sine, cubic) and with the property set to null (as would be the default) the code would be 100% backwards compatible.

Please let me know if this is something that might be desired.

EDIT: I should also mention that I am new to contributing to GitHub, so there might be some steps I am missing. What do I need to do to contribute? I'm sure there is a FAQ somewhere, as of now I can't find it. Probably my own fault ;)

Stroke bug when going backward

This example is a mix between DynamicFillExample and FillStrokeExample. When you draw a line and go backward, there is a problem with the textured stroke that becomes huge, like in this screenshot. The mouse path has been added in red afterward (on photoshop, so it not really precise).

Error: Unsupported display object: starling.display.graphics::Stroke

Game.class

package
{

    import starling.display.Shape;
    import starling.display.Sprite;
    import starling.events.Event;


    public class Game extends Sprite
    {
        public function Game()
        {
            super();
            this.addEventListener(Event.ADDED_TO_STAGE, onAddToStage);
        }


        private function onAddToStage(event:Event):void
        {
            this.removeEventListener(Event.ADDED_TO_STAGE, onAddToStage);

            var shape:Shape=new Shape();
            shape.graphics.lineStyle(1, 0x000000);
            shape.graphics.lineTo(100, 100);
            var sprite:Sprite=new Sprite();
            sprite.flatten();
            sprite.addChild(shape);
            this.addChild(sprite);
        }
    }
}

This class has a compile error

Error: Unsupported display object: starling.display.graphics::Stroke

But I just use the flatten method Why will complain.

beginFill alpha with drawRect

hello,
i have a simple test case:

            shape.graphics.beginFill(0x00ff00, 0.5);
            shape.graphics.lineStyle(4, 0xff0000, 0.5);
            shape.graphics.drawRect(0, 0, 300, 300);
            shape.graphics.endFill();

where the alpha for beginFill is ignored.

i've noticed 17098aa and perhaps it should be reverted as the alpha should be assigned to the StandardMaterial alpha instead?

Setting "y" of Shape also updates it's "height" property

hello,

i'm not sure if this is specific to the graphics extension or this is a starling bug, but this snippet produces a "y" dependent "height" out of the Shape class:

var shape:Shape = new Shape();
shape.graphics.beginFill(0);
shape.graphics.drawRect(0, 0, 100, 100);
shape.graphics.endFill();
cont.addChild(shape);
trace(shape.width, shape.height); // 100, 100
shape.x = 400;
shape.y = 200;
trace(shape.width, shape.height); // 100, 300

so the formula for "height" becomes:
height = "real graphics height" + x - y

an override in Shape for "get height()" is obvious, but does anyone have any idea why this actually happens?

thanks for any insights

#lineStyle does not produce expected colour

I'm using the following snippet to create squares with rounded corners and a stroke of a given colour...

var shape:Shape = new Shape();
shape.graphics.lineStyle(2, 0x0084b5);
shape.graphics.beginFill(0xffffff);
shape.graphics.drawRoundRectComplex(0, 0, width, height, radiuses[0], radiuses[1], radiuses[2], radiuses[3]);
shape.graphics.endFill();

However, the resulting stroke is not the colour I expected. Instead of 0x0084b5 it is 0x134680.

If I create the stroke from a texture I get the correct colour...

var lineTexture:Texture = Texture.fromColor(1, 1, 0xff0084b5);
shape.graphics.lineTexture(2, lineTexture);

lineStyle

Setting alpha property on a Shape doesn't seem to work

If you create a simple shape such as :

shape.graphics.beginFill(fillColor, fillAlpha);
shape.graphics.lineStyle(strokeThickness, strokeColor, strokeAlpha);
shape.graphics.drawCircle(0,0,25);
shape.graphics.endFill();

and then set
shape.alpha = .2;

alpha is not taken in account.

Is this expected? or a bug?

textfield not show when add shape on displaylist

code from GraphicsAPIExample.as and i add a textfield at the bottom:

        var rockTexture:Texture = Texture.fromBitmap( new RockBMP(), false );
        var grassTexture:Texture = Texture.fromBitmap( new GrassBMP(), false );

        shape.graphics.beginTextureFill(rockTexture, m);
        shape.graphics.lineTexture(20, grassTexture);
        shape.graphics.drawRect(top, left, right, bottom);
        shape.graphics.endFill();

        var txt:TextField = new TextField(50, 50, "hello");
        addChild(txt);

Performance of Stroke createPolyLine

From what I gather in the Roadmap section of this project, speed improvements are desired.

I have no mobile platform to test on, but I believe I have found some pretty good performance improvements in Stroke createPolyLine...

By pre-allocating the arrays we pass into the method in buildGeometry, significant speed ups can be achieved on my PC at least.

The speed improvement can be illustrated by this screenshot. after running 4 separate runs of 20 passes over the same, very long, stroke ( 25000 StrokeVertexes, generating 450000 vertices). The top two lines indicate the time spent through the pre-allocated buffers ( 1300 ms ) and the bottom two indicate the time spent through the default non-preallocated version of the code ( 2148 ms)

performancegaincreatepolyline

I will submit the code as "createPolyLinePreAlloc" and include a commented out section of how buildGeometry should look if we use the preAlloc version.

Any plan to expose the Material of a shape Graphics ?

Basically in case we want to create custom graphics optimized routine using custom shaders, would be nice to architect the Shape so we can easily swap for another Graphics implementation somehow so as developers we are not limited to the shaders and features you expose into Graphics.

I believe today one solution would be to extend Shape or create our own type of Shape which would use an extended version of Graphics.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.