Sunday, 29 November 2009

Overriding equals(Object): an optimally correct solution

Overriding Object's apparently innocuous equals(Object) method can be a source of difficulties. The first problem is that there appears to be no single implementation that meets all requirements. The second problem is the way that HashMap, the prime suspect for causing errors if the letter of the equals() specification is not met, uses equality to maintain its structure.

When equals() is overridden the initial requirement is to ensure that the Object in equals(Object) belongs to a class that is comparable with the current object. Two different implementations can be found in publications from authorities on the subject. They have some utility but both cause problems if implemented outside their limited applicable usage. Neither can provide a correct implementation of equals() for all inheritance requirements in a class hierarchy. A third published implementation can supply an equals() with correct behaviour in the two most commonly required cases but brings a considerable execution overhead when equals() is overridden in a subclass.

A simple equals() configuration is described that allows a class to have any of the three possible equality relationships with its super classes. For the two most commonly required relationships modifying the standard equals() implementation found in Java library classes to provide correct behaviour is trivial, simply a matter of factoring-off field comparisons to a separate method. Overriding equals() in a subclass is similarly trivial. If no modification to equality is required the new class can be derived without any additional coding related to equals() functionality. The approach brings almost no penalty for execution efficiency and additional coding is minimal.


Background


Overriding equals() allows a different view of object equality from Object's same-object implementation to be introduced. Used with hashCode(), equals() also provides the basis for object inclusion, exclusion and retrieval from a HashMap, a fast storage and retrieval structure appropriate for many applications.

Making an overridden equals() work according to plan brings two requirements: a well defined set of objects that the new method applies to and compliance with the so called equals() contract - in fact a definition of the required equality relationship between all objects. Its requirements are reflexivity, symmetry, transitivity, consistency and that a comparison with a null should always return false. These properties define an equality relationship found generally in most applications outside of quantum mechanics and we are on fairly safe ground.

An exceptionally lucid expose of the equals() contract and discussion of problems with published equals() implementations can be found at

http://www.angelikalanger.com/Articles/JavaSolutions/SecretsOfEquals/Equals.html


The problem identified

The equals() problem occurs anywhere we want to derive a subclass that has a concrete superclass other than Object, for which equals() has already been overridden and add some fields that are significant when computing subclass equality.

Figure 1 A moot choice

As shown in Figure 1 - ClassA, we would probably like to inherit from an existing class getting all its methods and functionality without writing any code, taking advantage of normal OOP provision for code reuse. The requirement to override equals() may prevent this course because the standard equals() implementation found in many Java library classes does not work in this situation.

To get a better understanding of the problem we can formalize this requirement of an object model that makes object equality other than basic identity a property of all objects as:

The first code reuse requirement: ability to derive a class that declares zero or more new significant fields and is not a member of its superclass comparison set.

It is apparent there are four possible requirements and this statement covers two of them. The remaining two are:

Second code reuse requirement: ability to derive a class that declares no new significant fields and is a member of its superclass comparison set.

Third code reuse requirement: ability to derive a class that declares new significant fields and is a member of its superclass comparison set.

We now need a definition for comparison set.


A comparison-set model

A comparison set is a set of classes having a root class for which instances of the root and some but possibly not all of its subclasses are compared for equality using significant fields declared or present in the root. For completeness we must also say that significant fields declared in a subclass may also figure in a comparison but this is an unusual condition satisfying the third code reuse requirement. When an object is compared with an object of a class not in its comparison set equals() is unable to make a meaningful comparison and must always return false.

Figure 2 sketches a class hierarchy with classes in a comparison set coloured green. Other classes are not in the green set and supply a potential root for other comparison sets.

Figure 2 A comparison set

A class that is a descendant of Object and does not override equals() is in a comparison set with Object as its root. The particular contract of Object's equals() - no two objects are equal, makes the standard implementation viable for overriding equals() in a direct subclass, A in Figure 2, but not in a sub classes B & C of a class in a derived comparison set. The standard implementation meets the first code reuse requirement in a class with no superclasses that have used it to override equals(), elsewhere it fails.

The Figure illustrates two important properties of comparison sets. Firstly, all classes in the set are descendants of a single root. The equals() implemented in the root must include a condition that determines whether the argument in equals(Object) is a member of the set of comparable objects for which a field comparison should be done or whether it is of another kind for which equals() should return false.


The 'standard' equals() implementation

The standard implementation employs instanceof the-root to exclude objects not in the comparison set. The instanceof statement can appear in a number of different guises, as illustrated using a class that declares a value field with an overloaded == operator:
    @Override public boolean equals(Object obj) {
        return obj instanceof Root &&
            value == ((Root) obj).value;
    }

    @Override public boolean equals(Object obj) {
        if (obj instanceof Root) {
            return (value == ((Root) obj).value);
        }
        return false;
    }

    @Override public boolean equals(Object obj) {
        if (this == obj) return true;
        if (! (obj instanceof Root)) return false;
        return (value == ((Root) obj).value);
    }
All configurations exclude instances of any class that is not a descendant of Root from field comparison and return false. The same-object check shown in the third configuration is of course optional and can be used in any implementation.

Which brings us to the second property of comparison sets and the problem with the standard equals() implementation: not all classes that are descendants of the Root are members of the same comparison set. The instanceof condition succeeds for instances of all subclasses irrespective of new fields. A superclass object can be found equal to a subclass object if fields declared in the superclass are equal to inherited fields in the subclass. Presenting the same superclass object to an overridden equals() in the subclass its instanceof will reject the superclass object and return false.
    @Override public boolean equals(Object obj) {
        if (obj instanceof Subclass) {
            Subclass sco = (Subclass) obj;
            return ( .......... );
        }
        return false;
    }
The symmetry requirement of object equality is broken and in the first case no proper equality assessment has been done making the result a nonsense.

