## Quadratic Arc Decorators for Freehand Drawing Library

I just finished the first cut at the quadratic arc decorators for the Freehand Drawing Library. Previously, only solid arcs could be drawn. The example below shows dashed- and dotted-line decoration applied to arrowed arcs.

The decorators all share a fast, on-the-fly arc-length parameterization utility. I still have a few tweaks to make to one of the decorators before full production release, but the new library is going out to all beta users this morning.

Based on feedback, I’m going to add one more stroke (Polygonal) and two spline-based drawing engines to the full release. Because of this new addition, I’m seeking a couple more beta users. If your drawing requirements could benefit from a variety of splines, including splines that auto-convert to shapes (i.e. lines and quads) for creating dynamic outlines/fills, please e-mail me for more information on entering the beta program.

The beta includes full source code and there is a small, 3-figure license fee. All beta users get FREE upgrades for life. Email is theAlgorithmist [at] gmail [dot] com. Thanks!

## Graphing Non-Functions

My current gig is winding down, so this will probably be the last update on the function graphing engine for a while. Although the function graphing engine is architected to graph cartesian or parameteric functions, only cartesian functions were supported in the initial release. All functions defined in XML must implement an IPlottable interface, which means that evaluation and derivative methods are interpreted with y as a strict function of x. All functions must be marked as cartesian, since a parametric function will not plot in the initial implementation.

What about non-functions, that is cases where y is not strictly a function of x? As the saying goes, there is always a back door. Functions may identify themselves as self-plotting. In this case, the engine does not sample the function. Instead, it provides the function with all the relevant information regarding the current graph window and calls the function’s *plot()* method. A self-plotting function is welcome to draw anything it pleases, including Bezier curves, conic sections, spirals, or even smiley faces 🙂

Problems may arise with derived functions, however, i.e. other functions that derive their visual display from the definition of another function. A graphical Marker function is a perfect example. The Marker is an artist-generated, interactive graphic asset that is constrained to the path of another function. If domain values exist for which there is not a unique range value, then Marker movement is unpredictable.

This example shows how to work around the non-function issue to a degree. It plots parabolas that open upward, downward, and to the left or right. More specifically, the parabola directrix is either parallel to the x or y axis. Parallel to the x-axis is good. Parallel to the y-axis causes problems.

Suppose we want a Marker constrained to the parabola along with a display of the tangent and normal, as well as the directrix. The fixed distance from the point on the parabola to the directrix and axis of symmetry is also drawn.

Of the four use cases, the Marker follows y as a function of x in two and x as a function of y in the other two. We can’t use the function graphing engine to manage the Marker display as it always calls the base function (parabola) *eval()* method with an input x-coordinate. The derivative and normal displays won’t work in two cases because *dy/dx* is not uniquely defined.

In general, the equation of a parabola with vertex *(h,k)*, focus *(h,k+p)*, and directrix *y=k-p* is given by

*(x-h) ^{2} = 4p(y-k)*

which allows y to be defined as a function of x, or x as a function of y. There are really only two use cases requiring consideration, directrix parallel to the y-axis and directrix parallel to the x-axis. In one case, horizontal mouse movement is used to position the Marker. Vertical mouse movements control the Marker in the other case.

The custom Marker is composed directly into the custom Parabola function, which is marked as self-plotting. This function is responsible for creating the Marker and controlling its placement as well as drawing all supporting graphics.

The Parabola function is defined in XML as

<function id=”Parabola” class=”graph.tests.Parabola” params=”h:0,k:0,p:-1,parallelTo:y”>

<lineMetrics thickness=”2″ color=”0xff0000″ />

<data markerParams=”marker:graph.symbols.CustomMarkerSymbol,rolloverColor:0x9ACD32,digits:2″

markerCoord=”1″ >

<directrix thickness=”3″ color=”0x9933CC” alpha=”1″ lineStyle=”line_dashed” dashWidth=”6″ dashSpacing=”4″ />

<lineSet1 thickness=”2″ color=”0x0000ff” />

