Created
May 22, 2013 10:04
-
-
Save Smithjoe1/5626522 to your computer and use it in GitHub Desktop.
Flipdot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import processing.core.PApplet; | |
import processing.core.PGraphics; | |
class Animation extends Flipdot{ | |
PApplet parent; | |
Animation(Flipdot p){ | |
parent = p; | |
} | |
Animation() { | |
} | |
//This renders the animation | |
PGraphics drawAnimation(PGraphics pg) { return pg; } | |
//This updates the animation | |
void updateAnimation(){} | |
//This resets the animation | |
void resetAnimation(){} | |
void loadAnimation(){} | |
void pauseAnimation(){} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import processing.core.PApplet; | |
/** | |
* Created with IntelliJ IDEA. | |
* User: Duncan | |
* Date: 13/03/13 | |
* Time: 2:06 PM | |
* To change this template use File | Settings | File Templates. | |
*/ | |
public class AnimationFactory { | |
Animation animation = null; | |
PApplet parent; | |
AnimationFactory(){ | |
} | |
Animation createGif(Flipdot p, String strLines){ | |
return new Images(p, strLines); | |
} | |
Animation createTetris(Flipdot p){ | |
return new TetrisClock(p); | |
} | |
Animation createDrones(Flipdot p){ | |
return new Drones(p); | |
} | |
Animation createDrones2(Flipdot p){ | |
return new Drones2(p); | |
} | |
Animation createMatrix(Flipdot p){ | |
return new Matrix(p); | |
} | |
Animation createSnow(Flipdot p){ | |
return new Snowflakes(p); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
/** | |
* If you use this code, please retain this comment block. | |
* @author Isak du Preez | |
* isak at du-preez dot com | |
* www.du-preez.com | |
*/ | |
public class CircularArrayList<E> | |
extends AbstractList<E> implements RandomAccess { | |
private final int n; // buffer length | |
private final List<E> buf; // a List implementing RandomAccess | |
private int head = 0; | |
private int tail = 0; | |
public CircularArrayList(int capacity) { | |
n = capacity + 1; | |
buf = new ArrayList<E>(Collections.nCopies(n, (E) null)); | |
} | |
public int capacity() { | |
return n - 1; | |
} | |
private int wrapIndex(int i) { | |
int m = i % n; | |
if (m < 0) { // java modulus can be negative | |
m += n; | |
} | |
return m; | |
} | |
// This method is O(n) but will never be called if the | |
// CircularArrayList is used in its typical/intended role. | |
private void shiftBlock(int startIndex, int endIndex) { | |
assert (endIndex > startIndex); | |
for (int i = endIndex - 1; i >= startIndex; i--) { | |
set(i + 1, get(i)); | |
} | |
} | |
@Override | |
public int size() { | |
return tail - head + (tail < head ? n : 0); | |
} | |
@Override | |
public E get(int i) { | |
if (i < 0 || i >= size()) { | |
System.out.println(i); | |
throw new IndexOutOfBoundsException(); | |
} | |
return buf.get(wrapIndex(head + i)); | |
} | |
@Override | |
public E set(int i, E e) { | |
if (i < 0 || i >= size()) { | |
System.out.print("s:");System.out.println(size()); | |
System.out.print("i:");System.out.println(i); | |
throw new IndexOutOfBoundsException(); | |
} | |
return buf.set(wrapIndex(head + i), e); | |
} | |
@Override | |
public void add(int i, E e) { | |
int s = size(); | |
if (s == n - 1) { | |
System.out.println(s); | |
throw new IllegalStateException("Cannot add element." | |
+ " CircularArrayList is filled to capacity."); | |
} | |
if (i < 0 || i > s) { | |
System.out.print("s:");System.out.println(s); | |
System.out.print("i:");System.out.println(i); | |
throw new IndexOutOfBoundsException(); | |
} | |
tail = wrapIndex(tail + 1); | |
if (i < s) { | |
shiftBlock(i, s); | |
} | |
set(i, e); | |
} | |
@Override | |
public E remove(int i) { | |
int s = size(); | |
if (i < 0 || i >= s) { | |
System.out.println(0); | |
throw new IndexOutOfBoundsException(); | |
} | |
E e = get(i); | |
if (i > 0) { | |
shiftBlock(0, i); | |
} | |
head = wrapIndex(head + 1); | |
return e; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import processing.core.PApplet; | |
import processing.core.PGraphics; | |
import processing.core.PImage; | |
import java.util.ArrayList; | |
import java.util.List; | |
/** | |
* Created with IntelliJ IDEA. | |
* User: Duncan | |
* Date: 10/02/13 | |
* Time: 1:21 PM | |
* To change this template use File | Settings | File Templates. | |
*/ | |
class Drones extends Animation implements Observer{ | |
static final int NUM_DRONES = 2000; | |
List<Drone> drones = new ArrayList<Drone>(NUM_DRONES); | |
static float TWO_PI = (float)Math.PI * 2f; | |
float t; | |
float dt; | |
PImage attractor; | |
Wanderer wanderer; | |
PApplet parent; | |
Drones(Flipdot p){ | |
parent = p; | |
attractor = p.loadImage("data/BuzzLogoStatic.gif"); | |
attractor.loadPixels(); | |
createDrones(attractor.get()); | |
wanderer = new Wanderer(parent, parent.random(xbound), parent.random(ybound)); | |
p.addObserver(this); | |
} | |
void createDrones(PImage pg){ | |
for(int i=0; i < pg.width; i++){ | |
for(int j = 0; j < pg.height; j++){ | |
pg.loadPixels(); | |
if(pg.get(i,j) != color(255)){ | |
drones.add(new Drone(parent, parent.random(i-5,i+5), parent.random(j-5,j+5), i, j, parent.random(TWO_PI))); | |
} | |
} | |
} | |
// for (int i = 0; i < NUM_DRONES; i++){ | |
// drones.add(new Drone(parent, parent.random(xbound), parent.random(ybound), parent.random(TWO_PI))); | |
// } | |
t = parent.millis() * (float)1e-3; | |
} | |
void resetAnimation(){ | |
for (Drone drone : drones) { | |
drone.x = parent.random(xbound); | |
drone.y = parent.random(ybound); | |
} | |
} | |
PGraphics drawAnimation(PGraphics pg) { | |
pg.loadPixels(); | |
pg.stroke(255); | |
pg.strokeWeight(1); | |
pg.beginDraw(); | |
pg.background(0); | |
for (Drone drone : drones) { | |
pg.point(drone.x, drone.y); | |
} | |
pg.endDraw(); | |
return pg; | |
} | |
void updateAnimation(){ | |
dt = -t; | |
t = parent.millis() * (float)1e-4; | |
dt += t; | |
wanderer.stayInsideCanvas(); | |
wanderer.move(); | |
for (Drone drone : drones) { | |
drone.update(dt); | |
} | |
} | |
public void update(char key){ | |
} | |
class Drone { | |
PApplet parent; | |
// Speed limits | |
final float MIN_SPEED = 50; | |
final float MAX_SPEED = 100; | |
// Acceleration and turning speed maximums | |
final float MAX_ACCEL = 50; | |
final float MAX_TURN = TWO_PI; | |
// Ranges used to determine behaviour mode | |
static final float OUTER_RANGE = 300; | |
static final float INNER_RANGE = 2; | |
// Enumerated behaviour modes | |
static final int MODE_ATTACK = 0; | |
static final int MODE_EVADE = 1; | |
public int Dmode = 0; | |
float xGoal, yGoal; //Where does the point want to go when in the right mode. | |
float x, y; // position (in pixel coordinates) | |
float theta; // direction | |
float speed; | |
float phi; | |
int mode; | |
Drone(PApplet p, float x, float y, float xGoal, float yGoal, float theta) { | |
this.x = x; | |
this.y = y; | |
this.xGoal = xGoal; | |
this.yGoal = yGoal; | |
this.theta = theta; | |
this.speed = MIN_SPEED; | |
this.mode = MODE_ATTACK; | |
parent = p; | |
} | |
void update(float dt) { | |
// Modify mode based on distance from cursor | |
float s = parent.dist(x, y, wanderer.getX() - x, wanderer.getY()); | |
if(Dmode == 0){ | |
switch (mode) { | |
case MODE_ATTACK: | |
if (parent.random(s) < parent.random(INNER_RANGE)) | |
mode = MODE_EVADE; | |
break; | |
case MODE_EVADE: | |
if (parent.random(s) > parent.random(OUTER_RANGE)) | |
mode = MODE_ATTACK; | |
break; | |
default: | |
return; | |
} | |
} | |
// Calculate accel and turn based on set mode. | |
if(Dmode == 0){ | |
phi = (float)(Math.atan2(wanderer.getY() - y, wanderer.getX() - x) - theta); | |
}else{ | |
phi = (float)(Math.atan2(yGoal - y, xGoal - x)-theta); | |
} | |
float accel, turn; | |
if(Dmode == 0){ | |
switch (mode) { | |
case MODE_ATTACK: | |
accel = (float)Math.cos(phi) * MAX_ACCEL; | |
turn = (float)Math.sin(phi) * MAX_TURN; | |
break; | |
case MODE_EVADE: | |
accel = (float)Math.sin(phi) * MAX_ACCEL; | |
turn = (float)Math.cos(phi) * MAX_TURN; | |
break; | |
default: | |
return; | |
} | |
}else{ | |
accel = (float)Math.cos(phi) * MAX_ACCEL/10; | |
turn = (float)Math.sin(phi) * MAX_TURN; | |
} | |
// Recalculate speed, keeping it between the predefined limits | |
float k = 0; | |
if(Dmode == 0){ | |
if (accel > 0) | |
k = (MAX_SPEED - speed) / (MAX_SPEED - MIN_SPEED); | |
else | |
k = (speed - MIN_SPEED) / (MAX_SPEED - MIN_SPEED); | |
}else{ | |
if(parent.dist(x, y, xGoal - x, yGoal) < 5){ | |
k = (MAX_SPEED/10 - speed) / (MAX_SPEED - MIN_SPEED); | |
} else{ | |
k = (speed - MIN_SPEED) / (MAX_SPEED/10 - MIN_SPEED); | |
} | |
} | |
speed += k * accel; | |
// Update direction | |
theta = (theta + turn * dt) % TWO_PI; | |
// Update position | |
x += speed * dt * Math.cos(theta); | |
y += speed * dt * Math.sin(theta); | |
//Check for extended bounds | |
if(x<xbound*-0.5){ | |
x = 0; | |
} else if(x>xbound*1.5){ | |
x = xbound; | |
} | |
if(y<ybound*-0.5){ | |
y = 0; | |
}else if(y>ybound*1.5){ | |
y = ybound; | |
} | |
} | |
} | |
class Wanderer { | |
PApplet parent; | |
float x; | |
float y; | |
float wander_theta; | |
float wander_radius; | |
// bigger = more edgier, hectic | |
float max_wander_offset = .30f; | |
// bigger = faster turns | |
float max_wander_radius = 3.5f; | |
Wanderer(PApplet p, float _x, float _y) | |
{ | |
parent = p; | |
x = _x; | |
y = _y; | |
wander_theta = parent.random(TWO_PI); | |
wander_radius = parent.random(max_wander_radius); | |
} | |
void stayInsideCanvas() | |
{ | |
if (x<5) | |
wander_theta = wander_theta * -1; | |
if (x>xbound-5) | |
wander_theta = wander_theta * -1; | |
if (y<5) | |
wander_theta = wander_theta * -1; | |
if (y> ybound-5) | |
wander_theta = wander_theta * -1; | |
if (x<=0) | |
x=xbound-3; | |
if (y<=0) | |
y=ybound-3; | |
x %= xbound; | |
y %= ybound; | |
} | |
void move() | |
{ | |
float wander_offset = parent.random(-max_wander_offset, max_wander_offset); | |
wander_theta += wander_offset; | |
x += Math.cos(wander_theta); | |
y += Math.sin(wander_theta); | |
parent.ellipse(getX(),getY(),2,2); | |
} | |
float getX() | |
{ | |
return x; | |
} | |
float getY() | |
{ | |
return y; | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import processing.core.PApplet; | |
import processing.core.PGraphics; | |
import processing.core.PImage; | |
import java.util.ArrayList; | |
import java.util.List; | |
/** | |
* Created with IntelliJ IDEA. | |
* User: Duncan | |
* Date: 2/04/13 | |
* Time: 3:43 PM | |
* To change this template use File | Settings | File Templates. | |
*/ | |
public class Drones2 extends Animation implements Observer{ | |
static final int NUM_DRONES = 2000; | |
List<Drone> drones = new ArrayList<Drone>(NUM_DRONES); | |
boolean free=false; //when this becomes false, the particles move toward their goals | |
float pAccel=.2f; //acceleration rate of the particles | |
float pMaxSpeed=2; //max speed the particles can move at | |
PApplet parent; | |
PImage attractor; | |
Drones2(Flipdot p){ | |
parent = p; | |
attractor = p.loadImage("data/BuzzLogoStatic.gif"); | |
attractor.loadPixels(); | |
createDrones(attractor.get()); | |
p.addObserver(this); | |
} | |
void createDrones(PImage pg){ | |
for(int i=0; i < pg.width; i++){ | |
for(int j = 0; j < pg.height; j++){ | |
pg.loadPixels(); | |
if(pg.get(i,j) != color(255)){ | |
drones.add(new Drone(i, j)); | |
} | |
} | |
} | |
} | |
void resetAnimation(){ | |
for (Drone drone : drones) { | |
drone.x = parent.random(xbound); | |
drone.y = parent.random(ybound); | |
} | |
} | |
PGraphics drawAnimation(PGraphics pg) { | |
pg.loadPixels(); | |
pg.stroke(255); | |
pg.strokeWeight(1); | |
pg.beginDraw(); | |
pg.background(0); | |
for (Drone drone : drones) { | |
pg.point(drone.x, drone.y); | |
} | |
pg.endDraw(); | |
return pg; | |
} | |
void updateAnimation(){ | |
for (Drone drone : drones) { | |
drone.update(); | |
} | |
} | |
class Drone{ | |
float x,y; | |
float xVel, yVel; | |
float xAccel, yAccel; | |
float xVelMax, yVelMax; | |
float ang; | |
float xGoal, yGoal; | |
Drone(float newXGoal, float newYGoal){ | |
x = parent.random(newXGoal-50,newXGoal+50); | |
y = parent.random(newYGoal-50,newYGoal+50); | |
xGoal = newXGoal; | |
yGoal = newYGoal; | |
ang = random(0,TWO_PI); | |
xVel = 0; | |
yVel = 0; | |
xAccel = pAccel * cos(ang); | |
yAccel = pAccel * sin(ang); | |
} | |
void update(){ | |
//println(degrees(ang)); | |
x+=xVel; | |
y+=yVel; | |
xVel+=xAccel; | |
yVel+=yAccel; | |
//if the particles are not free, move this particle toward its goal | |
if (!free){ | |
//get the ange of the thing point the particle should move toward | |
ang= atan2(yGoal-y, xGoal-x); | |
xAccel=pAccel*cos(ang); | |
yAccel=pAccel*sin(ang); | |
//slow it down a lot if it's close to the point | |
if (abs(x-xGoal) <abs(xVel*2) || abs(y-yGoal) <abs(yVel*2) ){ | |
xVel*=0.6; | |
yVel*=0.6; | |
} | |
}else{ | |
//make it bounce off edges if it's free moving | |
// CheckEdge(); | |
} | |
} | |
void CheckEdge(){ | |
if(x<xbound*-0.5){ | |
x = 0; | |
xAccel*=-1; | |
} else if(x>xbound*1.5){ | |
x = xbound; | |
xAccel*=-1; | |
} | |
if(y<ybound*-0.5){ | |
y = 0; | |
yAccel*=-1; | |
}else if(y>ybound*1.5){ | |
y = ybound; | |
yAccel*=-1; | |
} | |
} | |
} | |
@Override | |
public void update(char keyCode) { | |
//To change body of implemented methods use File | Settings | File Templates. | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created with IntelliJ IDEA. | |
* User: Duncan | |
* Date: 28/01/13 | |
* Time: 3:58 PM | |
* To change this template use File | Settings | File Templates. | |
*/ | |
import processing.core.*; | |
import java.util.*; | |
public class Fader{ | |
public PImage src1; //Start image | |
public PImage src2; //End image | |
public PGraphics alphaMask; | |
PApplet parent; | |
public int x, y; | |
boolean t = true; | |
double tmp; | |
Fader(PApplet p){ | |
parent = p; | |
alphaMask = new PGraphics(); | |
src1 = new PImage(); | |
src2 = new PImage(); | |
} | |
public void setImages(PImage sr1, PImage sr2) { | |
src1=sr1; | |
src2=sr2; | |
alphaMask = parent.createGraphics(src1.width, src1.height); | |
startFade(); | |
} | |
public void setXY(int x_, int y_){ | |
x = x_; | |
y = y_; | |
} | |
/** | |
* called to initialise fade. This default implementation starts | |
* with a black mask. Subclasses can override this to do other initialisation. | |
*/ | |
public void startFade() { | |
alphaMask.beginDraw(); | |
alphaMask.fill(0); | |
alphaMask.stroke(0); | |
alphaMask.rect(0, 0, src1.width, src1.height); | |
alphaMask.endDraw(); | |
} | |
/** | |
* called to end the fade. This default implementation creates a 100% white mask. | |
* May not be needed, but I've had some problems with rounding errors | |
* and arc drawing leaving gaps. Calling this will | |
* guarantee you see 100% final image. | |
*/ | |
public void endFade() { | |
alphaMask.beginDraw(); | |
alphaMask.fill(255); | |
alphaMask.stroke(255); | |
alphaMask.rect(0, 0, src1.width, src1.height); | |
alphaMask.endDraw(); | |
} | |
/** | |
* called for each frame of the animation. pass in the percentage (0.0-1.0) of the effect. | |
* this should be overridden for each effect subclass. | |
*/ | |
public void animateFade(float percent) { | |
; | |
} | |
/** | |
* Renders blended images. You shouldn't need to override this. | |
*/ | |
public PGraphics draw(PGraphics pg) { | |
pg.loadPixels(); | |
pg.beginDraw(); | |
src1.loadPixels(); | |
src2.loadPixels(); | |
int w=src1.width; | |
for (int ix=0;ix<src1.pixels.length;ix++) { | |
int y=ix/w; | |
int x=ix%w; | |
int col1=src1.pixels[ix]; | |
int r1=(col1&0xFF0000)>>16; | |
int g1=(col1&0xFF00)>>8; | |
int b1=(col1&0xFF); | |
int col2=src2.pixels[ix]; | |
int r2=(col2&0xFF0000)>>16; | |
int g2=(col2&0xFF00)>>8; | |
int b2=(col2&0xFF); | |
int colmask= alphaMask.pixels[ix]; | |
int level=(colmask&0xFF); // use blue channel | |
float lev= (float)level/256.0f; | |
int rr=(int)((r1*lev)+(r2*(1-lev))); | |
int gg=(int)((g1*lev)+(g2*(1-lev))); | |
int bb=(int)((b1*lev)+(b2*(1-lev))); | |
pg.pixels[ix]=0xFF000000|rr<<16|gg<<8|bb; | |
} | |
pg.updatePixels(); | |
pg.endDraw(); | |
return pg; | |
} | |
} | |
class CrossFade extends Fader { | |
CrossFade(PApplet p) { | |
super(p); | |
} | |
// simple crossfade. Mask is gradually changed from black (first image) | |
// to white (second image) | |
public void animateFade(float percent) { | |
alphaMask.beginDraw(); | |
alphaMask.fill(255 * percent); | |
alphaMask.stroke(255 * percent); | |
alphaMask.rect(0, 0, src1.width, src1.height); | |
alphaMask.endDraw(); | |
} | |
} | |
class DownFade extends Fader { | |
DownFade(PApplet p) { | |
super(p); | |
} | |
// Second image is introduced from the top | |
public void animateFade(float percent) { | |
alphaMask.beginDraw(); | |
alphaMask.fill(255); | |
alphaMask.stroke(255); | |
alphaMask.rect(0, 0, src1.width, src1.height * percent); | |
alphaMask.endDraw(); | |
} | |
} | |
class EllipseFade extends Fader { | |
EllipseFade(PApplet p) { | |
super(p); | |
} | |
// second image is introduced from the centre as an ellipse | |
public void animateFade(float percent) { | |
alphaMask.beginDraw(); | |
alphaMask.fill(255); | |
alphaMask.stroke(255); | |
parent.strokeWeight(3); | |
parent.ellipseMode(PConstants.CENTER); | |
alphaMask.ellipse(src1.width / 2.0f, src1.height / 2f, src1.width * 5f * percent, src1.height * 5f * percent); | |
alphaMask.endDraw(); | |
} | |
} | |
class EllipseFadePoint extends Fader { | |
EllipseFadePoint(PApplet p){ | |
super(p); | |
} | |
public void animateFade(float percent){ | |
alphaMask.beginDraw(); | |
alphaMask.fill(255); | |
alphaMask.stroke(255); | |
alphaMask.strokeWeight(3); | |
alphaMask.ellipseMode(PConstants.CENTER); | |
alphaMask.ellipse(x, y, src1.height * 5f * percent, src1.height * 5f * percent); | |
alphaMask.endDraw(); | |
} | |
} | |
class EllipseFadePointReverse extends Fader { | |
EllipseFadePointReverse(PApplet p){ | |
super(p); | |
} | |
public void animateFade(float percent){ | |
alphaMask.beginDraw(); | |
alphaMask.background(255); | |
alphaMask.fill(0); | |
alphaMask.stroke(0); | |
alphaMask.strokeWeight(3); | |
alphaMask.ellipseMode(PConstants.CENTER); | |
alphaMask.ellipse(x, y, src1.height * 5f * (1-percent), src1.height * 5f * (1-percent)); | |
alphaMask.endDraw(); | |
} | |
} | |
class LeftFade extends Fader { | |
LeftFade(PApplet p) { | |
super(p); | |
} | |
// second image is introduced from the left to right | |
public void animateFade(float percent) { | |
alphaMask.beginDraw(); | |
alphaMask.fill(255); | |
alphaMask.stroke(255); | |
alphaMask.rect(0, 0, src1.width * percent, src1.height); | |
alphaMask.endDraw(); | |
} | |
} | |
class RandomBlockFade extends Fader { | |
// second image is introduced using random 8x8 pixel blocks | |
boolean[][] used; | |
RandomBlockFade(PApplet p) { | |
super(p); | |
} | |
public void startFade() { | |
used=new boolean[200][200]; | |
super.startFade(); | |
} | |
public void animateFade(float percent) { | |
int numcells=(src1.height/8)*(src1.width/8); | |
if (percent==0.0f) used=new boolean[200][200]; | |
for (int i=0;i<(int)((float)numcells*percent);i++) { | |
int cellx=(int)parent.random((src1.width / 8.0f) + 1); | |
int celly=(int)parent.random((src1.height / 8.0f) + 1); | |
used[celly][cellx]=true; | |
} | |
alphaMask.beginDraw(); | |
alphaMask.fill(255); | |
alphaMask.stroke(255); | |
for (int y=0;y<=src1.height/8;y++) { | |
for (int x=0;x<=src1.width/8;x++) { | |
if (used[y][x]) { | |
alphaMask.fill(255); | |
alphaMask.stroke(255); | |
} else { | |
alphaMask.fill(0); | |
alphaMask.stroke(0); | |
} | |
alphaMask.rect(x * 8, y * 8, 8, 8); | |
} | |
} | |
alphaMask.endDraw(); | |
} | |
} | |
class RightFade extends Fader { | |
RightFade(PApplet p) { | |
super(p); | |
} | |
// second image is introduced from the right | |
public void animateFade(float percent) { | |
alphaMask.beginDraw(); | |
alphaMask.fill(255); | |
alphaMask.stroke(255); | |
if(percent<=1.2){ | |
alphaMask.rect(src1.width - (src1.width * percent), 0, src1.width, src1.height); | |
}else alphaMask.rect(0, 0, src1.width, src1.height); | |
alphaMask.endDraw(); | |
} | |
} | |
class RotateBoxFader extends Fader { | |
RotateBoxFader(PApplet p) { | |
super(p); | |
} | |
// second image is introduced using a growing spiral from the centre | |
public void animateFade(float percent) { | |
alphaMask.beginDraw(); | |
alphaMask.fill(255); | |
alphaMask.stroke(255); | |
alphaMask.pushMatrix(); | |
alphaMask.rectMode(parent.CENTER); | |
alphaMask.translate(src1.width / 2, src1.height / 2); | |
alphaMask.rotate((parent.TWO_PI * percent)/parent.frameRate); | |
alphaMask.rect(0, 0, src1.width * percent, src1.height * percent); | |
alphaMask.popMatrix(); | |
alphaMask.endDraw(); | |
} | |
} | |
class RotateFade extends Fader { | |
RotateFade(PApplet p) { | |
super(p); | |
} | |
// second image is introduced using a clockwise circular sweep from 3 o'clock | |
public void animateFade(float percent) { | |
alphaMask.beginDraw(); | |
alphaMask.fill(255); | |
alphaMask.stroke(255); | |
parent.strokeWeight(3); | |
alphaMask.arc(src1.width / 2.0f, src1.height / 2f, src1.width * 2.0f, src1.height * 2.0f, 0.0f, parent.TWO_PI * percent); | |
alphaMask.endDraw(); | |
} | |
} | |
class SanfuFade extends Fader{ | |
SanfuFade (PApplet p){ | |
super(p); | |
} | |
public void animateFade(float percent){ | |
alphaMask.beginDraw(); | |
alphaMask.fill(255); | |
alphaMask.stroke(255); | |
parent.strokeWeight(3); | |
float x; | |
for (int y = 0; y < src1.height; y=y+3){ | |
if(percent < 0.5){ | |
x = src1.width * percent*2; | |
if(y%3 == 0){ | |
alphaMask.line(0,y,x,y); | |
} | |
} else if(percent > 0.4){ | |
if(y%3 == 0){ | |
alphaMask.line(0,y,src1.width,y); | |
} | |
x = src1.width * (percent-0.5f)*2; | |
alphaMask.rect(0,0,x,src1.height); | |
} | |
} | |
alphaMask.endDraw(); | |
} | |
} | |
class SnakeFade extends Fader { | |
SnakeFade(PApplet p) { | |
super(p); | |
} | |
// second image is introduced from the left to right | |
public void animateFade(float percent) { | |
alphaMask.beginDraw(); | |
alphaMask.fill(255); | |
alphaMask.stroke(255); | |
alphaMask.strokeWeight(3); | |
alphaMask.noSmooth(); | |
int lines = 4; | |
float step=src1.pixels.length/(100*lines); | |
//parent.println(step); | |
float currPos = step*percent*100; | |
double currRow = Math.floor((currPos/(float)src1.width)*lines); | |
float PosX = (currPos*lines)-((float)currRow*src1.width); | |
alphaMask.rect(0,0,src1.width,(float)currRow-lines/2); | |
if(t){ | |
alphaMask.line(0, (float)currRow,PosX,(float)currRow); | |
if(currRow!=tmp){ | |
t =! t; | |
tmp = currRow; | |
} | |
//alphaMask.line(src1.width,(float)currRow,PosX,(float)currRow); | |
} else { | |
//alphaMask.line(0, (float)currRow,PosX,(float)currRow-1); | |
alphaMask.line(src1.width-PosX,(float)currRow,src1.width,(float)currRow); | |
if(currRow!=tmp){ | |
t =! t; | |
tmp = currRow; | |
} | |
} | |
alphaMask.endDraw(); | |
} | |
} | |
class SnakeFadeRight extends Fader { | |
SnakeFadeRight(PApplet p) { | |
super(p); | |
} | |
// second image is introduced from the left to right | |
public void animateFade(float percent) { | |
alphaMask.beginDraw(); | |
alphaMask.fill(255); | |
alphaMask.stroke(255); | |
alphaMask.strokeWeight(4); | |
float step=src1.pixels.length/900; | |
//parent.println(step); | |
float currPos = step*percent*100; | |
double currRow = Math.floor(currPos/(float)src1.width); | |
float PosX = currPos-((float)currRow*src1.width); | |
alphaMask.rect(0,0,src1.width,(float)currRow-1); | |
alphaMask.line(0,(float)currRow,PosX,(float)currRow); | |
alphaMask.endDraw(); | |
} | |
} | |
class waveFade extends Fader { | |
waveFade(PApplet p) { | |
super(p); | |
} | |
// second image is introduced from the left to right | |
public void animateFade(float percent) { | |
alphaMask.beginDraw(); | |
alphaMask.fill(255); | |
alphaMask.stroke(255); | |
alphaMask.strokeWeight(1); | |
float x = 0; | |
float wave = percent * 200; | |
while (x < src1.width){ | |
float k = wave * parent.noise(x/100,percent); | |
alphaMask.noStroke(); | |
alphaMask.ellipse(x,src1.height-k, 3, 3); | |
alphaMask.stroke(255); | |
alphaMask.strokeWeight(1); | |
alphaMask.line(x,src1.height-k,x,src1.height); | |
x++; | |
} | |
//parent.println(step); | |
alphaMask.endDraw(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Observer class from http://stackoverflow.com/questions/5131547/java-keylistener-in-separate-class | |
*/ | |
import processing.core.*; | |
//import processing.serial.*; | |
import java.io.File; | |
import java.util.*; | |
import g4p_controls.*; | |
//import processing.serial.Serial; | |
public class Flipdot extends PApplet implements Observabe{ | |
Fader f; | |
int Dmode; | |
// GSketchPad draw; | |
PGraphics pg; | |
PGraphics pgIN; | |
public ImageProcessor imgPr; | |
AnimationFactory af = new AnimationFactory(); | |
boolean animationBlock = true; | |
FrameSaver saver = new FrameSaver(this); | |
// sample set of faders to pick from at random | |
Fader[] faders=new Fader[]{ | |
//new RotateBoxFader(this), | |
new RightFade(this), | |
new RotateFade(this), | |
new EllipseFade(this), | |
new EllipseFadePoint(this), | |
new EllipseFadePointReverse(this), | |
// new CrossFade(this), //Wont work | |
new DownFade(this), | |
new LeftFade(this), | |
new RandomBlockFade(this), | |
new SanfuFade(this), | |
new SnakeFade(this), | |
new SnakeFadeRight(this), | |
new waveFade(this), | |
}; | |
ArrayList<Animation> images = new ArrayList<Animation>(); | |
ArrayList<String[]> config = new ArrayList<String[]>(); | |
//======================================================================== | |
//Transisiton Stuff | |
float delay = 1.0f*5; //How long until the transition happens | |
float speed = 100.0f; //How long will the transition takes, in frames (5/sec) | |
//This is the number of panels high | |
int partHeight = 14; // Number of pixels high per panel | |
int partWidth = 28; // Number of pixels wide per panel | |
int panelx = 7; | |
int panely = 4; | |
int xbound = panelx*partWidth; | |
int ybound = panely*partHeight; | |
int currImg = 0; | |
int nextImg = 2; | |
int carousel = 0; | |
int scale = 5; | |
int framerate = 5; | |
int validX, validY; | |
static public void main(String args[]){ | |
PApplet.main(new String[] {"Flipdot"}); | |
} | |
public void setup() { | |
size(xbound*scale, ybound*scale); | |
ybound = panely*partHeight; | |
pg = createGraphics(xbound, ybound); | |
pgIN = createGraphics(xbound, ybound); | |
// draw = new GSketchPad(this, 0, 0, xbound*scale, ybound*scale); | |
noSmooth(); | |
// draw.setGraphic(pg); | |
frameRate(framerate); | |
f=faders[(int)(random(0,faders.length))]; | |
loadConfig(); | |
f.setXY(120, 30); | |
reset(); | |
// saver.start(); | |
imgPr.start(); | |
} | |
public void draw(){ | |
background(250); | |
pg.beginDraw(); | |
pgIN.beginDraw(); | |
images.get(currImg).updateAnimation(); | |
images.get(nextImg).updateAnimation(); | |
images.get(currImg).drawAnimation(pg); //Draw the animation routine | |
images.get(nextImg).drawAnimation(pgIN); | |
f.setImages(pg.get(), pgIN.get()); | |
if(frameCount > delay){ | |
float percent = ((frameCount-delay)*framerate)/speed; | |
if (percent<=1) { | |
// show next frame of the animation | |
blockAnimationCheck(percent); | |
//Draw blocked animations to flush the buffer | |
images.get(currImg).updateAnimation(); | |
images.get(nextImg).updateAnimation(); | |
images.get(currImg).drawAnimation(pg); | |
images.get(nextImg).drawAnimation(pgIN); | |
f.setImages(pg.get(), pgIN.get()); | |
f.animateFade(percent); | |
} else { | |
// show end image | |
f.endFade(); | |
reset(); | |
} | |
} else { | |
f.startFade(); | |
} | |
//Buffer the animation once per draw cycle | |
// pg = imgPr.drawSplit(); | |
pg.filter(THRESHOLD); | |
pg = f.draw(pg); | |
pg.loadPixels(); | |
pg.filter(THRESHOLD); | |
imgPr.bufferImg(pg); | |
pg.endDraw(); | |
pgIN.endDraw(); | |
image(pg,0,0,xbound*scale, ybound*scale); | |
// saver.addImage(pg.get()); | |
// saver.run(); | |
} | |
void loadConfig(){ | |
String[] strValue; | |
String[] screenRes; | |
String[] strLines = loadStrings("config.txt"); | |
strValue = split(strLines[0], "="); | |
//Load serial port configuration | |
// println(Serial.list()); | |
try{ | |
imgPr = new ImageProcessor((strValue[2]),this); | |
}catch(UnsatisfiedLinkError e){ | |
println(e); | |
}catch(RuntimeException e){ | |
println(e); | |
} | |
//Load the screen resolution | |
if (strValue.length > 0) { | |
screenRes = split(strValue[1], "x"); | |
panelx = Integer.parseInt(screenRes[0]);//7 //This is the number of panels wide | |
panely = Integer.parseInt(screenRes[1]);//4 | |
} | |
//Create animation objects | |
images.add(af.createTetris(this)); | |
images.add(af.createDrones(this)); | |
images.add(af.createDrones2(this)); | |
images.add(af.createMatrix(this)); | |
images.add(af.createSnow(this)); | |
//Load the list of files | |
//TODO: Test this works, creates an array list for each line in the config file and then loads the file. | |
for (int i = 1; i < strLines.length; i++) { | |
try { | |
images.add(af.createGif(this, strLines[i])); | |
// print(i+3 + " :"); | |
// println(strLines[i]); | |
} catch (NullPointerException e) { | |
println(strLines[i]); | |
} | |
} | |
//Load the slideshow images into the caourosel | |
loadSlideshow(); | |
} | |
//Slideshow stuff | |
void loadSlideshow(){ | |
String[] strValue; | |
String[] strLines = loadStrings("Slideshow.txt"); | |
for (int i = 0; i < strLines.length; i++) { | |
try { | |
strValue = split(strLines[i], '\t'); | |
config.add(strValue); | |
}catch (NullPointerException e) { | |
println(strLines[i]); | |
} | |
} | |
} | |
public void blockAnimationCheck(float percent){ //Method to block animations while transitioning if they have problems with the draw before render stuff | |
//Lets reset all the animations the first time the loop is called. | |
if(animationBlock == true){ | |
for(int i = 0; i < images.size()-1; i++){ | |
//We wanto to reset everything asides the outbound animation | |
if(i != nextImg)images.get(i).resetAnimation(); | |
if(i != nextImg)images.get(i).updateAnimation(); | |
} | |
animationBlock = false; | |
} | |
//Custom animation blocks for circle animations | |
//Lets start the animations early otherwise we get an ugly pause before the image and animations load. | |
int img; | |
if(carousel == 0){ | |
img = 0; | |
}else{ | |
img = carousel-1; | |
} | |
if(Integer.parseInt(config.get(img)[1]) == 2){ | |
if(percent<0.25f){ | |
images.get(currImg).resetAnimation(); | |
} | |
} | |
else if(Integer.parseInt(config.get(img)[1]) >= 3 && Integer.parseInt(config.get(img)[1]) <= 4){ | |
if(percent<0.7f){ | |
images.get(currImg).resetAnimation(); | |
} | |
} | |
//Lets do the same for the Sanfu and Sname animations, blocking the outbound animations otherwise the visual is too noisy | |
else if(Integer.parseInt(config.get(img)[1]) >= 8 && Integer.parseInt(config.get(img)[1]) <= 10){ | |
if(percent<1){ | |
//Lets block both animations completley | |
images.get(currImg).resetAnimation(); | |
images.get(nextImg).loadAnimation(); | |
} | |
} | |
//Everything else | |
else{ | |
if(currImg==0){//Tetris clock | |
//Bugs out when not on screen, resulting in incomplete letters or are already drawn, want to see the inital animation | |
//So we will block the animation from rendering until the fade is complete. (possibly half complete) | |
if(percent<0.2f){ | |
images.get(currImg).resetAnimation(); | |
println("Blocking tetrisclock"); | |
} | |
println(percent); | |
} else if(currImg == 1){ //Drones | |
//Doesn't look right when not animating and transitioning. | |
} else { | |
//Everything else | |
if(percent<0.9f){ | |
images.get(nextImg).pauseAnimation(); | |
} else { //Make sure we unpause our animations once the transition is complete | |
images.get(nextImg).resetAnimation(); | |
} | |
if(currImg >= 21 && percent<=0.9f) { //If the animation isn't a city outbound, then stop it from looping | |
images.get(currImg).resetAnimation(); //This should be forcing the animation to stick to the 1st frame and reset all it's timer variables | |
images.get(nextImg).loadAnimation();//Keep the outbound animation stuck on the last frame | |
} | |
if( currImg >= 21 && percent >= 0.9f){ | |
images.get(nextImg).resetAnimation(); | |
} | |
} | |
} | |
} | |
public void reset() { | |
// println("Reset"); | |
frameCount=0; | |
animationBlock = true; | |
try{ | |
f = faders[Integer.parseInt(config.get(carousel)[1])]; | |
nextImg = Integer.parseInt(config.get(carousel)[0]); | |
if (1 + carousel <= config.size()-1) | |
currImg = Integer.parseInt(config.get(carousel + 1)[0]); //Wrap if greater than the arrayList | |
else currImg = Integer.parseInt(config.get(0)[0]); | |
images.get(currImg).drawAnimation(pg); | |
images.get(nextImg).drawAnimation(pgIN); | |
// println("Carolsel is :"+carousel); | |
// println("CurrImg is :"+currImg); | |
// println("NextImg is :"+nextImg); | |
f.setImages(pg, pgIN);//Draw the gif routine | |
f.startFade(); | |
speed = Integer.parseInt(config.get(carousel)[2]); | |
delay = Float.parseFloat(config.get(carousel)[3]); | |
if(Integer.parseInt(config.get(carousel)[4])==0){ //See if the current frame has a XY value, if it doesn;t, load a safe value | |
if(carousel + 1 < config.size()){ | |
if(Integer.parseInt(config.get(carousel+1)[4])!=0) { //See if the next frame has an XYvalue | |
f.setXY(Integer.parseInt(config.get(carousel+1)[4]),Integer.parseInt(config.get(carousel+1)[5])); | |
} else {f.setXY(validX, validY);} | |
} | |
}else{ //If the curent frame has an XY value, load it and set the safe value. | |
f.setXY(Integer.parseInt(config.get(carousel)[4]),Integer.parseInt(config.get(carousel)[5])); | |
validX = Integer.parseInt(config.get(carousel)[4]); | |
validY = Integer.parseInt(config.get(carousel)[5]); | |
} | |
// images.get(currImg).resetAnimation(); | |
// images.get(nextImg).resetAnimation(); | |
if(carousel < config.size()-1){ | |
carousel++; | |
} else { | |
carousel = 0; | |
println("looping"); | |
} | |
}catch(NumberFormatException e){ | |
println(e); | |
} | |
} | |
//Observers | |
private ArrayList<Observer> obsList = new ArrayList(); | |
public void keyPressed(){ | |
notifyObservers(key); | |
} | |
public void keyReleased(){} | |
public void keyTyped(){} | |
public void notifyObservers(char KeyCode){ | |
for(Observer obs: obsList){ | |
obs.update(key); | |
} | |
} | |
//Setters and Getters | |
public void addObserver(Observer obs){ | |
if(obs != null) | |
obsList.add(obs); | |
} | |
public void delObserver(Observer obs){ | |
if (obs != null) | |
obsList.remove(obs); | |
} | |
//Setters and getters | |
int getXbound(){return xbound;} | |
int getYbound(){return ybound;} | |
int getpartWidth(){return partWidth;} | |
int getpartHeight(){return partHeight;} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import processing.core.PApplet; | |
import processing.core.PImage; | |
import java.io.File; | |
import java.util.ArrayList; | |
class FrameSaver extends Thread { | |
CircularArrayList<PImage> imgstore; | |
int savecnt=0; | |
int index=0; | |
boolean running; | |
PApplet parent; | |
public FrameSaver (PApplet p) { | |
running = false; | |
parent = p; | |
imgstore = new CircularArrayList<PImage>(500); | |
} | |
public void start() { | |
parent.println("recording frames!"); | |
running = true; | |
try{ | |
super.start(); | |
} | |
catch(java.lang.IllegalThreadStateException itse){ | |
parent.println("cannot execute! ->" + itse); | |
} | |
} | |
public void addImage(PImage img){ | |
index ++; | |
try{ | |
imgstore.add(img); | |
} catch(OutOfMemoryError e){ | |
parent.println(e); | |
} | |
} | |
public void run(){ | |
while(running){ | |
if(imgstore.size()>1){ | |
saveIncremental(imgstore.get(0),"imageSequence/Flipdot","bmp"); | |
imgstore.remove(0); | |
} | |
} | |
} | |
public void quit() { | |
parent.println("stopped recording.."); | |
running = false; | |
interrupt(); | |
} | |
// Saves a file with automatically incrementing filename, | |
// so that existing files are not overwritten. Will | |
// function correctly for less than 1000 files. | |
void saveIncremental(PImage img,String prefix,String extension) { | |
boolean ok=false; | |
String filename=""; | |
File f; | |
while(!ok) { | |
// Get a correctly configured filename | |
filename=prefix; | |
if(savecnt<10) filename+="0000"; | |
else if(savecnt<100) filename+="000"; | |
else if(savecnt<1000) filename+="00"; | |
else if(savecnt<10000) filename+="0"; | |
filename+=""+savecnt+"."+extension; | |
// Check to see if file exists, using the undocumented | |
// savePath() to find sketch folder | |
f=new File(parent.savePath(filename)); | |
if(!f.exists()) ok=true; // File doesn't exist | |
savecnt++; | |
} | |
parent.println("Saving "+filename); | |
try{ | |
img.save(filename); | |
}catch(NullPointerException e){ | |
parent.println(e); | |
parent.println(imgstore.size()); | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package gifAnimation;/* | |
* GifAnimation is a processing library to play gif animations and to | |
* extract frames from a gif file. It can also export animated GIF animations | |
* This file class is under a GPL license. The Decoder used to open the | |
* gif files was written by Kevin Weiner. please see the separate copyright | |
* notice in the header of the GifDecoder / GifEncoder class. | |
* | |
* by extrapixel 2007 | |
* http://extrapixel.ch | |
* | |
This program is free software: you can redistribute it and/or modify | |
it under the terms of the GNU General Public License as published by | |
the Free Software Foundation, either version 3 of the License, or | |
(at your option) any later version. | |
This program is distributed in the hope that it will be useful, | |
but WITHOUT ANY WARRANTY; without even the implied warranty of | |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
GNU General Public License for more details. | |
You should have received a copy of the GNU General Public License | |
along with this program. If not, see <http://www.gnu.org/licenses/>. | |
*/ | |
import java.awt.image.BufferedImage; | |
import java.io.*; | |
import gifAnimation.GifDecoder; | |
import processing.core.*; | |
public class Gif extends PImage implements PConstants, Runnable { | |
private PApplet parent; | |
Thread runner; | |
// if the animation is currently playing | |
public boolean play; | |
// if the animation is currently looping | |
private boolean loop; | |
// wehter the repeat setting from the gif-file should be ignored | |
private boolean ignoreRepeatSetting = false; | |
// nr of repeats specified in the gif-file. 0 means repeat forever | |
private int repeatSetting = 1; | |
// how often this animation has repeated since last call to play() | |
private int repeatCount = 0; | |
// the current frame number | |
private int currentFrame; | |
// array containing the frames as PImages | |
private PImage[] frames; | |
// array containing the delay in ms of every frame | |
private int[] delays; | |
// last time the frame changed | |
private long lastJumpTime; | |
// version | |
private static String version = "2.3"; | |
public Gif(PApplet parent, String filename) { | |
// this creates a fake image so that the first time this | |
// attempts to draw, something happens that's not an exception | |
super(1, 1, ARGB); | |
this.parent = parent; | |
// create the GifDecoder | |
GifDecoder gifDecoder = createDecoder(parent, filename); | |
// fill up the PImage and the delay arrays | |
frames = extractFrames(gifDecoder); | |
delays = extractDelays(gifDecoder); | |
// get the GIFs repeat count | |
repeatSetting = gifDecoder.getLoopCount(); | |
// re-init our PImage with the new size | |
super.init(frames[0].width, frames[0].height, ARGB); | |
jump(0); | |
parent.registerDispose(this); | |
// and now, make the magic happen | |
runner = new Thread(this); | |
runner.start(); | |
} | |
public void dispose() { | |
// fin | |
// System.out.println("disposing"); | |
stop(); | |
runner = null; | |
} | |
/* | |
* the thread's run method | |
*/ | |
public void run() { | |
while (Thread.currentThread() == runner) { | |
try { | |
Thread.sleep(5); | |
} catch (InterruptedException e) { | |
} | |
if (play) { | |
// if playing, check if we need to go to next frame | |
if (parent.millis() - lastJumpTime >= delays[currentFrame]) { | |
// we need to jump | |
if (currentFrame == frames.length - 1) { | |
// its the last frame | |
if (loop) { | |
jump(0); // loop is on, so rewind | |
} else if (!ignoreRepeatSetting) { | |
// we're not looping, but we need to respect the | |
// GIF's repeat setting | |
repeatCount++; | |
if (repeatSetting == 0) { | |
// we need to repeat forever | |
jump(0); | |
} else if (repeatCount == repeatSetting) { | |
// stop repeating, we've reached the repeat | |
// setting | |
stop(); | |
} | |
} else { | |
// no loop & ignoring the repeat setting, so just | |
// stop. | |
stop(); | |
} | |
} else { | |
// go to the next frame | |
jump(currentFrame + 1); | |
} | |
} | |
} | |
} | |
} | |
/* | |
* creates an input stream using processings openStream() method to read | |
* from the sketch data-directory | |
*/ | |
private static InputStream createInputStream(PApplet parent, String filename) { | |
try{ | |
InputStream inputStream = parent.createInput(filename); | |
return inputStream; | |
}catch(RuntimeException e){ | |
parent.println(e); | |
return null; | |
} | |
} | |
/* | |
* in case someone wants to mess with the frames directly, they can get an | |
* array of PImages containing the animation frames. without having a | |
* gif-object with a seperate thread | |
* | |
* it takes a filename of a file in the datafolder. | |
*/ | |
public static PImage[] getPImages(PApplet parent, String filename) { | |
GifDecoder gifDecoder = createDecoder(parent, filename); | |
return extractFrames(gifDecoder); | |
} | |
/* | |
* probably someone wants all the frames even if he has a playback-gif... | |
*/ | |
public PImage[] getPImages() { | |
return frames; | |
} | |
public int getNumFrames(){ | |
return frames.length-1; | |
} | |
/* | |
* creates a GifDecoder object and loads a gif file | |
*/ | |
private static GifDecoder createDecoder(PApplet parent, String filename) { | |
GifDecoder gifDecoder = new GifDecoder(); | |
gifDecoder.read(createInputStream(parent, filename)); | |
return gifDecoder; | |
} | |
/* | |
* creates a PImage-array of gif frames in a GifDecoder object | |
*/ | |
private static PImage[] extractFrames(GifDecoder gifDecoder) { | |
int n = gifDecoder.getFrameCount(); | |
PImage[] frames = new PImage[n]; | |
for (int i = 0; i < n; i++) { | |
BufferedImage frame = gifDecoder.getFrame(i); | |
frames[i] = new PImage(frame.getWidth(), frame.getHeight(), ARGB); | |
System.arraycopy(frame.getRGB(0, 0, frame.getWidth(), frame | |
.getHeight(), null, 0, frame.getWidth()), 0, | |
frames[i].pixels, 0, frame.getWidth() * frame.getHeight()); | |
} | |
return frames; | |
} | |
/* | |
* creates an int-array of frame delays in the gifDecoder object | |
*/ | |
private static int[] extractDelays(GifDecoder gifDecoder) { | |
int n = gifDecoder.getFrameCount(); | |
int[] delays = new int[n]; | |
for (int i = 0; i < n; i++) { | |
delays[i] = gifDecoder.getDelay(i); // display duration of frame in | |
// milliseconds | |
} | |
return delays; | |
} | |
/* | |
* Can be called to ignore the repeat-count set in the gif-file. this does | |
* not affect loop()/noLoop() settings. | |
*/ | |
public void ignoreRepeat() { | |
ignoreRepeatSetting = true; | |
} | |
/* | |
* returns the number of repeats that is specified in the gif-file 0 means | |
* repeat forever | |
*/ | |
public int getRepeat() { | |
return repeatSetting; | |
} | |
/* | |
* returns true if this GIF object is playing | |
*/ | |
public boolean isPlaying() { | |
return play; | |
} | |
/* | |
* returns the current frame number | |
*/ | |
public int currentFrame() { | |
return currentFrame; | |
} | |
/* | |
* returns true if the animation is set to loop | |
*/ | |
public boolean isLooping() { | |
return loop; | |
} | |
/* | |
* returns true if this animation is set to ignore the file's repeat setting | |
*/ | |
public boolean isIgnoringRepeat() { | |
return ignoreRepeatSetting; | |
} | |
/* | |
* returns the version of the library | |
*/ | |
public static String version() { | |
return version; | |
} | |
/* | |
* following methods mimic the behaviour of processing's movie class. | |
*/ | |
/** | |
* Begin playing the animation, with no repeat. | |
*/ | |
public void play() { | |
play = true; | |
jump(0); | |
if (!ignoreRepeatSetting) { | |
repeatCount = 0; | |
} | |
} | |
/** | |
* Begin playing the animation, with repeat. | |
*/ | |
public void loop() { | |
play = true; | |
loop = true; | |
} | |
/** | |
* Shut off the repeating loop. | |
*/ | |
public void noLoop() { | |
loop = false; | |
} | |
/** | |
* Pause the animation at its current frame. | |
*/ | |
public void pause() { | |
// System.out.println("pause"); | |
play = false; | |
} | |
/** | |
* Stop the animation, and rewind. | |
*/ | |
public void stop() { | |
//System.out.println("stop"); | |
play = false; | |
currentFrame = 0; | |
repeatCount = 0; | |
} | |
/** | |
* Jump to a specific location (in frames). if the frame does not exist, go | |
* to last frame | |
*/ | |
public void jump(int where) { | |
if (frames.length > where) { | |
currentFrame = where; | |
// update the pixel-array | |
loadPixels(); | |
System.arraycopy(frames[currentFrame].pixels, 0, pixels, 0, width | |
* height); | |
updatePixels(); | |
// set the jump time | |
lastJumpTime = parent.millis(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package gifAnimation; | |
import java.awt.AlphaComposite; | |
import java.awt.Color; | |
import java.awt.Dimension; | |
import java.awt.Graphics2D; | |
import java.awt.Rectangle; | |
import java.awt.image.BufferedImage; | |
import java.awt.image.DataBufferInt; | |
import java.io.BufferedInputStream; | |
import java.io.FileInputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.net.URL; | |
import java.util.ArrayList; | |
/** | |
* Class GifDecoder - Decodes a GIF file into one or more frames. <br> | |
* <p/> | |
* <pre> | |
* Example: | |
* GifDecoder d = new GifDecoder(); | |
* d.read("sample.gif"); | |
* int n = d.getFrameCount(); | |
* for (int i = 0; i < n; i++) { | |
* BufferedImage frame = d.getFrame(i); // frame i | |
* int t = d.getDelay(i); // display duration of frame in milliseconds | |
* // do something with frame | |
* } | |
* </pre> | |
* <p/> | |
* No copyright asserted on the source code of this class. May be used for any | |
* purpose, however, refer to the Unisys LZW patent for any additional | |
* restrictions. Please forward any corrections to kweiner@fmsware.com. | |
* | |
* @author Kevin Weiner, FM Software; LZW decoder adapted from John Cristy's | |
* ImageMagick. | |
* @version 1.03 November 2003 | |
*/ | |
public class GifDecoder { | |
/** | |
* File read status: No errors. | |
*/ | |
public static final int STATUS_OK = 0; | |
/** | |
* File read status: Error decoding file (may be partially decoded) | |
*/ | |
public static final int STATUS_FORMAT_ERROR = 1; | |
/** | |
* File read status: Unable to open source. | |
*/ | |
public static final int STATUS_OPEN_ERROR = 2; | |
protected BufferedInputStream in; | |
protected int status; | |
protected int width; // full image width | |
protected int height; // full image height | |
protected boolean gctFlag; // global color table used | |
protected int gctSize; // size of global color table | |
protected int loopCount = 1; // iterations; 0 = repeat forever | |
protected int[] gct; // global color table | |
protected int[] lct; // local color table | |
protected int[] act; // active color table | |
protected int bgIndex; // background color index | |
protected int bgColor; // background color | |
protected int lastBgColor; // previous bg color | |
protected int pixelAspect; // pixel aspect ratio | |
protected boolean lctFlag; // local color table flag | |
protected boolean interlace; // interlace flag | |
protected int lctSize; // local color table size | |
protected int ix, iy, iw, ih; // current image rectangle | |
protected Rectangle lastRect; // last image rect | |
protected BufferedImage image; // current frame | |
protected BufferedImage lastImage; // previous frame | |
protected byte[] block = new byte[256]; // current data block | |
protected int blockSize = 0; // block size | |
// last graphic control extension info | |
protected int dispose = 0; | |
// 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev | |
protected int lastDispose = 0; | |
protected boolean transparency = false; // use transparent color | |
protected int delay = 0; // delay in milliseconds | |
protected int transIndex; // transparent color index | |
protected static final int MaxStackSize = 4096; | |
// max decoder pixel stack size | |
// LZW decoder working arrays | |
protected short[] prefix; | |
protected byte[] suffix; | |
protected byte[] pixelStack; | |
protected byte[] pixels; | |
protected ArrayList frames; // frames read from current file | |
protected int frameCount; | |
static class GifFrame { | |
public GifFrame(BufferedImage im, int del) { | |
image = im; | |
delay = del; | |
} | |
public BufferedImage image; | |
public int delay; | |
} | |
/** | |
* Gets display duration for specified frame. | |
* | |
* @param n int index of frame | |
* @return delay in milliseconds | |
*/ | |
public int getDelay(int n) { | |
// | |
delay = -1; | |
if ((n >= 0) && (n < frameCount)) { | |
delay = ((GifFrame) frames.get(n)).delay; | |
} | |
return delay; | |
} | |
/** | |
* Gets the number of frames read from file. | |
* | |
* @return frame count | |
*/ | |
public int getFrameCount() { | |
return frameCount; | |
} | |
/** | |
* Gets the first (or only) image read. | |
* | |
* @return BufferedImage containing first frame, or null if none. | |
*/ | |
public BufferedImage getImage() { | |
return getFrame(0); | |
} | |
/** | |
* Gets the "Netscape" iteration count, if any. A count of 0 means repeat | |
* indefinitiely. | |
* | |
* @return iteration count if one was specified, else 1. | |
*/ | |
public int getLoopCount() { | |
return loopCount; | |
} | |
/** | |
* Creates new frame image from current data (and previous frames as specified | |
* by their disposition codes). | |
*/ | |
protected void setPixels() { | |
// expose destination image's pixels as int array | |
int[] dest = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); | |
// fill in starting image contents based on last image's dispose code | |
if (lastDispose > 0) { | |
if (lastDispose == 3) { | |
// use image before last | |
int n = frameCount - 2; | |
if (n > 0) { | |
lastImage = getFrame(n - 1); | |
} else { | |
lastImage = null; | |
} | |
} | |
if (lastImage != null) { | |
int[] prev = ((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData(); | |
System.arraycopy(prev, 0, dest, 0, width * height); | |
// copy pixels | |
if (lastDispose == 2) { | |
// fill last image rect area with background color | |
Graphics2D g = image.createGraphics(); | |
Color c = null; | |
if (transparency) { | |
c = new Color(0, 0, 0, 0); // assume background is transparent | |
} else { | |
c = new Color(lastBgColor); // use given background color | |
} | |
g.setColor(c); | |
g.setComposite(AlphaComposite.Src); // replace area | |
g.fill(lastRect); | |
g.dispose(); | |
} | |
} | |
} | |
// copy each source line to the appropriate place in the destination | |
int pass = 1; | |
int inc = 8; | |
int iline = 0; | |
for (int i = 0; i < ih; i++) { | |
int line = i; | |
if (interlace) { | |
if (iline >= ih) { | |
pass++; | |
switch (pass) { | |
case 2: | |
iline = 4; | |
break; | |
case 3: | |
iline = 2; | |
inc = 4; | |
break; | |
case 4: | |
iline = 1; | |
inc = 2; | |
} | |
} | |
line = iline; | |
iline += inc; | |
} | |
line += iy; | |
if (line < height) { | |
int k = line * width; | |
int dx = k + ix; // start of line in dest | |
int dlim = dx + iw; // end of dest line | |
if ((k + width) < dlim) { | |
dlim = k + width; // past dest edge | |
} | |
int sx = i * iw; // start of line in source | |
while (dx < dlim) { | |
// map color and insert in destination | |
int index = ((int) pixels[sx++]) & 0xff; | |
int c = act[index]; | |
if (c != 0) { | |
dest[dx] = c; | |
} | |
dx++; | |
} | |
} | |
} | |
} | |
/** | |
* Gets the image contents of frame n. | |
* | |
* @return BufferedImage representation of frame, or null if n is invalid. | |
*/ | |
public BufferedImage getFrame(int n) { | |
BufferedImage im = null; | |
if ((n >= 0) && (n < frameCount)) { | |
im = ((GifFrame) frames.get(n)).image; | |
} | |
return im; | |
} | |
/** | |
* Gets image size. | |
* | |
* @return GIF image dimensions | |
*/ | |
public Dimension getFrameSize() { | |
return new Dimension(width, height); | |
} | |
/** | |
* Reads GIF image from stream | |
* | |
* @param BufferedInputStream containing GIF file. | |
* @return read status code (0 = no errors) | |
*/ | |
public int read(BufferedInputStream is) { | |
init(); | |
if (is != null) { | |
in = is; | |
readHeader(); | |
if (!err()) { | |
readContents(); | |
if (frameCount < 0) { | |
status = STATUS_FORMAT_ERROR; | |
} | |
} | |
} else { | |
status = STATUS_OPEN_ERROR; | |
} | |
try { | |
is.close(); | |
} catch (IOException e) { | |
} | |
return status; | |
} | |
/** | |
* Reads GIF image from stream | |
* | |
* @param InputStream containing GIF file. | |
* @return read status code (0 = no errors) | |
*/ | |
public int read(InputStream is) { | |
init(); | |
if (is != null) { | |
if (!(is instanceof BufferedInputStream)) | |
is = new BufferedInputStream(is); | |
in = (BufferedInputStream) is; | |
readHeader(); | |
if (!err()) { | |
readContents(); | |
if (frameCount < 0) { | |
status = STATUS_FORMAT_ERROR; | |
} | |
} | |
} else { | |
status = STATUS_OPEN_ERROR; | |
} | |
try { | |
is.close(); | |
} catch (IOException e) { | |
} | |
return status; | |
} | |
/** | |
* Reads GIF file from specified file/URL source (URL assumed if name contains | |
* ":/" or "file:") | |
* | |
* @param name String containing source | |
* @return read status code (0 = no errors) | |
*/ | |
public int read(String name) { | |
status = STATUS_OK; | |
try { | |
name = name.trim().toLowerCase(); | |
if ((name.indexOf("file:") >= 0) || (name.indexOf(":/") > 0)) { | |
URL url = new URL(name); | |
in = new BufferedInputStream(url.openStream()); | |
} else { | |
in = new BufferedInputStream(new FileInputStream(name)); | |
} | |
status = read(in); | |
} catch (IOException e) { | |
status = STATUS_OPEN_ERROR; | |
} | |
return status; | |
} | |
/** | |
* Decodes LZW image data into pixel array. Adapted from John Cristy's | |
* ImageMagick. | |
*/ | |
protected void decodeImageData() { | |
int NullCode = -1; | |
int npix = iw * ih; | |
int available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, count, i, datum, data_size, first, top, bi, pi; | |
if ((pixels == null) || (pixels.length < npix)) { | |
pixels = new byte[npix]; // allocate new pixel array | |
} | |
if (prefix == null) | |
prefix = new short[MaxStackSize]; | |
if (suffix == null) | |
suffix = new byte[MaxStackSize]; | |
if (pixelStack == null) | |
pixelStack = new byte[MaxStackSize + 1]; | |
// Initialize GIF data stream decoder. | |
data_size = read(); | |
clear = 1 << data_size; | |
end_of_information = clear + 1; | |
available = clear + 2; | |
old_code = NullCode; | |
code_size = data_size + 1; | |
code_mask = (1 << code_size) - 1; | |
for (code = 0; code < clear; code++) { | |
prefix[code] = 0; | |
suffix[code] = (byte) code; | |
} | |
// Decode GIF pixel stream. | |
datum = bits = count = first = top = pi = bi = 0; | |
for (i = 0; i < npix; ) { | |
if (top == 0) { | |
if (bits < code_size) { | |
// Load bytes until there are enough bits for a code. | |
if (count == 0) { | |
// Read a new data block. | |
count = readBlock(); | |
if (count <= 0) | |
break; | |
bi = 0; | |
} | |
datum += (((int) block[bi]) & 0xff) << bits; | |
bits += 8; | |
bi++; | |
count--; | |
continue; | |
} | |
// Get the next code. | |
code = datum & code_mask; | |
datum >>= code_size; | |
bits -= code_size; | |
// Interpret the code | |
if ((code > available) || (code == end_of_information)) | |
break; | |
if (code == clear) { | |
// Reset decoder. | |
code_size = data_size + 1; | |
code_mask = (1 << code_size) - 1; | |
available = clear + 2; | |
old_code = NullCode; | |
continue; | |
} | |
if (old_code == NullCode) { | |
pixelStack[top++] = suffix[code]; | |
old_code = code; | |
first = code; | |
continue; | |
} | |
in_code = code; | |
if (code == available) { | |
pixelStack[top++] = (byte) first; | |
code = old_code; | |
} | |
while (code > clear) { | |
pixelStack[top++] = suffix[code]; | |
code = prefix[code]; | |
} | |
first = ((int) suffix[code]) & 0xff; | |
// Add a new string to the string table, | |
if (available >= MaxStackSize) | |
break; | |
pixelStack[top++] = (byte) first; | |
prefix[available] = (short) old_code; | |
suffix[available] = (byte) first; | |
available++; | |
if (((available & code_mask) == 0) && (available < MaxStackSize)) { | |
code_size++; | |
code_mask += available; | |
} | |
old_code = in_code; | |
} | |
// Pop a pixel off the pixel stack. | |
top--; | |
pixels[pi++] = pixelStack[top]; | |
i++; | |
} | |
for (i = pi; i < npix; i++) { | |
pixels[i] = 0; // clear missing pixels | |
} | |
} | |
/** | |
* Returns true if an error was encountered during reading/decoding | |
*/ | |
protected boolean err() { | |
return status != STATUS_OK; | |
} | |
/** | |
* Initializes or re-initializes reader | |
*/ | |
protected void init() { | |
status = STATUS_OK; | |
frameCount = 0; | |
frames = new ArrayList(); | |
gct = null; | |
lct = null; | |
} | |
/** | |
* Reads a single byte from the input stream. | |
*/ | |
protected int read() { | |
int curByte = 0; | |
try { | |
curByte = in.read(); | |
} catch (IOException e) { | |
status = STATUS_FORMAT_ERROR; | |
} | |
return curByte; | |
} | |
/** | |
* Reads next variable length block from input. | |
* | |
* @return number of bytes stored in "buffer" | |
*/ | |
protected int readBlock() { | |
blockSize = read(); | |
int n = 0; | |
if (blockSize > 0) { | |
try { | |
int count = 0; | |
while (n < blockSize) { | |
count = in.read(block, n, blockSize - n); | |
if (count == -1) | |
break; | |
n += count; | |
} | |
} catch (IOException e) { | |
} | |
if (n < blockSize) { | |
status = STATUS_FORMAT_ERROR; | |
} | |
} | |
return n; | |
} | |
/** | |
* Reads color table as 256 RGB integer values | |
* | |
* @param ncolors int number of colors to read | |
* @return int array containing 256 colors (packed ARGB with full alpha) | |
*/ | |
protected int[] readColorTable(int ncolors) { | |
int nbytes = 3 * ncolors; | |
int[] tab = null; | |
byte[] c = new byte[nbytes]; | |
int n = 0; | |
try { | |
n = in.read(c); | |
} catch (IOException e) { | |
} | |
if (n < nbytes) { | |
status = STATUS_FORMAT_ERROR; | |
} else { | |
tab = new int[256]; // max size to avoid bounds checks | |
int i = 0; | |
int j = 0; | |
while (i < ncolors) { | |
int r = ((int) c[j++]) & 0xff; | |
int g = ((int) c[j++]) & 0xff; | |
int b = ((int) c[j++]) & 0xff; | |
tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b; | |
} | |
} | |
return tab; | |
} | |
/** | |
* Main file parser. Reads GIF content blocks. | |
*/ | |
protected void readContents() { | |
// read GIF file content blocks | |
boolean done = false; | |
while (!(done || err())) { | |
int code = read(); | |
switch (code) { | |
case 0x2C: // image separator | |
readImage(); | |
break; | |
case 0x21: // extension | |
code = read(); | |
switch (code) { | |
case 0xf9: // graphics control extension | |
readGraphicControlExt(); | |
break; | |
case 0xff: // application extension | |
readBlock(); | |
String app = ""; | |
for (int i = 0; i < 11; i++) { | |
app += (char) block[i]; | |
} | |
if (app.equals("NETSCAPE2.0")) { | |
readNetscapeExt(); | |
} else | |
skip(); // don't care | |
break; | |
default: // uninteresting extension | |
skip(); | |
} | |
break; | |
case 0x3b: // terminator | |
done = true; | |
break; | |
case 0x00: // bad byte, but keep going and see what happens | |
break; | |
default: | |
status = STATUS_FORMAT_ERROR; | |
} | |
} | |
} | |
/** | |
* Reads Graphics Control Extension values | |
*/ | |
protected void readGraphicControlExt() { | |
read(); // block size | |
int packed = read(); // packed fields | |
dispose = (packed & 0x1c) >> 2; // disposal method | |
if (dispose == 0) { | |
dispose = 1; // elect to keep old image if discretionary | |
} | |
transparency = (packed & 1) != 0; | |
delay = readShort() * 10; // delay in milliseconds | |
transIndex = read(); // transparent color index | |
read(); // block terminator | |
} | |
/** | |
* Reads GIF file header information. | |
*/ | |
protected void readHeader() { | |
String id = ""; | |
for (int i = 0; i < 6; i++) { | |
id += (char) read(); | |
} | |
if (!id.startsWith("GIF")) { | |
status = STATUS_FORMAT_ERROR; | |
return; | |
} | |
readLSD(); | |
if (gctFlag && !err()) { | |
gct = readColorTable(gctSize); | |
bgColor = gct[bgIndex]; | |
} | |
} | |
/** | |
* Reads next frame image | |
*/ | |
protected void readImage() { | |
ix = readShort(); // (sub)image position & size | |
iy = readShort(); | |
iw = readShort(); | |
ih = readShort(); | |
int packed = read(); | |
lctFlag = (packed & 0x80) != 0; // 1 - local color table flag | |
interlace = (packed & 0x40) != 0; // 2 - interlace flag | |
// 3 - sort flag | |
// 4-5 - reserved | |
lctSize = 2 << (packed & 7); // 6-8 - local color table size | |
if (lctFlag) { | |
lct = readColorTable(lctSize); // read table | |
act = lct; // make local table active | |
} else { | |
act = gct; // make global table active | |
if (bgIndex == transIndex) | |
bgColor = 0; | |
} | |
int save = 0; | |
if (transparency) { | |
save = act[transIndex]; | |
act[transIndex] = 0; // set transparent color if specified | |
} | |
if (act == null) { | |
status = STATUS_FORMAT_ERROR; // no color table defined | |
} | |
if (err()) | |
return; | |
decodeImageData(); // decode pixel data | |
skip(); | |
if (err()) | |
return; | |
frameCount++; | |
// create new image to receive frame data | |
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); | |
setPixels(); // transfer pixel data to image | |
frames.add(new GifFrame(image, delay)); // add image to frame list | |
if (transparency) { | |
act[transIndex] = save; | |
} | |
resetFrame(); | |
} | |
/** | |
* Reads Logical Screen Descriptor | |
*/ | |
protected void readLSD() { | |
// logical screen size | |
width = readShort(); | |
height = readShort(); | |
// packed fields | |
int packed = read(); | |
gctFlag = (packed & 0x80) != 0; // 1 : global color table flag | |
// 2-4 : color resolution | |
// 5 : gct sort flag | |
gctSize = 2 << (packed & 7); // 6-8 : gct size | |
bgIndex = read(); // background color index | |
pixelAspect = read(); // pixel aspect ratio | |
} | |
/** | |
* Reads Netscape extenstion to obtain iteration count | |
*/ | |
protected void readNetscapeExt() { | |
do { | |
readBlock(); | |
if (block[0] == 1) { | |
// loop count sub-block | |
int b1 = ((int) block[1]) & 0xff; | |
int b2 = ((int) block[2]) & 0xff; | |
loopCount = (b2 << 8) | b1; | |
} | |
} while ((blockSize > 0) && !err()); | |
} | |
/** | |
* Reads next 16-bit value, LSB first | |
*/ | |
protected int readShort() { | |
// read 16-bit value, LSB first | |
return read() | (read() << 8); | |
} | |
/** | |
* Resets frame state for reading next image. | |
*/ | |
protected void resetFrame() { | |
lastDispose = dispose; | |
lastRect = new Rectangle(ix, iy, iw, ih); | |
lastImage = image; | |
lastBgColor = bgColor; | |
int dispose = 0; | |
boolean transparency = false; | |
int delay = 0; | |
lct = null; | |
} | |
/** | |
* Skips variable length blocks up to and including next zero length block. | |
*/ | |
protected void skip() { | |
do { | |
readBlock(); | |
} while ((blockSize > 0) && !err()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package gifAnimation; | |
import java.io.*; | |
import java.awt.*; | |
import java.awt.image.*; | |
/** | |
* Class AnimatedGifEncoder - Encodes a GIF file consisting of one or more | |
* frames. | |
* <p/> | |
* <pre> | |
* Example: | |
* AnimatedGifEncoder e = new AnimatedGifEncoder(); | |
* e.start(outputFileName); | |
* e.setDelay(1000); // 1 frame per sec | |
* e.addFrame(image1); | |
* e.addFrame(image2); | |
* e.finish(); | |
* </pre> | |
* <p/> | |
* No copyright asserted on the source code of this class. May be used for any | |
* purpose, however, refer to the Unisys LZW patent for restrictions on use of | |
* the associated LZWEncoder class. Please forward any corrections to | |
* kweiner@fmsware.com. | |
* | |
* @author Kevin Weiner, FM Software | |
* @version 1.03 November 2003 | |
*/ | |
public class GifEncoder { | |
protected int width; // image size | |
protected int height; | |
protected Color transparent = null; // transparent color if given | |
protected int transIndex; // transparent index in color table | |
protected int repeat = -1; // no repeat | |
protected int delay = 0; // frame delay (hundredths) | |
protected boolean started = false; // ready to output frames | |
protected OutputStream out; | |
protected BufferedImage image; // current frame | |
protected byte[] pixels; // BGR byte array from frame | |
protected byte[] indexedPixels; // converted frame indexed to palette | |
protected int colorDepth; // number of bit planes | |
protected byte[] colorTab; // RGB palette | |
protected boolean[] usedEntry = new boolean[256]; // active palette entries | |
protected int palSize = 7; // color table size (bits-1) | |
protected int dispose = -1; // disposal code (-1 = use default) | |
protected boolean closeStream = false; // close stream when finished | |
protected boolean firstFrame = true; | |
protected boolean sizeSet = false; // if false, get size from first frame | |
protected int sample = 10; // default sample interval for quantizer | |
/** | |
* Sets the delay time between each frame, or changes it for subsequent frames | |
* (applies to last frame added). | |
* | |
* @param ms int delay time in milliseconds | |
*/ | |
public void setDelay(int ms) { | |
delay = Math.round(ms / 10.0f); | |
} | |
/** | |
* Sets the GIF frame disposal code for the last added frame and any | |
* subsequent frames. Default is 0 if no transparent color has been set, | |
* otherwise 2. | |
* | |
* @param code int disposal code. | |
*/ | |
public void setDispose(int code) { | |
if (code >= 0) { | |
dispose = code; | |
} | |
} | |
/** | |
* Sets the number of times the set of GIF frames should be played. Default is | |
* 1; 0 means play indefinitely. Must be invoked before the first image is | |
* added. | |
* | |
* @param iter int number of iterations. | |
* @return | |
*/ | |
public void setRepeat(int iter) { | |
if (iter >= 0) { | |
repeat = iter; | |
} | |
} | |
/** | |
* Sets the transparent color for the last added frame and any subsequent | |
* frames. Since all colors are subject to modification in the quantization | |
* process, the color in the final palette for each frame closest to the given | |
* color becomes the transparent color for that frame. May be set to null to | |
* indicate no transparent color. | |
* | |
* @param c Color to be treated as transparent on display. | |
*/ | |
public void setTransparent(Color c) { | |
transparent = c; | |
} | |
/** | |
* Adds next GIF frame. The frame is not written immediately, but is actually | |
* deferred until the next frame is received so that timing data can be | |
* inserted. Invoking <code>finish()</code> flushes all frames. If | |
* <code>setSize</code> was not invoked, the size of the first image is used | |
* for all subsequent frames. | |
* | |
* @param im BufferedImage containing frame to write. | |
* @return true if successful. | |
*/ | |
public boolean addFrame(BufferedImage im) { | |
if ((im == null) || !started) { | |
return false; | |
} | |
boolean ok = true; | |
try { | |
if (!sizeSet) { | |
// use first frame's size | |
setSize(im.getWidth(), im.getHeight()); | |
} | |
image = im; | |
getImagePixels(); // convert to correct format if necessary | |
analyzePixels(); // build color table & map pixels | |
if (firstFrame) { | |
writeLSD(); // logical screen descriptior | |
writePalette(); // global color table | |
if (repeat >= 0) { | |
// use NS app extension to indicate reps | |
writeNetscapeExt(); | |
} | |
} | |
writeGraphicCtrlExt(); // write graphic control extension | |
writeImageDesc(); // image descriptor | |
if (!firstFrame) { | |
writePalette(); // local color table | |
} | |
writePixels(); // encode and write pixel data | |
firstFrame = false; | |
} catch (IOException e) { | |
ok = false; | |
} | |
return ok; | |
} | |
/** | |
* Flushes any pending data and closes output file. If writing to an | |
* OutputStream, the stream is not closed. | |
*/ | |
public boolean finish() { | |
if (!started) | |
return false; | |
boolean ok = true; | |
started = false; | |
try { | |
out.write(0x3b); // gif trailer | |
out.flush(); | |
if (closeStream) { | |
out.close(); | |
} | |
} catch (IOException e) { | |
ok = false; | |
} | |
// reset for subsequent use | |
transIndex = 0; | |
out = null; | |
image = null; | |
pixels = null; | |
indexedPixels = null; | |
colorTab = null; | |
closeStream = false; | |
firstFrame = true; | |
return ok; | |
} | |
/** | |
* Sets frame rate in frames per second. Equivalent to | |
* <code>setDelay(1000/fps)</code>. | |
* | |
* @param fps float frame rate (frames per second) | |
*/ | |
public void setFrameRate(float fps) { | |
if (fps != 0f) { | |
delay = Math.round(100f / fps); | |
} | |
} | |
/** | |
* Sets quality of color quantization (conversion of images to the maximum 256 | |
* colors allowed by the GIF specification). Lower values (minimum = 1) | |
* produce better colors, but slow processing significantly. 10 is the | |
* default, and produces good color mapping at reasonable speeds. Values | |
* greater than 20 do not yield significant improvements in speed. | |
* | |
* @param quality int greater than 0. | |
* @return | |
*/ | |
public void setQuality(int quality) { | |
if (quality < 1) | |
quality = 1; | |
sample = quality; | |
} | |
/** | |
* Sets the GIF frame size. The default size is the size of the first frame | |
* added if this method is not invoked. | |
* | |
* @param w int frame width. | |
* @param h int frame width. | |
*/ | |
public void setSize(int w, int h) { | |
if (started && !firstFrame) | |
return; | |
width = w; | |
height = h; | |
if (width < 1) | |
width = 320; | |
if (height < 1) | |
height = 240; | |
sizeSet = true; | |
} | |
/** | |
* Initiates GIF file creation on the given stream. The stream is not closed | |
* automatically. | |
* | |
* @param os OutputStream on which GIF images are written. | |
* @return false if initial write failed. | |
*/ | |
public boolean start(OutputStream os) { | |
if (os == null) | |
return false; | |
boolean ok = true; | |
closeStream = false; | |
out = os; | |
try { | |
writeString("GIF89a"); // header | |
} catch (IOException e) { | |
ok = false; | |
} | |
return started = ok; | |
} | |
/** | |
* Initiates writing of a GIF file with the specified name. | |
* | |
* @param file String containing output file name. | |
* @return false if open or initial write failed. | |
*/ | |
public boolean start(String file) { | |
boolean ok = true; | |
try { | |
out = new BufferedOutputStream(new FileOutputStream(file)); | |
ok = start(out); | |
closeStream = true; | |
} catch (IOException e) { | |
ok = false; | |
} | |
return started = ok; | |
} | |
/** | |
* Analyzes image colors and creates color map. | |
*/ | |
protected void analyzePixels() { | |
int len = pixels.length; | |
int nPix = len / 3; | |
indexedPixels = new byte[nPix]; | |
NeuQuant nq = new NeuQuant(pixels, len, sample); | |
// initialize quantizer | |
colorTab = nq.process(); // create reduced palette | |
// convert map from BGR to RGB | |
for (int i = 0; i < colorTab.length; i += 3) { | |
byte temp = colorTab[i]; | |
colorTab[i] = colorTab[i + 2]; | |
colorTab[i + 2] = temp; | |
usedEntry[i / 3] = false; | |
} | |
// map image pixels to new palette | |
int k = 0; | |
for (int i = 0; i < nPix; i++) { | |
int index = nq.map(pixels[k++] & 0xff, pixels[k++] & 0xff, pixels[k++] & 0xff); | |
usedEntry[index] = true; | |
indexedPixels[i] = (byte) index; | |
} | |
pixels = null; | |
colorDepth = 8; | |
palSize = 7; | |
// get closest match to transparent color if specified | |
if (transparent != null) { | |
transIndex = findClosest(transparent); | |
} | |
} | |
/** | |
* Returns index of palette color closest to c | |
*/ | |
protected int findClosest(Color c) { | |
if (colorTab == null) | |
return -1; | |
int r = c.getRed(); | |
int g = c.getGreen(); | |
int b = c.getBlue(); | |
int minpos = 0; | |
int dmin = 256 * 256 * 256; | |
int len = colorTab.length; | |
for (int i = 0; i < len; ) { | |
int dr = r - (colorTab[i++] & 0xff); | |
int dg = g - (colorTab[i++] & 0xff); | |
int db = b - (colorTab[i] & 0xff); | |
int d = dr * dr + dg * dg + db * db; | |
int index = i / 3; | |
if (usedEntry[index] && (d < dmin)) { | |
dmin = d; | |
minpos = index; | |
} | |
i++; | |
} | |
return minpos; | |
} | |
/** | |
* Extracts image pixels into byte array "pixels" | |
*/ | |
protected void getImagePixels() { | |
int w = image.getWidth(); | |
int h = image.getHeight(); | |
int type = image.getType(); | |
if ((w != width) || (h != height) || (type != BufferedImage.TYPE_3BYTE_BGR)) { | |
// create new image with right size/format | |
BufferedImage temp = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); | |
Graphics2D g = temp.createGraphics(); | |
g.drawImage(image, 0, 0, null); | |
image = temp; | |
} | |
pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); | |
} | |
/** | |
* Writes Graphic Control Extension | |
*/ | |
protected void writeGraphicCtrlExt() throws IOException { | |
out.write(0x21); // extension introducer | |
out.write(0xf9); // GCE label | |
out.write(4); // data block size | |
int transp, disp; | |
if (transparent == null) { | |
transp = 0; | |
disp = 0; // dispose = no action | |
} else { | |
transp = 1; | |
disp = 2; // force clear if using transparent color | |
} | |
if (dispose >= 0) { | |
disp = dispose & 7; // user override | |
} | |
disp <<= 2; | |
// packed fields | |
out.write(0 | // 1:3 reserved | |
disp | // 4:6 disposal | |
0 | // 7 user input - 0 = none | |
transp); // 8 transparency flag | |
writeShort(delay); // delay x 1/100 sec | |
out.write(transIndex); // transparent color index | |
out.write(0); // block terminator | |
} | |
/** | |
* Writes Image Descriptor | |
*/ | |
protected void writeImageDesc() throws IOException { | |
out.write(0x2c); // image separator | |
writeShort(0); // image position x,y = 0,0 | |
writeShort(0); | |
writeShort(width); // image size | |
writeShort(height); | |
// packed fields | |
if (firstFrame) { | |
// no LCT - GCT is used for first (or only) frame | |
out.write(0); | |
} else { | |
// specify normal LCT | |
out.write(0x80 | // 1 local color table 1=yes | |
0 | // 2 interlace - 0=no | |
0 | // 3 sorted - 0=no | |
0 | // 4-5 reserved | |
palSize); // 6-8 size of color table | |
} | |
} | |
/** | |
* Writes Logical Screen Descriptor | |
*/ | |
protected void writeLSD() throws IOException { | |
// logical screen size | |
writeShort(width); | |
writeShort(height); | |
// packed fields | |
out.write((0x80 | // 1 : global color table flag = 1 (gct used) | |
0x70 | // 2-4 : color resolution = 7 | |
0x00 | // 5 : gct sort flag = 0 | |
palSize)); // 6-8 : gct size | |
out.write(0); // background color index | |
out.write(0); // pixel aspect ratio - assume 1:1 | |
} | |
/** | |
* Writes Netscape application extension to define repeat count. | |
*/ | |
protected void writeNetscapeExt() throws IOException { | |
out.write(0x21); // extension introducer | |
out.write(0xff); // app extension label | |
out.write(11); // block size | |
writeString("NETSCAPE" + "2.0"); // app id + auth code | |
out.write(3); // sub-block size | |
out.write(1); // loop sub-block id | |
writeShort(repeat); // loop count (extra iterations, 0=repeat forever) | |
out.write(0); // block terminator | |
} | |
/** | |
* Writes color table | |
*/ | |
protected void writePalette() throws IOException { | |
out.write(colorTab, 0, colorTab.length); | |
int n = (3 * 256) - colorTab.length; | |
for (int i = 0; i < n; i++) { | |
out.write(0); | |
} | |
} | |
/** | |
* Encodes and writes pixel data | |
*/ | |
protected void writePixels() throws IOException { | |
LZWEncoder encoder = new LZWEncoder(width, height, indexedPixels, colorDepth); | |
encoder.encode(out); | |
} | |
/** | |
* Write 16-bit value to output stream, LSB first | |
*/ | |
protected void writeShort(int value) throws IOException { | |
out.write(value & 0xff); | |
out.write((value >> 8) & 0xff); | |
} | |
/** | |
* Writes string to output stream | |
*/ | |
protected void writeString(String s) throws IOException { | |
for (int i = 0; i < s.length(); i++) { | |
out.write((byte) s.charAt(i)); | |
} | |
} | |
} | |
/* | |
* NeuQuant Neural-Net Quantization Algorithm | |
* ------------------------------------------ | |
* | |
* Copyright (c) 1994 Anthony Dekker | |
* | |
* NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994. See | |
* "Kohonen neural networks for optimal colour quantization" in "Network: | |
* Computation in Neural Systems" Vol. 5 (1994) pp 351-367. for a discussion of | |
* the algorithm. | |
* | |
* Any party obtaining a copy of these files from the author, directly or | |
* indirectly, is granted, free of charge, a full and unrestricted irrevocable, | |
* world-wide, paid up, royalty-free, nonexclusive right and license to deal in | |
* this software and documentation files (the "Software"), including without | |
* limitation the rights to use, copy, modify, merge, publish, distribute, | |
* sublicense, and/or sell copies of the Software, and to permit persons who | |
* receive copies from any such party to do so, with the only requirement being | |
* that this copyright notice remain intact. | |
*/ | |
// Ported to Java 12/00 K Weiner | |
class NeuQuant { | |
protected static final int netsize = 256; /* number of colours used */ | |
/* four primes near 500 - assume no image has a length so large */ | |
/* that it is divisible by all four primes */ | |
protected static final int prime1 = 499; | |
protected static final int prime2 = 491; | |
protected static final int prime3 = 487; | |
protected static final int prime4 = 503; | |
protected static final int minpicturebytes = (3 * prime4); | |
/* minimum size for input image */ | |
/* | |
* Program Skeleton ---------------- [select samplefac in range 1..30] [read | |
* image from input file] pic = (unsigned char*) malloc(3*width*height); | |
* initnet(pic,3*width*height,samplefac); learn(); unbiasnet(); [write output | |
* image header, using writecolourmap(f)] inxbuild(); write output image using | |
* inxsearch(b,g,r) | |
*/ | |
/* | |
* Network Definitions ------------------- | |
*/ | |
protected static final int maxnetpos = (netsize - 1); | |
protected static final int netbiasshift = 4; /* bias for colour values */ | |
protected static final int ncycles = 100; /* no. of learning cycles */ | |
/* defs for freq and bias */ | |
protected static final int intbiasshift = 16; /* bias for fractions */ | |
protected static final int intbias = (((int) 1) << intbiasshift); | |
protected static final int gammashift = 10; /* gamma = 1024 */ | |
protected static final int gamma = (((int) 1) << gammashift); | |
protected static final int betashift = 10; | |
protected static final int beta = (intbias >> betashift); /* beta = 1/1024 */ | |
protected static final int betagamma = (intbias << (gammashift - betashift)); | |
/* defs for decreasing radius factor */ | |
protected static final int initrad = (netsize >> 3); /* | |
* for 256 cols, radius | |
* starts | |
*/ | |
protected static final int radiusbiasshift = 6; /* at 32.0 biased by 6 bits */ | |
protected static final int radiusbias = (((int) 1) << radiusbiasshift); | |
protected static final int initradius = (initrad * radiusbias); /* | |
* and | |
* decreases | |
* by a | |
*/ | |
protected static final int radiusdec = 30; /* factor of 1/30 each cycle */ | |
/* defs for decreasing alpha factor */ | |
protected static final int alphabiasshift = 10; /* alpha starts at 1.0 */ | |
protected static final int initalpha = (((int) 1) << alphabiasshift); | |
protected int alphadec; /* biased by 10 bits */ | |
/* radbias and alpharadbias used for radpower calculation */ | |
protected static final int radbiasshift = 8; | |
protected static final int radbias = (((int) 1) << radbiasshift); | |
protected static final int alpharadbshift = (alphabiasshift + radbiasshift); | |
protected static final int alpharadbias = (((int) 1) << alpharadbshift); | |
/* | |
* Types and Global Variables -------------------------- | |
*/ | |
protected byte[] thepicture; /* the input image itself */ | |
protected int lengthcount; /* lengthcount = H*W*3 */ | |
protected int samplefac; /* sampling factor 1..30 */ | |
// typedef int pixel[4]; /* BGRc */ | |
protected int[][] network; /* the network itself - [netsize][4] */ | |
protected int[] netindex = new int[256]; | |
/* for network lookup - really 256 */ | |
protected int[] bias = new int[netsize]; | |
/* bias and freq arrays for learning */ | |
protected int[] freq = new int[netsize]; | |
protected int[] radpower = new int[initrad]; | |
/* radpower for precomputation */ | |
/* | |
* Initialise network in range (0,0,0) to (255,255,255) and set parameters | |
* ----------------------------------------------------------------------- | |
*/ | |
public NeuQuant(byte[] thepic, int len, int sample) { | |
int i; | |
int[] p; | |
thepicture = thepic; | |
lengthcount = len; | |
samplefac = sample; | |
network = new int[netsize][]; | |
for (i = 0; i < netsize; i++) { | |
network[i] = new int[4]; | |
p = network[i]; | |
p[0] = p[1] = p[2] = (i << (netbiasshift + 8)) / netsize; | |
freq[i] = intbias / netsize; /* 1/netsize */ | |
bias[i] = 0; | |
} | |
} | |
public byte[] colorMap() { | |
byte[] map = new byte[3 * netsize]; | |
int[] index = new int[netsize]; | |
for (int i = 0; i < netsize; i++) | |
index[network[i][3]] = i; | |
int k = 0; | |
for (int i = 0; i < netsize; i++) { | |
int j = index[i]; | |
map[k++] = (byte) (network[j][0]); | |
map[k++] = (byte) (network[j][1]); | |
map[k++] = (byte) (network[j][2]); | |
} | |
return map; | |
} | |
/* | |
* Insertion sort of network and building of netindex[0..255] (to do after | |
* unbias) | |
* ------------------------------------------------------------------------------- | |
*/ | |
public void inxbuild() { | |
int i, j, smallpos, smallval; | |
int[] p; | |
int[] q; | |
int previouscol, startpos; | |
previouscol = 0; | |
startpos = 0; | |
for (i = 0; i < netsize; i++) { | |
p = network[i]; | |
smallpos = i; | |
smallval = p[1]; /* index on g */ | |
/* find smallest in i..netsize-1 */ | |
for (j = i + 1; j < netsize; j++) { | |
q = network[j]; | |
if (q[1] < smallval) { /* index on g */ | |
smallpos = j; | |
smallval = q[1]; /* index on g */ | |
} | |
} | |
q = network[smallpos]; | |
/* swap p (i) and q (smallpos) entries */ | |
if (i != smallpos) { | |
j = q[0]; | |
q[0] = p[0]; | |
p[0] = j; | |
j = q[1]; | |
q[1] = p[1]; | |
p[1] = j; | |
j = q[2]; | |
q[2] = p[2]; | |
p[2] = j; | |
j = q[3]; | |
q[3] = p[3]; | |
p[3] = j; | |
} | |
/* smallval entry is now in position i */ | |
if (smallval != previouscol) { | |
netindex[previouscol] = (startpos + i) >> 1; | |
for (j = previouscol + 1; j < smallval; j++) | |
netindex[j] = i; | |
previouscol = smallval; | |
startpos = i; | |
} | |
} | |
netindex[previouscol] = (startpos + maxnetpos) >> 1; | |
for (j = previouscol + 1; j < 256; j++) | |
netindex[j] = maxnetpos; /* really 256 */ | |
} | |
/* | |
* Main Learning Loop ------------------ | |
*/ | |
public void learn() { | |
int i, j, b, g, r; | |
int radius, rad, alpha, step, delta, samplepixels; | |
byte[] p; | |
int pix, lim; | |
if (lengthcount < minpicturebytes) | |
samplefac = 1; | |
alphadec = 30 + ((samplefac - 1) / 3); | |
p = thepicture; | |
pix = 0; | |
lim = lengthcount; | |
samplepixels = lengthcount / (3 * samplefac); | |
delta = samplepixels / ncycles; | |
alpha = initalpha; | |
radius = initradius; | |
rad = radius >> radiusbiasshift; | |
if (rad <= 1) | |
rad = 0; | |
for (i = 0; i < rad; i++) | |
radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad)); | |
// fprintf(stderr,"beginning 1D learning: initial radius=%d\n", rad); | |
if (lengthcount < minpicturebytes) | |
step = 3; | |
else if ((lengthcount % prime1) != 0) | |
step = 3 * prime1; | |
else { | |
if ((lengthcount % prime2) != 0) | |
step = 3 * prime2; | |
else { | |
if ((lengthcount % prime3) != 0) | |
step = 3 * prime3; | |
else | |
step = 3 * prime4; | |
} | |
} | |
i = 0; | |
while (i < samplepixels) { | |
b = (p[pix + 0] & 0xff) << netbiasshift; | |
g = (p[pix + 1] & 0xff) << netbiasshift; | |
r = (p[pix + 2] & 0xff) << netbiasshift; | |
j = contest(b, g, r); | |
altersingle(alpha, j, b, g, r); | |
if (rad != 0) | |
alterneigh(rad, j, b, g, r); /* alter neighbours */ | |
pix += step; | |
if (pix >= lim) | |
pix -= lengthcount; | |
i++; | |
if (delta == 0) | |
delta = 1; | |
if (i % delta == 0) { | |
alpha -= alpha / alphadec; | |
radius -= radius / radiusdec; | |
rad = radius >> radiusbiasshift; | |
if (rad <= 1) | |
rad = 0; | |
for (j = 0; j < rad; j++) | |
radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad)); | |
} | |
} | |
// fprintf(stderr,"finished 1D learning: final alpha=%f | |
// !\n",((float)alpha)/initalpha); | |
} | |
/* | |
* Search for BGR values 0..255 (after net is unbiased) and return colour | |
* index | |
* ---------------------------------------------------------------------------- | |
*/ | |
public int map(int b, int g, int r) { | |
int i, j, dist, a, bestd; | |
int[] p; | |
int best; | |
bestd = 1000; /* biggest possible dist is 256*3 */ | |
best = -1; | |
i = netindex[g]; /* index on g */ | |
j = i - 1; /* start at netindex[g] and work outwards */ | |
while ((i < netsize) || (j >= 0)) { | |
if (i < netsize) { | |
p = network[i]; | |
dist = p[1] - g; /* inx key */ | |
if (dist >= bestd) | |
i = netsize; /* stop iter */ | |
else { | |
i++; | |
if (dist < 0) | |
dist = -dist; | |
a = p[0] - b; | |
if (a < 0) | |
a = -a; | |
dist += a; | |
if (dist < bestd) { | |
a = p[2] - r; | |
if (a < 0) | |
a = -a; | |
dist += a; | |
if (dist < bestd) { | |
bestd = dist; | |
best = p[3]; | |
} | |
} | |
} | |
} | |
if (j >= 0) { | |
p = network[j]; | |
dist = g - p[1]; /* inx key - reverse dif */ | |
if (dist >= bestd) | |
j = -1; /* stop iter */ | |
else { | |
j--; | |
if (dist < 0) | |
dist = -dist; | |
a = p[0] - b; | |
if (a < 0) | |
a = -a; | |
dist += a; | |
if (dist < bestd) { | |
a = p[2] - r; | |
if (a < 0) | |
a = -a; | |
dist += a; | |
if (dist < bestd) { | |
bestd = dist; | |
best = p[3]; | |
} | |
} | |
} | |
} | |
} | |
return (best); | |
} | |
public byte[] process() { | |
learn(); | |
unbiasnet(); | |
inxbuild(); | |
return colorMap(); | |
} | |
/* | |
* Unbias network to give byte values 0..255 and record position i to prepare | |
* for sort | |
* ----------------------------------------------------------------------------------- | |
*/ | |
public void unbiasnet() { | |
int i, j; | |
for (i = 0; i < netsize; i++) { | |
network[i][0] >>= netbiasshift; | |
network[i][1] >>= netbiasshift; | |
network[i][2] >>= netbiasshift; | |
network[i][3] = i; /* record colour no */ | |
} | |
} | |
/* | |
* Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in | |
* radpower[|i-j|] | |
* --------------------------------------------------------------------------------- | |
*/ | |
protected void alterneigh(int rad, int i, int b, int g, int r) { | |
int j, k, lo, hi, a, m; | |
int[] p; | |
lo = i - rad; | |
if (lo < -1) | |
lo = -1; | |
hi = i + rad; | |
if (hi > netsize) | |
hi = netsize; | |
j = i + 1; | |
k = i - 1; | |
m = 1; | |
while ((j < hi) || (k > lo)) { | |
a = radpower[m++]; | |
if (j < hi) { | |
p = network[j++]; | |
try { | |
p[0] -= (a * (p[0] - b)) / alpharadbias; | |
p[1] -= (a * (p[1] - g)) / alpharadbias; | |
p[2] -= (a * (p[2] - r)) / alpharadbias; | |
} catch (Exception e) { | |
} // prevents 1.3 miscompilation | |
} | |
if (k > lo) { | |
p = network[k--]; | |
try { | |
p[0] -= (a * (p[0] - b)) / alpharadbias; | |
p[1] -= (a * (p[1] - g)) / alpharadbias; | |
p[2] -= (a * (p[2] - r)) / alpharadbias; | |
} catch (Exception e) { | |
} | |
} | |
} | |
} | |
/* | |
* Move neuron i towards biased (b,g,r) by factor alpha | |
* ---------------------------------------------------- | |
*/ | |
protected void altersingle(int alpha, int i, int b, int g, int r) { | |
/* alter hit neuron */ | |
int[] n = network[i]; | |
n[0] -= (alpha * (n[0] - b)) / initalpha; | |
n[1] -= (alpha * (n[1] - g)) / initalpha; | |
n[2] -= (alpha * (n[2] - r)) / initalpha; | |
} | |
/* | |
* Search for biased BGR values ---------------------------- | |
*/ | |
protected int contest(int b, int g, int r) { | |
/* finds closest neuron (min dist) and updates freq */ | |
/* finds best neuron (min dist-bias) and returns position */ | |
/* for frequently chosen neurons, freq[i] is high and bias[i] is negative */ | |
/* bias[i] = gamma*((1/netsize)-freq[i]) */ | |
int i, dist, a, biasdist, betafreq; | |
int bestpos, bestbiaspos, bestd, bestbiasd; | |
int[] n; | |
bestd = ~(((int) 1) << 31); | |
bestbiasd = bestd; | |
bestpos = -1; | |
bestbiaspos = bestpos; | |
for (i = 0; i < netsize; i++) { | |
n = network[i]; | |
dist = n[0] - b; | |
if (dist < 0) | |
dist = -dist; | |
a = n[1] - g; | |
if (a < 0) | |
a = -a; | |
dist += a; | |
a = n[2] - r; | |
if (a < 0) | |
a = -a; | |
dist += a; | |
if (dist < bestd) { | |
bestd = dist; | |
bestpos = i; | |
} | |
biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift)); | |
if (biasdist < bestbiasd) { | |
bestbiasd = biasdist; | |
bestbiaspos = i; | |
} | |
betafreq = (freq[i] >> betashift); | |
freq[i] -= betafreq; | |
bias[i] += (betafreq << gammashift); | |
} | |
freq[bestpos] += beta; | |
bias[bestpos] -= betagamma; | |
return (bestbiaspos); | |
} | |
} | |
// ============================================================================== | |
// Adapted from Jef Poskanzer's Java port by way of J. M. G. Elliott. | |
// K Weiner 12/00 | |
class LZWEncoder { | |
private static final int EOF = -1; | |
private int imgW, imgH; | |
private byte[] pixAry; | |
private int initCodeSize; | |
private int remaining; | |
private int curPixel; | |
// GIFCOMPR.C - GIF Image compression routines | |
// | |
// Lempel-Ziv compression based on 'compress'. GIF modifications by | |
// David Rowley (mgardi@watdcsu.waterloo.edu) | |
// General DEFINEs | |
static final int BITS = 12; | |
static final int HSIZE = 5003; // 80% occupancy | |
// GIF Image compression - modified 'compress' | |
// | |
// Based on: compress.c - File compression ala IEEE Computer, June 1984. | |
// | |
// By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas) | |
// Jim McKie (decvax!mcvax!jim) | |
// Steve Davies (decvax!vax135!petsd!peora!srd) | |
// Ken Turkowski (decvax!decwrl!turtlevax!ken) | |
// James A. Woods (decvax!ihnp4!ames!jaw) | |
// Joe Orost (decvax!vax135!petsd!joe) | |
int n_bits; // number of bits/code | |
int maxbits = BITS; // user settable max # bits/code | |
int maxcode; // maximum code, given n_bits | |
int maxmaxcode = 1 << BITS; // should NEVER generate this code | |
int[] htab = new int[HSIZE]; | |
int[] codetab = new int[HSIZE]; | |
int hsize = HSIZE; // for dynamic table sizing | |
int free_ent = 0; // first unused entry | |
// block compression parameters -- after all codes are used up, | |
// and compression rate changes, start over. | |
boolean clear_flg = false; | |
// Algorithm: use open addressing double hashing (no chaining) on the | |
// prefix code / next character combination. We do a variant of Knuth's | |
// algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime | |
// secondary probe. Here, the modular division first probe is gives way | |
// to a faster exclusive-or manipulation. Also do block compression with | |
// an adaptive reset, whereby the code table is cleared when the compression | |
// ratio decreases, but after the table fills. The variable-length output | |
// codes are re-sized at this point, and a special CLEAR code is generated | |
// for the decompressor. Late addition: construct the table according to | |
// file size for noticeable speed improvement on small files. Please direct | |
// questions about this implementation to ames!jaw. | |
int g_init_bits; | |
int ClearCode; | |
int EOFCode; | |
// output | |
// | |
// Output the given code. | |
// Inputs: | |
// code: A n_bits-bit integer. If == -1, then EOF. This assumes | |
// that n_bits =< wordsize - 1. | |
// Outputs: | |
// Outputs code to the file. | |
// Assumptions: | |
// Chars are 8 bits long. | |
// Algorithm: | |
// Maintain a BITS character long buffer (so that 8 codes will | |
// fit in it exactly). Use the VAX insv instruction to insert each | |
// code in turn. When the buffer fills up empty it and start over. | |
int cur_accum = 0; | |
int cur_bits = 0; | |
int masks[] = {0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, | |
0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF}; | |
// Number of characters so far in this 'packet' | |
int a_count; | |
// Define the storage for the packet accumulator | |
byte[] accum = new byte[256]; | |
// ---------------------------------------------------------------------------- | |
LZWEncoder(int width, int height, byte[] pixels, int color_depth) { | |
imgW = width; | |
imgH = height; | |
pixAry = pixels; | |
initCodeSize = Math.max(2, color_depth); | |
} | |
// Add a character to the end of the current packet, and if it is 254 | |
// characters, flush the packet to disk. | |
void char_out(byte c, OutputStream outs) throws IOException { | |
accum[a_count++] = c; | |
if (a_count >= 254) | |
flush_char(outs); | |
} | |
// Clear out the hash table | |
// table clear for block compress | |
void cl_block(OutputStream outs) throws IOException { | |
cl_hash(hsize); | |
free_ent = ClearCode + 2; | |
clear_flg = true; | |
output(ClearCode, outs); | |
} | |
// reset code table | |
void cl_hash(int hsize) { | |
for (int i = 0; i < hsize; ++i) | |
htab[i] = -1; | |
} | |
void compress(int init_bits, OutputStream outs) throws IOException { | |
int fcode; | |
int i /* = 0 */; | |
int c; | |
int ent; | |
int disp; | |
int hsize_reg; | |
int hshift; | |
// Set up the globals: g_init_bits - initial number of bits | |
g_init_bits = init_bits; | |
// Set up the necessary values | |
clear_flg = false; | |
n_bits = g_init_bits; | |
maxcode = MAXCODE(n_bits); | |
ClearCode = 1 << (init_bits - 1); | |
EOFCode = ClearCode + 1; | |
free_ent = ClearCode + 2; | |
a_count = 0; // clear packet | |
ent = nextPixel(); | |
hshift = 0; | |
for (fcode = hsize; fcode < 65536; fcode *= 2) | |
++hshift; | |
hshift = 8 - hshift; // set hash code range bound | |
hsize_reg = hsize; | |
cl_hash(hsize_reg); // clear hash table | |
output(ClearCode, outs); | |
outer_loop: | |
while ((c = nextPixel()) != EOF) { | |
fcode = (c << maxbits) + ent; | |
i = (c << hshift) ^ ent; // xor hashing | |
if (htab[i] == fcode) { | |
ent = codetab[i]; | |
continue; | |
} else if (htab[i] >= 0) // non-empty slot | |
{ | |
disp = hsize_reg - i; // secondary hash (after G. Knott) | |
if (i == 0) | |
disp = 1; | |
do { | |
if ((i -= disp) < 0) | |
i += hsize_reg; | |
if (htab[i] == fcode) { | |
ent = codetab[i]; | |
continue outer_loop; | |
} | |
} while (htab[i] >= 0); | |
} | |
output(ent, outs); | |
ent = c; | |
if (free_ent < maxmaxcode) { | |
codetab[i] = free_ent++; // code -> hashtable | |
htab[i] = fcode; | |
} else | |
cl_block(outs); | |
} | |
// Put out the final code. | |
output(ent, outs); | |
output(EOFCode, outs); | |
} | |
// ---------------------------------------------------------------------------- | |
void encode(OutputStream os) throws IOException { | |
os.write(initCodeSize); // write "initial code size" byte | |
remaining = imgW * imgH; // reset navigation variables | |
curPixel = 0; | |
compress(initCodeSize + 1, os); // compress and write the pixel data | |
os.write(0); // write block terminator | |
} | |
// Flush the packet to disk, and reset the accumulator | |
void flush_char(OutputStream outs) throws IOException { | |
if (a_count > 0) { | |
outs.write(a_count); | |
outs.write(accum, 0, a_count); | |
a_count = 0; | |
} | |
} | |
final int MAXCODE(int n_bits) { | |
return (1 << n_bits) - 1; | |
} | |
// ---------------------------------------------------------------------------- | |
// Return the next pixel from the image | |
// ---------------------------------------------------------------------------- | |
private int nextPixel() { | |
if (remaining == 0) | |
return EOF; | |
--remaining; | |
byte pix = pixAry[curPixel++]; | |
return pix & 0xff; | |
} | |
void output(int code, OutputStream outs) throws IOException { | |
cur_accum &= masks[cur_bits]; | |
if (cur_bits > 0) | |
cur_accum |= (code << cur_bits); | |
else | |
cur_accum = code; | |
cur_bits += n_bits; | |
while (cur_bits >= 8) { | |
char_out((byte) (cur_accum & 0xff), outs); | |
cur_accum >>= 8; | |
cur_bits -= 8; | |
} | |
// If the next entry is going to be too big for the code size, | |
// then increase it, if possible. | |
if (free_ent > maxcode || clear_flg) { | |
if (clear_flg) { | |
maxcode = MAXCODE(n_bits = g_init_bits); | |
clear_flg = false; | |
} else { | |
++n_bits; | |
if (n_bits == maxbits) | |
maxcode = maxmaxcode; | |
else | |
maxcode = MAXCODE(n_bits); | |
} | |
} | |
if (code == EOFCode) { | |
// At EOF, write the rest of the buffer. | |
while (cur_bits > 0) { | |
char_out((byte) (cur_accum & 0xff), outs); | |
cur_accum >>= 8; | |
cur_bits -= 8; | |
} | |
flush_char(outs); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* GifAnimation is a processing library to play gif animations and to | |
* extract frames from a gif file. It can also export animated GIF animations | |
* This file class is under a GPL license. The Decoder used to open the | |
* gif files was written by Kevin Weiner. please see the separate copyright | |
* notice in the header of the GifDecoder / GifEncoder class. | |
* | |
* by extrapixel 2007 | |
* http://extrapixel.ch | |
* | |
This program is free software: you can redistribute it and/or modify | |
it under the terms of the GNU General Public License as published by | |
the Free Software Foundation, either version 3 of the License, or | |
(at your option) any later version. | |
This program is distributed in the hope that it will be useful, | |
but WITHOUT ANY WARRANTY; without even the implied warranty of | |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
GNU General Public License for more details. | |
You should have received a copy of the GNU General Public License | |
along with this program. If not, see <http://www.gnu.org/licenses/>. | |
*/ | |
package gifAnimation; | |
import java.awt.Color; | |
import java.awt.image.BufferedImage; | |
import processing.core.PApplet; | |
import processing.core.PConstants; | |
import processing.core.PImage; | |
public class GifMaker implements PConstants { | |
public final static int DISPOSE_NOTHING = 0; | |
public final static int DISPOSE_KEEP = 1; | |
public final static int DISPOSE_RESTORE_BACKGROUND = 2; | |
public final static int DISPOSE_REMOVE = 3; | |
private GifEncoder encoder; | |
private PApplet parent; | |
public GifMaker(PApplet parent, String filename) { | |
this.parent = parent; | |
parent.registerDispose(this); | |
encoder = initEncoder(filename); | |
} | |
public GifMaker(PApplet parent, String filename, int quality) { | |
this.parent = parent; | |
parent.registerDispose(this); | |
encoder = initEncoder(filename); | |
setQuality(quality); | |
} | |
public GifMaker(PApplet parent, String filename, int quality, int bgColor) { | |
this.parent = parent; | |
parent.registerDispose(this); | |
encoder = initEncoder(filename); | |
setQuality(quality); | |
setTransparent(bgColor); | |
} | |
/* | |
* finish stuff up when sketch is killed | |
*/ | |
public void dispose() { | |
finish(); | |
} | |
private GifEncoder initEncoder(String filename) { | |
GifEncoder returnEncoder = new GifEncoder(); | |
returnEncoder.start(parent.savePath(filename)); | |
return returnEncoder; | |
} | |
/* | |
* adds a delay to the last added frame int in milliseconds | |
*/ | |
public void setDelay(int delay) { | |
encoder.setDelay(delay); | |
} | |
/* | |
* set the disposal mode for the last added frame | |
* | |
* from GIF specs: CODE MEANING 00 Nothing special 01 KEEP - retain the | |
* current image 02 RESTORE BACKGROUND - restore the background color 03 | |
* REMOVE - remove the current image, and restore whatever image was beneath | |
* it. | |
*/ | |
public void setDispose(int dispose) { | |
encoder.setDispose(dispose); | |
} | |
/** | |
* description taken from GifEncoder-class: Sets quality of color | |
* quantization (conversion of images to the maximum 256 colors allowed by | |
* the GIF specification). Lower values (minimum = 1) produce better colors, | |
* but slow processing significantly. 10 is the default, and produces good | |
* color mapping at reasonable speeds. Values greater than 20 do not yield | |
* significant improvements in speed. | |
* | |
* @param quality int greater than 0. | |
* @return | |
*/ | |
public void setQuality(int quality) { | |
encoder.setQuality(quality); | |
} | |
/* | |
* sets the amount of times the animation should repeat | |
* | |
*/ | |
public void setRepeat(int repeat) { | |
encoder.setRepeat(repeat); | |
} | |
/* | |
* sets the size of the GIF-file. if this method is not invoked, the size of | |
* the first added frame will be the image size. | |
*/ | |
public void setSize(int width, int height) { | |
encoder.setSize(width, height); | |
} | |
/* | |
* Sets the transparent color. Every pixel with this color will be | |
* transparent in the output File | |
*/ | |
public void setTransparent(int color) { | |
setTransparent((int) parent.red(color), (int) parent.green(color), | |
(int) parent.blue(color)); | |
} | |
public void setTransparent(float red, float green, float blue) { | |
setTransparent((int) red, (int) green, (int) blue); | |
} | |
public void setTransparent(int red, int green, int blue) { | |
encoder.setTransparent(new Color(red, green, blue)); | |
} | |
/* | |
* adds a frame to the current animation takes a PImage, or a pixel-array. | |
* if no parameter is passed, the currently displayed pixels in the sketch | |
* window is used. | |
*/ | |
public void addFrame() { | |
parent.loadPixels(); | |
addFrame(parent.pixels, parent.width, parent.height); | |
} | |
public void addFrame(PImage newImage) { | |
addFrame(newImage.pixels, newImage.width, newImage.height); | |
} | |
public void addFrame(int[] pixels, int width, int height) { | |
BufferedImage frame = new BufferedImage(width, height, | |
BufferedImage.TYPE_INT_ARGB); | |
frame.setRGB(0, 0, width, height, pixels, 0, width); | |
encoder.addFrame(frame); | |
} | |
/* | |
* finishes off the GIF-file and saves it to the given filename | |
* in the sketch directory. if the file already exists, it will | |
* be overridden! | |
*/ | |
public boolean finish() { | |
return encoder.finish(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import processing.core.*; | |
//import processing.serial.*; | |
import jssc.SerialPort; | |
import jssc.SerialPortException; | |
import java.io.ByteArrayOutputStream; | |
import java.io.IOException; | |
public class ImageProcessor extends Thread { | |
int maxBytes = 112; | |
byte[] bytes = new byte[maxBytes]; | |
CircularArrayList<byte[]> outputBuffer; | |
PImage buff; | |
boolean running; | |
boolean addingFrame; | |
String serPort; | |
// CloseThread serCloser = new CloseThread(); | |
PGraphics buffer; | |
Flipdot parent; | |
SerialPort port; | |
int xcount; | |
int ycount; | |
PImage[] r; | |
ByteArrayOutputStream outputStream; | |
ImageProcessor(String Port, Flipdot p){ | |
parent = p; | |
initSer(Port); | |
buffer = parent.createGraphics(p.getXbound(),p.getYbound()); | |
xcount = (int)Math.ceil(p.getXbound()/(p.getpartWidth() + 0.0)); //Number of panels wide from the total pixel width | |
ycount = (int)Math.ceil(p.getYbound()/(p.getpartHeight() + 0.0)); // Number of panels high from the total pixel height | |
r = new PImage[xcount*ycount]; | |
outputBuffer = new CircularArrayList<byte[]>(1000); //Lets create a 100 frame output buffer | |
} | |
public void start() { | |
parent.println("Starting data steam!"); | |
running = true; | |
try{ | |
if(!port.isOpened())initSer(serPort); | |
super.start(); | |
} | |
catch(java.lang.IllegalThreadStateException itse){ | |
parent.println("cannot execute! ->" + itse); | |
} | |
} | |
public void run(){ | |
if(outputBuffer.size()>100)System.out.println(outputBuffer.size());// Print if the buffer gets too big | |
while(running){ | |
while(!addingFrame){ | |
if(outputBuffer.size()>1){ | |
try{ | |
sendData(outputBuffer.get(0)); | |
// parent.println("sending data"); | |
outputBuffer.remove(0); | |
}catch(IllegalStateException e){ | |
outputBuffer.clear();//Lets flush the buffer if we have any problems | |
parent.println("Trying to reinit serial"); | |
quit(); | |
start(); | |
parent.println(e); | |
} | |
} | |
} | |
} | |
} | |
public void quit() { | |
parent.println("stopped sending data.."); | |
closePort(); | |
running = false; | |
interrupt(); | |
} | |
void initSer(String _port){ | |
parent.println("Opening port"); | |
try{ | |
// parent.println(port.); | |
port = new SerialPort(_port); | |
try{ | |
port.openPort(); | |
port.setParams(57600, 8, 1, 0); | |
}catch(SerialPortException e){ | |
System.out.println(e); | |
} | |
serPort = _port; | |
System.out.println(port.toString()); | |
System.out.print("Is Opened?:"); System.out.println(port.isOpened()); | |
for (int i=0; i < maxBytes; i++) bytes[i] = parent.parseByte(0); | |
} catch (RuntimeException e){ | |
e.printStackTrace(); | |
} | |
} | |
void closePort(){ | |
try{ | |
port.closePort(); | |
}catch(SerialPortException e){System.out.println(e);} | |
// initSer(serPort); | |
} | |
void bufferImg(PGraphics pg){ | |
addingFrame = true; | |
buff = parent.createImage(parent.getXbound(), parent.getYbound(), parent.ARGB); | |
pg.loadPixels(); | |
buff.loadPixels(); | |
parent.arrayCopy(pg.pixels, buff.pixels); | |
buff.updatePixels(); | |
r = splitImage(buff); | |
for(int i = 0; i < r.length; i++){ | |
convertToByte(r[i],i); | |
try{ | |
outputBuffer.add(outputStream.toByteArray()); | |
}catch(Exception e){ | |
outputBuffer.clear(); | |
parent.print("Adding frame: ");parent.println(addingFrame); | |
parent.print("Running: ");parent.println(running); | |
parent.println("Trying to reinit serial"); | |
quit(); | |
start(); | |
parent.println(e); | |
} | |
// sendData(); | |
} finishFrame(); | |
outputBuffer.add(outputStream.toByteArray()); //Lets add the a byte array of the output stream to our buffer. //Does this need to be called twice, or does it get captured when the loop runs? | |
addingFrame = false; | |
// sendData(); | |
} | |
PImage[] splitImage(PImage originalImg){ | |
PImage[] output = new PImage[xcount*ycount]; | |
int index = 0; | |
for (int ax = 0; ax < xcount; ax ++) { // Shifting panel width | |
for (int ay = 0; ay < ycount; ay ++) { // Shifting panel height | |
//Create image at coordinate (ax, ay) from the top left of the original image | |
output[index] = parent.createImage(parent.getpartWidth(), parent.getpartHeight(), parent.ALPHA); | |
output[index].loadPixels(); | |
originalImg.loadPixels(); | |
//Loop to copy pixels for each chunk | |
for (int px = 0; px < parent.getpartWidth(); px ++){ | |
for (int py = 0; py < parent.getpartHeight(); py ++ ){ | |
int newLoc = px + py * parent.getpartWidth(); // Create a 2d location of the array | |
int oldLoc = (ax * parent.getpartHeight() + px) + ((ay * parent.getpartHeight()+py)*parent.getXbound()) ; | |
output[index].pixels[newLoc] = originalImg.pixels[oldLoc]; | |
} | |
} | |
index++; | |
} | |
} | |
return output; | |
} | |
PGraphics drawSplit(){ | |
buffer = parent.createGraphics(parent.getXbound(),parent.getYbound()); | |
buffer.beginDraw(); | |
int index = 0; | |
for (int dy = 0; dy < ycount; dy++) { | |
for (int dx = 0; dx < xcount; dx++) { | |
r[index].loadPixels(); | |
// buffer.image(r[index], dx * partWidth, dy * partHeight, partWidth, partHeight); | |
buffer.set( dx * parent.getpartWidth(), dy * parent.getpartHeight(), r[index]); | |
index ++; | |
} | |
} | |
buffer.endDraw(); | |
// buffer.loadPixels(); | |
return buffer; | |
} | |
void convertToByte(PImage frame, int address){ | |
int index = 0; | |
StringBuilder byteBuff = new StringBuilder(); | |
String[] Str = new String[2048]; //String for Stirngbuffer debugging | |
byte[] data = new byte[112]; | |
outputStream = new ByteArrayOutputStream(); //Flush the outputStream | |
outputStream.write(0x80); //Header ("0x80 "); | |
outputStream.write(0x84); //Command Byte ("0x84"); | |
outputStream.write(address); //Address (hex(address,2)); | |
for (int py = 0; py < parent.getpartHeight(); py ++ ){ | |
for (int px = 0; px < parent.getpartWidth(); px ++){ | |
int newLoc = px + py * parent.partWidth; // Create a 2d location of the array | |
//Convert the row of pixels into a string for byte conversion | |
//There are 7 bits before the byte resets | |
//We check the last bit, then append another byte onto the end for downstream processing. | |
//println((frame.pixels[newLoc])); | |
if (byteBuff.length() == 7) | |
//When the array is at it's 7th bit, append a 0 to the end and reverse the string direction | |
//Then convert the string from binary to an int and then into a byte | |
{ | |
byteBuff.append("0"); | |
byteBuff.reverse(); | |
data[index] = parent.parseByte(parent.unbinary(byteBuff.toString())); | |
byteBuff.delete(0,byteBuff.length()); | |
//print(hex(data[index])); //print the raw hex string as it's being created | |
outputStream.write(data[index]); //We append the data array to the output stream | |
index++; | |
//println("pop!"); | |
} else { | |
// parent.println(frame.pixels[newLoc]); | |
{ if (frame.pixels[newLoc] != -1) //Here we can test the value of the pixel, to determine if it's black or white | |
{ | |
byteBuff.append("1"); | |
} else { | |
byteBuff.append("0"); | |
} | |
} | |
} | |
} | |
} | |
//println(" hex"); | |
outputStream.write(0x8F); | |
//println(); | |
// println(" 0x84"); | |
} | |
void sendData(byte[] byteArray) { | |
//Prepare the outputbytestream so it's ready to be sent | |
// =outputStream.toByteArray(); //Convert the outputbytestream to a byte array to be sent down the serial port. | |
try{ | |
port.writeBytes(byteArray); | |
}catch(SerialPortException e){ | |
System.out.println(e); | |
} | |
} | |
void finishFrame(){ | |
outputStream = new ByteArrayOutputStream();//Flush the outputStream | |
//Refresh the entire panel | |
outputStream.write(0x80); | |
outputStream.write(0x82); | |
outputStream.write(0x8F); | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import gifAnimation.Gif; | |
import processing.core.*; | |
public class Images extends Animation{ | |
PImage[] image; | |
Gif animation; | |
Images(Flipdot p, String file){ | |
animation = new Gif(this, file); | |
animation.loop(); //Set the animation to loop over and over | |
// animation | |
} | |
PGraphics drawAnimation(PGraphics pg) { | |
pg.image(animation,0,0); | |
return pg; | |
} | |
void updateAnimation(){ | |
animation.run(); | |
} | |
void resetAnimation(){ | |
animation.play(); | |
} | |
void loadAnimation(){ | |
if(animation.getNumFrames()>1){ | |
animation.jump(animation.getNumFrames()-1); | |
} else { | |
animation.jump(0); | |
} | |
} | |
void pauseAnimation(){ | |
animation.pause(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
GNU GENERAL PUBLIC LICENSE | |
Version 3, 29 June 2007 | |
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> | |
Everyone is permitted to copy and distribute verbatim copies | |
of this license document, but changing it is not allowed. | |
Preamble | |
The GNU General Public License is a free, copyleft license for | |
software and other kinds of works. | |
The licenses for most software and other practical works are designed | |
to take away your freedom to share and change the works. By contrast, | |
the GNU General Public License is intended to guarantee your freedom to | |
share and change all versions of a program--to make sure it remains free | |
software for all its users. We, the Free Software Foundation, use the | |
GNU General Public License for most of our software; it applies also to | |
any other work released this way by its authors. You can apply it to | |
your programs, too. | |
When we speak of free software, we are referring to freedom, not | |
price. Our General Public Licenses are designed to make sure that you | |
have the freedom to distribute copies of free software (and charge for | |
them if you wish), that you receive source code or can get it if you | |
want it, that you can change the software or use pieces of it in new | |
free programs, and that you know you can do these things. | |
To protect your rights, we need to prevent others from denying you | |
these rights or asking you to surrender the rights. Therefore, you have | |
certain responsibilities if you distribute copies of the software, or if | |
you modify it: responsibilities to respect the freedom of others. | |
For example, if you distribute copies of such a program, whether | |
gratis or for a fee, you must pass on to the recipients the same | |
freedoms that you received. You must make sure that they, too, receive | |
or can get the source code. And you must show them these terms so they | |
know their rights. | |
Developers that use the GNU GPL protect your rights with two steps: | |
(1) assert copyright on the software, and (2) offer you this License | |
giving you legal permission to copy, distribute and/or modify it. | |
For the developers' and authors' protection, the GPL clearly explains | |
that there is no warranty for this free software. For both users' and | |
authors' sake, the GPL requires that modified versions be marked as | |
changed, so that their problems will not be attributed erroneously to | |
authors of previous versions. | |
Some devices are designed to deny users access to install or run | |
modified versions of the software inside them, although the manufacturer | |
can do so. This is fundamentally incompatible with the aim of | |
protecting users' freedom to change the software. The systematic | |
pattern of such abuse occurs in the area of products for individuals to | |
use, which is precisely where it is most unacceptable. Therefore, we | |
have designed this version of the GPL to prohibit the practice for those | |
products. If such problems arise substantially in other domains, we | |
stand ready to extend this provision to those domains in future versions | |
of the GPL, as needed to protect the freedom of users. | |
Finally, every program is threatened constantly by software patents. | |
States should not allow patents to restrict development and use of | |
software on general-purpose computers, but in those that do, we wish to | |
avoid the special danger that patents applied to a free program could | |
make it effectively proprietary. To prevent this, the GPL assures that | |
patents cannot be used to render the program non-free. | |
The precise terms and conditions for copying, distribution and | |
modification follow. | |
TERMS AND CONDITIONS | |
0. Definitions. | |
"This License" refers to version 3 of the GNU General Public License. | |
"Copyright" also means copyright-like laws that apply to other kinds of | |
works, such as semiconductor masks. | |
"The Program" refers to any copyrightable work licensed under this | |
License. Each licensee is addressed as "you". "Licensees" and | |
"recipients" may be individuals or organizations. | |
To "modify" a work means to copy from or adapt all or part of the work | |
in a fashion requiring copyright permission, other than the making of an | |
exact copy. The resulting work is called a "modified version" of the | |
earlier work or a work "based on" the earlier work. | |
A "covered work" means either the unmodified Program or a work based | |
on the Program. | |
To "propagate" a work means to do anything with it that, without | |
permission, would make you directly or secondarily liable for | |
infringement under applicable copyright law, except executing it on a | |
computer or modifying a private copy. Propagation includes copying, | |
distribution (with or without modification), making available to the | |
public, and in some countries other activities as well. | |
To "convey" a work means any kind of propagation that enables other | |
parties to make or receive copies. Mere interaction with a user through | |
a computer network, with no transfer of a copy, is not conveying. | |
An interactive user interface displays "Appropriate Legal Notices" | |
to the extent that it includes a convenient and prominently visible | |
feature that (1) displays an appropriate copyright notice, and (2) | |
tells the user that there is no warranty for the work (except to the | |
extent that warranties are provided), that licensees may convey the | |
work under this License, and how to view a copy of this License. If | |
the interface presents a list of user commands or options, such as a | |
menu, a prominent item in the list meets this criterion. | |
1. Source Code. | |
The "source code" for a work means the preferred form of the work | |
for making modifications to it. "Object code" means any non-source | |
form of a work. | |
A "Standard Interface" means an interface that either is an official | |
standard defined by a recognized standards body, or, in the case of | |
interfaces specified for a particular programming language, one that | |
is widely used among developers working in that language. | |
The "System Libraries" of an executable work include anything, other | |
than the work as a whole, that (a) is included in the normal form of | |
packaging a Major Component, but which is not part of that Major | |
Component, and (b) serves only to enable use of the work with that | |
Major Component, or to implement a Standard Interface for which an | |
implementation is available to the public in source code form. A | |
"Major Component", in this context, means a major essential component | |
(kernel, window system, and so on) of the specific operating system | |
(if any) on which the executable work runs, or a compiler used to | |
produce the work, or an object code interpreter used to run it. | |
The "Corresponding Source" for a work in object code form means all | |
the source code needed to generate, install, and (for an executable | |
work) run the object code and to modify the work, including scripts to | |
control those activities. However, it does not include the work's | |
System Libraries, or general-purpose tools or generally available free | |
programs which are used unmodified in performing those activities but | |
which are not part of the work. For example, Corresponding Source | |
includes interface definition files associated with source files for | |
the work, and the source code for shared libraries and dynamically | |
linked subprograms that the work is specifically designed to require, | |
such as by intimate data communication or control flow between those | |
subprograms and other parts of the work. | |
The Corresponding Source need not include anything that users | |
can regenerate automatically from other parts of the Corresponding | |
Source. | |
The Corresponding Source for a work in source code form is that | |
same work. | |
2. Basic Permissions. | |
All rights granted under this License are granted for the term of | |
copyright on the Program, and are irrevocable provided the stated | |
conditions are met. This License explicitly affirms your unlimited | |
permission to run the unmodified Program. The output from running a | |
covered work is covered by this License only if the output, given its | |
content, constitutes a covered work. This License acknowledges your | |
rights of fair use or other equivalent, as provided by copyright law. | |
You may make, run and propagate covered works that you do not | |
convey, without conditions so long as your license otherwise remains | |
in force. You may convey covered works to others for the sole purpose | |
of having them make modifications exclusively for you, or provide you | |
with facilities for running those works, provided that you comply with | |
the terms of this License in conveying all material for which you do | |
not control copyright. Those thus making or running the covered works | |
for you must do so exclusively on your behalf, under your direction | |
and control, on terms that prohibit them from making any copies of | |
your copyrighted material outside their relationship with you. | |
Conveying under any other circumstances is permitted solely under | |
the conditions stated below. Sublicensing is not allowed; section 10 | |
makes it unnecessary. | |
3. Protecting Users' Legal Rights From Anti-Circumvention Law. | |
No covered work shall be deemed part of an effective technological | |
measure under any applicable law fulfilling obligations under article | |
11 of the WIPO copyright treaty adopted on 20 December 1996, or | |
similar laws prohibiting or restricting circumvention of such | |
measures. | |
When you convey a covered work, you waive any legal power to forbid | |
circumvention of technological measures to the extent such circumvention | |
is effected by exercising rights under this License with respect to | |
the covered work, and you disclaim any intention to limit operation or | |
modification of the work as a means of enforcing, against the work's | |
users, your or third parties' legal rights to forbid circumvention of | |
technological measures. | |
4. Conveying Verbatim Copies. | |
You may convey verbatim copies of the Program's source code as you | |
receive it, in any medium, provided that you conspicuously and | |
appropriately publish on each copy an appropriate copyright notice; | |
keep intact all notices stating that this License and any | |
non-permissive terms added in accord with section 7 apply to the code; | |
keep intact all notices of the absence of any warranty; and give all | |
recipients a copy of this License along with the Program. | |
You may charge any price or no price for each copy that you convey, | |
and you may offer support or warranty protection for a fee. | |
5. Conveying Modified Source Versions. | |
You may convey a work based on the Program, or the modifications to | |
produce it from the Program, in the form of source code under the | |
terms of section 4, provided that you also meet all of these conditions: | |
a) The work must carry prominent notices stating that you modified | |
it, and giving a relevant date. | |
b) The work must carry prominent notices stating that it is | |
released under this License and any conditions added under section | |
7. This requirement modifies the requirement in section 4 to | |
"keep intact all notices". | |
c) You must license the entire work, as a whole, under this | |
License to anyone who comes into possession of a copy. This | |
License will therefore apply, along with any applicable section 7 | |
additional terms, to the whole of the work, and all its parts, | |
regardless of how they are packaged. This License gives no | |
permission to license the work in any other way, but it does not | |
invalidate such permission if you have separately received it. | |
d) If the work has interactive user interfaces, each must display | |
Appropriate Legal Notices; however, if the Program has interactive | |
interfaces that do not display Appropriate Legal Notices, your | |
work need not make them do so. | |
A compilation of a covered work with other separate and independent | |
works, which are not by their nature extensions of the covered work, | |
and which are not combined with it such as to form a larger program, | |
in or on a volume of a storage or distribution medium, is called an | |
"aggregate" if the compilation and its resulting copyright are not | |
used to limit the access or legal rights of the compilation's users | |
beyond what the individual works permit. Inclusion of a covered work | |
in an aggregate does not cause this License to apply to the other | |
parts of the aggregate. | |
6. Conveying Non-Source Forms. | |
You may convey a covered work in object code form under the terms | |
of sections 4 and 5, provided that you also convey the | |
machine-readable Corresponding Source under the terms of this License, | |
in one of these ways: | |
a) Convey the object code in, or embodied in, a physical product | |
(including a physical distribution medium), accompanied by the | |
Corresponding Source fixed on a durable physical medium | |
customarily used for software interchange. | |
b) Convey the object code in, or embodied in, a physical product | |
(including a physical distribution medium), accompanied by a | |
written offer, valid for at least three years and valid for as | |
long as you offer spare parts or customer support for that product | |
model, to give anyone who possesses the object code either (1) a | |
copy of the Corresponding Source for all the software in the | |
product that is covered by this License, on a durable physical | |
medium customarily used for software interchange, for a price no | |
more than your reasonable cost of physically performing this | |
conveying of source, or (2) access to copy the | |
Corresponding Source from a network server at no charge. | |
c) Convey individual copies of the object code with a copy of the | |
written offer to provide the Corresponding Source. This | |
alternative is allowed only occasionally and noncommercially, and | |
only if you received the object code with such an offer, in accord | |
with subsection 6b. | |
d) Convey the object code by offering access from a designated | |
place (gratis or for a charge), and offer equivalent access to the | |
Corresponding Source in the same way through the same place at no | |
further charge. You need not require recipients to copy the | |
Corresponding Source along with the object code. If the place to | |
copy the object code is a network server, the Corresponding Source | |
may be on a different server (operated by you or a third party) | |
that supports equivalent copying facilities, provided you maintain | |
clear directions next to the object code saying where to find the | |
Corresponding Source. Regardless of what server hosts the | |
Corresponding Source, you remain obligated to ensure that it is | |
available for as long as needed to satisfy these requirements. | |
e) Convey the object code using peer-to-peer transmission, provided | |
you inform other peers where the object code and Corresponding | |
Source of the work are being offered to the general public at no | |
charge under subsection 6d. | |
A separable portion of the object code, whose source code is excluded | |
from the Corresponding Source as a System Library, need not be | |
included in conveying the object code work. | |
A "User Product" is either (1) a "consumer product", which means any | |
tangible personal property which is normally used for personal, family, | |
or household purposes, or (2) anything designed or sold for incorporation | |
into a dwelling. In determining whether a product is a consumer product, | |
doubtful cases shall be resolved in favor of coverage. For a particular | |
product received by a particular user, "normally used" refers to a | |
typical or common use of that class of product, regardless of the status | |
of the particular user or of the way in which the particular user | |
actually uses, or expects or is expected to use, the product. A product | |
is a consumer product regardless of whether the product has substantial | |
commercial, industrial or non-consumer uses, unless such uses represent | |
the only significant mode of use of the product. | |
"Installation Information" for a User Product means any methods, | |
procedures, authorization keys, or other information required to install | |
and execute modified versions of a covered work in that User Product from | |
a modified version of its Corresponding Source. The information must | |
suffice to ensure that the continued functioning of the modified object | |
code is in no case prevented or interfered with solely because | |
modification has been made. | |
If you convey an object code work under this section in, or with, or | |
specifically for use in, a User Product, and the conveying occurs as | |
part of a transaction in which the right of possession and use of the | |
User Product is transferred to the recipient in perpetuity or for a | |
fixed term (regardless of how the transaction is characterized), the | |
Corresponding Source conveyed under this section must be accompanied | |
by the Installation Information. But this requirement does not apply | |
if neither you nor any third party retains the ability to install | |
modified object code on the User Product (for example, the work has | |
been installed in ROM). | |
The requirement to provide Installation Information does not include a | |
requirement to continue to provide support service, warranty, or updates | |
for a work that has been modified or installed by the recipient, or for | |
the User Product in which it has been modified or installed. Access to a | |
network may be denied when the modification itself materially and | |
adversely affects the operation of the network or violates the rules and | |
protocols for communication across the network. | |
Corresponding Source conveyed, and Installation Information provided, | |
in accord with this section must be in a format that is publicly | |
documented (and with an implementation available to the public in | |
source code form), and must require no special password or key for | |
unpacking, reading or copying. | |
7. Additional Terms. | |
"Additional permissions" are terms that supplement the terms of this | |
License by making exceptions from one or more of its conditions. | |
Additional permissions that are applicable to the entire Program shall | |
be treated as though they were included in this License, to the extent | |
that they are valid under applicable law. If additional permissions | |
apply only to part of the Program, that part may be used separately | |
under those permissions, but the entire Program remains governed by | |
this License without regard to the additional permissions. | |
When you convey a copy of a covered work, you may at your option | |
remove any additional permissions from that copy, or from any part of | |
it. (Additional permissions may be written to require their own | |
removal in certain cases when you modify the work.) You may place | |
additional permissions on material, added by you to a covered work, | |
for which you have or can give appropriate copyright permission. | |
Notwithstanding any other provision of this License, for material you | |
add to a covered work, you may (if authorized by the copyright holders of | |
that material) supplement the terms of this License with terms: | |
a) Disclaiming warranty or limiting liability differently from the | |
terms of sections 15 and 16 of this License; or | |
b) Requiring preservation of specified reasonable legal notices or | |
author attributions in that material or in the Appropriate Legal | |
Notices displayed by works containing it; or | |
c) Prohibiting misrepresentation of the origin of that material, or | |
requiring that modified versions of such material be marked in | |
reasonable ways as different from the original version; or | |
d) Limiting the use for publicity purposes of names of licensors or | |
authors of the material; or | |
e) Declining to grant rights under trademark law for use of some | |
trade names, trademarks, or service marks; or | |
f) Requiring indemnification of licensors and authors of that | |
material by anyone who conveys the material (or modified versions of | |
it) with contractual assumptions of liability to the recipient, for | |
any liability that these contractual assumptions directly impose on | |
those licensors and authors. | |
All other non-permissive additional terms are considered "further | |
restrictions" within the meaning of section 10. If the Program as you | |
received it, or any part of it, contains a notice stating that it is | |
governed by this License along with a term that is a further | |
restriction, you may remove that term. If a license document contains | |
a further restriction but permits relicensing or conveying under this | |
License, you may add to a covered work material governed by the terms | |
of that license document, provided that the further restriction does | |
not survive such relicensing or conveying. | |
If you add terms to a covered work in accord with this section, you | |
must place, in the relevant source files, a statement of the | |
additional terms that apply to those files, or a notice indicating | |
where to find the applicable terms. | |
Additional terms, permissive or non-permissive, may be stated in the | |
form of a separately written license, or stated as exceptions; | |
the above requirements apply either way. | |
8. Termination. | |
You may not propagate or modify a covered work except as expressly | |
provided under this License. Any attempt otherwise to propagate or | |
modify it is void, and will automatically terminate your rights under | |
this License (including any patent licenses granted under the third | |
paragraph of section 11). | |
However, if you cease all violation of this License, then your | |
license from a particular copyright holder is reinstated (a) | |
provisionally, unless and until the copyright holder explicitly and | |
finally terminates your license, and (b) permanently, if the copyright | |
holder fails to notify you of the violation by some reasonable means | |
prior to 60 days after the cessation. | |
Moreover, your license from a particular copyright holder is | |
reinstated permanently if the copyright holder notifies you of the | |
violation by some reasonable means, this is the first time you have | |
received notice of violation of this License (for any work) from that | |
copyright holder, and you cure the violation prior to 30 days after | |
your receipt of the notice. | |
Termination of your rights under this section does not terminate the | |
licenses of parties who have received copies or rights from you under | |
this License. If your rights have been terminated and not permanently | |
reinstated, you do not qualify to receive new licenses for the same | |
material under section 10. | |
9. Acceptance Not Required for Having Copies. | |
You are not required to accept this License in order to receive or | |
run a copy of the Program. Ancillary propagation of a covered work | |
occurring solely as a consequence of using peer-to-peer transmission | |
to receive a copy likewise does not require acceptance. However, | |
nothing other than this License grants you permission to propagate or | |
modify any covered work. These actions infringe copyright if you do | |
not accept this License. Therefore, by modifying or propagating a | |
covered work, you indicate your acceptance of this License to do so. | |
10. Automatic Licensing of Downstream Recipients. | |
Each time you convey a covered work, the recipient automatically | |
receives a license from the original licensors, to run, modify and | |
propagate that work, subject to this License. You are not responsible | |
for enforcing compliance by third parties with this License. | |
An "entity transaction" is a transaction transferring control of an | |
organization, or substantially all assets of one, or subdividing an | |
organization, or merging organizations. If propagation of a covered | |
work results from an entity transaction, each party to that | |
transaction who receives a copy of the work also receives whatever | |
licenses to the work the party's predecessor in interest had or could | |
give under the previous paragraph, plus a right to possession of the | |
Corresponding Source of the work from the predecessor in interest, if | |
the predecessor has it or can get it with reasonable efforts. | |
You may not impose any further restrictions on the exercise of the | |
rights granted or affirmed under this License. For example, you may | |
not impose a license fee, royalty, or other charge for exercise of | |
rights granted under this License, and you may not initiate litigation | |
(including a cross-claim or counterclaim in a lawsuit) alleging that | |
any patent claim is infringed by making, using, selling, offering for | |
sale, or importing the Program or any portion of it. | |
11. Patents. | |
A "contributor" is a copyright holder who authorizes use under this | |
License of the Program or a work on which the Program is based. The | |
work thus licensed is called the contributor's "contributor version". | |
A contributor's "essential patent claims" are all patent claims | |
owned or controlled by the contributor, whether already acquired or | |
hereafter acquired, that would be infringed by some manner, permitted | |
by this License, of making, using, or selling its contributor version, | |
but do not include claims that would be infringed only as a | |
consequence of further modification of the contributor version. For | |
purposes of this definition, "control" includes the right to grant | |
patent sublicenses in a manner consistent with the requirements of | |
this License. | |
Each contributor grants you a non-exclusive, worldwide, royalty-free | |
patent license under the contributor's essential patent claims, to | |
make, use, sell, offer for sale, import and otherwise run, modify and | |
propagate the contents of its contributor version. | |
In the following three paragraphs, a "patent license" is any express | |
agreement or commitment, however denominated, not to enforce a patent | |
(such as an express permission to practice a patent or covenant not to | |
sue for patent infringement). To "grant" such a patent license to a | |
party means to make such an agreement or commitment not to enforce a | |
patent against the party. | |
If you convey a covered work, knowingly relying on a patent license, | |
and the Corresponding Source of the work is not available for anyone | |
to copy, free of charge and under the terms of this License, through a | |
publicly available network server or other readily accessible means, | |
then you must either (1) cause the Corresponding Source to be so | |
available, or (2) arrange to deprive yourself of the benefit of the | |
patent license for this particular work, or (3) arrange, in a manner | |
consistent with the requirements of this License, to extend the patent | |
license to downstream recipients. "Knowingly relying" means you have | |
actual knowledge that, but for the patent license, your conveying the | |
covered work in a country, or your recipient's use of the covered work | |
in a country, would infringe one or more identifiable patents in that | |
country that you have reason to believe are valid. | |
If, pursuant to or in connection with a single transaction or | |
arrangement, you convey, or propagate by procuring conveyance of, a | |
covered work, and grant a patent license to some of the parties | |
receiving the covered work authorizing them to use, propagate, modify | |
or convey a specific copy of the covered work, then the patent license | |
you grant is automatically extended to all recipients of the covered | |
work and works based on it. | |
A patent license is "discriminatory" if it does not include within | |
the scope of its coverage, prohibits the exercise of, or is | |
conditioned on the non-exercise of one or more of the rights that are | |
specifically granted under this License. You may not convey a covered | |
work if you are a party to an arrangement with a third party that is | |
in the business of distributing software, under which you make payment | |
to the third party based on the extent of your activity of conveying | |
the work, and under which the third party grants, to any of the | |
parties who would receive the covered work from you, a discriminatory | |
patent license (a) in connection with copies of the covered work | |
conveyed by you (or copies made from those copies), or (b) primarily | |
for and in connection with specific products or compilations that | |
contain the covered work, unless you entered into that arrangement, | |
or that patent license was granted, prior to 28 March 2007. | |
Nothing in this License shall be construed as excluding or limiting | |
any implied license or other defenses to infringement that may | |
otherwise be available to you under applicable patent law. | |
12. No Surrender of Others' Freedom. | |
If conditions are imposed on you (whether by court order, agreement or | |
otherwise) that contradict the conditions of this License, they do not | |
excuse you from the conditions of this License. If you cannot convey a | |
covered work so as to satisfy simultaneously your obligations under this | |
License and any other pertinent obligations, then as a consequence you may | |
not convey it at all. For example, if you agree to terms that obligate you | |
to collect a royalty for further conveying from those to whom you convey | |
the Program, the only way you could satisfy both those terms and this | |
License would be to refrain entirely from conveying the Program. | |
13. Use with the GNU Affero General Public License. | |
Notwithstanding any other provision of this License, you have | |
permission to link or combine any covered work with a work licensed | |
under version 3 of the GNU Affero General Public License into a single | |
combined work, and to convey the resulting work. The terms of this | |
License will continue to apply to the part which is the covered work, | |
but the special requirements of the GNU Affero General Public License, | |
section 13, concerning interaction through a network will apply to the | |
combination as such. | |
14. Revised Versions of this License. | |
The Free Software Foundation may publish revised and/or new versions of | |
the GNU General Public License from time to time. Such new versions will | |
be similar in spirit to the present version, but may differ in detail to | |
address new problems or concerns. | |
Each version is given a distinguishing version number. If the | |
Program specifies that a certain numbered version of the GNU General | |
Public License "or any later version" applies to it, you have the | |
option of following the terms and conditions either of that numbered | |
version or of any later version published by the Free Software | |
Foundation. If the Program does not specify a version number of the | |
GNU General Public License, you may choose any version ever published | |
by the Free Software Foundation. | |
If the Program specifies that a proxy can decide which future | |
versions of the GNU General Public License can be used, that proxy's | |
public statement of acceptance of a version permanently authorizes you | |
to choose that version for the Program. | |
Later license versions may give you additional or different | |
permissions. However, no additional obligations are imposed on any | |
author or copyright holder as a result of your choosing to follow a | |
later version. | |
15. Disclaimer of Warranty. | |
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY | |
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT | |
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY | |
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, | |
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | |
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM | |
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF | |
ALL NECESSARY SERVICING, REPAIR OR CORRECTION. | |
16. Limitation of Liability. | |
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING | |
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS | |
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY | |
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE | |
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF | |
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD | |
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), | |
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF | |
SUCH DAMAGES. | |
17. Interpretation of Sections 15 and 16. | |
If the disclaimer of warranty and limitation of liability provided | |
above cannot be given local legal effect according to their terms, | |
reviewing courts shall apply local law that most closely approximates | |
an absolute waiver of all civil liability in connection with the | |
Program, unless a warranty or assumption of liability accompanies a | |
copy of the Program in return for a fee. | |
END OF TERMS AND CONDITIONS | |
How to Apply These Terms to Your New Programs | |
If you develop a new program, and you want it to be of the greatest | |
possible use to the public, the best way to achieve this is to make it | |
free software which everyone can redistribute and change under these terms. | |
To do so, attach the following notices to the program. It is safest | |
to attach them to the start of each source file to most effectively | |
state the exclusion of warranty; and each file should have at least | |
the "copyright" line and a pointer to where the full notice is found. | |
<one line to give the program's name and a brief idea of what it does.> | |
Copyright (C) <year> <name of author> | |
This program is free software: you can redistribute it and/or modify | |
it under the terms of the GNU General Public License as published by | |
the Free Software Foundation, either version 3 of the License, or | |
(at your option) any later version. | |
This program is distributed in the hope that it will be useful, | |
but WITHOUT ANY WARRANTY; without even the implied warranty of | |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
GNU General Public License for more details. | |
You should have received a copy of the GNU General Public License | |
along with this program. If not, see <http://www.gnu.org/licenses/>. | |
Also add information on how to contact you by electronic and paper mail. | |
If the program does terminal interaction, make it output a short | |
notice like this when it starts in an interactive mode: | |
<program> Copyright (C) <year> <name of author> | |
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. | |
This is free software, and you are welcome to redistribute it | |
under certain conditions; type `show c' for details. | |
The hypothetical commands `show w' and `show c' should show the appropriate | |
parts of the General Public License. Of course, your program's commands | |
might be different; for a GUI interface, you would use an "about box". | |
You should also get your employer (if you work as a programmer) or school, | |
if any, to sign a "copyright disclaimer" for the program, if necessary. | |
For more information on this, and how to apply and follow the GNU GPL, see | |
<http://www.gnu.org/licenses/>. | |
The GNU General Public License does not permit incorporating your program | |
into proprietary programs. If your program is a subroutine library, you | |
may consider it more useful to permit linking proprietary applications with | |
the library. If this is what you want to do, use the GNU Lesser General | |
Public License instead of this License. But first, please read | |
<http://www.gnu.org/philosophy/why-not-lgpl.html>. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
GNU LESSER GENERAL PUBLIC LICENSE | |
Version 3, 29 June 2007 | |
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> | |
Everyone is permitted to copy and distribute verbatim copies | |
of this license document, but changing it is not allowed. | |
This version of the GNU Lesser General Public License incorporates | |
the terms and conditions of version 3 of the GNU General Public | |
License, supplemented by the additional permissions listed below. | |
0. Additional Definitions. | |
As used herein, "this License" refers to version 3 of the GNU Lesser | |
General Public License, and the "GNU GPL" refers to version 3 of the GNU | |
General Public License. | |
"The Library" refers to a covered work governed by this License, | |
other than an Application or a Combined Work as defined below. | |
An "Application" is any work that makes use of an interface provided | |
by the Library, but which is not otherwise based on the Library. | |
Defining a subclass of a class defined by the Library is deemed a mode | |
of using an interface provided by the Library. | |
A "Combined Work" is a work produced by combining or linking an | |
Application with the Library. The particular version of the Library | |
with which the Combined Work was made is also called the "Linked | |
Version". | |
The "Minimal Corresponding Source" for a Combined Work means the | |
Corresponding Source for the Combined Work, excluding any source code | |
for portions of the Combined Work that, considered in isolation, are | |
based on the Application, and not on the Linked Version. | |
The "Corresponding Application Code" for a Combined Work means the | |
object code and/or source code for the Application, including any data | |
and utility programs needed for reproducing the Combined Work from the | |
Application, but excluding the System Libraries of the Combined Work. | |
1. Exception to Section 3 of the GNU GPL. | |
You may convey a covered work under sections 3 and 4 of this License | |
without being bound by section 3 of the GNU GPL. | |
2. Conveying Modified Versions. | |
If you modify a copy of the Library, and, in your modifications, a | |
facility refers to a function or data to be supplied by an Application | |
that uses the facility (other than as an argument passed when the | |
facility is invoked), then you may convey a copy of the modified | |
version: | |
a) under this License, provided that you make a good faith effort to | |
ensure that, in the event an Application does not supply the | |
function or data, the facility still operates, and performs | |
whatever part of its purpose remains meaningful, or | |
b) under the GNU GPL, with none of the additional permissions of | |
this License applicable to that copy. | |
3. Object Code Incorporating Material from Library Header Files. | |
The object code form of an Application may incorporate material from | |
a header file that is part of the Library. You may convey such object | |
code under terms of your choice, provided that, if the incorporated | |
material is not limited to numerical parameters, data structure | |
layouts and accessors, or small macros, inline functions and templates | |
(ten or fewer lines in length), you do both of the following: | |
a) Give prominent notice with each copy of the object code that the | |
Library is used in it and that the Library and its use are | |
covered by this License. | |
b) Accompany the object code with a copy of the GNU GPL and this license | |
document. | |
4. Combined Works. | |
You may convey a Combined Work under terms of your choice that, | |
taken together, effectively do not restrict modification of the | |
portions of the Library contained in the Combined Work and reverse | |
engineering for debugging such modifications, if you also do each of | |
the following: | |
a) Give prominent notice with each copy of the Combined Work that | |
the Library is used in it and that the Library and its use are | |
covered by this License. | |
b) Accompany the Combined Work with a copy of the GNU GPL and this license | |
document. | |
c) For a Combined Work that displays copyright notices during | |
execution, include the copyright notice for the Library among | |
these notices, as well as a reference directing the user to the | |
copies of the GNU GPL and this license document. | |
d) Do one of the following: | |
0) Convey the Minimal Corresponding Source under the terms of this | |
License, and the Corresponding Application Code in a form | |
suitable for, and under terms that permit, the user to | |
recombine or relink the Application with a modified version of | |
the Linked Version to produce a modified Combined Work, in the | |
manner specified by section 6 of the GNU GPL for conveying | |
Corresponding Source. | |
1) Use a suitable shared library mechanism for linking with the | |
Library. A suitable mechanism is one that (a) uses at run time | |
a copy of the Library already present on the user's computer | |
system, and (b) will operate properly with a modified version | |
of the Library that is interface-compatible with the Linked | |
Version. | |
e) Provide Installation Information, but only if you would otherwise | |
be required to provide such information under section 6 of the | |
GNU GPL, and only to the extent that such information is | |
necessary to install and execute a modified version of the | |
Combined Work produced by recombining or relinking the | |
Application with a modified version of the Linked Version. (If | |
you use option 4d0, the Installation Information must accompany | |
the Minimal Corresponding Source and Corresponding Application | |
Code. If you use option 4d1, you must provide the Installation | |
Information in the manner specified by section 6 of the GNU GPL | |
for conveying Corresponding Source.) | |
5. Combined Libraries. | |
You may place library facilities that are a work based on the | |
Library side by side in a single library together with other library | |
facilities that are not Applications and are not covered by this | |
License, and convey such a combined library under terms of your | |
choice, if you do both of the following: | |
a) Accompany the combined library with a copy of the same work based | |
on the Library, uncombined with any other library facilities, | |
conveyed under the terms of this License. | |
b) Give prominent notice with the combined library that part of it | |
is a work based on the Library, and explaining where to find the | |
accompanying uncombined form of the same work. | |
6. Revised Versions of the GNU Lesser General Public License. | |
The Free Software Foundation may publish revised and/or new versions | |
of the GNU Lesser General Public License from time to time. Such new | |
versions will be similar in spirit to the present version, but may | |
differ in detail to address new problems or concerns. | |
Each version is given a distinguishing version number. If the | |
Library as you received it specifies that a certain numbered version | |
of the GNU Lesser General Public License "or any later version" | |
applies to it, you have the option of following the terms and | |
conditions either of that published version or of any later version | |
published by the Free Software Foundation. If the Library as you | |
received it does not specify a version number of the GNU Lesser | |
General Public License, you may choose any version of the GNU Lesser | |
General Public License ever published by the Free Software Foundation. | |
If the Library as you received it specifies that a proxy can decide | |
whether future versions of the GNU Lesser General Public License shall | |
apply, that proxy's public statement of acceptance of any version is | |
permanent authorization for you to choose that version for the | |
Library. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PK fn�? javadoc/PK fn�?*�"N X javadoc/allclasses-frame.html�T]k�0}�?� | |
Ŗ�tdv�_i�;8*�OC���ŵ;KM���Ir2R�FX^l���sν�ʹ����#��Y�?�@��a�qH���ʴl mx%���5�Q� ��xa��n���l�&9^��� | |
�m˙Y��߾q.#e�9]1�P{Ū�����5����p��{��e[��.�6?������6��!!+``�=}�G��3ri G�˶�W�E���`?��������=2E�s�`�B�� | |
Śv� ��L�/�:�IɅW�Ԕs�%��A&�f��J*$q��$J������I�~�<J�E\�j� � | |
�6 | |
�L�hrajTIʰ��{>eD�P/�,��:Ȓ,w�v] �L���/�K[�K���E��>�)�eլ&�:���`�`����^�x~���a$U,�8$Sٖ���f6��[����7�4[��|���0�Ы;�{��`]E딊j�byM�Z0S�Q�Z�R(�P5�$J�{Xq��_eq�����D�m'�SI��BmXs���?](��P��R�:��ߢN<�����I�����s | |
>p�"( ��\�~,�9�ޑ�s Wj�&O��w�7PK fn�?#$ B � javadoc/allclasses-noframe.html�T]o�0}���pkiҦ | |
I����J�F "��>M.x ��I�_?�$[*�/`_�{ι�\��(��*�Y��� | |
�$d`���G$.L��Ӗע�Z�`g�V�������Oͮ�Ť�[q�\��83+Q!��;��02�_�[fj�X�;���9\���T� | |
n���hՕ���n*��/��s��t-l$$b%Ll�����̶�rIέ�̲`b�6*˘�<��c�sQص��� �A9�\$ؓж�C��=g½"s㛶N��r�7 � �q���Q&**$q�g$Έ��Þ �4�~@��".�Ʒ� � | |
6J�,�x~�0uTIJ�Z�>eD�P/�<���2�Ӽp�~[ s����sѹ-ݥ�z�yO�قѪno�x'e:8����Q1�?Hc�"����`�Dd�"۲> X_-�~q?w�~F���_y���`����ʾ��k�״ɨ�w,�����%3�!�hd-�r u*y�f8����5�U� | |
6�*ޱv,�'Mk.�|�$��u�p�T'�(���=�1[�?�\�� =�<|�r�"�#CP�r��jt���PK fn�?f�P� y javadoc/constant-values.html�]�o�@��������~��t�:C����N�I�Z��*�Uc��}���THO�%��8���w�p����ލE��FC4�t�1�F��7�&�{�&�4W�=�7[� Qbs�����z����u�=mhJ��?����xF}�ϙ��7o�j���F�����V�p?ze؆����|E�}����i�[RoN[O �F�PE0f��"��|�}�6ѫ����~�l�V�eie$j�k��y�ax�� ۯi_��f$�a|��~�fg��~g��jtm� EH�����>� z�[+Ã�BԠč�3�}h��%M���Q��V��2��p �F�8D��Z�wf>��2B@3�cP_{���7 �T\�O��XC>H�)�f���q��ʞaݡ�iϝ�f�q����n�@�3���t\�~��:T3�ȋ��L��3\P{�wWƽ��A5��dž����uP��'|8? �J�����@s-�I����,6����;�}��CY�0�33�ؖ��!��E����Y'�!U� �=��c�ڛ.�D{C��i�'�;��%s�O�w6��J����'sYKUD!*�#(7O��˴?yLt��u�"�ʊ �,M��a�f���8�9AH�����1�C>��NF#Ny�a��*��ג:����"�z=8ŐS�#�]�� �b��N���E������L� (ↃWR��6X�ބyh7�#��-)��Gϛ5����4���\w��q�!z��g�`aO�hL9ltAH\1���}�-_@~ӕ���y�����x�_i �չ0��X�|�0�����e3B27��1��D�2=?!>�D���-L�� �f�થ :3�e <q}�� �WA�')�8����陟��H���>:G�Q��O�rZ��Hu�<U��=;V�7$�H�[-� 7�Gml�:���,�j������SB�p����*��=ea�'�y6IF??�/� ��7�[sq����>��!|�G�}�^R���]�W�����W �,�dg��ރ`����50~\1�����F����j�4�d�����] | |
DI�"d��(�8�E���T��*^�0� Ф*+���1$�sF ҆�*u2< | |
�ƣ$��cs���FT�R2⽿�ٟ��_�)��/�4��2�>7�Sޱ�я܆e,�l{�7"R���65Bz����"�6%PW'�"����P#وD5\S�$ /��x��u&F�L�m=���#A�8�,v�Y��7�����N��d�6k3��~�I����p��˜W��G� W$i��a#�|�?oFP)/���Q | |
C��>fō4S�J%w��S�P�o�>�`�]˪<䔁J'�1�$���VU$A>���|�.@1���_x��s�;��c������4��&��i�e��mo1W���ӹ�Ɩ3,m���j��+��-(�.ԯ�`*�� ��U{Ф�Z;SP�ރf5����/A��bwo�r�Q��T��gxV�kh�?��5D���\ԯ�5�)d7����ڮ���m�:�/�o���۽ | |
�%�S�"��TB���'2�N�p�+!�Fj����R���*�d��Tb�f 4u�O�i�I:?����:2q��O� | |
�|J��8I�'�idPG& N���<(�LQQde<�A�ȩ��)���D���t&���r��R��aR{G��t.?�{�Q����pEN%Y���_ƽQR����A)�ʃ�P�� ����`+e[�h���^���r�[Yz+�z��w��B^����j��[v3�c����v�{M�i�I:?�OJ�� ���Z � �0U�٬��RP�h�F��4�%ޒ Ј | |
]<x�T[e��R�$'�s��/�(��*��e 8N��]b�J���]]<��d�t���� 9�:z9���%�Gcznie1'���E�M�7"5W��I��5g�&��� �@N2.��y9(�'Uw[3�Ifwxd��p)�8N�J�C8�Uڬ3Ĝ���2ǣ��J������S�:�-pW��Q)D�EzB� Щl��īx�H��Vc�a�����T "m5f��j�~U��`�а�P�F���Y��&p�yl2�9�yt��8?Ԣ�P@�������E/���t\���� J&)�n��wg~�`�b~2Ec�wG�& ,*�&SxweV��bV2Ea�wg&$ 0:&$S$��3I��1��� ޙiH���i���ݙ�$�h��LQAޝ�G�����1�5��O_�|�K�7)Q�.Ub8���S����"��=�L� | |
���t���uK�O����03���XW�*�Y^�?��k��W���;���<F'�e�g�%�v|���Ɯ)ϏlѨ*j0㪖y5Z�*y.��p��K:�s��T�N";�rC���M�W�e�tU)�*���Y "d�L�B��W�Zq����X | |
xAï䍵K�ۤ�y�?Q��U�L�1Nw��+ԧ4�7Դ�XTF��P�6���(�4ieY��4�sӯRK�����j���E�˜�JWW�����R������C?3�@3Dž5/��S��חǢ�Ot��Rm�S�������Yv��#�N�2/@+��%�/p}Jtq��V���{�D�g�IJ�˅�;�ageW�/ �?��eJ�k�b"���wv6�f��0[W�4y-���N�w���F�ҽ@��z��?\2�z������m�]��v�F��m��h���d���*m���˴����A{�2�? PK fn�?��Dr� � javadoc/deprecated-list.html�Xm��@�n����ŔR�-w�L�� �����~1����b���wv��x��� %i�ev��ݙ'4�n����l�7�n��������)'�V��Y����$�U�r�1c�cU],�E��fW��c6���q��2dCrz�^ぢ8t�����>�*��a�pF����>�`��px9��!h���ڋ#H�@��P�@�?ӎ�*���'��q� | |
�����ҳ|8F�~�Es��҄ф)���eO'�~a� �� �)����R@���maäӌ���g�r�4�=K'C�!�r�r|�p<�VSj��v�y �e�Nrv�|L)#�����9��g�W%*b��D�.� Z^��C���<xy�ES�EF�$��(�?b1=<����{�O4��8 .RgtTA1��D���h���lF�@�Aю��-�i�a+�Y� o0ԏ@6�EN�o��}㡓�y|����tx��l��;h��\��t�G<�i�������]�xb]q���ox>�m��>�כ�ᕳš)�1 �A���Srʕ��j�bs柢��"�����8J>�\�Mۂ���R%p�5�N�j�˶�iv�3��A�ha_�{=�{�y:=�6�q)G��D顅O��*lc0Љ̛A֢q��{�ae9�����[0o��n��o�@�`��3G'!M�LxS��n)c�����.|��P��'�]��dd�~�щ6��u m���4O�rICm��\P��8�̧'x����t��V�4�L����(��i6��Ba����蝢����H<:G0r�-&���z�h����Q�X�mm�8t��]�3�1�� | |
f�]PtP� T�=Tq�e˔餼�Yt5f�W<�Bd��i��U�Y..����ʹ��f�te�}��H��| ��=�l�#���/|�&����^���.O�c���ڃ�"Y(*B��a���O�0��w���s���� <g�o4:�%Q�Q�Z/K�"�����d�!�P4W�t�y�2#��%'KlG���/U�*qKI��kc����oߛ��Y���-*`9�X�%�h�,�r�թ�{-���J�rN]����� z�1LK�.h�t����g��lі���n��3�r�2�Nv�.R���/҇=���R�g0w����О��̞�܉�,� �Y�0۬`��H��Oa����;PK fn�?�H�ؚ | |