There are of course occasions when we want to derive a class from a superclass without overriding equals(): the second code reuse requirement. A subclass might introduce a next field for example, a reference to an instance of the subclass so that a linked list of objects can be constructed. The standard implementation meets the second requirement. It fails when presented with a subclass instance that uses new fields to check equality and is not in the comparison set. It does not enable us to implement ClassA in Figure 1. Can an additional or modified condition be introduced to exclude instances of these classes from field comparison?


equals() using class comparison


Another commonly seen equals() implementation compares the runtime Class reference of the two objects to determine comparison set membership:
obj != null && obj.getClass == this.getClass
replaces obj instanceof Root in the condition. It could be used to derive Figure 1 - ClassA if used in the existing and new classes but does not allow any further subclasses that belong to one or other comparison set to be derived. All objects that are not of the same class are excluded and equals() returns false for these objects.

This means that superclass objects are excluded from subclass superclass comparisons and get a false return. If anything this characteristic is more dangerous in use than the instanceof problem. When equals() is not overridden in a subclass its functionality is modified by proxy to get a constant false return for superclass objects. A person who derives the subclass and has not modified equals() may be left unaware of this side effect until the application fails at a later time. A class comparison equals() implementation meets the first code reuse requirement. It cannot meet the second.


The third code reuse requirement


Not surprisingly, overriding equals() from a concrete superclass is seldom seen in Java code but there is one pertinent and frequently quoted example: java.sql.Timestamp. This class is a java.util.Date subclass that overrides equals to include a nanos field. Comparing a Date with a Timestamp returns true if the dates match irrespective of the value of nanos. Comparing a Timestamp with a Date always returns false even with matching dates: 'because the nanos component of a date is unknown.'

If equals() was overridden in both classes using the implementation proposed here there would be an open choice as to whether to make both comparisons return false or to allow a Timestamp to be equal to a Date if and only if its nanos field was zero (or any other single value). The methodology also allows a Timestamp to have symmetrical equality with a Date if dates match or if a Timestamp is within 500,000 nanos of a Date but these options break the equals() specification requirement for transitivity while the zero nanos option does not.

Here the valid option where a Timestamp with a zero nanos field may be equal to a Date supplies an example of a third possible equality relationship between a sub and superclass and the third if seldom needed code reuse requirement.


Alternatives to the standard implementation

An alternative to producing a flawed equals() in a subclass using the standard or class comparison implementations is to use composition, as illustrated by Figure 1 - ClassB. Using composition to implement structural elements of a program or even a data type where it fits well is one thing. Being forced to use it to implement equals() is something else. Do this and we can be faced with another set of no-win choices: write a lot of methods that do nothing except call composed object methods or include a method that returns the composed object - a possible solution if the object is immutable, otherwise doing this is likely to cause more problems that it solves. There may still be a problem even when the returned object is a clone - the clone does not reflect legitimate modifications to the original.

The standard equals() implementation used in library classes leaves no satisfactory alternative to composition when equals() is overridden but otherwise it is not a desirable alternative.

Taking on board the fact that neither of the commonly used implementations work satisfactorily an artima article posts a working solution for overriding equals() to get two of the code reuse requirements identified above:

http://www.artima.com/lejava/articles/equality.html

The third code reuse requirement is seldom needed and is therefore relatively unimportant but a problem with this implementation is that it uses a canEqual(Object) method that introduces an additional instanceof check and execution overhead for all calls to equals() even when comparing same-class objects. Consequently it cannot be seen as an optimal replacement for the standard implementation that can be put in place as a matter of course to allow subclasses to be derived at a later time.

Another downside is that the basic cost of a call doubles for an overridden equals in a subclass: super equals() is called to get superclass field comparison involving a second call to canEqual() and duplicate instanceof tests. The primary indication for using hashed storage is to provide fast access making this implementation not ideal for specific use even when the requirement to override equals() is known in advance.

The artima article shows a way forward and that a solution is possible but additional requirements to be addressed here are to devise an equals() implementation with a minimal code footprint and execution overhead that can be used as a matter of course in any class that overrides equals(). The implementation must allow fully working subclasses to be derived in all three cases where they may be required to meet OOP standards for code reuse.

We have now identified the requirements that an optimal equals() implementation must meet and can assess how the proposed alternative stands up.


Devising a solution

Figure 3 shows an inheritance structure containing four comparison sets.

Figure 3 Green, red, yellow and blue comparison sets

Here we consider a base class that is a concrete subclass of Object. Using an abstract base has only minor implications and then only if it declares significant fields. The simplest possible class will supply examples: one with a single integer field is used. The number of fields or even a complete audit of the current state of a data structure as used by HashMap has no bearing on the problem. This class is called GreenBase in the diagram and is the root of a green comparison set.

With the exception of ZGreen, GreenBase descendants in the green comparison set do not override equals(). They introduce no new fields that figure in comparison and are comparable using the equals() inherited from GreenBase. They can of course introduce other fields, the one on the left could be a LinkedGreen with a field referencing the next object in a list.

Implementing these classes requires that the equals() implementation satisfies the second requirement for code reuse: ability to derive a class that declares no new significant fields and is a member of its superclass comparison set. From the Figure we can see that there is a secondary requirement - that the condition used to determine comparison set membership should include all possible descendants of the base on all branches.

The standard implementation satisfies both these requirements using instanceof the-base but now we come to the apparently conflicting code reuse requirement: ability to derive a class that declares zero or more new significant fields and is not a member of its superclass comparison set. The equals() in GreenBase inherited by green subclasses can do an initial assessment for comparison set membership using instanceof or some similar isA condition but if it is going to make provision for derived comparison sets it must exclude instances of RedBase, YellowBase and BlueBase that supply the base class for new sets. All these classes are also GreenBase subclasses and instances will pass the initial assessment.

This problem raised the question as to what additional isA or class comparison check could be put in equals() to exclude instances on the same or a different branch from the root. After some thought and deciphering of the contracts of various Class methods it was decided that there wasn't one. We could perhaps give all comparable objects an additional property, say Class comparisonBase() or a similar final field, but doing this adds additional coding and additional logic in equals().