<lineSet2 thickness=”1″ color=”0x00ff00″ alpha=”0.5″/>

</data>

</function>

and the display is shown below.

The aspect ratio of this graph is not ideal for the example, but it’s adequate for illustrating the example. Note that the custom Parabola function is welcome to plot not only the parabola, but as many supporting graphics as it likes. The custom Marker may be dragged along the boundaries of the parabola and rollover displays the current y-coordinate by default.

A simple parameter change, h:0,k:0,p:1,parallelTo:y, causes the parabola to open to the right.

Parametric function graphing should be supported in the future, providing for a more clean and general-purpose means to plot any general parabola and supporting visuals. I thought this was an interesting example of how a decent architecture and simple concepts like Composition open up possibilities that do not seem possible based on the defined constraints of an engine.

Next post will be an update on new capability in the Freehand Drawing Library.

## Graphing Freeform Functions And Derivative

I’m currently working on an interactive set of unit tests for the function graphing engine I wrote over three years ago. We’ve made some hasty modifications to the engine over the last six months and only tested the mods within the actual learning applications. The engine is now sufficiently complex that I’m worried about making changes in one area that have undesired consequences in another area.

This unit test engine allows any number of specific graph tests to be coded to an IGraphTest interface and added in XML. The ComboBoxes for selecting graph tests and functions inside those tests are auto-populated based on XML data.

One of my favorite features of the graph engine (and the least tested) is freeform function input. In the past, freeform functions and parameter values were defined completely in XML, i.e.

<function id=”freeForm1″ class=”graphing.functions.library.**FreeForm**” **params**=”1,-1,2,1″>

<**data** vars=”a,b,c,d,x” function=”a*x + b*x^2 – 3*sin(c*x) + d*x^3″ />

<lineMetrics thickness=”2″ color=”0xff0000″ />

</function>

The *data* node defines parameters *a*, *b*, *c*, and *d* that may take on any real value. The independent variable is *x*. The *params* attribute in the *function* node defines the actual parameter values. Function parsing is handled by an independent class that may be used in any other application, independent of the graphing engine.

That’s all well and good, but I wanted to test the ability to define functions and parameters programmatically, specifically typing a function into an input text field. In this test, the XML looks like

<learningObject id=”testGraph” class=”graphing.functions.FunctionPlot”

x=”25″ y=”60″ width=”350″ height=”280″ display=”freeForm” pannable=”true” >

.

.

.

<function id=”freeForm” class=”graphing.functions.library.FreeForm” >

<lineMetrics thickness=”2″ color=”0xff0000″ />

</function>

<function id=”deriv” class=”graphing.functions.library.Derivative”

derivedFrom=”freeForm”>

<lineMetrics thickness=”2″ color=”0x0000ff”/>

</function>

The graph engine displays an initially undefined function (I had to correct a couple of typos to get that to work). A function is defined in XML (the Derivative) that is derived from that undefined freeform function (yes, two more corrections there).

The function is typed into an input box in the test application. Spinners are used to set parameter values. The code automatically determines the presence of a, b, c, and d parameters and disables spinners for which there are no parameters in the function. That was a little tricky, because of situations where ‘c’ may be used as a parameter or in the function, i.e. *sin(c*x)* vs. *cos(x)*.

Here is a screenshot of a simple example with the first derivative automatically computed from the freeform function definition. Each function is coded to a specific interface and must be able to evaluate itself and its first derivative. Although I’d like to get into symbolic differentiation one day, the current approach is numerical and it uses an adaptive differencing algorithm based on graph scale.

It is, without question, the ugliest demo you will ever see, but its sole purpose is to facilitate rapid unit testing of both new functionality and prior capability that is to be used in new ways.

I’m really liking the freeform graphing now that it can be done purely programmatically and I’ve almost decided to add symbolic differentiation to my bucket list 🙂

## Recent Work on Unit Conversion

