Drawing smooth lines with cocos2d
You’ve probably seen Paper by http://www.fiftythree.com/, the app is pretty cool and the drawings look really nice and smooth. I’m working on my personal app that needs something similar, and after doing some research I’ve seen that there isn’t really anything like that available, some people try to use catmull roms etc. but that doesn’t look good enough. I will show you how you can achieve pretty cool drawing app.
If you play with first Paper tool, you will notice few key points that we need to duplicate:
- Even if you draw fast, the lines will be bend by some kind of splines.
- Lines width is depended on the speed of touches.
- Lines are very smooth, no hard edges are visible.
I will explain my solution in a few steps that allow you to go from this: to this:
Look at the images in full resolution to really see how big the difference is…
Let’s get to work.
Connecting the dots
To draw anything we first need to collect touches positions for drawing. I’ve used UIPanGestureRecognizer to collect them, to have them working with cocos2d I just included my category. After you have some points we need to render them, and since we will be needing line segments that can start at arbitrary width and end at totally different one, we need to make our own rendering. To render the lines with variable width at both ends of a single line segment we need to draw them by using triangles, this is how we can do that:
As you can see here:
- p0, p1 are the line segment begin / end points.
- perp is perpendicular to segment direction ( -y, x of direction ), if we normalize it we can use it to create ABCD coordinates, simply by multiplying it by our desired width and either adding or subtracting from our base points p0, p1
- ABC, BCD will be our triangles.
- both line start and end can have arbitrary width.
We need to calculate ABCD coordinates, we have p0, p1 and start width and end width. In code we do this as follows:
1 2 3 4 5 6
- Calculate direction from p0 ( prevPoint ) to p1 ( curPoint )
- Calculate perpendicular vector and normalize it.
- Use perpendicular multiplied by line width to get coordinates for ABCD.
- prevValue / curValue are the widths of line segment start / end points.
Then you go through all the points you have and calculate each line segment.
But there is something more you need to do, if you would just calculate each of this vertices per segment, you would end up with disconnected segments:
We don’t want that. To make it work let’s make each line C, D vertices the A, B vertices of the next segment, that way we will have proper connection’s between segments, generating full line.
1 2 3 4
Since we will need to store position and size in each point, we introduce new class for that:
1 2 3 4
Since the user can draw as many lines as he want and they can be of arbitrary length, if we would draw them in each frame that would very quickly become performance problem. There is a simple solution for that i.e. draw each line segment we get into a texture, that way it doesn’t really matter how many lines user draws or how long they will be. At this point we would just get straight lines connecting our points:
Nothing impressive, but this is just the first step…
Calculating width based on speed of panning
We need to have slim lines when the user is panning slowly and fat lines if he is moving very quickly, we can use UIPanGestureRecognizer velocityInView: method to recognize that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
- We calculate length of velocity vector, then we adjust the value to fit between 1 and 40 pixels.
- By weighting new velocity value we will make nicer transition between sizes, instead of jumpy ones…
Remember that this function was result of trial & error, so feel free and play around with it if you wan’t…
Bending the lines
Research in the internet would suggest to use Catmull-rom algorithm for drawing smooth lines that we want. This splines are one of few splines that go through all control points you specify, it’s really good algorithm for some cases e.g. interpolating Camera position for cutscenes. But for drawing I don’t believe that to be best solution because for me it has 2 major caveats:
- You need to simplify point’s list, so that points are not too close to each other or the algorithm won’t really yield good results.
- This algorithm works nice if you have a final set of control points, in case of drawing app you don’t have that, points will be added after user moves his finger, and we need to draw new lines immediately.
So contrary to what you can find in google, I decided to not use Catmull-rom for drawing app…
Quad curves require 3 points to calculate, we will be using our original touch points as control points and the start / end coordinates will be calculated as the point in the middle between our control points:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
- We need at least 3 points to use quad curves.
- Each time we need our current point and 2 previous ones.
- Calculate our middle points between touch points.
- Calculate number of segments, for each 2 pixels there will be one extra segment, minimum of 32 segments and maximum of 128. If 2 mid points would be 100 pixels apart we would have 50 segments, we need to make sure we have at least 32 segments or the bending will look aliased…
- Calculate our interpolation t increase based on the number of segments.
- Calculate our new points by using quad curve equation. Also use same interpolation for line width.
- Add final point connecting to our end point
- Since we will be drawing right after this function, we don’t need old points except the last 2. That way each time user moves his finger we can draw next segment.
Now we use this smoothed points for drawing, exactly as we did with the old ones… At this point the app generates something like this:
It start’s to look interesting, the lines are bending pretty nice ( we could play around with number of segments we used to smooth our lines to get even more quality ). There is quite a bit of aliasing visible here that doesn’t look nice, and also the start / end point of line don’t look nice…
Aliasing is pretty common problem in computer graphics, usually you could just use hardware Multisampling, cocos also supports that ( just set proper flags in CCGLView creation ). But this is overkill for our drawing, if we would enable multisampling here, not only we would get performance hit but that way we would also make rest of the app use multisampling… There is a lot simpler solution… Aliasing is so visible because we go from full color straight to an empty one ( black to white ) in an instant. So let’s not do that, let’s make the color linearly interpolate from full color to an empty one. We just need to modify alpha value from 1 to 0 over some range of pixels and hardware blending will do the rest for us… Let’s create additional triangles at the edges of our line and modify alpha there:
1 2 3 4
So we just expand even further from our fat line by the amount of overdraw we want, this vertices will have alpha value = 0 so that linear interpolation occur. Then from this vertices we generate 4 overdraw triangles: FAG, AGC, BHD, HDI Since lines can be drawn over each other, we need to make sure our overdraw doesn’t render over full lines, or we would get artifacts… To get correct blending between overdraw / full lines I decided to use GL_ONE, GL_ONE_MINUS_SRC_ALPHA, use pre-multiplied blending (read why it’s better to use it here: http://blogs.msdn.com/b/shawnhar/archive/2009/11/06/premultiplied-alpha.aspx ):
Last thing we need to do is make sure our start / end line points are circular and smooth instead of hard cut off. But we can’t draw full circles at end points or the overdraw alpha would add up and it would look weird, instead we will draw just the half circle placed exactly at the last or first point of line. We need to calculate the exact angle we should start our circle fragment from,
As you can see here, we need to figure out what angle of our circle is pointing at C ( Circle is not rotated, it’s just placed at the end point ) , again we can use Perpendicular to line direction to calculate that. I like dot products, so let’s use them to calculate the angle.
1 2 3 4 5 6
As you probably remember from school the value of dot product of normalized vectors is equal to cos angle between them, we will calculate dot product between the perpendicular to line direction and vector (0, 1). Since we also need to take into consideration the direction of our angle, we should also calculate dot product between perpendicular and right vector, then according to that we can modify the angle. When calculating aLineDir make sure that for start of the line you reverse the direction. The final result of our algorithm should look like this:
Download project from GitHub.At this point we have a really nice drawing application. I decided to share my solution because I couldn’t find a complete one shared by anyone else… I’m sure it could be improved even more I just don’t have more time to spend on it and I’m pretty pleased with how it works right now, if you manage to improve any parts or find any bug make sure you will send me a pull request on GitHub. I hope you liked it!
I’m merowing_ on twitter if you feel like talking about it.