Otherwise only the received object can do the necessary checks but it was also found that when the decision on membership was passed to that object checking ancestry was no longer a requirement. The same is true when the received object's class has the third equality relationship, ZGreen in Figure 3, but as discussed below an additional isA check is then required.

The following sections assess how this implementation fairs with regard to the criteria for minimum code size and effect on execution efficiency over the standard implementation.


Minimizing the code footprint

The requirement here was to develop an implementation that was altogether trivial to code and required a minimum of extra coding over the standard equals(). GreenBase supplies a standard where differences are not overwhelmed by other code when the two implementations are shown side by side:


Excluding braces from the calculation the difference amounts to the two extra lines of code used by the fEquals(GreenBase) method. The field comparison method can have any name even equals(GreenBase) but it is suggested that standardizing the name to fEquals will facilitate use of this implementation and that fEquals should be overloaded when equals() is overridden in descendants to maintain consistency in use.

The extra coding is nothing compared with the complication of using composition to get a subclass equivalent and the chore of writing many do-nothing methods in a real life situation.


Minimizing the overhead

In GreenBase the equals() implementation introduces the smallest possible overhead above the standard, only the cost of calling fEquals(). The initial task is to exclude equals(Object) arguments that are instances of any class not a GreenBase or a subclass. The instanceof operator includes a check that the argument is not null and provides an economical solution:
public class GreenBase
{
    private final  int value;

    public GreenBase(int value) {
        this.value = value;
    }

    public int getValue() {
         return value;
    }

    @Override public boolean equals(Object obj) {
        return obj instanceof GreenBase &&
                ((GreenBase) obj).fEquals(this);
    }

    protected boolean fEquals(GreenBase obj) {
         return  ( value == obj.value );
    }

    @Override public int hashCode() {
        return 21 + value;
    }

}
Having determined that the equals(Object) argument is a GreenBase or a subclass and therefore a type that has an fEquals(GreenBase) method the next step is to call the argument's version passing a reference to the current object. This call is the only addition to the overhead for an implementation with field comparison done inline.

The decision on equality is passed to the received object. It is already known that the object is a GreenBase or a subclass. If the object's class is a member of the same comparison set it will have the same version of fEquals(GreenBase), which does the field comparison and returns the result, otherwise an overridden version simply returns false.


Deriving a new comparison set

RedBase introduces a new significant field, is not comparable with a GreenBase or instances of any green subclass and forms the root of the red comparison set:
public class RedBase extends GreenBase
{
    private final  long x;

    public RedBase(int value, long x) {
        super (value);
        this.x = x;
    }

    public long getX() {
         return x;
    }

    @Override public boolean equals(Object obj) {
        return obj instanceof RedBase &&
            ((RedBase) obj).fEquals(this);
    }

    protected boolean fEquals(RedBase obj) {
        return (x == obj.x && super.fEquals(obj));
    }

    @Override protected boolean fEquals(GreenBase obj) {
        return false;
    }

    @Override public int hashCode() {
        return super.hashCode() * 31 + (int) (x ^ (x >>> 32));
    }

}
RedBase overrides equals() with a new instanceof condition excluding instances of GreenBase and its other subclasses and calls a new fEquals(RedBase) overloading of the field comparison method on the received object. fEquals(GreenBase) is overridden to return false.

When a RedBase equals() receives a GreenBase or an instance of any of its other subclasses, including those that may have override equals(), the instanceof RedBase condition fails and false is returned. When the equals() in a GreenBase or another subclass is passed a RedBase either its overriden instanceof fails − it is a member of another derived comaprison set, or it is a member of the GreenBase comparison set and calls the object's overridden version of fEquals(GreenBase). Either case gets a symmetric false result for the two comparisons − exactly what is required.

Implementing classes that form the root of the other two comparison sets shown in Figure 3 follows the same pattern. BlueBase for example, inherits RedBase's constant false fEquals(GreenBase). It will override fEquals(RedBase) to return a constant false and implement a new fEquals overloading to deal with objects in the blue comparison set.

The logic is completely straightforward, but now we move on to implementing the unusual equality relationship where a class declares a new field that is used for comparison with instances of the same class and its subclasses but comparison with a superclass and other subclasses in the comparison set is permitted.


Equality of the third kind

ZGreen introduces a z field that is significant for equality. Comparison with instances of GreenBase and all other classes in the green comparison set is allowed.

The only circumstance where doing this makes any sense is if GreenBase is seen as supplying some kind of default z. If z is a string the default might be "" or null. If it is an integer it could be zero but the default can be any value from the range, yes even 42 is a possible candidate for an integer default. No approximate or wildcard value is permitted for the default or transitivity will no longer apply.

A default of zero seems to make a little sense so ZGreen is implemented with an integer z field and all other objects in the green comparison set are seen as having z == 0:
public class ZGreen extends GreenBase
{
   private final  int z;

    public ZGreen(int value, int z) {
        super (value);
        this.z = z;
    }

    public int getZ() {
         return z;
    }


    @Override public boolean equals(Object obj) {
        if (obj instanceof GreenBase) {
            if (obj instanceof ZGreen)
                return ((ZGreen) obj).fEquals(this);
            return (z == 0 && ((GreenBase) obj).fEquals(this));
        }
        return false;
    }

    protected boolean fEquals(ZGreen obj) {
        return (z == obj.z && super.fEquals(obj));
    }

    @Override protected boolean fEquals(GreenBase obj) {
        return z == 0 && super.fEquals(obj);
    }
}
In GreenBase the first instanceof condition admits objects that are GreenBase or a subclass and false is returned for any other object. Here a second grouping of the comparison set is made to include instances of ZGreen and its subclasses using a second instanceof comparison. Other objects that may or may not belong to the green comparison set are treated separately.