My first thought about this project was “boring, but at least it’s a payday.” This application allows students to practice converting across different types of units on actual problems. In terms of interactivity, it’s pretty much dragging rectangular tiles with a numerator and denominator into slots inside a work area. Yes, I’m fading off to sleep as I write 🙂 A screenshot of the basic layout is shown below.

Standard tiles are fixed-width and defined in XML so that the tile set for a conversion category can be easily changed (and it was changed multiple times during development).

<category name="Distance"> <metric> <tile id="Distance0" > <numerator value="1000" useCommas="false">meters</numerator> <denominator value="1" useCommas="false">kilometer</denominator> </tile> . . .

which brings us to the interesting part of the application – the text formatting. I worked within the framework used by this client and all UI text components are based on Flash TextFields. Each numerator and denominator has a value and units. Units are written out as text strings, however, units may have singular, plural, and abbreviated forms. The rules for formatting values are comma-formatted unless otherwise specified and scientific notation is used if the number is outside a pre-specified range. The number of displayed digits in scientific notation is also variable. Powers are handled with a superscript font. I had to test if an exponent was applied in the formatting to vertically adjust text placement.

Unit text is auto-converted to an abbreviation if the text is to wide to fit inside the tile. The XML unit type is the preferred formatting, but only if it fits.

The objective of the lesson is to convert the starting units to the requested units using the minimum number of tiles. No more than three tiles may be dragged into the work area and each problem can be solved using no more than three tiles. Tiles may be flipped, which adjusts the numerator and denominator; however, tiles are restored to their original (XML) form when moved back into the work area. When a tile is released outside the work area, it automatically jumps to the nearest open slot (left-to-right).

As tiles are dragged into position, the program checks if any units cancel. Cancellation must take into account any combination of singular, plural, or abbreviated unit.

This is where it gets fun. The program is supposed to draw a red, diagonal strike-through mark across the unit when cancelation is detected. Again, this has to work for any combination of singular, plural, or abbreviated unit, so the drawing is completely programmatic.

The other interesting text-processing aspect of units is that units must be gathered into like form with a single power in the event there is no cancellation. There are also rules for formatting the answer that vary from the work-area tiles, such as rounding to the nearest 0.001 where the rounding value is arbitrary. An example is shown below.

In the denominator, the singular unit, ‘cubic centimeter’ is combined with the abbreviated unit ‘cm^3’ to create a new unit cm^6. This processing is done by a gathering pass where all units are broken down into a ‘fundamental’ unit and exponent. All like units are gathered and the exponents processed to produce the output.

Currently, there is no cancellation in this step unless there is an exact unit match, i.e. cm in the denominator does not cancel cm^4 in the numerator. The goal is to make it easier for the student to see the unit collections across tiles so that they can quickly decide which tiles to move back to the work area.

The text and dynamic drawing aspects of this project proved to be quite interesting. The next time I think someone is presenting me with a boring project, I’ll know to think again 🙂

## Arrowed Arcs in Freehand Drawing Library

As promised, arrowed (quadratic) arcs are now in the Freehand Drawing Library. They use the same two-point stroke as arrowed lines, but a different drawing engine. Since three points are required to draw a quadratic arc, the free constraint is automatically computed based on a curvature parameter and a multiplier of the segment length between the two endpoints. The curvature parameter controls whether the curve is concave upward or downward and the multiplier controls the overall general curvature (i.e. smaller values produce overall flatter curves).

A screen shot is provided below.

Start and end arrows are optional, so the ArrowedArc engine offers a back-door to creating simple quadratic arcs.

Lines and arcs use the same stroke, i.e.

import net.algorithmist.freehand.twopoint.TwoPoint;

private var __stroke:TwoPoint = new TwoPoint();

Simply inject the desired stroke engine,

__data.drawingEngine = “net.algorithmist.freehand.engine.ArrowedArc”;

__stroke.data = __data;

Then, draw and have fun. I have not yet coded arc decorators, so only solid-line arcs may be drawn with the current beta.

I’ll add one more stroke to the library before RC1 and hopefully blog about it some time next week. Thanks for your inquiries to date!

## Arrowed Lines in Freehand Drawing Library

