package org.openslx.graph; import java.awt.Color; import org.apache.commons.math3.util.FastMath; public class Edge implements java.io.Serializable { private static final long serialVersionUID = 4401455477347084262L; private Node _source; private Node _target; private double _weight; private String _id = null; private int _age = 0; private static final Color[] COLORS = new Color[ 20 ]; private final int _maxHealth; private int _health; static { for ( int i = 0; i < COLORS.length; ++i ) { int r = blend( 255, 100, i, COLORS.length - 1 ); int g = blend( 0, 100, i, COLORS.length - 1 ); int b = blend( 0, 255, i, COLORS.length - 1 ); COLORS[i] = new Color( r, g, b ); } } private static int blend( int a, int b, int current, int max ) { a *= a; b *= b; return (int)FastMath.sqrt( ( ( b * current ) + ( a * ( max - current ) ) ) / max ); } public Edge( Node source, Node target ) { // Note that this graph is actually undirected. _source = source; _target = target; _weight = 0; _maxHealth = Math.max( source.getMaxHealth(), target.getMaxHealth() ); _health = _maxHealth; } public void resetWeight() { if ( _health == _maxHealth && _maxHealth != 1 && _source.wasActivated() && _target.wasActivated() ) { _health = 1; } else { _health--; } _age++; } public boolean isAlive() { return _health > 0; } public void setWeight( double weight ) { _weight = weight; _health = _maxHealth; } public double getWeight() { return _weight; } public Node getSource() { return _source; } public Node getTarget() { return _target; } public boolean equals( Object o ) { if ( o instanceof Edge ) { Edge other = (Edge)o; return ( _source.equals( other._source ) && _target.equals( other._target ) ) || ( _source.equals( other._target ) && _target.equals( other._source ) ); } return false; } public boolean hasNode( Node node ) { return _source.equals( node ) || _target.equals( node ); } public double getLengthSquared() { final double dx = _source.getX() - _target.getX(); final double dy = _source.getY() - _target.getY(); return dx * dx + dy * dy; } public int hashCode() { return _source.hashCode() ^ _target.hashCode(); } public String toString() { return _source + " " + _target + " w(" + _weight + ")"; } public String getId() { if ( _id == null ) { if ( _source.getId().compareTo( _target.getId() ) > 0 ) _id = _target.getId() + "==" + _source.getId(); _id = _source.getId() + "==" + _target.getId(); } return _id; } public Color getColor() { return COLORS[_age >= COLORS.length ? COLORS.length - 1 : _age]; } }