ZGreen arguments are dealt with by calling the object's fEquals(ZGreen). For other types, a check for the default z value is made and if this succeeds the object's fEquals(GreenBase) is called. The local fEquals(GreenBase) is overridden to deal with direct calls from other objects in the comparison set when their equals() receives a ZGreen argument. Other GreenBase subclass objects will not be calling fEquals(GreenBase) because a ZGreen will fail their initial instanceof condition.

hashCode() is not overridden - the inherited version returns a value based on the inherited value field so that GreenBase and ZGreen objects with a matching value both have the same hashcode.


Implementing an isA comparison


In ZGreen the second instanceof comparison includes a redundant check that the Object argument is not null. It can be eliminated by substituting an isA comparison using the Class method isInstance(Object).
    @Override public boolean equals(Object obj) {
        if (obj instanceof GreenBase) {

            // if obj isA ZGreen
            if (ZGreen.class.isInstance(obj))
                return ((ZGreen) obj).fEquals(this);
            return (z == 0 && ((GreenBase) obj).fEquals(this));
        }
        return false;
    }
Interpreting the meaning of Class' isInstance() method is quite brain numbing. One trick is to correct the English in your head to what it actually means - 'obj.getClass().hasInstance(this)' for example. Another trick is to read the statement right to left: this isInstance obj.getClass(). Failing these you can put your own isA() method in the base class - the only con is execution efficiency:
public boolean isA(Object obj) {
        if (obj == null) return false;      // optional check here - may be better done by caller
        return obj.getClass().isInstance(this);
    }
Summary

The equals() implementation shown here produces a correct comparison that complies with the equals() meta-contract for all of the three possible equality relationships that a subclass can have with a superclass. Analysis using the comparison-set model demonstrates that there are only three such relationships that equals() needs to support.

It is suggested that any additional overhead from calling a factored-off field comparison method is insignificant in most cases and that the ability to produce subclasses with a fully functional overridden equals(), allowing OOP code reuse without employing composition indicates that this implementation should be used as a matter of course when coding any class that overrides equals().

There are other related topics that may be addressed in a later posting: using an abstract superclass, the HashMap put(K, V) gotcha and implications of the Liskov Substitution Principle. Currently all that needs to be said on the LSP is that the second Liskov and Wing paper excludes relationships between objects from general discussion but groups this aspect with other 'safety properties (nothing bad happens)'. Certainly the LSP does not appear to address anything beyond Object's view of equality. It is down to us to make sure 'nothing bad happens' when equals() is overridden but it will certainly help if the implementation used works in the first place.

Barbara Liskov, Jeannette M Wing - A Behavioral Notion of Subtyping - ACM 1994

Test listing:
public class TestEquals {

    public static void eqPrint(Object a, Object b) {
        String ac = a.getClass().getCanonicalName();
        if (ac == null) ac = "?"; else ac = 
            ac.substring(ac.indexOf('.') + 1);
        String bc = b.getClass().getCanonicalName();
        if (bc == null) bc = "?"; else bc = 
            bc.substring(bc.indexOf('.') + 1);
        System.out.println(ac + " a equals() " + bc + " b: " +
            a.equals(b));
        System.out.println(bc + " b equals() " + ac + " a: " + 
            b.equals(a));
        System.out.println("Hashcodes are equal: " +
                              (a.hashCode() == b.hashCode()));
    }
    public static void nl() {System.out.println();}
    public static void main(String[] args) {
        Object a = new GreenBase(42);
        eqPrint(a, "");                     // false - false
        eqPrint(a, new GreenBase(42));      // true  - true
        eqPrint(a, new GreenSubA(42));      // true  - true
        eqPrint(a, new GreenSubA(41));      // false - false
        Object b = new GreenBase(42) {
            String s = "local class";
        };
        eqPrint(a, b);                      // true  - true
        nl();
        a = new GreenSubA(42);
        eqPrint(a, new GreenSubA(42));      // true - true
        eqPrint(a, new GreenSubB(42));      // true - true
        nl();
        a = new RedBase(42, 7);
        eqPrint(a, new RedBase(42, 7));     // true  - true
        eqPrint(a, new RedBase(41, 7));     // false - false
        eqPrint(a, new GreenBase(42));      // false - false
        eqPrint(a, new GreenSubA(42));      // false - false
        nl();
        a = new ZGreen(42, 0);
        eqPrint(a, new GreenBase(42));      // true  - true
        eqPrint(a, new GreenSubA(42));      // true  - true
        eqPrint(a, new ZGreenSubA(42, 0));  // true  - true
        eqPrint(a, new GreenSubA(41));      // false - false
        eqPrint(a, new RedBase(42, 0));     // false - false
        eqPrint(a, new RedSubA(42, 0));     // false - false
    }

    public static class GreenBase {

        private final int value;

        public GreenBase(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

        @Override public boolean equals(Object obj) {
            return obj instanceof GreenBase &&
                    ((GreenBase) obj).fEquals(this);
        }
        protected boolean fEquals(GreenBase obj) {
            return (value == obj.value);
        }
        @Override public int hashCode() {
            return 21 + value;
        }
    }

    public static class GreenSubA extends GreenBase {
        GreenSubA next;
        public GreenSubA(int value) {
            super (value);
        }
    }
    public static class GreenSubB extends GreenBase {
        GreenSubB next;
        public GreenSubB(int value) {
            super (value);
        }
    }

    public static class RedBase extends GreenBase {

        private final long x;

        public RedBase(int value, long x) {
            super(value);
            this.x = x;
        }

        public long getX() {
            return x;
        }

        @Override public boolean equals(Object obj) {
            return obj instanceof RedBase &&
                    ((RedBase) obj).fEquals(this);
        }
        protected boolean fEquals(RedBase obj) {
            return (x == obj.x && super.fEquals(obj));
        }
        @Override protected boolean fEquals(GreenBase obj) {
            return false;
        }
        @Override public int hashCode() {
            return super.hashCode() * 31 + (int) (x ^ (x >>> 32));
        }
    }