Drawing lines does not sound very interesting, but in addition to my own app. development, another user expressed a desire for animated arrowed lines. So, a new two-point stroke has been added to the library. The TwoPoint class is the base for a family of classes in which a stroke is defined only by a starting point and the current mouse/touch point.

In keeping with the FDL architecture, an engine is assigned to a two-point stroke. Two engines will be provided in the first release candidate, arrowed lines and arcs. The start and end arrows are optional, so these engines provide a back-door to drawing lines and arcs. Not sexy, but the existing line decorators are applicable, so it’s incredibly easy to draw dotted or dashed lines.

Since the point sequence to a stroke may be simulated in an animation, it’s now very easy to draw animated dashed or solid, arrowed lines. Here is a screen shot from one of the demos.

Injecting a new line decorator is a matter of assigning the fully qualified class name of the decorator,

__data.lineDecorator = “net.algorithmist.freehand.decorators.SolidLine”;

or

__data.lineDecorator = “net.algorithmist.freehand.decorators.DashedLine”;

then, re-assign the stroke’s data provider,

__stroke.data = __data;

There are still a couple beta slots open, so if you are interested in developing a Flex-based application (mobile or otherwise) involving freehand drawing, please contact me at theAlgorithmist [at] gmail [dot] com. There is a small, three-figure license fee that is a one-time cost. Beta users get free upgrades for life!

I’ll be posting a roadmap for the anticipated release cycle shortly, so even if you are not interested in Flex/Actionscript development, say tuned. A subset of the Freehand Drawing Library may be coming for JS or Corona developers.

## Image Painting in Freehand Drawing Library

A bonus project is going out to all Freehand Drawing Library beta users this morning. Currently, the library contains one fixed-width stroke with three drawing engines and three line decorators. One question arose about how to create different strokes and the role of engines within the architecture. I also received a comment about an iPad drawing app. that allowed people to ‘stamp’ or ‘paint’ smooth strokes with images.

Having an artist create any variety of cool images in Flash is a no-brainer. The question is how to stamp that image repeatedly along a smooth stroke. The answer provides a perfect illustration of stroke creation in the Freehand Drawing Library. A stroke is designed based on certain desired characteristics, in this case the ability to distribute images along a smooth path. A stroke engine (that implements IDrawingEngine) is created to match the general characteristics of a stroke. Not all engines are compatible with all strokes, and that’s fine.

A StampedStroke class (implementing IFreehandDrawable, so it can be used in a Factory) was developed for the desired purpose. A single engine, Stamp, computes the same smoothed stroke coordinates as the SmoothedStroke engine. Since nothing is drawn into any graphics context, the concept of line decorators does not apply. The stroke engine directly instantiates the image symbol and adds it to the display list.

The Stamp engine accepts a single engine parameter, ‘imagestamp’, which is the reference to the symbol created in Flash and exported with a base class that extends MovieClip. Using the stroke is as simple as instantiation,

private var __stroke:StampedStroke = new StampedStroke();

private var __data:StrokeDataVO = new StrokeDataVO();

Make sure the stroke engine and symbol are compiled into the SWF,

import net.algorithmist.freehand.StampedStroke;

import net.algorithmist.freehand.symbols.Starburst;

private static const STAMP_ENGINE:Class = Stamp;

private static const STAR_CLASS:Class = Starburst;

Then, inject stroke engine and assign engine parameters,

__data.drawingEngine = “net.algorithmist.freehand.engine.Stamp”;

__data.engineParams = {imagestamp:”net.algorithmist.freehand.symbols.Starburst”};

Assign the data provider for the stroke,

__stroke.data = __data;

Draw, and have fun. The Stamp engine contains a back door to animating the stroke while it’s being drawn. I may create an online example since it’s pretty cool 🙂

The library is currently in the final beta phase before RC1. Because of all the new capability, I’ve opened up several beta slots. There is a small, three-figure license fee, which is a one-time cost. All beta testers get free upgrades for life!

Please contact me at theAlgorithmist [at] gmail [dot] com if interested.