    public static class RedSubA extends RedBase {
        RedSubA next;
        public RedSubA(int value, long x) {
            super(value, x);
        }
    }

    public static class ZGreen extends GreenBase {

        private final int z;

        public ZGreen(int value, int z) {
            super(value);
            this.z = z;
        }

        public int getZ() {
            return z;
        }

        @Override public boolean equals(Object obj) {
            if (obj instanceof GreenBase) {
                if (obj instanceof ZGreen) {
                    return ((ZGreen) obj).fEquals(this);
                }
                return (z == 0 && ((GreenBase) obj).fEquals(this));
            }
            return false;
        }
        protected boolean fEquals(ZGreen obj) {
            return (z == obj.z && super.fEquals(obj));
        }
        @Override protected boolean fEquals(GreenBase obj) {
            return z == 0 && super.fEquals(obj);
        }
    }

    public static class ZGreenSubA extends ZGreen {
        ZGreenSubA next;
        public ZGreenSubA(int value, int z) {
            super(value, z);
        }
    }
}

Monday, 22 June 2009

Using Processing in NetBeans (6.5)

Boyd mentioned passing a reference to the current PApplet to separate classes from a Processing app. For anyone who has not yet tried combining Processing and NetBeans, points I have noted are here - there may be better alternatives. This post shows an example that implements a clipboard Copy and Paste subsystem. The code can be used in any processing application. Three variants are discussed: implementation as an inner class in a NetBeans (or PDE) environment, as a separate class in NetBeans and, using the resulting .jar from the Processing IDE (PDE). Initially a NetBeans Processing application is needed.

Creating a NetBeans Processing app.

1) In NetBeans make a New project, say 'Processing Template', with Create Main Class say 'processing.ProcessingApp'. (if you change the package name in the wizard, the package is created OK but the package processing; statement may be missing from the listing: just type it in)

2) Right click on the Libraries node in the project tree: Add JAR/folder, navigate to the folder where Processing core.jar is located, ...\processing-1.0.2-expert\ processing-1.0.2-expert\lib on my system. Select 'core.jar', and Open.

3) Modify the class ProcessingApp as shown:


package processing;

import processing.core.*;

/**
*
* @author Martin Humby
*/
public class ProcessingApp extends PApplet {

public static void main(String[] args) {
PApplet.main(new String[]{"processing.ProcessingApp"});
}

// Code that can optionally be copied to and compiled from the PDE goes here.
// The PDE only requires explicit import of packages it does not import
// implicitly: import java.awt.datatransfer and java.awt.image for the example
// below. Duplicating implicit imports is OK, for the standard imports
// that is. The PDE does not like public void setup() { } - delete public

} // end of ProcessingApp

Note that the string literal in main() must match the package name and class name. If you use Copy, Paste - Refactor to get a version copy and want to be able to run the copy, refactor does not modify the string and the new package and/or class-name must be changed by hand (otherwise the copy runs the current version of the original - confusing!).

To get a slightly more convenient way of accessing the library path to core.jar, select Tools - Libraries from the NetBeans menu bar. New Library, Library Name: 'Processing', Library Type: Class Libraries. Make sure Processing is selected in the Libraries tree and do Add JAR/Folder as in 2) above. Now right click the Libraries node for the project select Add Library. Scroll down the list of Global Libraries and select Processing.

Making the outline shown above a module template or plugin that can be installed into the IDE appears to have disadvantages. Seems to me the easiest way to keep a framework for Processing apps. handy is simply to save the outline as a standard project. Open the outline and use right-click Copy from the project node to get and rename a new project complete with the core.jar path already set up. You can of course include other Processing libraries with the outline.

Passing an explicit PApplet

An inner class that might be factored off to a separate class is a Clipboard Copy and Paste subsystem. Hiding its implementation means passing the current PApplet instance to its Copy and Paste functions. Writing subsystem access methods and the inner class as static ensures a separate class can be got with minimum modifications. Here the static keyword excludes passing an implicit this reference to the inner class: same situation as in a separate class. A difference is that enclosing class static fields remain accessible without qualification. Need to put this in if a straight transfer is going to work, (g.format == PApplet.ARGB) for example, or add such qualifications later.

To try this approach Copy the 'Processing Template' as a new project say 'Processing Clipboard' and modify the class ProcessingApp as shown. You can of course use Refactor to rename the class if you wish and modify the string in main() to suit.

package processing;

import java.awt.*;
import processing.core.*;
import java.awt.datatransfer.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
*
* @author Martin Humby
*/
public class ProcessingApp extends PApplet {

public static void main(String[] args) {
PApplet.main(new String[]{"processing.ProcessingApp"});
}

static final int WIDTH = 500;
static final int PANEL_HT = 160;
static final int HEIGHT = PANEL_HT + 500;
static final int DRAWING_HEIGHT = HEIGHT - PANEL_HT;
static final int PANEL_TOP = DRAWING_HEIGHT;

public void setup() {
size(WIDTH, HEIGHT);
background(255);

// include a panel below drawing area
fill(128);
rect(0, PANEL_TOP, WIDTH - 1, PANEL_HT - 1);
}

// draw() is required to get keyboard monitoring apparently
public void draw() {
}

public void keyReleased() {
// CTRL+C: Copy to Clipboard
if (key == 3) {
copyImageToClipboard(0, 0, width, height - PANEL_HT, this);
}

// CTRL+V: Paste Clipboard
if (key == 22) {
PImage img = getClipboardImage(this);
if (img == null)
return; // not an image on clipboard

// blank drawing area if required
background(255);

// paste image centred on area above panel
int w = img.width;
int h = img.height;
int dx = (width - w) / 2;
int dy = (height - PANEL_HT - h) / 2;
image(img, dx, dy);

// restore the panel area
fill(128);
rect(0, PANEL_TOP, WIDTH - 1, PANEL_HT - 1);
}
}

/////////////////////////////////////////////////////////////////////////////
//
// COPY AND PASTE SUBSYSTEM
//

/**
* Clipboard copy and paste: the following references were used
* http://processing.org/hacks/hacks:clipboard
* http://www.devx.com/Java/Article/22326/0/page/1 et seq.
*
*/

public static void copyImageToClipboard(int top, int left, int width,
int height, PApplet p) {

// could pass this.g directly but passing this for both functions gets
// consistency in use
PGraphics g = p.g;

// g is needed to get format
BufferedImage bImage = new BufferedImage(width, height,
(g.format == PApplet.ARGB) ?
BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB);
g.loadPixels();

// some explicit identifiers clarify setRGB() usage:
// setRGB(bImageX, bImageY, bothW, bothH, source[], srcOffset, sourceW);
bImage.setRGB(0, 0, width, height, g.pixels, left + top * g.width, g.width);

TransferablePImage imageSelection = new TransferablePImage(bImage);
Toolkit.getDefaultToolkit().
getSystemClipboard().setContents(imageSelection, null);
}

// return a PImage rather than an awt.Image
public static PImage getClipboardImage(PApplet p) {

Transferable t =
Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try {
if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
BufferedImage bimg = (BufferedImage)
t.getTransferData(DataFlavor.imageFlavor);
int w = bimg.getWidth();
int h = bimg.getHeight();

// make it ARGB to be on the safe side - makes no difference
// unless clipboard image has some tranparency could be?
PImage pImg = p.createImage(w, h, PApplet.ARGB);
pImg.loadPixels();
bimg.getRGB(0, 0, w, h, pImg.pixels, 0, w);
pImg.updatePixels();
return pImg;
}
} catch (UnsupportedFlavorException e) {
} catch (IOException e) {
}
return null;
}

static class TransferablePImage implements Transferable {

// the class-name makes more sense as a separate class
private Image image; // an awt.Image

public TransferablePImage(Image image) {
this.image = image;
}

public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException {
if (!flavor.equals(DataFlavor.imageFlavor)) {
throw new UnsupportedFlavorException(flavor);
}
return image;
}

public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(DataFlavor.imageFlavor);
}

public DataFlavor[] getTransferDataFlavors() {
// in some cases there may be more than one flavour?
return new DataFlavor[]{DataFlavor.imageFlavor};
}
}
} // end of ProcessingApp

To test it open say Paint and load an image. Copy a selection smaller than 500 x 500, and paste to the Processing app. Copy and paste it back to Paint - the white border now surrounds the pasted area.


Factoring off the Clipboard Subsystem

It is optional whether a separate TransferablePImage class is put in a new package but doing this will make life easier if you want to use it from the Processing IDE. Right click Source Packages - New - Java Package, 'utilities' then
utilities - New - Java Class - 'TransferablePImage'.

Copy the inner class to the new file and modify it copying the subsystem interface methods as static class methods:

package utilities;

import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import processing.core.*;

/**
* Copy or paste Processing PImage to / from system clipboard
*
* @author Martin Humby
*/
public class TransferablePImage implements Transferable{

private Image image;

public TransferablePImage(Image image) {
this.image = image;
}

// static methods now part of class

public static void copyImageToClipboard(int top, int left, int width,
int height, PApplet p) {

... body as inner class

}

public static PImage getClipboardImage(PApplet p) {

... body as inner class

}

... other methods as inner class
}


To test the new class make a copy of ProcessingApp, say ProcessingApp1, using copy and paste to the processing package. Do not forget to change the class name in the string literal! Add import utilities.TransferablePImage; Delete the COPY AND PASTE SUBSYSTEM. Modify lines that call Copy and Paste to:

TransferablePImage.copyImageToClipboard(0, 0, width, height - PANEL_HT, this);

PImage img = TransferablePImage.getClipboardImage(this);

Optionally delete ProcessingApp1 imports that are no longer used and proceed as before.


Using TransferablePImage from the PDE

Create a new NetBeans project 'processing utilities' with Create Main Class unchecked. Fix up the libraries path to core.jar. Copy and Paste the utilities package from its current location to the new project's Source Packages node. Build the project: the location of the resulting processing_utilities.jar file is shown in the NetBeans Output window.

Make a new folder called maybe 'jars'. A good place could be in the default My Docments\Processing folder. Copy the processing_utilities.jar file to the new folder. Open the Processing IDE and make a new Sketch. Copy in the code from ProcessingApp1.java from after the main() method. Do not include the last curly bracket that belongs to the enclosing class. Delete public from the setup() method.

From the PDE menu bar select Sketch - Add File... navigate to the 'jars' folder and open processing_utilities.jar. The IDE reports 'One file added to the sketch.' No import statement is required and putting one in gets a compilation error. Run the sketch - the result should be identical to the NetBeans version. You can of course include several other classes in processing_utilities.

For more on this subject see http://dev.processing.org/libraries/


Summary

Most code that compiles in the Processing IDE will compile in NetBeans with a PApplet wrapper and fixed up imports. There are a few exceptions. The non-Java color data type is an integer and needs changing to int. A second minor but annoying problem is the fact that Java has the default type for floating point as double. Processing makes the type implied but overflow checked on compile (neither check for values effectively zero apparently).

Processing: float h = 4.13566733e-15; Java: float h = 4.13566733e-15f; Compiler simplicity maybe but after inserting a few dozen 'f's you begin to wonder whether it generates float g = 42; as a promotion. Java of course insists that PApplet methods that get overridden have the same public access as in PApplet but adding this is trivial.

Similarly, most code that will compile in NetBeans compiles in the PDE. To avoid problems particularly when there are errors in the code, delete public access for setup(). Processing is perfectly happy with anonymous classes, which may save a few lines of code here and there. Currently generics are not supported. A pity. I like Java generics. They seem to fit nicely with the object model without providing a sledgehammer capability for wholesale obfuscation. Of course, this opinion may be a reaction to an excess of _traits and spiky brackets elsewhere but generics could be useful to reduce code size in some applications. A set of minimalistic controls managed and drawn by Processing for example:


There is little problem implementing a tiny control management subsystem using a state machine: there are less than a dozen states for a complete set and some can be excluded - no drag and drop for example. Similarly, a single Control type with action and graphics closures, implemented as classes and assigned to its attributes on a mix and match basis, keeps coding to a minimum. Controls manage themselves for radio-button selection and which control gets input (focus). Problems come up when programmatic access to a control is needed - to modify text in controls that show drawing status and size for example.

Arguably this is the wrong way to do it. Perhaps closures should monitor status in the wider environment of the enclosing PApplet but doing this means that controls that can otherwise be entirely passive require a specific action closure or active graphic to do the monitoring. A single line of code, in the draw() function say, can modify a passive control. Alternatively a new closure class is required to implement monitoring.

Control action and graphic attributes are coresponding base classes. Access to a specific attribute means either retaining a reference to the control and casting attributes to their actual type or retaining a reference to the attribute itself. Neither way is ideal as far as code size and clarity goes. Generics can do the casting once for a control reference and all specific attribute types are then accessible directly through that reference. There must be other situations where using generics from the PDE could be useful.

Tuesday, 28 April 2009

Chunk 37 Outline

Next step to apply abstraction and functional approach to drawing lines with special properties.

Characteristics of line: start, end points and path between. Anything can happen along line as random or other factors are applied to it.

Underlying path across a grid of pixels and problems drawing it: Bresenham's algorithm.

Abstracting error-value checking to a closure - simple implementation, optimization.

Writing a function to draw a line between any two points, any width with a colour gradient along its length: needs end points of lines normal to conceptual underlying line.

Writing another closure to return maximum-width end-points of lines at points along underlying length. Problem: filling in missing pixels between adjacent lines due to jagged profile when they offset along underlying line.

Program draws colour gradient lines.

Applying similar closure approach to diverse grids: circular and random spaced grid using array.

PROGRAM 3D grid and thistle-down blob drawn with colour grad lines, moves along its length.

Mostly code: say 48 hours work, 2 weeks max. Time to post code on blogger????

Thursday, 9 April 2009

In Search of Processings Lost

As you may have noticed, Processing programs that use random() and/or noise() and do not set the seed for these functions before they are called, create a different output for each run. The run that gets the superb effect is lost forever but setting seeds always gets the same old effect as the last time. To retain random creation and the capability of recreating a successful run it would nice if the value of seeds could be read at the beginning of a run and stored for future reference. Unfortunately this is not possible - the underlying Java Random class sets seed randomly from its () constructor and does not include a method for retrieving a value that can be used with setSeed().

A workaround is to generate a value for seed using a similar procedure to Random's, record it, and then pass it to a seed setter:


void setup() {
size(WIDTH, HEIGHT);
long seed = 8682522807148013L + System.nanoTime();
System.out.println(seed);
randomSeed(seed);
doDrawing();
}

output: 8702777365341749

If this run turns out to be the great one change setup() to

void setup() {
size(WIDTH, HEIGHT);
// long seed = 8682522807148013L + System.nanoTime();
// System.out.println(seed);
randomSeed(8702777365341749L);
doDrawing();
}

identical graphic output is recreated. Otherwise, just continue with the original setup() version and hope for the best. The same seed generation method is appropriate for noiseSeed(). The seed calculation shown will avoid holes in the total sequence of values returned by nextLong() - if such exist and affect the 48 bit seed used by Random that is.

Thursday, 26 March 2009

Drawing with Lines

This Chapter examines the nature of lines and how they can be used to create art using the line drawing facilities provided by Processing. Initially we look at the broadest possible description of a line and then get down to the nitty-gritty of making a program produce a required result by drawing lines.

Not all lines are straight. A geodesic, the shortest distance between two points on the surface of the Earth, is a curve. Add random noise to a line and it can take on an aspect of a lightning strike, flickering flames, a rough sea, rain falling on a lake and other representations of chaotic behaviour or liquid flow according to the frequencies present in the noise. Any kind of line, straight, curved or distorted, can suggest an edge, a boundary or a link between two locations.

Alternatively we may want a simplified view where the purity of straight lines or the intersections of many lines are used to represent underlying curvature or some more complex shape. A grid of lines can define a two or three dimensional space where equal spacing represents the world as we see it but other spacings can give the effect of non-linearity. We can show distances and dimensions that would otherwise be too small or too large to see. We can also employ the additional dimensions of light, colour, hardness, discontinuity (dots and dashes) and blur to achieve the effect we want.

There are few straight lines in nature and even fewer orthogonal straight lines. A straight line has its own special significance when used representationally. An icon of human-kind one might say.





















Satelight image of the nazca lines
from Wikimedia Commons NASA/GSFC/MITI/ERSDAC/JAROS, and U.S./Japan ASTER Science Team



The Line Drawing Functions

Having got to grips with coordinates, setting colours and suchlike you will probably find line drawing relatively simple. Unlike some less enlightened environments Processing has only a single line drawing function and three line attribute setters.

The line() function

Line(), is overloaded for drawing in 2D and in 3D. A line function with four arguments draws a line on the picture plane, the screen for current purposes.
   line(x1, y1, x2, y2)

draws a line from the point (x1, y1) to (x2, y2).

To draw in 3D we must first setup a 3D drawing environment. Two 3D environments are available and as detailed in XXXX they are invoked by passing an extra argument to the function that sets the window size at the start of the program. You can use either


  size(x, y, P3D);   or   size(x, y, OPENGL);
size() can also be called with a P2D argument to get faster 2D drawing than the default JAVA2D environment provides: size(x, y, P2D). At the time of writing P2D did not support all the facilities of the default mode for line drawing. Try its effect using the simple line drawing program we come to in a moment and check the line drawing and attribute setter functions on the Processing website for current details.

With a 3D environment in place use:
  line(x1, y1, z1, x2, y2, z2);
to draw a line between points (1) and (2) in three dimensional space. The extra coordinates z1 and z2 are the distances of points behind the picture plane. Their depth back from the front face of the screen is another way of thinking about it. If a line is located behind the picture plane and/or tilted in the depth dimension, it will be shown shorter than its length drawn flat on the screen.

The line() functions accept floating point values and can be called with floating point or integer coordinates. Fractional values are rounded to the nearest pixel but casting arguments to integer can be sometimes be useful to smooth jagged parallel line endings e.g:

   line(floatX1, floatY1, (int)floatX2, (int)floatY2); // smooth endings at X2, Y2


Line attribute setters

Three functions set the 'style' of the line that will be drawn by the next and subsequent calls to line(). The effect of calling any one of these functions remains in place until the same function is called again. To be able to revert to a previous value we need to make sure the old values are stored. Line style setters and many other functions that modify the drawing environment have a corresponding variable in the current instance of the Processing application interface, called 'g'. To store the current line colour, for example, we can write
  int oldColour =  g.strokeColor.
Accessing variables using 'dot' notation is discussed later, particularly in Chapter ZZ: Object Oriented Programming. To revert to the old colour write
  stroke(oldColour);
The facility to store and to revert to old settings allows a section of code or a function to draw using settings applicable to the task in hand and restore old settings afterwards - an aid to abstraction discussed later in this Chapter in connection with parametric graphics.

The stroke() line colour setter accepts the same colour and alpha opacity values as the other Processing colour setters detailed earlier in XXXXX. Two other setters affect line drawing: strokeWeight() sets line thickness, strokeCap() the shape or relative location of the end of a line. The program in Listing CC.1 demonstrates the effect of the line style setters.


/* set window size and drawing environment */

// declaring constants static final makes sure they
// cannot be altered by mistake later in the program
static final int WIDTH = 200;
static final int HEIGHT = 200;
static final int OS = 20; // lines offset from edges

void setup() {
// size(WIDTH, HEIGHT, P2D);
// PD2 mode not fully functional in Processing 1.0.2
// so use:
size(WIDTH, HEIGHT);
}

/* draw in continuous mode */
void draw() {
// fill the window with charcoal grey
background(0.25 * 255);

/* draw a 45 deg line top-right to bottom-left */
// set line colour to greyscale white
stroke(255);
// set line width to 12 pixels
strokeWeight(15);
// make the ends of the line squared off
strokeCap(SQUARE);
// draw the line
line(WIDTH - 2*OS, 2*OS, 2*OS, HEIGHT - 2*OS);

/* draw two lines same length, parallel to it */
// rounded ends
strokeCap(ROUND);

/* draw a red line 20 pixels wide above */
strokeWeight(23);
stroke(255, 0, 0); // colour red
line(WIDTH - 3*OS, OS, OS, HEIGHT - 3*OS);

/* draw a green line 20 pixels wide below */
stroke(0, 255, 0); // colour green
line(WIDTH - OS, 3*OS, 3*OS, HEIGHT - OS);

/* draw a blue line 50% opaque, width 20,
top-left to the mouse cursor */
stroke(25, 25, 255, 255 / 2);
strokeWeight(25);
// extend line past cursor point
strokeCap(PROJECT);
line(30, 30, mouseX, mouseY);
}

Listing CC.1











Figure CC.2 Listing CC.1 running.




Running the program note the effect of the attribute setter functions strokeWeight() and strokeCap() for changing line thickness and the shape or relative location of the end of a line as shown in Figure CC.1. Use the mouse to move the blue line over the other lines and note alpha transparency generally and where the lines intersect. Graphics behind an area of transparent colour may appear lighter or darker according to relative brightness values. Try changing the blue line to white, stroke(255, 255, 255, 255 / 2); colours behind are now lightened.

Parametric Grids


The effect of drawing a single line tends to be minimal and it is more likely that many lines will be needed to produce a required effect. In this section we look at a strategy for doing this that extends the repetition facility provided by loops.

Another name for arguments is parameters and parametric graphics is a common feature of vector graphics applications. Using this approach a drawing task is abstracted (taken out) from the main part of the program and done by passing arguments to a function that draws the graphic. Many similar objects can be drawn with different sizes, locations, colours, and other properties determined by values passed to arguments.

Initially we experiment with parametric grids and to do this with a minimum of work the initial step is to set up a basic grid drawing program for testing them out. Optionally the basic structure can be extended to produce actual drawings that include grids. Listing CC.2 shows the outline:


/* set window size and drawing environment */

static final int WIDTH = 900;
static final int HEIGHT = 600;

void setup() {
size(WIDTH, HEIGHT); // default environment
doDrawing();
}

/* draw the drawing */

void doDrawing() {
// charcole grey background, again!
background(0.25 * 255);
// white grid lines
stroke(255);
// one pixel wide
strokeWeight(1);

// draw a grid with number of cells xCells * yCells
int xCells = 13;
int yCells = 19;
drawGrid(0, 0, WIDTH, HEIGHT, xCells, yCells, true);

}

void drawGrid(int left, int top, int width, int height, int xCells,
int yCells, boolean drawOutline){

}

Listing CC.2


As it stands the outline will compile and run but does nothing except opening a window with a grey background. Sections of functionality will be factored off using calls to drawGrid()to draw as many different grids as we require. Such power should be used carefully so the first thing is to decide exactly what we want a drawGrid() function to do and make sure all drawGrids variations we write do just that.

Arguments left and top are where the top-left corner of the grid will be positioned. Width and height specify the size of the grid in pixels, xCells and yCells the number of areas the grid is divided into in the horizontal and vertical directions respectively. Cells are to be made to fit the grid exactly by distributing any odd pixels evenly across cell widths and heights. If draw outline is passed true a one pixel wide line is to be drawn around the grid within the size given. All this sounds complicated but is actually very easy when we divide up the work using functions.