processing-core-1.2.1/ 0000755 0001750 0001750 00000000000 11550154145 014140 5 ustar andrew andrew processing-core-1.2.1/src/ 0000755 0001750 0001750 00000000000 11550154145 014727 5 ustar andrew andrew processing-core-1.2.1/src/processing/ 0000755 0001750 0001750 00000000000 11550154145 017103 5 ustar andrew andrew processing-core-1.2.1/src/processing/core/ 0000755 0001750 0001750 00000000000 11550154145 020033 5 ustar andrew andrew processing-core-1.2.1/src/processing/core/PShape.java 0000644 0001750 0001750 00000076756 11411146532 022100 0 ustar andrew andrew /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2006-10 Ben Fry and Casey Reas
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 2.1 as published by the Free Software Foundation.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
import java.util.HashMap;
import processing.core.PApplet;
/**
* Datatype for storing shapes. Processing can currently load and display SVG (Scalable Vector Graphics) shapes.
* Before a shape is used, it must be loaded with the loadShape() function. The shape() function is used to draw the shape to the display window.
* The PShape object contain a group of methods, linked below, that can operate on the shape data.
*
The loadShape() method supports SVG files created with Inkscape and Adobe Illustrator.
* It is not a full SVG implementation, but offers some straightforward support for handling vector data.
* =advanced
*
* In-progress class to handle shape data, currently to be considered of
* alpha or beta quality. Major structural work may be performed on this class
* after the release of Processing 1.0. Such changes may include:
*
*
For the time being, this class and its shape() and loadShape() friends in * PApplet exist as placeholders for more exciting things to come. If you'd * like to work with this class, make a subclass (see how PShapeSVG works) * and you can play with its internal methods all you like.
* *Library developers are encouraged to create PShape objects when loading * shape data, so that they can eventually hook into the bounty that will be * the PShape interface, and the ease of loadShape() and shape().
* * @webref Shape * @usage Web & Application * @see PApplet#shape(PShape) * @see PApplet#loadShape(String) * @see PApplet#shapeMode(int) * @instanceName sh any variable of type PShape */ public class PShape implements PConstants { protected String name; protected HashMap* public class ExampleFrame extends Frame { * * public ExampleFrame() { * super("Embedded PApplet"); * * setLayout(new BorderLayout()); * PApplet embed = new Embedded(); * add(embed, BorderLayout.CENTER); * * // important to call this whenever embedding a PApplet. * // It ensures that the animation thread is started and * // that other internal variables are properly set. * embed.init(); * } * } * * public class Embedded extends PApplet { * * public void setup() { * // original setup code here ... * size(400, 400); * * // prevent thread from starving everything else * noLoop(); * } * * public void draw() { * // drawing code goes here * } * * public void mousePressed() { * // do something based on mouse movement * * // update the screen (run draw once) * redraw(); * } * } ** *
I was asked about Processing with multiple displays, and for lack of a * better place to document it, things will go here.
*You can address both screens by making a window the width of both, * and the height of the maximum of both screens. In this case, do not use * present mode, because that's exclusive to one screen. Basically it'll * give you a PApplet that spans both screens. If using one half to control * and the other half for graphics, you'd just have to put the 'live' stuff * on one half of the canvas, the control stuff on the other. This works * better in windows because on the mac we can't get rid of the menu bar * unless it's running in present mode.
*For more control, you need to write straight java code that uses p5. * You can create two windows, that are shown on two separate screens, * that have their own PApplet. this is just one of the tradeoffs of one of * the things that we don't support in p5 from within the environment * itself (we must draw the line somewhere), because of how messy it would * get to start talking about multiple screens. It's also not that tough to * do by hand w/ some Java code.
* @usage Web & Application */ public class PApplet extends Applet implements PConstants, Runnable, MouseListener, MouseMotionListener, KeyListener, FocusListener { /** * Full name of the Java version (i.e. 1.5.0_11). * Prior to 0125, this was only the first three digits. */ public static final String javaVersionName = System.getProperty("java.version"); /** * Version of Java that's in use, whether 1.1 or 1.3 or whatever, * stored as a float. ** Note that because this is stored as a float, the values may * not be exactly 1.3 or 1.4. Instead, make sure you're * comparing against 1.3f or 1.4f, which will have the same amount * of error (i.e. 1.40000001). This could just be a double, but * since Processing only uses floats, it's safer for this to be a float * because there's no good way to specify a double with the preproc. */ public static final float javaVersion = new Float(javaVersionName.substring(0, 3)).floatValue(); /** * Current platform in use. *
* Equivalent to System.getProperty("os.name"), just used internally. */ /** * Current platform in use, one of the * PConstants WINDOWS, MACOSX, MACOS9, LINUX or OTHER. */ static public int platform; /** * Name associated with the current 'platform' (see PConstants.platformNames) */ //static public String platformName; static { String osname = System.getProperty("os.name"); if (osname.indexOf("Mac") != -1) { platform = MACOSX; } else if (osname.indexOf("Windows") != -1) { platform = WINDOWS; } else if (osname.equals("Linux")) { // true for the ibm vm platform = LINUX; } else { platform = OTHER; } } /** * Setting for whether to use the Quartz renderer on OS X. The Quartz * renderer is on its way out for OS X, but Processing uses it by default * because it's much faster than the Sun renderer. In some cases, however, * the Quartz renderer is preferred. For instance, fonts are less thick * when using the Sun renderer, so to improve how fonts look, * change this setting before you call PApplet.main(). *
* static public void main(String[] args) { * PApplet.useQuartz = "false"; * PApplet.main(new String[] { "YourSketch" }); * } ** This setting must be called before any AWT work happens, so that's why * it's such a terrible hack in how it's employed here. Calling setProperty() * inside setup() is a joke, since it's long since the AWT has been invoked. */ static public boolean useQuartz = true; //static public String useQuartz = "true"; /** * Modifier flags for the shortcut key used to trigger menus. * (Cmd on Mac OS X, Ctrl on Linux and Windows) */ static public final int MENU_SHORTCUT = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** The PGraphics renderer associated with this PApplet */ public PGraphics g; //protected Object glock = new Object(); // for sync /** The frame containing this applet (if any) */ public Frame frame; /** * The screen size when the applet was started. *
* Access this via screen.width and screen.height. To make an applet * run at full screen, use size(screen.width, screen.height). *
* If you have multiple displays, this will be the size of the main * display. Running full screen across multiple displays isn't * particularly supported, and requires more monkeying with the values. * This probably can't/won't be fixed until/unless I get a dual head * system. *
* Note that this won't update if you change the resolution * of your screen once the the applet is running. *
* This variable is not static because in the desktop version of Processing, * not all instances of PApplet will necessarily be started on a screen of * the same size. */ public int screenWidth, screenHeight; /** * Use screenW and screenH instead. * @deprecated */ public Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); /** * A leech graphics object that is echoing all events. */ public PGraphics recorder; /** * Command line options passed in from main(). *
* This does not include the arguments passed in to PApplet itself. */ public String args[]; /** Path to sketch folder */ public String sketchPath; //folder; /** When debugging headaches */ static final boolean THREAD_DEBUG = false; /** Default width and height for applet when not specified */ static public final int DEFAULT_WIDTH = 100; static public final int DEFAULT_HEIGHT = 100; /** * Minimum dimensions for the window holding an applet. * This varies between platforms, Mac OS X 10.3 can do any height * but requires at least 128 pixels width. Windows XP has another * set of limitations. And for all I know, Linux probably lets you * make windows with negative sizes. */ static public final int MIN_WINDOW_WIDTH = 128; static public final int MIN_WINDOW_HEIGHT = 128; /** * Exception thrown when size() is called the first time. *
* This is used internally so that setup() is forced to run twice
* when the renderer is changed. This is the only way for us to handle
* invoking the new renderer while also in the midst of rendering.
*/
static public class RendererChangeException extends RuntimeException { }
/**
* true if no size() command has been executed. This is used to wait until
* a size has been set before placing in the window and showing it.
*/
public boolean defaultSize;
volatile boolean resizeRequest;
volatile int resizeWidth;
volatile int resizeHeight;
/**
* Array containing the values for all the pixels in the display window. These values are of the color datatype. This array is the size of the display window. For example, if the image is 100x100 pixels, there will be 10000 values and if the window is 200x300 pixels, there will be 60000 values. The index value defines the position of a value within the array. For example, the statment color b = pixels[230] will set the variable b to be equal to the value at that location in the array.
Before accessing this array, the data must loaded with the loadPixels() function. After the array data has been modified, the updatePixels() function must be run to update the changes. Without loadPixels(), running the code may (or will in future releases) result in a NullPointerException.
* Pixel buffer from this applet's PGraphics.
*
* When used with OpenGL or Java2D, this value will * be null until loadPixels() has been called. * * @webref image:pixels * @see processing.core.PApplet#loadPixels() * @see processing.core.PApplet#updatePixels() * @see processing.core.PApplet#get(int, int, int, int) * @see processing.core.PApplet#set(int, int, int) * @see processing.core.PImage */ public int pixels[]; /** width of this applet's associated PGraphics * @webref environment */ public int width; /** height of this applet's associated PGraphics * @webref environment * */ public int height; /** * The system variable mouseX always contains the current horizontal coordinate of the mouse. * @webref input:mouse * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() * * */ public int mouseX; /** * The system variable mouseY always contains the current vertical coordinate of the mouse. * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() * */ public int mouseY; /** * Previous x/y position of the mouse. This will be a different value * when inside a mouse handler (like the mouseMoved() method) versus * when inside draw(). Inside draw(), pmouseX is updated once each * frame, but inside mousePressed() and friends, it's updated each time * an event comes through. Be sure to use only one or the other type of * means for tracking pmouseX and pmouseY within your sketch, otherwise * you're gonna run into trouble. * @webref input:mouse * @see PApplet#pmouseY * @see PApplet#mouseX * @see PApplet#mouseY */ public int pmouseX; /** * @webref input:mouse * @see PApplet#pmouseX * @see PApplet#mouseX * @see PApplet#mouseY */ public int pmouseY; /** * previous mouseX/Y for the draw loop, separated out because this is * separate from the pmouseX/Y when inside the mouse event handlers. */ protected int dmouseX, dmouseY; /** * pmouseX/Y for the event handlers (mousePressed(), mouseDragged() etc) * these are different because mouse events are queued to the end of * draw, so the previous position has to be updated on each event, * as opposed to the pmouseX/Y that's used inside draw, which is expected * to be updated once per trip through draw(). */ protected int emouseX, emouseY; /** * Used to set pmouseX/Y to mouseX/Y the first time mouseX/Y are used, * otherwise pmouseX/Y are always zero, causing a nasty jump. *
* Just using (frameCount == 0) won't work since mouseXxxxx() * may not be called until a couple frames into things. */ public boolean firstMouse; /** * Processing automatically tracks if the mouse button is pressed and which button is pressed. * The value of the system variable mouseButton is either LEFT, RIGHT, or CENTER depending on which button is pressed. *
* If it's a coded key, i.e. UP/DOWN/CTRL/SHIFT/ALT,
* this will be set to CODED (0xffff or 65535).
* @webref input:keyboard
* @see PApplet#keyCode
* @see PApplet#keyPressed
* @see PApplet#keyPressed()
* @see PApplet#keyReleased()
*/
public char key;
/**
* The variable keyCode is used to detect special keys such as the UP, DOWN, LEFT, RIGHT arrow keys and ALT, CONTROL, SHIFT.
* When checking for these keys, it's first necessary to check and see if the key is coded. This is done with the conditional "if (key == CODED)" as shown in the example.
*
The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and DELETE) do not require checking to see if they key is coded, and you should simply use the key variable instead of keyCode
* If you're making cross-platform projects, note that the ENTER key is commonly used on PCs and Unix and the RETURN key is used instead on Macintosh.
* Check for both ENTER and RETURN to make sure your program will work for all platforms.
*
For users familiar with Java, the values for UP and DOWN are simply shorter versions of Java's KeyEvent.VK_UP and KeyEvent.VK_DOWN.
* Other keyCode values can be found in the Java KeyEvent reference.
*
* =advanced
* When "key" is set to CODED, this will contain a Java key code.
*
* For the arrow keys, keyCode will be one of UP, DOWN, LEFT and RIGHT. * Also available are ALT, CONTROL and SHIFT. A full set of constants * can be obtained from java.awt.event.KeyEvent, from the VK_XXXX variables. * @webref input:keyboard * @see PApplet#key * @see PApplet#keyPressed * @see PApplet#keyPressed() * @see PApplet#keyReleased() */ public int keyCode; /** * The boolean system variable keyPressed is true if any key is pressed and false if no keys are pressed. * @webref input:keyboard * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed() * @see PApplet#keyReleased() */ public boolean keyPressed; /** * the last KeyEvent object passed into a mouse function. */ public KeyEvent keyEvent; /** * Gets set to true/false as the applet gains/loses focus. * @webref environment */ public boolean focused = false; /** * true if the applet is online. *
* This can be used to test how the applet should behave * since online situations are different (no file writing, etc). * @webref environment */ public boolean online = false; /** * Time in milliseconds when the applet was started. *
* Used by the millis() function. */ long millisOffset; /** * The current value of frames per second. *
* The initial value will be 10 fps, and will be updated with each * frame thereafter. The value is not instantaneous (since that * wouldn't be very useful since it would jump around so much), * but is instead averaged (integrated) over several frames. * As such, this value won't be valid until after 5-10 frames. */ public float frameRate = 10; /** Last time in nanoseconds that frameRate was checked */ protected long frameRateLastNanos = 0; /** As of release 0116, frameRate(60) is called as a default */ protected float frameRateTarget = 60; protected long frameRatePeriod = 1000000000L / 60L; protected boolean looping; /** flag set to true when a redraw is asked for by the user */ protected boolean redraw; /** * How many frames have been displayed since the applet started. *
* This value is read-only do not attempt to set it, * otherwise bad things will happen. *
* Inside setup(), frameCount is 0. * For the first iteration of draw(), frameCount will equal 1. */ public int frameCount; /** * true if this applet has had it. */ public boolean finished; /** * true if exit() has been called so that things shut down * once the main thread kicks off. */ protected boolean exitCalled; Thread thread; protected RegisteredMethods sizeMethods; protected RegisteredMethods preMethods, drawMethods, postMethods; protected RegisteredMethods mouseEventMethods, keyEventMethods; protected RegisteredMethods disposeMethods; // messages to send if attached as an external vm /** * Position of the upper-lefthand corner of the editor window * that launched this applet. */ static public final String ARGS_EDITOR_LOCATION = "--editor-location"; /** * Location for where to position the applet window on screen. *
* This is used by the editor to when saving the previous applet * location, or could be used by other classes to launch at a * specific position on-screen. */ static public final String ARGS_EXTERNAL = "--external"; static public final String ARGS_LOCATION = "--location"; static public final String ARGS_DISPLAY = "--display"; static public final String ARGS_BGCOLOR = "--bgcolor"; static public final String ARGS_PRESENT = "--present"; static public final String ARGS_EXCLUSIVE = "--exclusive"; static public final String ARGS_STOP_COLOR = "--stop-color"; static public final String ARGS_HIDE_STOP = "--hide-stop"; /** * Allows the user or PdeEditor to set a specific sketch folder path. *
* Used by PdeEditor to pass in the location where saveFrame() * and all that stuff should write things. */ static public final String ARGS_SKETCH_FOLDER = "--sketch-path"; /** * When run externally to a PdeEditor, * this is sent by the applet when it quits. */ //static public final String EXTERNAL_QUIT = "__QUIT__"; static public final String EXTERNAL_STOP = "__STOP__"; /** * When run externally to a PDE Editor, this is sent by the applet * whenever the window is moved. *
* This is used so that the editor can re-open the sketch window * in the same position as the user last left it. */ static public final String EXTERNAL_MOVE = "__MOVE__"; /** true if this sketch is being run by the PDE */ boolean external = false; static final String ERROR_MIN_MAX = "Cannot use min() or max() on an empty array."; // during rev 0100 dev cycle, working on new threading model, // but need to disable and go conservative with changes in order // to get pdf and audio working properly first. // for 0116, the CRUSTY_THREADS are being disabled to fix lots of bugs. //static final boolean CRUSTY_THREADS = false; //true; public void init() { // println("Calling init()"); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); screenWidth = screen.width; screenHeight = screen.height; // send tab keys through to the PApplet setFocusTraversalKeysEnabled(false); millisOffset = System.currentTimeMillis(); finished = false; // just for clarity // this will be cleared by draw() if it is not overridden looping = true; redraw = true; // draw this guy once firstMouse = true; // these need to be inited before setup sizeMethods = new RegisteredMethods(); preMethods = new RegisteredMethods(); drawMethods = new RegisteredMethods(); postMethods = new RegisteredMethods(); mouseEventMethods = new RegisteredMethods(); keyEventMethods = new RegisteredMethods(); disposeMethods = new RegisteredMethods(); try { getAppletContext(); online = true; } catch (NullPointerException e) { online = false; } try { if (sketchPath == null) { sketchPath = System.getProperty("user.dir"); } } catch (Exception e) { } // may be a security problem Dimension size = getSize(); if ((size.width != 0) && (size.height != 0)) { // When this PApplet is embedded inside a Java application with other // Component objects, its size() may already be set externally (perhaps // by a LayoutManager). In this case, honor that size as the default. // Size of the component is set, just create a renderer. g = makeGraphics(size.width, size.height, getSketchRenderer(), null, true); // This doesn't call setSize() or setPreferredSize() because the fact // that a size was already set means that someone is already doing it. } else { // Set the default size, until the user specifies otherwise this.defaultSize = true; int w = getSketchWidth(); int h = getSketchHeight(); g = makeGraphics(w, h, getSketchRenderer(), null, true); // Fire component resize event setSize(w, h); setPreferredSize(new Dimension(w, h)); } width = g.width; height = g.height; addListeners(); // this is automatically called in applets // though it's here for applications anyway start(); } public int getSketchWidth() { return DEFAULT_WIDTH; } public int getSketchHeight() { return DEFAULT_HEIGHT; } public String getSketchRenderer() { return JAVA2D; } /** * Called by the browser or applet viewer to inform this applet that it * should start its execution. It is called after the init method and * each time the applet is revisited in a Web page. *
* Called explicitly via the first call to PApplet.paint(), because * PAppletGL needs to have a usable screen before getting things rolling. */ public void start() { // When running inside a browser, start() will be called when someone // returns to a page containing this applet. // http://dev.processing.org/bugs/show_bug.cgi?id=581 finished = false; if (thread != null) return; thread = new Thread(this, "Animation Thread"); thread.start(); } /** * Called by the browser or applet viewer to inform * this applet that it should stop its execution. * * Unfortunately, there are no guarantees from the Java spec * when or if stop() will be called (i.e. on browser quit, * or when moving between web pages), and it's not always called. */ public void stop() { // bringing this back for 0111, hoping it'll help opengl shutdown finished = true; // why did i comment this out? // don't run stop and disposers twice if (thread == null) return; thread = null; // call to shut down renderer, in case it needs it (pdf does) if (g != null) g.dispose(); // maybe this should be done earlier? might help ensure it gets called // before the vm just craps out since 1.5 craps out so aggressively. disposeMethods.handle(); } /** * Called by the browser or applet viewer to inform this applet * that it is being reclaimed and that it should destroy * any resources that it has allocated. * * This also attempts to call PApplet.stop(), in case there * was an inadvertent override of the stop() function by a user. * * destroy() supposedly gets called as the applet viewer * is shutting down the applet. stop() is called * first, and then destroy() to really get rid of things. * no guarantees on when they're run (on browser quit, or * when moving between pages), though. */ public void destroy() { ((PApplet)this).stop(); } /** * This returns the last width and height specified by the user * via the size() command. */ // public Dimension getPreferredSize() { // return new Dimension(width, height); // } // public void addNotify() { // super.addNotify(); // println("addNotify()"); // } ////////////////////////////////////////////////////////////// public class RegisteredMethods { int count; Object objects[]; Method methods[]; // convenience version for no args public void handle() { handle(new Object[] { }); } public void handle(Object oargs[]) { for (int i = 0; i < count; i++) { try { //System.out.println(objects[i] + " " + args); methods[i].invoke(objects[i], oargs); } catch (Exception e) { if (e instanceof InvocationTargetException) { InvocationTargetException ite = (InvocationTargetException) e; ite.getTargetException().printStackTrace(); } else { e.printStackTrace(); } } } } public void add(Object object, Method method) { if (objects == null) { objects = new Object[5]; methods = new Method[5]; } if (count == objects.length) { objects = (Object[]) PApplet.expand(objects); methods = (Method[]) PApplet.expand(methods); // Object otemp[] = new Object[count << 1]; // System.arraycopy(objects, 0, otemp, 0, count); // objects = otemp; // Method mtemp[] = new Method[count << 1]; // System.arraycopy(methods, 0, mtemp, 0, count); // methods = mtemp; } objects[count] = object; methods[count] = method; count++; } /** * Removes first object/method pair matched (and only the first, * must be called multiple times if object is registered multiple times). * Does not shrink array afterwards, silently returns if method not found. */ public void remove(Object object, Method method) { int index = findIndex(object, method); if (index != -1) { // shift remaining methods by one to preserve ordering count--; for (int i = index; i < count; i++) { objects[i] = objects[i+1]; methods[i] = methods[i+1]; } // clean things out for the gc's sake objects[count] = null; methods[count] = null; } } protected int findIndex(Object object, Method method) { for (int i = 0; i < count; i++) { if (objects[i] == object && methods[i].equals(method)) { //objects[i].equals() might be overridden, so use == for safety // since here we do care about actual object identity //methods[i]==method is never true even for same method, so must use // equals(), this should be safe because of object identity return i; } } return -1; } } public void registerSize(Object o) { Class> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE }; registerWithArgs(sizeMethods, "size", o, methodArgs); } public void registerPre(Object o) { registerNoArgs(preMethods, "pre", o); } public void registerDraw(Object o) { registerNoArgs(drawMethods, "draw", o); } public void registerPost(Object o) { registerNoArgs(postMethods, "post", o); } public void registerMouseEvent(Object o) { Class> methodArgs[] = new Class[] { MouseEvent.class }; registerWithArgs(mouseEventMethods, "mouseEvent", o, methodArgs); } public void registerKeyEvent(Object o) { Class> methodArgs[] = new Class[] { KeyEvent.class }; registerWithArgs(keyEventMethods, "keyEvent", o, methodArgs); } public void registerDispose(Object o) { registerNoArgs(disposeMethods, "dispose", o); } protected void registerNoArgs(RegisteredMethods meth, String name, Object o) { Class> c = o.getClass(); try { Method method = c.getMethod(name, new Class[] {}); meth.add(o, method); } catch (NoSuchMethodException nsme) { die("There is no public " + name + "() method in the class " + o.getClass().getName()); } catch (Exception e) { die("Could not register " + name + " + () for " + o, e); } } protected void registerWithArgs(RegisteredMethods meth, String name, Object o, Class> cargs[]) { Class> c = o.getClass(); try { Method method = c.getMethod(name, cargs); meth.add(o, method); } catch (NoSuchMethodException nsme) { die("There is no public " + name + "() method in the class " + o.getClass().getName()); } catch (Exception e) { die("Could not register " + name + " + () for " + o, e); } } public void unregisterSize(Object o) { Class> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE }; unregisterWithArgs(sizeMethods, "size", o, methodArgs); } public void unregisterPre(Object o) { unregisterNoArgs(preMethods, "pre", o); } public void unregisterDraw(Object o) { unregisterNoArgs(drawMethods, "draw", o); } public void unregisterPost(Object o) { unregisterNoArgs(postMethods, "post", o); } public void unregisterMouseEvent(Object o) { Class> methodArgs[] = new Class[] { MouseEvent.class }; unregisterWithArgs(mouseEventMethods, "mouseEvent", o, methodArgs); } public void unregisterKeyEvent(Object o) { Class> methodArgs[] = new Class[] { KeyEvent.class }; unregisterWithArgs(keyEventMethods, "keyEvent", o, methodArgs); } public void unregisterDispose(Object o) { unregisterNoArgs(disposeMethods, "dispose", o); } protected void unregisterNoArgs(RegisteredMethods meth, String name, Object o) { Class> c = o.getClass(); try { Method method = c.getMethod(name, new Class[] {}); meth.remove(o, method); } catch (Exception e) { die("Could not unregister " + name + "() for " + o, e); } } protected void unregisterWithArgs(RegisteredMethods meth, String name, Object o, Class> cargs[]) { Class> c = o.getClass(); try { Method method = c.getMethod(name, cargs); meth.remove(o, method); } catch (Exception e) { die("Could not unregister " + name + "() for " + o, e); } } ////////////////////////////////////////////////////////////// public void setup() { } public void draw() { // if no draw method, then shut things down //System.out.println("no draw method, goodbye"); finished = true; } ////////////////////////////////////////////////////////////// protected void resizeRenderer(int iwidth, int iheight) { // println("resizeRenderer request for " + iwidth + " " + iheight); if (width != iwidth || height != iheight) { // println(" former size was " + width + " " + height); g.setSize(iwidth, iheight); width = iwidth; height = iheight; } } /** * Defines the dimension of the display window in units of pixels. The size() function must be the first line in setup(). If size() is not called, the default size of the window is 100x100 pixels. The system variables width and height are set by the parameters passed to the size() function.* This should be the first thing called inside of setup(). *
* If using Java 1.3 or later, this will default to using * PGraphics2, the Java2D-based renderer. If using Java 1.1, * or if PGraphics2 is not available, then PGraphics will be used. * To set your own renderer, use the other version of the size() * method that takes a renderer as its last parameter. *
* If called once a renderer has already been set, this will
* use the previous renderer and simply resize it.
*
* @webref structure
* @param iwidth width of the display window in units of pixels
* @param iheight height of the display window in units of pixels
*/
public void size(int iwidth, int iheight) {
size(iwidth, iheight, JAVA2D, null);
}
/**
*
* @param irenderer Either P2D, P3D, JAVA2D, or OPENGL
*/
public void size(int iwidth, int iheight, String irenderer) {
size(iwidth, iheight, irenderer, null);
}
/**
* Creates a new PGraphics object and sets it to the specified size.
*
* Note that you cannot change the renderer once outside of setup().
* In most cases, you can call size() to give it a new size,
* but you need to always ask for the same renderer, otherwise
* you're gonna run into trouble.
*
* The size() method should *only* be called from inside the setup() or
* draw() methods, so that it is properly run on the main animation thread.
* To change the size of a PApplet externally, use setSize(), which will
* update the component size, and queue a resize of the renderer as well.
*/
public void size(final int iwidth, final int iheight,
String irenderer, String ipath) {
// Run this from the EDT, just cuz it's AWT stuff (or maybe later Swing)
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Set the preferred size so that the layout managers can handle it
setPreferredSize(new Dimension(iwidth, iheight));
setSize(iwidth, iheight);
}
});
// ensure that this is an absolute path
if (ipath != null) ipath = savePath(ipath);
String currentRenderer = g.getClass().getName();
if (currentRenderer.equals(irenderer)) {
// Avoid infinite loop of throwing exception to reset renderer
resizeRenderer(iwidth, iheight);
//redraw(); // will only be called insize draw()
} else { // renderer is being changed
// otherwise ok to fall through and create renderer below
// the renderer is changing, so need to create a new object
g = makeGraphics(iwidth, iheight, irenderer, ipath, true);
width = iwidth;
height = iheight;
// fire resize event to make sure the applet is the proper size
// setSize(iwidth, iheight);
// this is the function that will run if the user does their own
// size() command inside setup, so set defaultSize to false.
defaultSize = false;
// throw an exception so that setup() is called again
// but with a properly sized render
// this is for opengl, which needs a valid, properly sized
// display before calling anything inside setup().
throw new RendererChangeException();
}
}
/**
* Creates and returns a new PGraphics object of the types P2D, P3D, and JAVA2D. Use this class if you need to draw into an off-screen graphics buffer. It's not possible to use createGraphics() with OPENGL, because it doesn't allow offscreen use. The DXF and PDF renderers require the filename parameter.
*
It's important to call any drawing commands between beginDraw() and endDraw() statements. This is also true for any commands that affect drawing, such as smooth() or colorMode().
*
Unlike the main drawing surface which is completely opaque, surfaces created with createGraphics() can have transparency. This makes it possible to draw into a graphics and maintain the alpha channel. By using save() to write a PNG or TGA file, the transparency of the graphics object will be honored. Note that transparency levels are binary: pixels are either complete opaque or transparent. For the time being (as of release 0127), this means that text characters will be opaque blocks. This will be fixed in a future release (Bug 641).
*
* =advanced
* Create an offscreen PGraphics object for drawing. This can be used
* for bitmap or vector images drawing or rendering.
*
* * PGraphics big; * * void setup() { * big = createGraphics(3000, 3000, P3D); * * big.beginDraw(); * big.background(128); * big.line(20, 1800, 1800, 900); * // etc.. * big.endDraw(); * * // make sure the file is written to the sketch folder * big.save("big.tif"); * } * **
* Examples for key handling: * (Tested on Windows XP, please notify if different on other * platforms, I have a feeling Mac OS and Linux may do otherwise) *
* 1. Pressing 'a' on the keyboard: * keyPressed with key == 'a' and keyCode == 'A' * keyTyped with key == 'a' and keyCode == 0 * keyReleased with key == 'a' and keyCode == 'A' * * 2. Pressing 'A' on the keyboard: * keyPressed with key == 'A' and keyCode == 'A' * keyTyped with key == 'A' and keyCode == 0 * keyReleased with key == 'A' and keyCode == 'A' * * 3. Pressing 'shift', then 'a' on the keyboard (caps lock is off): * keyPressed with key == CODED and keyCode == SHIFT * keyPressed with key == 'A' and keyCode == 'A' * keyTyped with key == 'A' and keyCode == 0 * keyReleased with key == 'A' and keyCode == 'A' * keyReleased with key == CODED and keyCode == SHIFT * * 4. Holding down the 'a' key. * The following will happen several times, * depending on your machine's "key repeat rate" settings: * keyPressed with key == 'a' and keyCode == 'A' * keyTyped with key == 'a' and keyCode == 0 * When you finally let go, you'll get: * keyReleased with key == 'a' and keyCode == 'A' * * 5. Pressing and releasing the 'shift' key * keyPressed with key == CODED and keyCode == SHIFT * keyReleased with key == CODED and keyCode == SHIFT * (note there is no keyTyped) * * 6. Pressing the tab key in an applet with Java 1.4 will * normally do nothing, but PApplet dynamically shuts * this behavior off if Java 1.4 is in use (tested 1.4.2_05 Windows). * Java 1.1 (Microsoft VM) passes the TAB key through normally. * Not tested on other platforms or for 1.3. ** @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed * @see PApplet#keyReleased() * @webref input:keyboard */ public void keyPressed() { } /** * The keyReleased() function is called once every time a key is released. The key that was released will be stored in the key variable. See key and keyReleased for more information. * * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed * @see PApplet#keyPressed() * @webref input:keyboard */ public void keyReleased() { } /** * Only called for "regular" keys like letters, * see keyPressed() for full documentation. */ public void keyTyped() { } ////////////////////////////////////////////////////////////// // i am focused man, and i'm not afraid of death. // and i'm going all out. i circle the vultures in a van // and i run the block. public void focusGained() { } public void focusGained(FocusEvent e) { focused = true; focusGained(); } public void focusLost() { } public void focusLost(FocusEvent e) { focused = false; focusLost(); } ////////////////////////////////////////////////////////////// // getting the time /** * Returns the number of milliseconds (thousandths of a second) since starting an applet. This information is often used for timing animation sequences. * * =advanced *
* This is a function, rather than a variable, because it may * change multiple times per frame. * * @webref input:time_date * @see processing.core.PApplet#second() * @see processing.core.PApplet#minute() * @see processing.core.PApplet#hour() * @see processing.core.PApplet#day() * @see processing.core.PApplet#month() * @see processing.core.PApplet#year() * */ public int millis() { return (int) (System.currentTimeMillis() - millisOffset); } /** Seconds position of the current time. * * @webref input:time_date * @see processing.core.PApplet#millis() * @see processing.core.PApplet#minute() * @see processing.core.PApplet#hour() * @see processing.core.PApplet#day() * @see processing.core.PApplet#month() * @see processing.core.PApplet#year() * */ static public int second() { return Calendar.getInstance().get(Calendar.SECOND); } /** * Processing communicates with the clock on your computer. The minute() function returns the current minute as a value from 0 - 59. * * @webref input:time_date * @see processing.core.PApplet#millis() * @see processing.core.PApplet#second() * @see processing.core.PApplet#hour() * @see processing.core.PApplet#day() * @see processing.core.PApplet#month() * @see processing.core.PApplet#year() * * */ static public int minute() { return Calendar.getInstance().get(Calendar.MINUTE); } /** * Processing communicates with the clock on your computer. The hour() function returns the current hour as a value from 0 - 23. * =advanced * Hour position of the current time in international format (0-23). *
* To convert this value to American time:
*
int yankeeHour = (hour() % 12); * if (yankeeHour == 0) yankeeHour = 12;* * @webref input:time_date * @see processing.core.PApplet#millis() * @see processing.core.PApplet#second() * @see processing.core.PApplet#minute() * @see processing.core.PApplet#day() * @see processing.core.PApplet#month() * @see processing.core.PApplet#year() * */ static public int hour() { return Calendar.getInstance().get(Calendar.HOUR_OF_DAY); } /** * Processing communicates with the clock on your computer. The day() function returns the current day as a value from 1 - 31. * =advanced * Get the current day of the month (1 through 31). *
* If you're looking for the day of the week (M-F or whatever)
* or day of the year (1..365) then use java's Calendar.get()
*
* @webref input:time_date
* @see processing.core.PApplet#millis()
* @see processing.core.PApplet#second()
* @see processing.core.PApplet#minute()
* @see processing.core.PApplet#hour()
* @see processing.core.PApplet#month()
* @see processing.core.PApplet#year()
*/
static public int day() {
return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
}
/**
* Processing communicates with the clock on your computer. The month() function returns the current month as a value from 1 - 12.
*
* @webref input:time_date
* @see processing.core.PApplet#millis()
* @see processing.core.PApplet#second()
* @see processing.core.PApplet#minute()
* @see processing.core.PApplet#hour()
* @see processing.core.PApplet#day()
* @see processing.core.PApplet#year()
*/
static public int month() {
// months are number 0..11 so change to colloquial 1..12
return Calendar.getInstance().get(Calendar.MONTH) + 1;
}
/**
* Processing communicates with the clock on your computer.
* The year() function returns the current year as an integer (2003, 2004, 2005, etc).
*
* @webref input:time_date
* @see processing.core.PApplet#millis()
* @see processing.core.PApplet#second()
* @see processing.core.PApplet#minute()
* @see processing.core.PApplet#hour()
* @see processing.core.PApplet#day()
* @see processing.core.PApplet#month()
*/
static public int year() {
return Calendar.getInstance().get(Calendar.YEAR);
}
//////////////////////////////////////////////////////////////
// controlling time (playing god)
/**
* The delay() function causes the program to halt for a specified time.
* Delay times are specified in thousandths of a second. For example,
* running delay(3000) will stop the program for three seconds and
* delay(500) will stop the program for a half-second. Remember: the
* display window is updated only at the end of draw(), so putting more
* than one delay() inside draw() will simply add them together and the new
* frame will be drawn when the total delay is over.
*
* I'm not sure if this is even helpful anymore, as the screen isn't
* updated before or after the delay, meaning which means it just
* makes the app lock up temporarily.
*/
public void delay(int napTime) {
if (frameCount != 0) {
if (napTime > 0) {
try {
Thread.sleep(napTime);
} catch (InterruptedException e) { }
}
}
}
/**
* Specifies the number of frames to be displayed every second.
* If the processor is not fast enough to maintain the specified rate, it will not be achieved.
* For example, the function call frameRate(30) will attempt to refresh 30 times a second.
* It is recommended to set the frame rate within setup(). The default rate is 60 frames per second.
* =advanced
* Set a target frameRate. This will cause delay() to be called
* after each frame so that the sketch synchronizes to a particular speed.
* Note that this only sets the maximum frame rate, it cannot be used to
* make a slow sketch go faster. Sketches have no default frame rate
* setting, and will attempt to use maximum processor power to achieve
* maximum speed.
* @webref environment
* @param newRateTarget number of frames per second
* @see PApplet#delay(int)
*/
public void frameRate(float newRateTarget) {
frameRateTarget = newRateTarget;
frameRatePeriod = (long) (1000000000.0 / frameRateTarget);
}
//////////////////////////////////////////////////////////////
/**
* Reads the value of a param.
* Values are always read as a String so if you want them to be an integer or other datatype they must be converted.
* The param() function will only work in a web browser.
* The function should be called inside setup(),
* otherwise the applet may not yet be initialized and connected to its parent web browser.
*
* @webref input:web
* @usage Web
*
* @param what name of the param to read
*/
public String param(String what) {
if (online) {
return getParameter(what);
} else {
System.err.println("param() only works inside a web browser");
}
return null;
}
/**
* Displays message in the browser's status area. This is the text area in the lower left corner of the browser.
* The status() function will only work when the Processing program is running in a web browser.
* =advanced
* Show status in the status bar of a web browser, or in the
* System.out console. Eventually this might show status in the
* p5 environment itself, rather than relying on the console.
*
* @webref input:web
* @usage Web
* @param what any valid String
*/
public void status(String what) {
if (online) {
showStatus(what);
} else {
System.out.println(what); // something more interesting?
}
}
public void link(String here) {
link(here, null);
}
/**
* Links to a webpage either in the same window or in a new window. The complete URL must be specified.
* =advanced
* Link to an external page without all the muss.
*
* When run with an applet, uses the browser to open the url, * for applications, attempts to launch a browser with the url. *
* Works on Mac OS X and Windows. For Linux, use: *
open(new String[] { "firefox", url });* or whatever you want as your browser, since Linux doesn't * yet have a standard method for launching URLs. * * @webref input:web * @param url complete url as a String in quotes * @param frameTitle name of the window to load the URL as a string in quotes * */ public void link(String url, String frameTitle) { if (online) { try { if (frameTitle == null) { getAppletContext().showDocument(new URL(url)); } else { getAppletContext().showDocument(new URL(url), frameTitle); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Could not open " + url); } } else { try { if (platform == WINDOWS) { // the following uses a shell execute to launch the .html file // note that under cygwin, the .html files have to be chmodded +x // after they're unpacked from the zip file. i don't know why, // and don't understand what this does in terms of windows // permissions. without the chmod, the command prompt says // "Access is denied" in both cygwin and the "dos" prompt. //Runtime.getRuntime().exec("cmd /c " + currentDir + "\\reference\\" + // referenceFile + ".html"); // replace ampersands with control sequence for DOS. // solution contributed by toxi on the bugs board. url = url.replaceAll("&","^&"); // open dos prompt, give it 'start' command, which will // open the url properly. start by itself won't work since // it appears to need cmd Runtime.getRuntime().exec("cmd /c start " + url); } else if (platform == MACOSX) { //com.apple.mrj.MRJFileUtils.openURL(url); try { // Class> mrjFileUtils = Class.forName("com.apple.mrj.MRJFileUtils"); // Method openMethod = // mrjFileUtils.getMethod("openURL", new Class[] { String.class }); Class> eieio = Class.forName("com.apple.eio.FileManager"); Method openMethod = eieio.getMethod("openURL", new Class[] { String.class }); openMethod.invoke(null, new Object[] { url }); } catch (Exception e) { e.printStackTrace(); } } else { //throw new RuntimeException("Can't open URLs for this platform"); // Just pass it off to open() and hope for the best open(url); } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Could not open " + url); } } } /** * Attempts to open an application or file using your platform's launcher. The file parameter is a String specifying the file name and location. The location parameter must be a full path name, or the name of an executable in the system's PATH. In most cases, using a full path is the best option, rather than relying on the system PATH. Be sure to make the file executable before attempting to open it (chmod +x). *
* Best used just before endDraw() at the end of your draw(). * This can only create .tif or .tga images, so if neither extension * is specified it defaults to writing a tiff and adds a .tif suffix. */ public void saveFrame() { try { g.save(savePath("screen-" + nf(frameCount, 4) + ".tif")); } catch (SecurityException se) { System.err.println("Can't use saveFrame() when running in a browser, " + "unless using a signed applet."); } } /** * Save the current frame as a .tif or .tga image. *
* The String passed in can contain a series of # signs * that will be replaced with the screengrab number. *
* i.e. saveFrame("blah-####.tif"); * // saves a numbered tiff image, replacing the * // #### signs with zeros and the frame number*/ public void saveFrame(String what) { try { g.save(savePath(insertFrame(what))); } catch (SecurityException se) { System.err.println("Can't use saveFrame() when running in a browser, " + "unless using a signed applet."); } } /** * Check a string for #### signs to see if the frame number should be * inserted. Used for functions like saveFrame() and beginRecord() to * replace the # marks with the frame number. If only one # is used, * it will be ignored, under the assumption that it's probably not * intended to be the frame number. */ protected String insertFrame(String what) { int first = what.indexOf('#'); int last = what.lastIndexOf('#'); if ((first != -1) && (last - first > 0)) { String prefix = what.substring(0, first); int count = last - first + 1; String suffix = what.substring(last + 1); return prefix + nf(frameCount, count) + suffix; } return what; // no change } ////////////////////////////////////////////////////////////// // CURSOR // int cursorType = ARROW; // cursor type boolean cursorVisible = true; // cursor visibility flag PImage invisibleCursor; /** * Set the cursor type * @param cursorType either ARROW, CROSS, HAND, MOVE, TEXT, WAIT */ public void cursor(int cursorType) { setCursor(Cursor.getPredefinedCursor(cursorType)); cursorVisible = true; this.cursorType = cursorType; } /** * Replace the cursor with the specified PImage. The x- and y- * coordinate of the center will be the center of the image. */ public void cursor(PImage image) { cursor(image, image.width/2, image.height/2); } /** * Sets the cursor to a predefined symbol, an image, or turns it on if already hidden. * If you are trying to set an image as the cursor, it is recommended to make the size 16x16 or 32x32 pixels. * It is not possible to load an image as the cursor if you are exporting your program for the Web. * The values for parameters x and y must be less than the dimensions of the image. * =advanced * Set a custom cursor to an image with a specific hotspot. * Only works with JDK 1.2 and later. * Currently seems to be broken on Java 1.4 for Mac OS X *
* Based on code contributed by Amit Pitaru, plus additional * code to handle Java versions via reflection by Jonathan Feinberg. * Reflection removed for release 0128 and later. * @webref environment * @see PApplet#noCursor() * @param image any variable of type PImage * @param hotspotX the horizonal active spot of the cursor * @param hotspotY the vertical active spot of the cursor */ public void cursor(PImage image, int hotspotX, int hotspotY) { // don't set this as cursor type, instead use cursor_type // to save the last cursor used in case cursor() is called //cursor_type = Cursor.CUSTOM_CURSOR; Image jimage = createImage(new MemoryImageSource(image.width, image.height, image.pixels, 0, image.width)); Point hotspot = new Point(hotspotX, hotspotY); Toolkit tk = Toolkit.getDefaultToolkit(); Cursor cursor = tk.createCustomCursor(jimage, hotspot, "Custom Cursor"); setCursor(cursor); cursorVisible = true; } /** * Show the cursor after noCursor() was called. * Notice that the program remembers the last set cursor type */ public void cursor() { // maybe should always set here? seems dangerous, since // it's likely that java will set the cursor to something // else on its own, and the applet will be stuck b/c bagel // thinks that the cursor is set to one particular thing if (!cursorVisible) { cursorVisible = true; setCursor(Cursor.getPredefinedCursor(cursorType)); } } /** * Hides the cursor from view. Will not work when running the program in a web browser. * =advanced * Hide the cursor by creating a transparent image * and using it as a custom cursor. * @webref environment * @see PApplet#cursor() * @usage Application */ public void noCursor() { if (!cursorVisible) return; // don't hide if already hidden. if (invisibleCursor == null) { invisibleCursor = new PImage(16, 16, ARGB); } // was formerly 16x16, but the 0x0 was added by jdf as a fix // for macosx, which wasn't honoring the invisible cursor cursor(invisibleCursor, 8, 8); cursorVisible = false; } ////////////////////////////////////////////////////////////// static public void print(byte what) { System.out.print(what); System.out.flush(); } static public void print(boolean what) { System.out.print(what); System.out.flush(); } static public void print(char what) { System.out.print(what); System.out.flush(); } static public void print(int what) { System.out.print(what); System.out.flush(); } static public void print(float what) { System.out.print(what); System.out.flush(); } static public void print(String what) { System.out.print(what); System.out.flush(); } static public void print(Object what) { if (what == null) { // special case since this does fuggly things on > 1.1 System.out.print("null"); } else { System.out.println(what.toString()); } } // static public void println() { System.out.println(); } // static public void println(byte what) { print(what); System.out.println(); } static public void println(boolean what) { print(what); System.out.println(); } static public void println(char what) { print(what); System.out.println(); } static public void println(int what) { print(what); System.out.println(); } static public void println(float what) { print(what); System.out.println(); } static public void println(String what) { print(what); System.out.println(); } static public void println(Object what) { if (what == null) { // special case since this does fuggly things on > 1.1 System.out.println("null"); } else { String name = what.getClass().getName(); if (name.charAt(0) == '[') { switch (name.charAt(1)) { case '[': // don't even mess with multi-dimensional arrays (case '[') // or anything else that's not int, float, boolean, char System.out.println(what); break; case 'L': // print a 1D array of objects as individual elements Object poo[] = (Object[]) what; for (int i = 0; i < poo.length; i++) { if (poo[i] instanceof String) { System.out.println("[" + i + "] \"" + poo[i] + "\""); } else { System.out.println("[" + i + "] " + poo[i]); } } break; case 'Z': // boolean boolean zz[] = (boolean[]) what; for (int i = 0; i < zz.length; i++) { System.out.println("[" + i + "] " + zz[i]); } break; case 'B': // byte byte bb[] = (byte[]) what; for (int i = 0; i < bb.length; i++) { System.out.println("[" + i + "] " + bb[i]); } break; case 'C': // char char cc[] = (char[]) what; for (int i = 0; i < cc.length; i++) { System.out.println("[" + i + "] '" + cc[i] + "'"); } break; case 'I': // int int ii[] = (int[]) what; for (int i = 0; i < ii.length; i++) { System.out.println("[" + i + "] " + ii[i]); } break; case 'F': // float float ff[] = (float[]) what; for (int i = 0; i < ff.length; i++) { System.out.println("[" + i + "] " + ff[i]); } break; case 'D': // double double dd[] = (double[]) what; for (int i = 0; i < dd.length; i++) { System.out.println("[" + i + "] " + dd[i]); } break; default: System.out.println(what); } } else { // not an array System.out.println(what); } } } // /* // not very useful, because it only works for public (and protected?) // fields of a class, not local variables to methods public void printvar(String name) { try { Field field = getClass().getDeclaredField(name); println(name + " = " + field.get(this)); } catch (Exception e) { e.printStackTrace(); } } */ ////////////////////////////////////////////////////////////// // MATH // lots of convenience methods for math with floats. // doubles are overkill for processing applets, and casting // things all the time is annoying, thus the functions below. static public final float abs(float n) { return (n < 0) ? -n : n; } static public final int abs(int n) { return (n < 0) ? -n : n; } static public final float sq(float a) { return a*a; } static public final float sqrt(float a) { return (float)Math.sqrt(a); } static public final float log(float a) { return (float)Math.log(a); } static public final float exp(float a) { return (float)Math.exp(a); } static public final float pow(float a, float b) { return (float)Math.pow(a, b); } static public final int max(int a, int b) { return (a > b) ? a : b; } static public final float max(float a, float b) { return (a > b) ? a : b; } /* static public final double max(double a, double b) { return (a > b) ? a : b; } */ static public final int max(int a, int b, int c) { return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); } static public final float max(float a, float b, float c) { return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); } /** * Find the maximum value in an array. * Throws an ArrayIndexOutOfBoundsException if the array is length 0. * @param list the source array * @return The maximum value */ static public final int max(int[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } int max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } /** * Find the maximum value in an array. * Throws an ArrayIndexOutOfBoundsException if the array is length 0. * @param list the source array * @return The maximum value */ static public final float max(float[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } float max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } /** * Find the maximum value in an array. * Throws an ArrayIndexOutOfBoundsException if the array is length 0. * @param list the source array * @return The maximum value */ /* static public final double max(double[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } double max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } */ static public final int min(int a, int b) { return (a < b) ? a : b; } static public final float min(float a, float b) { return (a < b) ? a : b; } /* static public final double min(double a, double b) { return (a < b) ? a : b; } */ static public final int min(int a, int b, int c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } static public final float min(float a, float b, float c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } /* static public final double min(double a, double b, double c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } */ /** * Find the minimum value in an array. * Throws an ArrayIndexOutOfBoundsException if the array is length 0. * @param list the source array * @return The minimum value */ static public final int min(int[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } int min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } /** * Find the minimum value in an array. * Throws an ArrayIndexOutOfBoundsException if the array is length 0. * @param list the source array * @return The minimum value */ static public final float min(float[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } float min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } /** * Find the minimum value in an array. * Throws an ArrayIndexOutOfBoundsException if the array is length 0. * @param list the source array * @return The minimum value */ /* static public final double min(double[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } double min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } */ static public final int constrain(int amt, int low, int high) { return (amt < low) ? low : ((amt > high) ? high : amt); } static public final float constrain(float amt, float low, float high) { return (amt < low) ? low : ((amt > high) ? high : amt); } static public final float sin(float angle) { return (float)Math.sin(angle); } static public final float cos(float angle) { return (float)Math.cos(angle); } static public final float tan(float angle) { return (float)Math.tan(angle); } static public final float asin(float value) { return (float)Math.asin(value); } static public final float acos(float value) { return (float)Math.acos(value); } static public final float atan(float value) { return (float)Math.atan(value); } static public final float atan2(float a, float b) { return (float)Math.atan2(a, b); } static public final float degrees(float radians) { return radians * RAD_TO_DEG; } static public final float radians(float degrees) { return degrees * DEG_TO_RAD; } static public final int ceil(float what) { return (int) Math.ceil(what); } static public final int floor(float what) { return (int) Math.floor(what); } static public final int round(float what) { return (int) Math.round(what); } static public final float mag(float a, float b) { return (float)Math.sqrt(a*a + b*b); } static public final float mag(float a, float b, float c) { return (float)Math.sqrt(a*a + b*b + c*c); } static public final float dist(float x1, float y1, float x2, float y2) { return sqrt(sq(x2-x1) + sq(y2-y1)); } static public final float dist(float x1, float y1, float z1, float x2, float y2, float z2) { return sqrt(sq(x2-x1) + sq(y2-y1) + sq(z2-z1)); } static public final float lerp(float start, float stop, float amt) { return start + (stop-start) * amt; } /** * Normalize a value to exist between 0 and 1 (inclusive). * Mathematically the opposite of lerp(), figures out what proportion * a particular value is relative to start and stop coordinates. */ static public final float norm(float value, float start, float stop) { return (value - start) / (stop - start); } /** * Convenience function to map a variable from one coordinate space * to another. Equivalent to unlerp() followed by lerp(). */ static public final float map(float value, float istart, float istop, float ostart, float ostop) { return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); } /* static public final double map(double value, double istart, double istop, double ostart, double ostop) { return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); } */ ////////////////////////////////////////////////////////////// // RANDOM NUMBERS Random internalRandom; /** * Return a random number in the range [0, howbig). *
* The number returned will range from zero up to * (but not including) 'howbig'. */ public final float random(float howbig) { // for some reason (rounding error?) Math.random() * 3 // can sometimes return '3' (once in ~30 million tries) // so a check was added to avoid the inclusion of 'howbig' // avoid an infinite loop if (howbig == 0) return 0; // internal random number object if (internalRandom == null) internalRandom = new Random(); float value = 0; do { //value = (float)Math.random() * howbig; value = internalRandom.nextFloat() * howbig; } while (value == howbig); return value; } /** * Return a random number in the range [howsmall, howbig). *
* The number returned will range from 'howsmall' up to * (but not including 'howbig'. *
* If howsmall is >= howbig, howsmall will be returned,
* meaning that random(5, 5) will return 5 (useful)
* and random(7, 4) will return 7 (not useful.. better idea?)
*/
public final float random(float howsmall, float howbig) {
if (howsmall >= howbig) return howsmall;
float diff = howbig - howsmall;
return random(diff) + howsmall;
}
public final void randomSeed(long what) {
// internal random number object
if (internalRandom == null) internalRandom = new Random();
internalRandom.setSeed(what);
}
//////////////////////////////////////////////////////////////
// PERLIN NOISE
// [toxi 040903]
// octaves and amplitude amount per octave are now user controlled
// via the noiseDetail() function.
// [toxi 030902]
// cleaned up code and now using bagel's cosine table to speed up
// [toxi 030901]
// implementation by the german demo group farbrausch
// as used in their demo "art": http://www.farb-rausch.de/fr010src.zip
static final int PERLIN_YWRAPB = 4;
static final int PERLIN_YWRAP = 1<
* Generally, loadImage() should only be used during setup, because
* re-loading images inside draw() is likely to cause a significant
* delay while memory is allocated and the thread blocks while waiting
* for the image to load because loading is not asynchronous.
*
* To load several images asynchronously, see more information in the
* FAQ about writing your own threaded image loading method.
*
* As of 0096, returns null if no image of that name is found,
* rather than an error.
*
* Release 0115 also provides support for reading TIFF and RLE-encoded
* Targa (.tga) files written by Processing via save() and saveFrame().
* Other TIFF and Targa files will probably not load, use a different
* format (gif, jpg and png are safest bets) when creating images with
* another application to use with Processing.
*
* Also in release 0115, more image formats (BMP and others) can
* be read when using Java 1.4 and later. Because many people still
* use Java 1.1 and 1.3, these formats are not recommended for
* work that will be posted on the web. To get a list of possible
* image formats for use with Java 1.4 and later, use the following:
* println(javax.imageio.ImageIO.getReaderFormatNames())
*
* Images are loaded via a byte array that is passed to
* Toolkit.createImage(). Unfortunately, we cannot use Applet.getImage()
* because it takes a URL argument, which would be a pain in the a--
* to make work consistently for online and local sketches.
* Sometimes this causes problems, resulting in issues like
* Bug 279
* and
* Bug 305.
* In release 0115, everything was instead run through javax.imageio,
* but that turned out to be very slow, see
* Bug 392.
* As a result, starting with 0116, the following happens:
*
* Rewritten for 0115 to read/write RLE-encoded targa images.
* For 0125, non-RLE encoded images are now supported, along with
* images whose y-order is reversed (which is standard for TGA files).
*/
protected PImage loadImageTGA(String filename) throws IOException {
InputStream is = createInput(filename);
if (is == null) return null;
byte header[] = new byte[18];
int offset = 0;
do {
int count = is.read(header, offset, header.length - offset);
if (count == -1) return null;
offset += count;
} while (offset < 18);
/*
header[2] image type code
2 (0x02) - Uncompressed, RGB images.
3 (0x03) - Uncompressed, black and white images.
10 (0x0A) - Runlength encoded RGB images.
11 (0x0B) - Compressed, black and white images. (grayscale?)
header[16] is the bit depth (8, 24, 32)
header[17] image descriptor (packed bits)
0x20 is 32 = origin upper-left
0x28 is 32 + 8 = origin upper-left + 32 bits
7 6 5 4 3 2 1 0
128 64 32 16 8 4 2 1
*/
int format = 0;
if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not
(header[16] == 8) && // 8 bits
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit
format = ALPHA;
} else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not
(header[16] == 24) && // 24 bits
((header[17] == 0x20) || (header[17] == 0))) { // origin
format = RGB;
} else if (((header[2] == 2) || (header[2] == 10)) &&
(header[16] == 32) &&
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32
format = ARGB;
}
if (format == 0) {
System.err.println("Unknown .tga file format for " + filename);
//" (" + header[2] + " " +
//(header[16] & 0xff) + " " +
//hex(header[17], 2) + ")");
return null;
}
int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff);
int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff);
PImage outgoing = createImage(w, h, format);
// where "reversed" means upper-left corner (normal for most of
// the modernized world, but "reversed" for the tga spec)
boolean reversed = (header[17] & 0x20) != 0;
if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded
if (reversed) {
int index = (h-1) * w;
switch (format) {
case ALPHA:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] = is.read();
}
index -= w;
}
break;
case RGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
index -= w;
}
break;
case ARGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
index -= w;
}
}
} else { // not reversed
int count = w * h;
switch (format) {
case ALPHA:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] = is.read();
}
break;
case RGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
break;
case ARGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
break;
}
}
} else { // header[2] is 10 or 11
int index = 0;
int px[] = outgoing.pixels;
while (index < px.length) {
int num = is.read();
boolean isRLE = (num & 0x80) != 0;
if (isRLE) {
num -= 127; // (num & 0x7F) + 1
int pixel = 0;
switch (format) {
case ALPHA:
pixel = is.read();
break;
case RGB:
pixel = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
break;
case ARGB:
pixel = is.read() |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
break;
}
for (int i = 0; i < num; i++) {
px[index++] = pixel;
if (index == px.length) break;
}
} else { // write up to 127 bytes as uncompressed
num += 1;
switch (format) {
case ALPHA:
for (int i = 0; i < num; i++) {
px[index++] = is.read();
}
break;
case RGB:
for (int i = 0; i < num; i++) {
px[index++] = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
case ARGB:
for (int i = 0; i < num; i++) {
px[index++] = is.read() | //(is.read() << 24) |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
}
}
}
if (!reversed) {
int[] temp = new int[w];
for (int y = 0; y < h/2; y++) {
int z = (h-1) - y;
System.arraycopy(px, y*w, temp, 0, w);
System.arraycopy(px, z*w, px, y*w, w);
System.arraycopy(temp, 0, px, z*w, w);
}
}
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// SHAPE I/O
/**
* Loads vector shapes into a variable of type PShape. Currently, only SVG files may be loaded.
* To load correctly, the file must be located in the data directory of the current sketch.
* In most cases, loadShape() should be used inside setup() because loading shapes inside draw() will reduce the speed of a sketch.
*
* This method is useful if you want to use the facilities provided
* by PApplet to easily open things from the data folder or from a URL,
* but want an InputStream object so that you can use other Java
* methods to take more control of how the stream is read.
*
* If the requested item doesn't exist, null is returned.
* (Prior to 0096, die() would be called, killing the applet)
*
* For 0096+, the "data" folder is exported intact with subfolders,
* and openStream() properly handles subdirectories from the data folder
*
* If not online, this will also check to see if the user is asking
* for a file whose name isn't properly capitalized. This helps prevent
* issues when a sketch is exported to the web, where case sensitivity
* matters, as opposed to Windows and the Mac OS default where
* case sensitivity is preserved but ignored.
*
* It is strongly recommended that libraries use this method to open
* data files, so that the loading sequence is handled in the same way
* as functions like loadBytes(), loadImage(), etc.
*
* The filename passed in can be:
*
* Exceptions are handled internally, when an error, occurs, an
* exception is printed to the console and 'null' is returned,
* but the program continues running. This is a tradeoff between
* 1) showing the user that there was a problem but 2) not requiring
* that all i/o code is contained in try/catch blocks, for the sake
* of new users (or people who are just trying to get things done
* in a "scripting" fashion. If you want to handle exceptions,
* use Java methods for I/O.
*
* @webref input:files
* @param filename name of the file or url to load
*
* @see processing.core.PApplet#loadBytes(String)
* @see processing.core.PApplet#saveStrings(String, String[])
* @see processing.core.PApplet#saveBytes(String, byte[])
*/
public String[] loadStrings(String filename) {
InputStream is = createInput(filename);
if (is != null) return loadStrings(is);
System.err.println("The file \"" + filename + "\" " +
"is missing or inaccessible, make sure " +
"the URL is valid or that the file has been " +
"added to your sketch and is readable.");
return null;
}
static public String[] loadStrings(InputStream input) {
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(input, "UTF-8"));
String lines[] = new String[100];
int lineCount = 0;
String line = null;
while ((line = reader.readLine()) != null) {
if (lineCount == lines.length) {
String temp[] = new String[lineCount << 1];
System.arraycopy(lines, 0, temp, 0, lineCount);
lines = temp;
}
lines[lineCount++] = line;
}
reader.close();
if (lineCount == lines.length) {
return lines;
}
// resize array to appropriate amount for these lines
String output[] = new String[lineCount];
System.arraycopy(lines, 0, output, 0, lineCount);
return output;
} catch (IOException e) {
e.printStackTrace();
//throw new RuntimeException("Error inside loadStrings()");
}
return null;
}
//////////////////////////////////////////////////////////////
// FILE OUTPUT
/**
* Similar to createInput() (formerly openStream), this creates a Java
* OutputStream for a given filename or path. The file will be created in
* the sketch folder, or in the same folder as an exported application.
*
* In this method, the data path is defined not as the applet's actual
* data path, but a folder titled "data" in the sketch's working
* directory. When running inside the PDE, this will be the sketch's
* "data" folder. However, when exported (as application or applet),
* sketch's data folder is exported as part of the applications jar file,
* and it's not possible to read/write from the jar file in a generic way.
* If you need to read data from the jar file, you should use other methods
* such as createInput(), createReader(), or loadStrings().
*/
public String dataPath(String where) {
// isAbsolute() could throw an access exception, but so will writing
// to the local disk using the sketch path, so this is safe here.
if (new File(where).isAbsolute()) return where;
return sketchPath + File.separator + "data" + File.separator + where;
}
/**
* Return a full path to an item in the data folder as a File object.
* See the dataPath() method for more information.
*/
public File dataFile(String where) {
return new File(dataPath(where));
}
/**
* Takes a path and creates any in-between folders if they don't
* already exist. Useful when trying to save to a subfolder that
* may not actually exist.
*/
static public void createPath(String path) {
createPath(new File(path));
}
static public void createPath(File file) {
try {
String parent = file.getParent();
if (parent != null) {
File unit = new File(parent);
if (!unit.exists()) unit.mkdirs();
}
} catch (SecurityException se) {
System.err.println("You don't have permissions to create " +
file.getAbsolutePath());
}
}
//////////////////////////////////////////////////////////////
// SORT
static public byte[] sort(byte what[]) {
return sort(what, what.length);
}
static public byte[] sort(byte[] what, int count) {
byte[] outgoing = new byte[what.length];
System.arraycopy(what, 0, outgoing, 0, what.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public char[] sort(char what[]) {
return sort(what, what.length);
}
static public char[] sort(char[] what, int count) {
char[] outgoing = new char[what.length];
System.arraycopy(what, 0, outgoing, 0, what.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public int[] sort(int what[]) {
return sort(what, what.length);
}
static public int[] sort(int[] what, int count) {
int[] outgoing = new int[what.length];
System.arraycopy(what, 0, outgoing, 0, what.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public float[] sort(float what[]) {
return sort(what, what.length);
}
static public float[] sort(float[] what, int count) {
float[] outgoing = new float[what.length];
System.arraycopy(what, 0, outgoing, 0, what.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public String[] sort(String what[]) {
return sort(what, what.length);
}
static public String[] sort(String[] what, int count) {
String[] outgoing = new String[what.length];
System.arraycopy(what, 0, outgoing, 0, what.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
//////////////////////////////////////////////////////////////
// ARRAY UTILITIES
/**
* Calls System.arraycopy(), included here so that we can
* avoid people needing to learn about the System object
* before they can just copy an array.
*/
static public void arrayCopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* Convenience method for arraycopy().
* Identical to
* To use this on numbers, first pass the array to nf() or nfs()
* to get a list of String objects, then use join on that.
*
* The whitespace characters are "\t\n\r\f", which are the defaults
* for java.util.StringTokenizer, plus the unicode non-breaking space
* character, which is found commonly on files created by or used
* in conjunction with Mac OS X (character 160, or 0x00A0 in hex).
*
* This operates differently than the others, where the
* single delimeter is the only breaking point, and consecutive
* delimeters will produce an empty string (""). This way,
* one can split on tab characters, but maintain the column
* alignments (of say an excel file) where there are empty columns.
*/
static public String[] split(String what, char delim) {
// do this so that the exception occurs inside the user's
// program, rather than appearing to be a bug inside split()
if (what == null) return null;
//return split(what, String.valueOf(delim)); // huh
char chars[] = what.toCharArray();
int splitCount = 0; //1;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) splitCount++;
}
// make sure that there is something in the input string
//if (chars.length > 0) {
// if the last char is a delimeter, get rid of it..
//if (chars[chars.length-1] == delim) splitCount--;
// on second thought, i don't agree with this, will disable
//}
if (splitCount == 0) {
String splits[] = new String[1];
splits[0] = new String(what);
return splits;
}
//int pieceCount = splitCount + 1;
String splits[] = new String[splitCount + 1];
int splitIndex = 0;
int startIndex = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) {
splits[splitIndex++] =
new String(chars, startIndex, i-startIndex);
startIndex = i + 1;
}
}
//if (startIndex != chars.length) {
splits[splitIndex] =
new String(chars, startIndex, chars.length-startIndex);
//}
return splits;
}
/**
* Split a String on a specific delimiter. Unlike Java's String.split()
* method, this does not parse the delimiter as a regexp because it's more
* confusing than necessary, and String.split() is always available for
* those who want regexp.
*/
static public String[] split(String what, String delim) {
ArrayList Convert an integer to a boolean. Because of how Java handles upgrading
* numbers, this will also cover byte and char (as they will upgrade to
* an int without any sort of explicit cast). The preprocessor will convert boolean(what) to parseBoolean(what).
* The options shown here are not yet finalized and will be
* changing over the next several releases.
*
* The simplest way to turn and applet into an application is to
* add the following code to your program:
*
* Differences between beginShape() and line() and point() methods.
*
* beginShape() is intended to be more flexible at the expense of being
* a little more complicated to use. it handles more complicated shapes
* that can consist of many connected lines (so you get joins) or lines
* mixed with curves.
*
* The line() and point() command are for the far more common cases
* (particularly for our audience) that simply need to draw a line
* or a point on the screen.
*
* From the code side of things, line() may or may not call beginShape()
* to do the drawing. In the beta code, they do, but in the alpha code,
* they did not. they might be implemented one way or the other depending
* on tradeoffs of runtime efficiency vs. implementation efficiency &mdash
* meaning the speed that things run at vs. the speed it takes me to write
* the code and maintain it. for beta, the latter is most important so
* that's how things are implemented.
*/
public void beginShape(int kind) {
if (recorder != null) recorder.beginShape(kind);
g.beginShape(kind);
}
/**
* Sets whether the upcoming vertex is part of an edge.
* Equivalent to glEdgeFlag(), for people familiar with OpenGL.
*/
public void edge(boolean edge) {
if (recorder != null) recorder.edge(edge);
g.edge(edge);
}
/**
* Sets the current normal vector. Only applies with 3D rendering
* and inside a beginShape/endShape block.
*
* Implementation notes:
*
* cache all the points of the sphere in a static array
* top and bottom are just a bunch of triangles that land
* in the center point
*
* sphere is a series of concentric circles who radii vary
* along the shape, based on, er.. cos or something
*
* Identical to typing:
*
* Identical to typing out:
* Given an (x, y, z) coordinate, returns the x position of where
* that point would be placed on screen, once affected by translate(),
* scale(), or any other transformations.
*/
public float screenX(float x, float y, float z) {
return g.screenX(x, y, z);
}
/**
* Maps a three dimensional point to its placement on-screen.
*
* Given an (x, y, z) coordinate, returns the y position of where
* that point would be placed on screen, once affected by translate(),
* scale(), or any other transformations.
*/
public float screenY(float x, float y, float z) {
return g.screenY(x, y, z);
}
/**
* Maps a three dimensional point to its placement on-screen.
*
* Given an (x, y, z) coordinate, returns its z value.
* This value can be used to determine if an (x, y, z) coordinate
* is in front or in back of another (x, y, z) coordinate.
* The units are based on how the zbuffer is set up, and don't
* relate to anything "real". They're only useful for in
* comparison to another value obtained from screenZ(),
* or directly out of the zbuffer[].
*/
public float screenZ(float x, float y, float z) {
return g.screenZ(x, y, z);
}
/**
* Returns the model space x value for an x, y, z coordinate.
*
* This will give you a coordinate after it has been transformed
* by translate(), rotate(), and camera(), but not yet transformed
* by the projection matrix. For instance, his can be useful for
* figuring out how points in 3D space relate to the edge
* coordinates of a shape.
*/
public float modelX(float x, float y, float z) {
return g.modelX(x, y, z);
}
/**
* Returns the model space y value for an x, y, z coordinate.
*/
public float modelY(float x, float y, float z) {
return g.modelY(x, y, z);
}
/**
* Returns the model space z value for an x, y, z coordinate.
*/
public float modelZ(float x, float y, float z) {
return g.modelZ(x, y, z);
}
public void pushStyle() {
if (recorder != null) recorder.pushStyle();
g.pushStyle();
}
public void popStyle() {
if (recorder != null) recorder.popStyle();
g.popStyle();
}
public void style(PStyle s) {
if (recorder != null) recorder.style(s);
g.style(s);
}
public void strokeWeight(float weight) {
if (recorder != null) recorder.strokeWeight(weight);
g.strokeWeight(weight);
}
public void strokeJoin(int join) {
if (recorder != null) recorder.strokeJoin(join);
g.strokeJoin(join);
}
public void strokeCap(int cap) {
if (recorder != null) recorder.strokeCap(cap);
g.strokeCap(cap);
}
/**
* Disables drawing the stroke (outline). If both noStroke() and
* noFill() are called, no shapes will be drawn to the screen.
*
* @webref color:setting
*
* @see PGraphics#stroke(float, float, float, float)
*/
public void noStroke() {
if (recorder != null) recorder.noStroke();
g.noStroke();
}
/**
* Set the tint to either a grayscale or ARGB value.
* See notes attached to the fill() function.
* @param rgb color value in hexadecimal notation
* (i.e. #FFCC00 or 0xFFFFCC00) or any value of the color datatype
*/
public void stroke(int rgb) {
if (recorder != null) recorder.stroke(rgb);
g.stroke(rgb);
}
public void stroke(int rgb, float alpha) {
if (recorder != null) recorder.stroke(rgb, alpha);
g.stroke(rgb, alpha);
}
/**
*
* @param gray specifies a value between white and black
*/
public void stroke(float gray) {
if (recorder != null) recorder.stroke(gray);
g.stroke(gray);
}
public void stroke(float gray, float alpha) {
if (recorder != null) recorder.stroke(gray, alpha);
g.stroke(gray, alpha);
}
public void stroke(float x, float y, float z) {
if (recorder != null) recorder.stroke(x, y, z);
g.stroke(x, y, z);
}
/**
* Sets the color used to draw lines and borders around shapes. This color
* is either specified in terms of the RGB or HSB color depending on the
* current colorMode() (the default color space is RGB, with each
* value in the range from 0 to 255).
*
* For the main drawing surface, the alpha value will be ignored. However,
* alpha can be used on PGraphics objects from createGraphics(). This is
* the only way to set all the pixels partially transparent, for instance.
*
* Note that background() should be called before any transformations occur,
* because some implementations may require the current transformation matrix
* to be identity before drawing.
*
* @param rgb color value in hexadecimal notation (i.e. #FFCC00 or 0xFFFFCC00) Clear the background with a color that includes an alpha value. This can
* only be used with objects created by createGraphics(), because the main
* drawing surface cannot be set transparent. It might be tempting to use this function to partially clear the screen
* on each frame, however that's not how this function works. When calling
* background(), the pixels will be replaced with pixels that have that level
* of transparency. To do a semi-transparent overlay, use fill() with alpha
* and draw a rectangle.
* Note that even if the image is set as RGB, the high 8 bits of each pixel
* should be set opaque (0xFF000000), because the image data will be copied
* directly to the screen, and non-opaque background images may have strange
* behavior. Using image.filter(OPAQUE) will handle this easily.
*
* When using 3D, this will also clear the zbuffer (if it exists).
*/
public void background(PImage image) {
if (recorder != null) recorder.background(image);
g.background(image);
}
/**
* @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness
* @param max range for all color elements
*/
public void colorMode(int mode) {
if (recorder != null) recorder.colorMode(mode);
g.colorMode(mode);
}
public void colorMode(int mode, float max) {
if (recorder != null) recorder.colorMode(mode, max);
g.colorMode(mode, max);
}
/**
* Set the colorMode and the maximum values for (r, g, b)
* or (h, s, b).
*
* Note that this doesn't set the maximum for the alpha value,
* which might be confusing if for instance you switched to
*
* If the image is in RGB format (i.e. on a PVideo object),
* the value will get its high bits set, just to avoid cases where
* they haven't been set already.
*
* If the image is in ALPHA format, this returns a white with its
* alpha value set.
*
* This function is included primarily for beginners. It is quite
* slow because it has to check to see if the x, y that was provided
* is inside the bounds, and then has to check to see what image
* type it is. If you want things to be more efficient, access the
* pixels[] array directly.
*/
public int get(int x, int y) {
return g.get(x, y);
}
/**
* Reads the color of any pixel or grabs a group of pixels. If no parameters are specified, the entire image is returned. Get the value of one pixel by specifying an x,y coordinate. Get a section of the display window by specifing an additional width and height parameter. If the pixel requested is outside of the image window, black is returned. The numbers returned are scaled according to the current color ranges, but only RGB values are returned by this function. Even though you may have drawn a shape with colorMode(HSB), the numbers returned will be in RGB.
*
* Strictly speaking the "blue" value from the source image is
* used as the alpha color. For a fully grayscale image, this
* is correct, but for a color image it's not 100% accurate.
* For a more accurate conversion, first use filter(GRAY)
* which will make the image into a "correct" grayscale by
* performing a proper luminance-based conversion.
*
* @param maskArray any array of Integer numbers used as the alpha channel, needs to be same length as the image's pixel array
*/
public void mask(int maskArray[]) {
if (recorder != null) recorder.mask(maskArray);
g.mask(maskArray);
}
/**
* Masks part of an image from displaying by loading another image and using it as an alpha channel.
* This mask image should only contain grayscale data, but only the blue color channel is used.
* The mask image needs to be the same size as the image to which it is applied.
* In addition to using a mask image, an integer array containing the alpha channel data can be specified directly.
* This method is useful for creating dynamically generated alpha masks.
* This array must be of the same length as the target image's pixels array and should contain only grayscale data of values between 0-255.
* @webref
* @brief Masks part of the image from displaying
* @param maskImg any PImage object used as the alpha channel for "img", needs to be same size as "img"
*/
public void mask(PImage maskImg) {
if (recorder != null) recorder.mask(maskImg);
g.mask(maskImg);
}
public void filter(int kind) {
if (recorder != null) recorder.filter(kind);
g.filter(kind);
}
/**
* Filters an image as defined by one of the following modes:
* A useful reference for blending modes and their algorithms can be
* found in the SVG
* specification. It is important to note that Processing uses "fast" code, not
* necessarily "correct" code. No biggie, most software does. A nitpicker
* can find numerous "off by 1 division" problems in the blend code where
* >>8 or >>7 is used when strictly speaking
* /255.0 or /127.0 should have been used. For instance, exclusion (not intended for real-time use) reads
* r1 + r2 - ((2 * r1 * r2) / 255) because 255 == 1.0
* not 256 == 1.0. In other words, (255*255)>>8 is not
* the same as (255*255)/255. But for real-time use the shifts
* are preferrable, and the difference is insignificant for applications
* built with Processing.
* Note that the camera matrix is *not* the perspective matrix,
* it is in front of the modelview matrix (hence the name "model"
* and "view" for that matrix).
*
* beginCamera() specifies that all coordinate transforms until endCamera()
* should be pre-applied in inverse to the camera transform matrix.
* Note that this is only challenging when a user specifies an arbitrary
* matrix with applyMatrix(). Then that matrix will need to be inverted,
* which may not be possible. But take heart, if a user is applying a
* non-invertible matrix to the camera transform, then he is clearly
* up to no good, and we can wash our hands of those bad intentions.
*
* begin/endCamera clauses do not automatically reset the camera transform
* matrix. That's because we set up a nice default camera transform int
* setup(), and we expect it to hold through draw(). So we don't reset
* the camera transform matrix at the top of draw(). That means that an
* innocuous-looking clause like
*
* Note that this will destroy any settings to scale(), translate(),
* or whatever, because the final camera matrix will be copied
* (not multiplied) into the modelview.
*/
public void endCamera() {
if (!manipulatingCamera) {
throw new RuntimeException("Cannot call endCamera() " +
"without first calling beginCamera()");
}
// reset the modelview to use this new camera matrix
modelview.set(camera);
modelviewInv.set(cameraInv);
// set matrix mode back to modelview
forwardTransform = modelview;
reverseTransform = modelviewInv;
// all done
manipulatingCamera = false;
}
/**
* Set camera to the default settings.
*
* Processing camera behavior:
*
* Camera behavior can be split into two separate components, camera
* transformation, and projection. The transformation corresponds to the
* physical location, orientation, and scale of the camera. In a physical
* camera metaphor, this is what can manipulated by handling the camera
* body (with the exception of scale, which doesn't really have a physcial
* analog). The projection corresponds to what can be changed by
* manipulating the lens.
*
* We maintain separate matrices to represent the camera transform and
* projection. An important distinction between the two is that the camera
* transform should be invertible, where the projection matrix should not,
* since it serves to map three dimensions to two. It is possible to bake
* the two matrices into a single one just by multiplying them together,
* but it isn't a good idea, since lighting, z-ordering, and z-buffering
* all demand a true camera z coordinate after modelview and camera
* transforms have been applied but before projection. If the camera
* transform and projection are combined there is no way to recover a
* good camera-space z-coordinate from a model coordinate.
*
* Fortunately, there are no functions that manipulate both camera
* transformation and projection.
*
* camera() sets the camera position, orientation, and center of the scene.
* It replaces the camera transform with a new one. This is different from
* gluLookAt(), but I think the only reason that GLU's lookat doesn't fully
* replace the camera matrix with the new one, but instead multiplies it,
* is that GL doesn't enforce the separation of camera transform and
* projection, so it wouldn't be safe (you'd probably stomp your projection).
*
* The transformation functions are the same ones used to manipulate the
* modelview matrix (scale, translate, rotate, etc.). But they are bracketed
* with beginCamera(), endCamera() to indicate that they should apply
* (in inverse), to the camera transformation matrix.
*
* This differs considerably from camera transformation in OpenGL.
* OpenGL only lets you say, apply everything from here out to the
* projection or modelview matrix. This makes it very hard to treat camera
* manipulation as if it were a physical camera. Imagine that you want to
* move your camera 100 units forward. In OpenGL, you need to apply the
* inverse of that transformation or else you'll move your scene 100 units
* forward--whether or not you've specified modelview or projection matrix.
* Remember they're just multiplied by model coods one after another.
* So in order to treat a camera like a physical camera, it is necessary
* to pre-apply inverse transforms to a matrix that will be applied to model
* coordinates. OpenGL provides nothing of this sort, but Processing does!
* This is the camera transform matrix.
*/
public void camera() {
camera(cameraX, cameraY, cameraZ,
cameraX, cameraY, 0,
0, 1, 0);
}
/**
* More flexible method for dealing with camera().
*
* The actual call is like gluLookat. Here's the real skinny on
* what does what:
*
* Now, beginCamera(); and endCamera(); are useful if you want to move
* the camera around using transforms like translate(), etc. They will
* wipe out any coordinate system transforms that occur before them in
* draw(), but they will not automatically wipe out the camera transform.
* This means that they should be at the top of draw(). It also means
* that the following:
*
* Implementation partially based on Mesa's matrix.c.
*/
public void ortho(float left, float right,
float bottom, float top,
float near, float far) {
float x = 2.0f / (right - left);
float y = 2.0f / (top - bottom);
float z = -2.0f / (far - near);
float tx = -(right + left) / (right - left);
float ty = -(top + bottom) / (top - bottom);
float tz = -(far + near) / (far - near);
projection.set(x, 0, 0, tx,
0, y, 0, ty,
0, 0, z, tz,
0, 0, 0, 1);
updateProjection();
frustumMode = false;
}
/**
* Calls perspective() with Processing's standard coordinate projection.
*
* Projection functions:
*
* This behavior is pretty much familiar from OpenGL, except where
* functions replace matrices, rather than multiplying against the
* previous.
*
*/
public void perspective() {
perspective(cameraFOV, cameraAspect, cameraNear, cameraFar);
}
/**
* Similar to gluPerspective(). Implementation based on Mesa's glu.c
*/
public void perspective(float fov, float aspect, float zNear, float zFar) {
//float ymax = zNear * tan(fovy * PI / 360.0f);
float ymax = zNear * (float) Math.tan(fov / 2);
float ymin = -ymax;
float xmin = ymin * aspect;
float xmax = ymax * aspect;
frustum(xmin, xmax, ymin, ymax, zNear, zFar);
}
/**
* Same as glFrustum(), except that it wipes out (rather than
* multiplies against) the current perspective matrix.
*
* Implementation based on the explanation in the OpenGL blue book.
*/
public void frustum(float left, float right, float bottom,
float top, float znear, float zfar) {
leftScreen = left;
rightScreen = right;
bottomScreen = bottom;
topScreen = top;
nearPlane = znear;
frustumMode = true;
//System.out.println(projection);
projection.set((2*znear)/(right-left), 0, (right+left)/(right-left), 0,
0, (2*znear)/(top-bottom), (top+bottom)/(top-bottom), 0,
0, 0, -(zfar+znear)/(zfar-znear),-(2*zfar*znear)/(zfar-znear),
0, 0, -1, 0);
updateProjection();
}
/** Called after the 'projection' PMatrix3D has changed. */
protected void updateProjection() {
}
/**
* Print the current projection matrix.
*/
public void printProjection() {
projection.print();
}
//////////////////////////////////////////////////////////////
// SCREEN AND MODEL COORDS
public float screenX(float x, float y) {
return screenX(x, y, 0);
}
public float screenY(float x, float y) {
return screenY(x, y, 0);
}
public float screenX(float x, float y, float z) {
float ax =
modelview.m00*x + modelview.m01*y + modelview.m02*z + modelview.m03;
float ay =
modelview.m10*x + modelview.m11*y + modelview.m12*z + modelview.m13;
float az =
modelview.m20*x + modelview.m21*y + modelview.m22*z + modelview.m23;
float aw =
modelview.m30*x + modelview.m31*y + modelview.m32*z + modelview.m33;
float ox =
projection.m00*ax + projection.m01*ay +
projection.m02*az + projection.m03*aw;
float ow =
projection.m30*ax + projection.m31*ay +
projection.m32*az + projection.m33*aw;
if (ow != 0) ox /= ow;
return width * (1 + ox) / 2.0f;
}
public float screenY(float x, float y, float z) {
float ax =
modelview.m00*x + modelview.m01*y + modelview.m02*z + modelview.m03;
float ay =
modelview.m10*x + modelview.m11*y + modelview.m12*z + modelview.m13;
float az =
modelview.m20*x + modelview.m21*y + modelview.m22*z + modelview.m23;
float aw =
modelview.m30*x + modelview.m31*y + modelview.m32*z + modelview.m33;
float oy =
projection.m10*ax + projection.m11*ay +
projection.m12*az + projection.m13*aw;
float ow =
projection.m30*ax + projection.m31*ay +
projection.m32*az + projection.m33*aw;
if (ow != 0) oy /= ow;
return height * (1 + oy) / 2.0f;
}
public float screenZ(float x, float y, float z) {
float ax =
modelview.m00*x + modelview.m01*y + modelview.m02*z + modelview.m03;
float ay =
modelview.m10*x + modelview.m11*y + modelview.m12*z + modelview.m13;
float az =
modelview.m20*x + modelview.m21*y + modelview.m22*z + modelview.m23;
float aw =
modelview.m30*x + modelview.m31*y + modelview.m32*z + modelview.m33;
float oz =
projection.m20*ax + projection.m21*ay +
projection.m22*az + projection.m23*aw;
float ow =
projection.m30*ax + projection.m31*ay +
projection.m32*az + projection.m33*aw;
if (ow != 0) oz /= ow;
return (oz + 1) / 2.0f;
}
public float modelX(float x, float y, float z) {
float ax =
modelview.m00*x + modelview.m01*y + modelview.m02*z + modelview.m03;
float ay =
modelview.m10*x + modelview.m11*y + modelview.m12*z + modelview.m13;
float az =
modelview.m20*x + modelview.m21*y + modelview.m22*z + modelview.m23;
float aw =
modelview.m30*x + modelview.m31*y + modelview.m32*z + modelview.m33;
float ox =
cameraInv.m00*ax + cameraInv.m01*ay +
cameraInv.m02*az + cameraInv.m03*aw;
float ow =
cameraInv.m30*ax + cameraInv.m31*ay +
cameraInv.m32*az + cameraInv.m33*aw;
return (ow != 0) ? ox / ow : ox;
}
public float modelY(float x, float y, float z) {
float ax =
modelview.m00*x + modelview.m01*y + modelview.m02*z + modelview.m03;
float ay =
modelview.m10*x + modelview.m11*y + modelview.m12*z + modelview.m13;
float az =
modelview.m20*x + modelview.m21*y + modelview.m22*z + modelview.m23;
float aw =
modelview.m30*x + modelview.m31*y + modelview.m32*z + modelview.m33;
float oy =
cameraInv.m10*ax + cameraInv.m11*ay +
cameraInv.m12*az + cameraInv.m13*aw;
float ow =
cameraInv.m30*ax + cameraInv.m31*ay +
cameraInv.m32*az + cameraInv.m33*aw;
return (ow != 0) ? oy / ow : oy;
}
public float modelZ(float x, float y, float z) {
float ax =
modelview.m00*x + modelview.m01*y + modelview.m02*z + modelview.m03;
float ay =
modelview.m10*x + modelview.m11*y + modelview.m12*z + modelview.m13;
float az =
modelview.m20*x + modelview.m21*y + modelview.m22*z + modelview.m23;
float aw =
modelview.m30*x + modelview.m31*y + modelview.m32*z + modelview.m33;
float oz =
cameraInv.m20*ax + cameraInv.m21*ay +
cameraInv.m22*az + cameraInv.m23*aw;
float ow =
cameraInv.m30*ax + cameraInv.m31*ay +
cameraInv.m32*az + cameraInv.m33*aw;
return (ow != 0) ? oz / ow : oz;
}
//////////////////////////////////////////////////////////////
// STYLE
// pushStyle(), popStyle(), style() and getStyle() inherited.
//////////////////////////////////////////////////////////////
// STROKE CAP/JOIN/WEIGHT
// public void strokeWeight(float weight) {
// if (weight != DEFAULT_STROKE_WEIGHT) {
// showMethodWarning("strokeWeight");
// }
// }
public void strokeJoin(int join) {
if (join != DEFAULT_STROKE_JOIN) {
showMethodWarning("strokeJoin");
}
}
public void strokeCap(int cap) {
if (cap != DEFAULT_STROKE_CAP) {
showMethodWarning("strokeCap");
}
}
//////////////////////////////////////////////////////////////
// STROKE COLOR
// All methods inherited from PGraphics.
//////////////////////////////////////////////////////////////
// TINT COLOR
// All methods inherited from PGraphics.
//////////////////////////////////////////////////////////////
// FILL COLOR
protected void fillFromCalc() {
super.fillFromCalc();
ambientFromCalc();
}
//////////////////////////////////////////////////////////////
// MATERIAL PROPERTIES
// ambient, specular, shininess, and emissive all inherited.
//////////////////////////////////////////////////////////////
// LIGHTS
PVector lightPositionVec = new PVector();
PVector lightDirectionVec = new PVector();
/**
* Sets up an ambient and directional light.
*
* An attempt is made to keep the constants as short/non-verbose
* as possible. For instance, the constant is TIFF instead of
* FILE_TYPE_TIFF. We'll do this as long as we can get away with it.
*
* @usage Web & Application
*/
public interface PConstants {
static public final int X = 0; // model coords xyz (formerly MX/MY/MZ)
static public final int Y = 1;
static public final int Z = 2;
static public final int R = 3; // actual rgb, after lighting
static public final int G = 4; // fill stored here, transform in place
static public final int B = 5; // TODO don't do that anymore (?)
static public final int A = 6;
static public final int U = 7; // texture
static public final int V = 8;
static public final int NX = 9; // normal
static public final int NY = 10;
static public final int NZ = 11;
static public final int EDGE = 12;
// stroke
/** stroke argb values */
static public final int SR = 13;
static public final int SG = 14;
static public final int SB = 15;
static public final int SA = 16;
/** stroke weight */
static public final int SW = 17;
// transformations (2D and 3D)
static public final int TX = 18; // transformed xyzw
static public final int TY = 19;
static public final int TZ = 20;
static public final int VX = 21; // view space coords
static public final int VY = 22;
static public final int VZ = 23;
static public final int VW = 24;
// material properties
// Ambient color (usually to be kept the same as diffuse)
// fill(_) sets both ambient and diffuse.
static public final int AR = 25;
static public final int AG = 26;
static public final int AB = 27;
// Diffuse is shared with fill.
static public final int DR = 3; // TODO needs to not be shared, this is a material property
static public final int DG = 4;
static public final int DB = 5;
static public final int DA = 6;
// specular (by default kept white)
static public final int SPR = 28;
static public final int SPG = 29;
static public final int SPB = 30;
static public final int SHINE = 31;
// emissive (by default kept black)
static public final int ER = 32;
static public final int EG = 33;
static public final int EB = 34;
// has this vertex been lit yet
static public final int BEEN_LIT = 35;
static public final int VERTEX_FIELD_COUNT = 36;
// renderers known to processing.core
static final String P2D = "processing.core.PGraphics2D";
static final String P3D = "processing.core.PGraphics3D";
static final String JAVA2D = "processing.core.PGraphicsJava2D";
static final String OPENGL = "processing.opengl.PGraphicsOpenGL";
static final String PDF = "processing.pdf.PGraphicsPDF";
static final String DXF = "processing.dxf.RawDXF";
// platform IDs for PApplet.platform
static final int OTHER = 0;
static final int WINDOWS = 1;
static final int MACOSX = 2;
static final int LINUX = 3;
static final String[] platformNames = {
"other", "windows", "macosx", "linux"
};
static final float EPSILON = 0.0001f;
// max/min values for numbers
/**
* Same as Float.MAX_VALUE, but included for parity with MIN_VALUE,
* and to avoid teaching static methods on the first day.
*/
static final float MAX_FLOAT = Float.MAX_VALUE;
/**
* Note that Float.MIN_VALUE is the smallest positive value
* for a floating point number, not actually the minimum (negative) value
* for a float. This constant equals 0xFF7FFFFF, the smallest (farthest
* negative) value a float can have before it hits NaN.
*/
static final float MIN_FLOAT = -Float.MAX_VALUE;
/** Largest possible (positive) integer value */
static final int MAX_INT = Integer.MAX_VALUE;
/** Smallest possible (negative) integer value */
static final int MIN_INT = Integer.MIN_VALUE;
// useful goodness
/**
* PI is a mathematical constant with the value 3.14159265358979323846.
* It is the ratio of the circumference of a circle to its diameter.
* It is useful in combination with the trigonometric functions sin() and cos().
*
* @webref constants
* @see processing.core.PConstants#HALF_PI
* @see processing.core.PConstants#TWO_PI
* @see processing.core.PConstants#QUARTER_PI
*
*/
static final float PI = (float) Math.PI;
/**
* HALF_PI is a mathematical constant with the value 1.57079632679489661923.
* It is half the ratio of the circumference of a circle to its diameter.
* It is useful in combination with the trigonometric functions sin() and cos().
*
* @webref constants
* @see processing.core.PConstants#PI
* @see processing.core.PConstants#TWO_PI
* @see processing.core.PConstants#QUARTER_PI
*/
static final float HALF_PI = PI / 2.0f;
static final float THIRD_PI = PI / 3.0f;
/**
* QUARTER_PI is a mathematical constant with the value 0.7853982.
* It is one quarter the ratio of the circumference of a circle to its diameter.
* It is useful in combination with the trigonometric functions sin() and cos().
*
* @webref constants
* @see processing.core.PConstants#PI
* @see processing.core.PConstants#TWO_PI
* @see processing.core.PConstants#HALF_PI
*/
static final float QUARTER_PI = PI / 4.0f;
/**
* TWO_PI is a mathematical constant with the value 6.28318530717958647693.
* It is twice the ratio of the circumference of a circle to its diameter.
* It is useful in combination with the trigonometric functions sin() and cos().
*
* @webref constants
* @see processing.core.PConstants#PI
* @see processing.core.PConstants#HALF_PI
* @see processing.core.PConstants#QUARTER_PI
*/
static final float TWO_PI = PI * 2.0f;
static final float DEG_TO_RAD = PI/180.0f;
static final float RAD_TO_DEG = 180.0f/PI;
// angle modes
//static final int RADIANS = 0;
//static final int DEGREES = 1;
// used by split, all the standard whitespace chars
// (also includes unicode nbsp, that little bostage)
static final String WHITESPACE = " \t\n\r\f\u00A0";
// for colors and/or images
static final int RGB = 1; // image & color
static final int ARGB = 2; // image
static final int HSB = 3; // color
static final int ALPHA = 4; // image
static final int CMYK = 5; // image & color (someday)
// image file types
static final int TIFF = 0;
static final int TARGA = 1;
static final int JPEG = 2;
static final int GIF = 3;
// filter/convert types
static final int BLUR = 11;
static final int GRAY = 12;
static final int INVERT = 13;
static final int OPAQUE = 14;
static final int POSTERIZE = 15;
static final int THRESHOLD = 16;
static final int ERODE = 17;
static final int DILATE = 18;
// blend mode keyword definitions
// @see processing.core.PImage#blendColor(int,int,int)
public final static int REPLACE = 0;
public final static int BLEND = 1 << 0;
public final static int ADD = 1 << 1;
public final static int SUBTRACT = 1 << 2;
public final static int LIGHTEST = 1 << 3;
public final static int DARKEST = 1 << 4;
public final static int DIFFERENCE = 1 << 5;
public final static int EXCLUSION = 1 << 6;
public final static int MULTIPLY = 1 << 7;
public final static int SCREEN = 1 << 8;
public final static int OVERLAY = 1 << 9;
public final static int HARD_LIGHT = 1 << 10;
public final static int SOFT_LIGHT = 1 << 11;
public final static int DODGE = 1 << 12;
public final static int BURN = 1 << 13;
// colour component bitmasks
public static final int ALPHA_MASK = 0xff000000;
public static final int RED_MASK = 0x00ff0000;
public static final int GREEN_MASK = 0x0000ff00;
public static final int BLUE_MASK = 0x000000ff;
// for messages
static final int CHATTER = 0;
static final int COMPLAINT = 1;
static final int PROBLEM = 2;
// types of projection matrices
static final int CUSTOM = 0; // user-specified fanciness
static final int ORTHOGRAPHIC = 2; // 2D isometric projection
static final int PERSPECTIVE = 3; // perspective matrix
// shapes
// the low four bits set the variety,
// higher bits set the specific shape type
//static final int GROUP = (1 << 2);
static final int POINT = 2; // shared with light (!)
static final int POINTS = 2;
static final int LINE = 4;
static final int LINES = 4;
static final int TRIANGLE = 8;
static final int TRIANGLES = 9;
static final int TRIANGLE_STRIP = 10;
static final int TRIANGLE_FAN = 11;
static final int QUAD = 16;
static final int QUADS = 16;
static final int QUAD_STRIP = 17;
static final int POLYGON = 20;
static final int PATH = 21;
static final int RECT = 30;
static final int ELLIPSE = 31;
static final int ARC = 32;
static final int SPHERE = 40;
static final int BOX = 41;
// shape closing modes
static final int OPEN = 1;
static final int CLOSE = 2;
// shape drawing modes
/** Draw mode convention to use (x, y) to (width, height) */
static final int CORNER = 0;
/** Draw mode convention to use (x1, y1) to (x2, y2) coordinates */
static final int CORNERS = 1;
/** Draw mode from the center, and using the radius */
static final int RADIUS = 2;
/** @deprecated Use RADIUS instead. */
static final int CENTER_RADIUS = 2;
/**
* Draw from the center, using second pair of values as the diameter.
* Formerly called CENTER_DIAMETER in alpha releases.
*/
static final int CENTER = 3;
/**
* Synonym for the CENTER constant. Draw from the center,
* using second pair of values as the diameter.
*/
static final int DIAMETER = 3;
/** @deprecated Use DIAMETER instead. */
static final int CENTER_DIAMETER = 3;
// vertically alignment modes for text
/** Default vertical alignment for text placement */
static final int BASELINE = 0;
/** Align text to the top */
static final int TOP = 101;
/** Align text from the bottom, using the baseline. */
static final int BOTTOM = 102;
// uv texture orientation modes
/** texture coordinates in 0..1 range */
static final int NORMAL = 1;
/** @deprecated use NORMAL instead */
static final int NORMALIZED = 1;
/** texture coordinates based on image width/height */
static final int IMAGE = 2;
// text placement modes
/**
* textMode(MODEL) is the default, meaning that characters
* will be affected by transformations like any other shapes.
*
* Originally written by sami (www.sumea.com)
*/
public class PTriangle implements PConstants
{
static final float PIXEL_CENTER = 0.5f; // for polygon aa
static final int R_GOURAUD = 0x1;
static final int R_TEXTURE8 = 0x2;
static final int R_TEXTURE24 = 0x4;
static final int R_TEXTURE32 = 0x8;
static final int R_ALPHA = 0x10;
private int[] m_pixels;
private int[] m_texture;
//private int[] m_stencil;
private float[] m_zbuffer;
private int SCREEN_WIDTH;
private int SCREEN_HEIGHT;
//private int SCREEN_WIDTH1;
//private int SCREEN_HEIGHT1;
private int TEX_WIDTH;
private int TEX_HEIGHT;
private float F_TEX_WIDTH;
private float F_TEX_HEIGHT;
public boolean INTERPOLATE_UV;
public boolean INTERPOLATE_RGB;
public boolean INTERPOLATE_ALPHA;
// the power of 2 that tells how many pixels to interpolate
// for between exactly computed texture coordinates
private static final int DEFAULT_INTERP_POWER = 3;
private static int TEX_INTERP_POWER = DEFAULT_INTERP_POWER;
// Vertex coordinates
private float[] x_array;
private float[] y_array;
private float[] z_array;
private float[] camX;
private float[] camY;
private float[] camZ;
// U,V coordinates
private float[] u_array;
private float[] v_array;
// Vertex Intensity
private float[] r_array;
private float[] g_array;
private float[] b_array;
private float[] a_array;
// vertex offsets
private int o0;
private int o1;
private int o2;
/* rgb & a */
private float r0;
private float r1;
private float r2;
private float g0;
private float g1;
private float g2;
private float b0;
private float b1;
private float b2;
private float a0;
private float a1;
private float a2;
/* accurate texture uv coordinates */
private float u0;
private float u1;
private float u2;
private float v0;
private float v1;
private float v2;
/* deltas */
//private float dx0;
//private float dx1;
private float dx2;
private float dy0;
private float dy1;
private float dy2;
private float dz0;
//private float dz1;
private float dz2;
/* texture deltas */
private float du0;
//private float du1;
private float du2;
private float dv0;
//private float dv1;
private float dv2;
/* rgba deltas */
private float dr0;
//private float dr1;
private float dr2;
private float dg0;
//private float dg1;
private float dg2;
private float db0;
//private float db1;
private float db2;
private float da0;
//private float da1;
private float da2;
/* */
private float uleft;
private float vleft;
private float uleftadd;
private float vleftadd;
/* polyedge positions & adds */
private float xleft;
private float xrght;
private float xadd1;
private float xadd2;
private float zleft;
private float zleftadd;
/* rgba positions & adds */
private float rleft;
private float gleft;
private float bleft;
private float aleft;
private float rleftadd;
private float gleftadd;
private float bleftadd;
private float aleftadd;
/* other somewhat useful variables :) */
private float dta;
//private float dta2;
private float temp;
private float width;
/* integer poly UV adds */
private int iuadd;
private int ivadd;
private int iradd;
private int igadd;
private int ibadd;
private int iaadd;
private float izadd;
/* fill color */
private int m_fill;
/* draw flags */
public int m_drawFlags;
/* current poly number */
// private int m_index;
/** */
private PGraphics3D parent;
private boolean noDepthTest;
//private boolean argbSurface;
/** */
private boolean m_culling;
/** */
private boolean m_singleRight;
/**
* True if using bilinear interpolation for textures.
* Always set to true. If this is ever changed (maybe with a hint()?)
* will need to write code for texture8/24/32 et al that will handle mixing
* the m_fill color in with the texture color.
*/
private boolean m_bilinear = true; // always set to true
// Vectors needed in accurate texture code
// We store them as class members to avoid too much code duplication
private float ax,ay,az;
private float bx,by,bz;
private float cx,cy,cz;
private float nearPlaneWidth;
private float nearPlaneHeight;
private float nearPlaneDepth;
private float xmult;
private float ymult;
// optimization vars...not pretty, but save a couple mults per pixel
private float newax,newbx,newcx;
// are we currently drawing the first piece of the triangle,
// or have we already done so?
private boolean firstSegment;
public PTriangle(PGraphics3D g) {
x_array = new float[3];
y_array = new float[3];
z_array = new float[3];
u_array = new float[3];
v_array = new float[3];
r_array = new float[3];
g_array = new float[3];
b_array = new float[3];
a_array = new float[3];
camX = new float[3];
camY = new float[3];
camZ = new float[3];
this.parent = g;
reset();
}
/**
* Resets polygon attributes
*/
public void reset() {
// reset these in case PGraphics was resized
SCREEN_WIDTH = parent.width;
SCREEN_HEIGHT = parent.height;
//SCREEN_WIDTH1 = SCREEN_WIDTH-1;
//SCREEN_HEIGHT1 = SCREEN_HEIGHT-1;
m_pixels = parent.pixels;
// m_stencil = parent.stencil;
m_zbuffer = parent.zbuffer;
noDepthTest = parent.hints[DISABLE_DEPTH_TEST];
//argbSurface = parent.format == PConstants.ARGB;
// other things to reset
INTERPOLATE_UV = false;
INTERPOLATE_RGB = false;
INTERPOLATE_ALPHA = false;
//m_tImage = null;
m_texture = null;
m_drawFlags = 0;
}
/**
* Sets backface culling on/off
*/
public void setCulling(boolean tf) {
m_culling = tf;
}
/**
* Sets vertex coordinates for the triangle
*/
public void setVertices(float x0, float y0, float z0,
float x1, float y1, float z1,
float x2, float y2, float z2) {
x_array[0] = x0;
x_array[1] = x1;
x_array[2] = x2;
y_array[0] = y0;
y_array[1] = y1;
y_array[2] = y2;
z_array[0] = z0;
z_array[1] = z1;
z_array[2] = z2;
}
/**
* Pass camera-space coordinates for the triangle.
* Needed to render if hint(ENABLE_ACCURATE_TEXTURES) enabled.
* Generally this will not need to be called manually,
* currently called from PGraphics3D.render_triangles()
*/
public void setCamVertices(float x0, float y0, float z0,
float x1, float y1, float z1,
float x2, float y2, float z2) {
camX[0] = x0;
camX[1] = x1;
camX[2] = x2;
camY[0] = y0;
camY[1] = y1;
camY[2] = y2;
camZ[0] = z0;
camZ[1] = z1;
camZ[2] = z2;
}
/**
* Sets the UV coordinates of the texture
*/
public void setUV(float u0, float v0,
float u1, float v1,
float u2, float v2) {
// sets & scales uv texture coordinates to center of the pixel
u_array[0] = (u0 * F_TEX_WIDTH + 0.5f) * 65536f;
u_array[1] = (u1 * F_TEX_WIDTH + 0.5f) * 65536f;
u_array[2] = (u2 * F_TEX_WIDTH + 0.5f) * 65536f;
v_array[0] = (v0 * F_TEX_HEIGHT + 0.5f) * 65536f;
v_array[1] = (v1 * F_TEX_HEIGHT + 0.5f) * 65536f;
v_array[2] = (v2 * F_TEX_HEIGHT + 0.5f) * 65536f;
}
/**
* Sets vertex intensities in 0xRRGGBBAA format
*/
public void setIntensities(float r0, float g0, float b0, float a0,
float r1, float g1, float b1, float a1,
float r2, float g2, float b2, float a2) {
// Check if we need alpha or not?
if ((a0 != 1.0f) || (a1 != 1.0f) || (a2 != 1.0f)) {
INTERPOLATE_ALPHA = true;
a_array[0] = (a0 * 253f + 1.0f) * 65536f;
a_array[1] = (a1 * 253f + 1.0f) * 65536f;
a_array[2] = (a2 * 253f + 1.0f) * 65536f;
m_drawFlags|=R_ALPHA;
} else {
INTERPOLATE_ALPHA = false;
m_drawFlags&=~R_ALPHA;
}
// Check if we need to interpolate the intensity values
if ((r0 != r1) || (r1 != r2)) {
INTERPOLATE_RGB = true;
m_drawFlags |= R_GOURAUD;
} else if ((g0 != g1) || (g1 != g2)) {
INTERPOLATE_RGB = true;
m_drawFlags |= R_GOURAUD;
} else if ((b0 != b1) || (b1 != b2)) {
INTERPOLATE_RGB = true;
m_drawFlags |= R_GOURAUD;
} else {
//m_fill = parent.filli;
m_drawFlags &=~ R_GOURAUD;
}
// push values to arrays.. some extra scaling is added
// to prevent possible color "overflood" due to rounding errors
r_array[0] = (r0 * 253f + 1.0f) * 65536f;
r_array[1] = (r1 * 253f + 1.0f) * 65536f;
r_array[2] = (r2 * 253f + 1.0f) * 65536f;
g_array[0] = (g0 * 253f + 1.0f) * 65536f;
g_array[1] = (g1 * 253f + 1.0f) * 65536f;
g_array[2] = (g2 * 253f + 1.0f) * 65536f;
b_array[0] = (b0 * 253f + 1.0f) * 65536f;
b_array[1] = (b1 * 253f + 1.0f) * 65536f;
b_array[2] = (b2 * 253f + 1.0f) * 65536f;
// for plain triangles
m_fill = 0xFF000000 |
((int)(255*r0) << 16) | ((int)(255*g0) << 8) | (int)(255*b0);
}
/**
* Sets texture image used for the polygon
*/
public void setTexture(PImage image) {
//m_tImage = image;
m_texture = image.pixels;
TEX_WIDTH = image.width;
TEX_HEIGHT = image.height;
F_TEX_WIDTH = TEX_WIDTH-1;
F_TEX_HEIGHT = TEX_HEIGHT-1;
INTERPOLATE_UV = true;
if (image.format == ARGB) {
m_drawFlags |= R_TEXTURE32;
} else if (image.format == RGB) {
m_drawFlags |= R_TEXTURE24;
} else if (image.format == ALPHA) {
m_drawFlags |= R_TEXTURE8;
}
}
/**
*
*/
public void setUV(float[] u, float[] v) {
if (m_bilinear) {
// sets & scales uv texture coordinates to edges of pixels
u_array[0] = (u[0] * F_TEX_WIDTH) * 65500f;
u_array[1] = (u[1] * F_TEX_WIDTH) * 65500f;
u_array[2] = (u[2] * F_TEX_WIDTH) * 65500f;
v_array[0] = (v[0] * F_TEX_HEIGHT) * 65500f;
v_array[1] = (v[1] * F_TEX_HEIGHT) * 65500f;
v_array[2] = (v[2] * F_TEX_HEIGHT) * 65500f;
} else {
// sets & scales uv texture coordinates to center of the pixel
u_array[0] = (u[0] * TEX_WIDTH) * 65500f;
u_array[1] = (u[1] * TEX_WIDTH) * 65500f;
u_array[2] = (u[2] * TEX_WIDTH) * 65500f;
v_array[0] = (v[0] * TEX_HEIGHT) * 65500f;
v_array[1] = (v[1] * TEX_HEIGHT) * 65500f;
v_array[2] = (v[2] * TEX_HEIGHT) * 65500f;
}
}
// public void setIndex(int index) {
// m_index = index;
// }
/**
* Renders the polygon
*/
public void render() {
float x0, x1, x2;
float z0, z1, z2;
float y0 = y_array[0];
float y1 = y_array[1];
float y2 = y_array[2];
//System.out.println(PApplet.hex(m_drawFlags));
// For accurate texture interpolation, need to mark whether
// we've already pre-calculated for the triangle
firstSegment = true;
// do backface culling?
if (m_culling) {
x0 = x_array[0];
if ((x_array[2]-x0)*(y1-y0) < (x_array[1]-x0)*(y2-y0))
return;
}
/* get vertex order from top -> down */
if (y0 < y1) {
if (y2 < y1) {
if (y2 < y0) { // 2,0,1
o0 = 2;
o1 = 0;
o2 = 1;
} else { // 0,2,1
o0 = 0;
o1 = 2;
o2 = 1;
}
} else { // 0,1,2
o0 = 0;
o1 = 1;
o2 = 2;
}
} else {
if (y2 > y1) {
if (y2 < y0) { // 1,2,0
o0 = 1;
o1 = 2;
o2 = 0;
} else { // 1,0,2
o0 = 1;
o1 = 0;
o2 = 2;
}
} else { // 2,1,0
o0 = 2;
o1 = 1;
o2 = 0;
}
}
/**
* o0 = "top" vertex offset
* o1 = "mid" vertex offset
* o2 = "bot" vertex offset
*/
y0 = y_array[o0];
int yi0 = (int) (y0 + PIXEL_CENTER);
if (yi0 > SCREEN_HEIGHT) {
return;
} else if (yi0 < 0) {
yi0 = 0;
}
y2 = y_array[o2];
int yi2 = (int) (y2 + PIXEL_CENTER);
if (yi2 < 0) {
return;
} else if (yi2 > SCREEN_HEIGHT) {
yi2 = SCREEN_HEIGHT;
}
// Does the poly actually cross a scanline?
if (yi2 > yi0) {
x0 = x_array[o0];
x1 = x_array[o1];
x2 = x_array[o2];
// get mid Y and clip it
y1 = y_array[o1];
int yi1 = (int) (y1 + PIXEL_CENTER);
if (yi1 < 0)
yi1 = 0;
if (yi1 > SCREEN_HEIGHT)
yi1 = SCREEN_HEIGHT;
// calculate deltas etc.
dx2 = x2 - x0;
dy0 = y1 - y0;
dy2 = y2 - y0;
xadd2 = dx2 / dy2; // xadd for "single" edge
temp = dy0 / dy2;
width = temp * dx2 + x0 - x1;
// calculate alpha blend interpolation
if (INTERPOLATE_ALPHA) {
a0 = a_array[o0];
a1 = a_array[o1];
a2 = a_array[o2];
da0 = a1-a0;
da2 = a2-a0;
iaadd = (int) ((temp * da2 - da0) / width); // alpha add
}
// calculate intensity interpolation
if (INTERPOLATE_RGB) {
r0 = r_array[o0];
r1 = r_array[o1];
r2 = r_array[o2];
g0 = g_array[o0];
g1 = g_array[o1];
g2 = g_array[o2];
b0 = b_array[o0];
b1 = b_array[o1];
b2 = b_array[o2];
dr0 = r1-r0;
dg0 = g1-g0;
db0 = b1-b0;
dr2 = r2-r0;
dg2 = g2-g0;
db2 = b2-b0;
iradd = (int) ((temp * dr2 - dr0) / width); // r add
igadd = (int) ((temp * dg2 - dg0) / width); // g add
ibadd = (int) ((temp * db2 - db0) / width); // b add
}
// calculate UV interpolation
if (INTERPOLATE_UV) {
u0 = u_array[o0];
u1 = u_array[o1];
u2 = u_array[o2];
v0 = v_array[o0];
v1 = v_array[o1];
v2 = v_array[o2];
du0 = u1-u0;
dv0 = v1-v0;
du2 = u2-u0;
dv2 = v2-v0;
iuadd = (int) ((temp * du2 - du0) / width); // u add
ivadd = (int) ((temp * dv2 - dv0) / width); // v add
}
z0 = z_array[o0];
z1 = z_array[o1];
z2 = z_array[o2];
dz0 = z1-z0;
dz2 = z2-z0;
izadd = (temp * dz2 - dz0) / width;
// draw the upper poly segment if it's visible
if (yi1 > yi0) {
dta = (yi0 + PIXEL_CENTER) - y0;
xadd1 = (x1 - x0) / dy0;
// we can determine which side is "single" side
// by comparing left/right edge adds
if (xadd2 > xadd1) {
xleft = x0 + dta * xadd1;
xrght = x0 + dta * xadd2;
zleftadd = dz0 / dy0;
zleft = dta*zleftadd+z0;
if (INTERPOLATE_UV) {
uleftadd = du0 / dy0;
vleftadd = dv0 / dy0;
uleft = dta*uleftadd+u0;
vleft = dta*vleftadd+v0;
}
if (INTERPOLATE_RGB) {
rleftadd = dr0 / dy0;
gleftadd = dg0 / dy0;
bleftadd = db0 / dy0;
rleft = dta*rleftadd+r0;
gleft = dta*gleftadd+g0;
bleft = dta*bleftadd+b0;
}
if (INTERPOLATE_ALPHA) {
aleftadd = da0 / dy0;
aleft = dta*aleftadd+a0;
if (m_drawFlags == R_ALPHA) {
drawsegment_plain_alpha(xadd1,xadd2, yi0,yi1);
} else if (m_drawFlags == (R_GOURAUD + R_ALPHA)) {
drawsegment_gouraud_alpha(xadd1,xadd2, yi0,yi1);
} else if (m_drawFlags == (R_TEXTURE8 + R_ALPHA)) {
drawsegment_texture8_alpha(xadd1,xadd2, yi0,yi1);
} else if (m_drawFlags == (R_TEXTURE24 + R_ALPHA)) {
drawsegment_texture24_alpha(xadd1,xadd2, yi0,yi1);
} else if (m_drawFlags == (R_TEXTURE32 + R_ALPHA)) {
drawsegment_texture32_alpha(xadd1,xadd2, yi0,yi1);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8 + R_ALPHA)) {
drawsegment_gouraud_texture8_alpha(xadd1,xadd2, yi0,yi1);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24 + R_ALPHA)) {
drawsegment_gouraud_texture24_alpha(xadd1,xadd2, yi0,yi1);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32 + R_ALPHA)) {
drawsegment_gouraud_texture32_alpha(xadd1,xadd2, yi0,yi1);
}
} else {
if (m_drawFlags == 0) {
drawsegment_plain(xadd1,xadd2, yi0,yi1);
} else if (m_drawFlags == R_GOURAUD) {
drawsegment_gouraud(xadd1,xadd2, yi0,yi1);
} else if (m_drawFlags == R_TEXTURE8) {
drawsegment_texture8(xadd1,xadd2, yi0,yi1);
} else if (m_drawFlags == R_TEXTURE24) {
drawsegment_texture24(xadd1,xadd2, yi0,yi1);
} else if (m_drawFlags == R_TEXTURE32) {
drawsegment_texture32(xadd1,xadd2, yi0,yi1);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8)) {
drawsegment_gouraud_texture8(xadd1,xadd2, yi0,yi1);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24)) {
drawsegment_gouraud_texture24(xadd1,xadd2, yi0,yi1);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32)) {
drawsegment_gouraud_texture32(xadd1,xadd2, yi0,yi1);
}
}
m_singleRight = true;
} else {
xleft = x0 + dta * xadd2;
xrght = x0 + dta * xadd1;
zleftadd = dz2 / dy2;
zleft = dta*zleftadd+z0;
//
if (INTERPOLATE_UV) {
uleftadd = du2 / dy2;
vleftadd = dv2 / dy2;
uleft = dta*uleftadd+u0;
vleft = dta*vleftadd+v0;
}
//
if (INTERPOLATE_RGB) {
rleftadd = dr2 / dy2;
gleftadd = dg2 / dy2;
bleftadd = db2 / dy2;
rleft = dta*rleftadd+r0;
gleft = dta*gleftadd+g0;
bleft = dta*bleftadd+b0;
}
if (INTERPOLATE_ALPHA) {
aleftadd = da2 / dy2;
aleft = dta*aleftadd+a0;
if (m_drawFlags == R_ALPHA) {
drawsegment_plain_alpha(xadd2, xadd1, yi0,yi1);
} else if (m_drawFlags == (R_GOURAUD + R_ALPHA)) {
drawsegment_gouraud_alpha(xadd2, xadd1, yi0,yi1);
} else if (m_drawFlags == (R_TEXTURE8 + R_ALPHA)) {
drawsegment_texture8_alpha(xadd2, xadd1, yi0,yi1);
} else if (m_drawFlags == (R_TEXTURE24 + R_ALPHA)) {
drawsegment_texture24_alpha(xadd2, xadd1, yi0,yi1);
} else if (m_drawFlags == (R_TEXTURE32 + R_ALPHA)) {
drawsegment_texture32_alpha(xadd2, xadd1, yi0,yi1);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8 + R_ALPHA)) {
drawsegment_gouraud_texture8_alpha(xadd2, xadd1, yi0,yi1);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24 + R_ALPHA)) {
drawsegment_gouraud_texture24_alpha(xadd2, xadd1, yi0,yi1);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32 + R_ALPHA)) {
drawsegment_gouraud_texture32_alpha(xadd2, xadd1, yi0,yi1);
}
} else {
if (m_drawFlags == 0) {
drawsegment_plain(xadd2, xadd1, yi0,yi1);
} else if (m_drawFlags == R_GOURAUD) {
drawsegment_gouraud(xadd2, xadd1, yi0,yi1);
} else if (m_drawFlags == R_TEXTURE8) {
drawsegment_texture8(xadd2, xadd1, yi0,yi1);
} else if (m_drawFlags == R_TEXTURE24) {
drawsegment_texture24(xadd2, xadd1, yi0,yi1);
} else if (m_drawFlags == R_TEXTURE32) {
drawsegment_texture32(xadd2, xadd1, yi0,yi1);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8)) {
drawsegment_gouraud_texture8(xadd2, xadd1, yi0,yi1);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24)) {
drawsegment_gouraud_texture24(xadd2, xadd1, yi0,yi1);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32)) {
drawsegment_gouraud_texture32(xadd2, xadd1, yi0,yi1);
}
}
m_singleRight = false;
}
// if bottom segment height is zero, return
if (yi2 == yi1) return;
// calculate xadd 1
dy1 = y2 - y1;
xadd1 = (x2 - x1) / dy1;
} else {
// top seg height was zero, calculate & clip single edge X
dy1 = y2 - y1;
xadd1 = (x2 - x1) / dy1;
// which edge is left?
if (xadd2 < xadd1) {
xrght = ((yi1 + PIXEL_CENTER) - y0) * xadd2 + x0;
m_singleRight = true;
} else {
dta = (yi1 + PIXEL_CENTER) - y0;
xleft = dta * xadd2 + x0;
zleftadd = dz2 / dy2;
zleft = dta * zleftadd + z0;
if (INTERPOLATE_UV) {
uleftadd = du2 / dy2;
vleftadd = dv2 / dy2;
uleft = dta * uleftadd + u0;
vleft = dta * vleftadd + v0;
}
if (INTERPOLATE_RGB) {
rleftadd = dr2 / dy2;
gleftadd = dg2 / dy2;
bleftadd = db2 / dy2;
rleft = dta * rleftadd + r0;
gleft = dta * gleftadd + g0;
bleft = dta * bleftadd + b0;
}
//
if (INTERPOLATE_ALPHA) {
aleftadd = da2 / dy2;
aleft = dta * aleftadd + a0;
}
m_singleRight = false;
}
}
// draw the lower segment
if (m_singleRight) {
dta = (yi1 + PIXEL_CENTER) - y1;
xleft = dta * xadd1 + x1;
zleftadd = (z2 - z1) / dy1;
zleft = dta * zleftadd + z1;
if (INTERPOLATE_UV) {
uleftadd = (u2 - u1) / dy1;
vleftadd = (v2 - v1) / dy1;
uleft = dta * uleftadd + u1;
vleft = dta * vleftadd + v1;
}
if (INTERPOLATE_RGB) {
rleftadd = (r2 - r1) / dy1;
gleftadd = (g2 - g1) / dy1;
bleftadd = (b2 - b1) / dy1;
rleft = dta * rleftadd + r1;
gleft = dta * gleftadd + g1;
bleft = dta * bleftadd + b1;
}
if (INTERPOLATE_ALPHA) {
aleftadd = (a2 - a1) / dy1;
aleft = dta * aleftadd + a1;
if (m_drawFlags == R_ALPHA) {
drawsegment_plain_alpha(xadd1, xadd2, yi1,yi2);
} else if (m_drawFlags == (R_GOURAUD + R_ALPHA)) {
drawsegment_gouraud_alpha(xadd1, xadd2, yi1,yi2);
} else if (m_drawFlags == (R_TEXTURE8 + R_ALPHA)) {
drawsegment_texture8_alpha(xadd1, xadd2, yi1,yi2);
} else if (m_drawFlags == (R_TEXTURE24 + R_ALPHA)) {
drawsegment_texture24_alpha(xadd1, xadd2, yi1,yi2);
} else if (m_drawFlags == (R_TEXTURE32 + R_ALPHA)) {
drawsegment_texture32_alpha(xadd1, xadd2, yi1,yi2);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8 + R_ALPHA)) {
drawsegment_gouraud_texture8_alpha(xadd1, xadd2, yi1,yi2);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24 + R_ALPHA)) {
drawsegment_gouraud_texture24_alpha(xadd1, xadd2, yi1,yi2);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32 + R_ALPHA)) {
drawsegment_gouraud_texture32_alpha(xadd1, xadd2, yi1,yi2);
}
} else {
if (m_drawFlags == 0) {
drawsegment_plain(xadd1, xadd2, yi1,yi2);
} else if (m_drawFlags == R_GOURAUD) {
drawsegment_gouraud(xadd1, xadd2, yi1,yi2);
} else if (m_drawFlags == R_TEXTURE8) {
drawsegment_texture8(xadd1, xadd2, yi1,yi2);
} else if (m_drawFlags == R_TEXTURE24) {
drawsegment_texture24(xadd1, xadd2, yi1,yi2);
} else if (m_drawFlags == R_TEXTURE32) {
drawsegment_texture32(xadd1, xadd2, yi1,yi2);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8)) {
drawsegment_gouraud_texture8(xadd1, xadd2, yi1,yi2);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24)) {
drawsegment_gouraud_texture24(xadd1, xadd2, yi1,yi2);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32)) {
drawsegment_gouraud_texture32(xadd1, xadd2, yi1,yi2);
}
}
} else {
xrght = ((yi1 + PIXEL_CENTER)- y1) * xadd1 + x1;
if (INTERPOLATE_ALPHA) {
if (m_drawFlags == R_ALPHA) {
drawsegment_plain_alpha(xadd2, xadd1, yi1,yi2);
} else if (m_drawFlags == (R_GOURAUD + R_ALPHA)) {
drawsegment_gouraud_alpha(xadd2, xadd1, yi1,yi2);
} else if (m_drawFlags == (R_TEXTURE8 + R_ALPHA)) {
drawsegment_texture8_alpha(xadd2, xadd1, yi1,yi2);
} else if (m_drawFlags == (R_TEXTURE24 + R_ALPHA)) {
drawsegment_texture24_alpha(xadd2, xadd1, yi1,yi2);
} else if (m_drawFlags == (R_TEXTURE32 + R_ALPHA)) {
drawsegment_texture32_alpha(xadd2, xadd1, yi1,yi2);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8 + R_ALPHA)) {
drawsegment_gouraud_texture8_alpha(xadd2, xadd1, yi1,yi2);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24 + R_ALPHA)) {
drawsegment_gouraud_texture24_alpha(xadd2, xadd1, yi1,yi2);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32 + R_ALPHA)) {
drawsegment_gouraud_texture32_alpha(xadd2, xadd1, yi1,yi2);
}
} else {
if (m_drawFlags == 0) {
drawsegment_plain(xadd2, xadd1, yi1,yi2);
} else if (m_drawFlags == R_GOURAUD) {
drawsegment_gouraud(xadd2, xadd1, yi1,yi2);
} else if (m_drawFlags == R_TEXTURE8) {
drawsegment_texture8(xadd2, xadd1, yi1,yi2);
} else if (m_drawFlags == R_TEXTURE24) {
drawsegment_texture24(xadd2, xadd1, yi1,yi2);
} else if (m_drawFlags == R_TEXTURE32) {
drawsegment_texture32(xadd2, xadd1, yi1,yi2);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE8)) {
drawsegment_gouraud_texture8(xadd2, xadd1, yi1,yi2);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE24)) {
drawsegment_gouraud_texture24(xadd2, xadd1, yi1,yi2);
} else if (m_drawFlags == (R_GOURAUD + R_TEXTURE32)) {
drawsegment_gouraud_texture32(xadd2, xadd1, yi1,yi2);
}
}
}
}
}
/**
* Accurate texturing code by ewjordan@gmail.com, April 14, 2007
* The getColorFromTexture() function should be inlined and optimized
* so that most of the heavy lifting happens outside the per-pixel loop.
* The unoptimized generic algorithm looks like this (unless noted,
* all of these variables are vectors, so the actual code will look messier):
*
* p = camera space vector where u == 0, v == 0;
* m = vector from p to location where u == TEX_WIDTH;
* n = vector from p to location where v == TEX_HEIGHT;
*
* A = p cross n;
* B = m cross p;
* C = n cross m;
* A *= texture.width;
* B *= texture.height;
*
* for (scanlines in triangle){
* float a = S * A;
* float b = S * B;
* float c = S * C;
* for (pixels in scanline){
* int u = a/c;
* int v = b/c;
* color = texture[v * texture.width + u];
* a += A.x;
* b += B.x;
* c += C.x;
* }
* }
*
* We don't use this exact algorithm here, however, because of the extra
* overhead from the divides. Instead we compute the exact u and v (labelled
* iu and iv in the code) at the start of each scanline and we perform a
* linear interpolation for every linearInterpLength = 1 << TEX_INTERP_POWER
* pixels. This means that we only perform the true calculation once in a
* while, and the rest of the time the algorithm functions exactly as in the
* fast inaccurate case, at least in theory. In practice, even if we set
* linearInterpLength very high we still incur some speed penalty due to the
* preprocessing that must take place per-scanline. A similar method could
* be applied per scanline to avoid this, but it would only be worthwhile in
* the case that we never compute more than one exact calculation per
* scanline. If we want something like this, however, it would be best to
* create another mode of calculation called "constant-z" interpolation,
* which could be used for things like floors and ceilings where the
* distance from the camera plane never changes over the course of a
* scanline. We could also add the vertical analogue for drawing vertical
* walls. In any case, these are not critical as the current algorithm runs
* fairly well, perhaps ~10% slower than the default perspective-less one.
*/
/**
* Solve for camera space coordinates of critical texture points and
* set up per-triangle variables for accurate texturing.
* Sets all class variables relevant to accurate texture computation
* Should be called once per triangle - checks firstSegment to see if
* we've already called.
*/
private boolean precomputeAccurateTexturing() {
// rescale u/v_array values when inverting matrix and performing other calcs
float myFact = 65500.0f;
float myFact2 = 65500.0f;
//Matrix inversion to find affine transform between (u,v,(1)) -> (x,y,z)
// OPTIMIZE: There should be a way to avoid the inversion here, which is
// quite expensive (~150 mults). Also it might crap out due to loss of
// precision depending on the scaling of the u/v_arrays. Nothing clever
// currently happens if the inversion fails, since this means the
// transformation is degenerate - we just pass false back to the caller
// and let it handle the situation. [There is no good solution to this
// case from within this function, since the way the calculation proceeds
// presumes a non-degenerate transformation matrix between camera space
// and uv space]
// Obvious optimization: if the vertices are actually at the appropriate
// texture coordinates (e.g. (0,0), (TEX_WIDTH,0), and (0,TEX_HEIGHT))
// then we can immediately return the right solution without the inversion.
// This is fairly common, so could speed up many cases of drawing.
// [not implemented]
// Furthermore, we could cache the p,resultT0,result0T vectors in the
// triangle's basis, since we could then do a look-up and generate the
// resulting coordinates very simply. This would include the above
// optimization as a special case - we could pre-populate the cache with
// special cases like that and dynamically add more. The idea here is that
// most people simply paste textures onto triangles and move the triangles
// from frame to frame, so any per-triangle-per-frame code is likely
// wasted effort. [not implemented]
// Note: o0, o1, and o2 vary depending on view angle to triangle,
// but p, n, and m should not depend on ordering differences
if (firstSegment){
PMatrix3D myMatrix =
new PMatrix3D(u_array[o0]/myFact, v_array[o0]/myFact2, 1, 0,
u_array[o1]/myFact, v_array[o1]/myFact2, 1, 0,
u_array[o2]/myFact, v_array[o2]/myFact2, 1, 0,
0, 0, 0, 1);
// A 3x3 inversion would be more efficient here,
// given that the fourth r/c are unity
myMatrix.invert();
// if the matrix inversion had trouble, let the caller know
if (myMatrix == null) return false;
float m00, m01, m02, m10, m11, m12, m20, m21, m22;
m00 = myMatrix.m00*camX[o0]+myMatrix.m01*camX[o1]+myMatrix.m02*camX[o2];
m01 = myMatrix.m10*camX[o0]+myMatrix.m11*camX[o1]+myMatrix.m12*camX[o2];
m02 = myMatrix.m20*camX[o0]+myMatrix.m21*camX[o1]+myMatrix.m22*camX[o2];
m10 = myMatrix.m00*camY[o0]+myMatrix.m01*camY[o1]+myMatrix.m02*camY[o2];
m11 = myMatrix.m10*camY[o0]+myMatrix.m11*camY[o1]+myMatrix.m12*camY[o2];
m12 = myMatrix.m20*camY[o0]+myMatrix.m21*camY[o1]+myMatrix.m22*camY[o2];
m20 = -(myMatrix.m00*camZ[o0]+myMatrix.m01*camZ[o1]+myMatrix.m02*camZ[o2]);
m21 = -(myMatrix.m10*camZ[o0]+myMatrix.m11*camZ[o1]+myMatrix.m12*camZ[o2]);
m22 = -(myMatrix.m20*camZ[o0]+myMatrix.m21*camZ[o1]+myMatrix.m22*camZ[o2]);
float px = m02;
float py = m12;
float pz = m22;
// Bugfix: possibly we should use F_TEX_WIDTH/HEIGHT instead?
// Seems to read off end of array in that case, though...
float resultT0x = m00*TEX_WIDTH+m02;
float resultT0y = m10*TEX_WIDTH+m12;
float resultT0z = m20*TEX_WIDTH+m22;
float result0Tx = m01*TEX_HEIGHT+m02;
float result0Ty = m11*TEX_HEIGHT+m12;
float result0Tz = m21*TEX_HEIGHT+m22;
float mx = resultT0x-m02;
float my = resultT0y-m12;
float mz = resultT0z-m22;
float nx = result0Tx-m02;
float ny = result0Ty-m12;
float nz = result0Tz-m22;
//avec = p x n
ax = (py*nz-pz*ny)*TEX_WIDTH; //F_TEX_WIDTH/HEIGHT?
ay = (pz*nx-px*nz)*TEX_WIDTH;
az = (px*ny-py*nx)*TEX_WIDTH;
//bvec = m x p
bx = (my*pz-mz*py)*TEX_HEIGHT;
by = (mz*px-mx*pz)*TEX_HEIGHT;
bz = (mx*py-my*px)*TEX_HEIGHT;
//cvec = n x m
cx = ny*mz-nz*my;
cy = nz*mx-nx*mz;
cz = nx*my-ny*mx;
}
nearPlaneWidth = parent.rightScreen-parent.leftScreen;
nearPlaneHeight = parent.topScreen-parent.bottomScreen;
nearPlaneDepth = parent.nearPlane;
// one pixel width in nearPlane coordinates
xmult = nearPlaneWidth / SCREEN_WIDTH;
ymult = nearPlaneHeight / SCREEN_HEIGHT;
// Extra scalings to map screen plane units to pixel units
newax = ax*xmult;
newbx = bx*xmult;
newcx = cx*xmult;
return true;
}
/**
* Set the power of two used for linear interpolation of texture coordinates.
* A true texture coordinate is computed every 2^pwr pixels along a scanline.
*/
static public void setInterpPower(int pwr) {
//Currently must be invoked from P5 as PTriangle.setInterpPower(...)
TEX_INTERP_POWER = pwr;
}
/**
* Plain color
*/
private void drawsegment_plain(float leftadd,
float rghtadd,
int ytop,
int ybottom) {
ytop *= SCREEN_WIDTH;
ybottom *= SCREEN_WIDTH;
// int f = m_fill;
// int p = m_index;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
for ( ; xstart < xend; xstart++ ) {
if (noDepthTest || (iz <= m_zbuffer[xstart])) {
m_zbuffer[xstart] = iz;
m_pixels[xstart] = m_fill;
// m_stencil[xstart] = p;
}
iz+=izadd;
}
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
zleft+=zleftadd;
}
}
/**
* Plain color, interpolated alpha
*/
private void drawsegment_plain_alpha(float leftadd,
float rghtadd,
int ytop,
int ybottom) {
ytop *= SCREEN_WIDTH;
ybottom *= SCREEN_WIDTH;
int pr = m_fill & 0xFF0000;
int pg = m_fill & 0xFF00;
int pb = m_fill & 0xFF;
// int p = m_index;
float iaf = iaadd;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
float iz = izadd * xdiff + zleft;
int ia = (int) (iaf * xdiff + aleft);
xstart += ytop;
xend += ytop;
//int ma0 = 0xFF000000;
for ( ; xstart < xend; xstart++ ) {
if (noDepthTest || (iz <= m_zbuffer[xstart])) {
// don't set zbuffer when not fully opaque
//m_zbuffer[xstart] = iz;
int alpha = ia >> 16;
int mr0 = m_pixels[xstart];
/*
if (argbSurface) {
ma0 = (((mr0 >>> 24) * alpha) << 16) & 0xFF000000;
if (ma0 == 0) ma0 = alpha << 24;
}
*/
int mg0 = mr0 & 0xFF00;
int mb0 = mr0 & 0xFF;
mr0 &= 0xFF0000;
mr0 = mr0 + (((pr - mr0) * alpha) >> 8);
mg0 = mg0 + (((pg - mg0) * alpha) >> 8);
mb0 = mb0 + (((pb - mb0) * alpha) >> 8);
m_pixels[xstart] = 0xFF000000 |
(mr0 & 0xFF0000) | (mg0 & 0xFF00) | (mb0 & 0xFF);
// m_stencil[xstart] = p;
}
iz += izadd;
ia += iaadd;
}
ytop += SCREEN_WIDTH;
xleft += leftadd;
xrght += rghtadd;
zleft += zleftadd;
}
}
/**
* RGB gouraud
*/
private void drawsegment_gouraud(float leftadd,
float rghtadd,
int ytop,
int ybottom) {
float irf = iradd;
float igf = igadd;
float ibf = ibadd;
ytop *= SCREEN_WIDTH;
ybottom *= SCREEN_WIDTH;
// int p = m_index;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
int ir = (int) (irf * xdiff + rleft);
int ig = (int) (igf * xdiff + gleft);
int ib = (int) (ibf * xdiff + bleft);
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
for ( ; xstart < xend; xstart++ ) {
if (noDepthTest || (iz <= m_zbuffer[xstart])) {
m_zbuffer[xstart] = iz;
m_pixels[xstart] = 0xFF000000 |
((ir & 0xFF0000) | ((ig >> 8) & 0xFF00) | (ib >> 16));
// m_stencil[xstart] = p;
}
ir+=iradd;
ig+=igadd;
ib+=ibadd;
iz+=izadd;
}
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
rleft+=rleftadd;
gleft+=gleftadd;
bleft+=bleftadd;
zleft+=zleftadd;
}
}
/**
* RGB gouraud + interpolated alpha
*/
private void drawsegment_gouraud_alpha(float leftadd,
float rghtadd,
int ytop,
int ybottom) {
ytop *= SCREEN_WIDTH;
ybottom *= SCREEN_WIDTH;
// int p = m_index;
float irf = iradd;
float igf = igadd;
float ibf = ibadd;
float iaf = iaadd;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
int ir = (int) (irf * xdiff + rleft);
int ig = (int) (igf * xdiff + gleft);
int ib = (int) (ibf * xdiff + bleft);
int ia = (int) (iaf * xdiff + aleft);
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
for ( ; xstart < xend; xstart++ ) {
if (noDepthTest || (iz <= m_zbuffer[xstart])) {
//m_zbuffer[xstart] = iz;
//
int red = (ir & 0xFF0000);
int grn = (ig >> 8) & 0xFF00;
int blu = (ib >> 16);
// get buffer pixels
int bb = m_pixels[xstart];
int br = (bb & 0xFF0000); // 0x00FF0000
int bg = (bb & 0xFF00); // 0x0000FF00
bb = (bb & 0xFF); // 0x000000FF
// blend alpha
int al = ia >> 16;
//
m_pixels[xstart] = 0xFF000000 |
((br + (((red - br) * al) >> 8)) & 0xFF0000) |
((bg + (((grn - bg) * al) >> 8)) & 0xFF00) |
((bb + (((blu - bb) * al) >> 8)) & 0xFF);
// m_stencil[xstart] = p;
}
//
ir+=iradd;
ig+=igadd;
ib+=ibadd;
ia+=iaadd;
iz+=izadd;
}
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
rleft+=rleftadd;
gleft+=gleftadd;
bleft+=bleftadd;
aleft+=aleftadd;
zleft+=zleftadd;
}
}
/**
* 8-bit plain texture
*/
//THIS IS MESSED UP, NEED TO GRAB ORIGINAL VERSION!!!
private void drawsegment_texture8(float leftadd,
float rghtadd,
int ytop,
int ybottom) {
// Accurate texture mode added - comments stripped from dupe code,
// see drawsegment_texture24() for details
int ypixel = ytop;
int lastRowStart = m_texture.length - TEX_WIDTH - 2;
boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES];
float screenx = 0; float screeny = 0; float screenz = 0;
float a = 0; float b = 0; float c = 0;
int linearInterpPower = TEX_INTERP_POWER;
int linearInterpLength = 1 << linearInterpPower;
if (accurateMode) {
// see if the precomputation goes well, if so finish the setup
if (precomputeAccurateTexturing()) {
newax *= linearInterpLength;
newbx *= linearInterpLength;
newcx *= linearInterpLength;
screenz = nearPlaneDepth;
firstSegment = false;
} else{
// if the matrix inversion screwed up, revert to normal rendering
// (something is degenerate)
accurateMode = false;
}
}
ytop *= SCREEN_WIDTH;
ybottom *= SCREEN_WIDTH;
// int p = m_index;
float iuf = iuadd;
float ivf = ivadd;
int red = m_fill & 0xFF0000;
int grn = m_fill & 0xFF00;
int blu = m_fill & 0xFF;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xpixel = xstart;//accurate mode
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
int iu = (int) (iuf * xdiff + uleft);
int iv = (int) (ivf * xdiff + vleft);
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
if (accurateMode){
screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f));
screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f));
a = screenx*ax+screeny*ay+screenz*az;
b = screenx*bx+screeny*by+screenz*bz;
c = screenx*cx+screeny*cy+screenz*cz;
}
boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true;
int interpCounter = 0;
int deltaU = 0; int deltaV = 0;
float fu = 0; float fv = 0;
float oldfu = 0; float oldfv = 0;
if (accurateMode && goingIn) {
int rightOffset = (xend-xstart-1)%linearInterpLength;
int leftOffset = linearInterpLength-rightOffset;
float rightOffset2 = rightOffset / ((float)linearInterpLength);
float leftOffset2 = leftOffset / ((float)linearInterpLength);
interpCounter = leftOffset;
float ao = a-leftOffset2*newax;
float bo = b-leftOffset2*newbx;
float co = c-leftOffset2*newcx;
float oneoverc = 65536.0f/co;
oldfu = (ao*oneoverc); oldfv = (bo*oneoverc);
a += rightOffset2*newax;
b += rightOffset2*newbx;
c += rightOffset2*newcx;
oneoverc = 65536.0f/c;
fu = a*oneoverc; fv = b*oneoverc;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
iu = ( (int)oldfu )+(leftOffset-1)*deltaU;
iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack
} else {
float preoneoverc = 65536.0f/c;
fu = (a*preoneoverc);
fv = (b*preoneoverc);
}
for ( ; xstart < xend; xstart++ ) {
if (accurateMode) {
if (interpCounter == linearInterpLength) interpCounter = 0;
if (interpCounter == 0){
a += newax;
b += newbx;
c += newcx;
float oneoverc = 65536.0f/c;
oldfu = fu; oldfv = fv;
fu = (a*oneoverc); fv = (b*oneoverc);
iu = (int)oldfu; iv = (int)oldfv;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
} else {
iu += deltaU;
iv += deltaV;
}
interpCounter++;
}
// try-catch just in case pixel offset it out of range
try {
if (noDepthTest || (iz <= m_zbuffer[xstart])) {
//m_zbuffer[xstart] = iz;
int al0;
if (m_bilinear) {
int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16);
int iui = iu & 0xFFFF;
al0 = m_texture[ofs] & 0xFF;
int al1 = m_texture[ofs + 1] & 0xFF;
if (ofs < lastRowStart) ofs+=TEX_WIDTH;
int al2 = m_texture[ofs] & 0xFF;
int al3 = m_texture[ofs + 1] & 0xFF;
al0 = al0 + (((al1-al0) * iui) >> 16);
al2 = al2 + (((al3-al2) * iui) >> 16);
al0 = al0 + (((al2-al0) * (iv & 0xFFFF)) >> 16);
} else {
al0 = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)] & 0xFF;
}
int br = m_pixels[xstart];
int bg = (br & 0xFF00);
int bb = (br & 0xFF);
br = (br & 0xFF0000);
m_pixels[xstart] = 0xFF000000 |
((br + (((red - br) * al0) >> 8)) & 0xFF0000) |
((bg + (((grn - bg) * al0) >> 8)) & 0xFF00) |
((bb + (((blu - bb) * al0) >> 8)) & 0xFF);
// m_stencil[xstart] = p;
}
}
catch (Exception e) {
}
xpixel++;//accurate mode
if (!accurateMode){
iu+=iuadd;
iv+=ivadd;
}
iz+=izadd;
}
ypixel++;//accurate mode
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
uleft+=uleftadd;
vleft+=vleftadd;
zleft+=zleftadd;
}
}
/**
* 8-bit texutre + alpha
*/
private void drawsegment_texture8_alpha(float leftadd,
float rghtadd,
int ytop,
int ybottom) {
// Accurate texture mode added - comments stripped from dupe code,
// see drawsegment_texture24() for details
int ypixel = ytop;
int lastRowStart = m_texture.length - TEX_WIDTH - 2;
boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES];
float screenx = 0; float screeny = 0; float screenz = 0;
float a = 0; float b = 0; float c = 0;
int linearInterpPower = TEX_INTERP_POWER;
int linearInterpLength = 1 << linearInterpPower;
if (accurateMode) {
// see if the precomputation goes well, if so finish the setup
if (precomputeAccurateTexturing()) {
newax *= linearInterpLength;
newbx *= linearInterpLength;
newcx *= linearInterpLength;
screenz = nearPlaneDepth;
firstSegment = false;
} else {
// if the matrix inversion screwed up,
// revert to normal rendering (something is degenerate)
accurateMode = false;
}
}
ytop*=SCREEN_WIDTH;
ybottom*=SCREEN_WIDTH;
// int p = m_index;
float iuf = iuadd;
float ivf = ivadd;
float iaf = iaadd;
int red = m_fill & 0xFF0000;
int grn = m_fill & 0xFF00;
int blu = m_fill & 0xFF;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xpixel = xstart;//accurate mode
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
int iu = (int) (iuf * xdiff + uleft);
int iv = (int) (ivf * xdiff + vleft);
int ia = (int) (iaf * xdiff + aleft);
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
if (accurateMode){
screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f));
screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f));
a = screenx*ax+screeny*ay+screenz*az;
b = screenx*bx+screeny*by+screenz*bz;
c = screenx*cx+screeny*cy+screenz*cz;
}
boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true;
int interpCounter = 0;
int deltaU = 0; int deltaV = 0;
float fu = 0; float fv = 0;
float oldfu = 0; float oldfv = 0;
if (accurateMode&&goingIn){
int rightOffset = (xend-xstart-1)%linearInterpLength;
int leftOffset = linearInterpLength-rightOffset;
float rightOffset2 = rightOffset / ((float)linearInterpLength);
float leftOffset2 = leftOffset / ((float)linearInterpLength);
interpCounter = leftOffset;
float ao = a-leftOffset2*newax;
float bo = b-leftOffset2*newbx;
float co = c-leftOffset2*newcx;
float oneoverc = 65536.0f/co;
oldfu = (ao*oneoverc); oldfv = (bo*oneoverc);
a += rightOffset2*newax;
b += rightOffset2*newbx;
c += rightOffset2*newcx;
oneoverc = 65536.0f/c;
fu = a*oneoverc; fv = b*oneoverc;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack
} else{
float preoneoverc = 65536.0f/c;
fu = (a*preoneoverc);
fv = (b*preoneoverc);
}
for ( ; xstart < xend; xstart++ ) {
if(accurateMode){
if (interpCounter == linearInterpLength) interpCounter = 0;
if (interpCounter == 0){
a += newax;
b += newbx;
c += newcx;
float oneoverc = 65536.0f/c;
oldfu = fu; oldfv = fv;
fu = (a*oneoverc); fv = (b*oneoverc);
iu = (int)oldfu; iv = (int)oldfv;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
} else{
iu += deltaU;
iv += deltaV;
}
interpCounter++;
}
// try-catch just in case pixel offset it out of range
try
{
if (noDepthTest || (iz <= m_zbuffer[xstart])) {
//m_zbuffer[xstart] = iz;
int al0;
if (m_bilinear) {
int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16);
int iui = iu & 0xFFFF;
al0 = m_texture[ofs] & 0xFF;
int al1 = m_texture[ofs + 1] & 0xFF;
if (ofs < lastRowStart) ofs+=TEX_WIDTH;
int al2 = m_texture[ofs] & 0xFF;
int al3 = m_texture[ofs + 1] & 0xFF;
al0 = al0 + (((al1-al0) * iui) >> 16);
al2 = al2 + (((al3-al2) * iui) >> 16);
al0 = al0 + (((al2-al0) * (iv & 0xFFFF)) >> 16);
} else {
al0 = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)] & 0xFF;
}
al0 = (al0 * (ia >> 16)) >> 8;
int br = m_pixels[xstart];
int bg = (br & 0xFF00);
int bb = (br & 0xFF);
br = (br & 0xFF0000);
m_pixels[xstart] = 0xFF000000 |
((br + (((red - br) * al0) >> 8)) & 0xFF0000) |
((bg + (((grn - bg) * al0) >> 8)) & 0xFF00) |
((bb + (((blu - bb) * al0) >> 8)) & 0xFF);
// m_stencil[xstart] = p;
}
}
catch (Exception e) {
}
xpixel++;//accurate mode
if (!accurateMode){
iu+=iuadd;
iv+=ivadd;
}
iz+=izadd;
ia+=iaadd;
}
ypixel++;//accurate mode
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
uleft+=uleftadd;
vleft+=vleftadd;
zleft+=zleftadd;
aleft+=aleftadd;
}
}
/**
* Plain 24-bit texture
*/
private void drawsegment_texture24(float leftadd,
float rghtadd,
int ytop,
int ybottom) {
ytop *= SCREEN_WIDTH;
ybottom *= SCREEN_WIDTH;
// int p = m_index;
float iuf = iuadd;
float ivf = ivadd;
boolean tint = (m_fill & 0xFFFFFF) != 0xFFFFFF;
int rtint = (m_fill >> 16) & 0xff;
int gtint = (m_fill >> 8) & 0xff;
int btint = m_fill & 0xFF;
int ypixel = ytop/SCREEN_WIDTH;//ACCTEX
int lastRowStart = m_texture.length - TEX_WIDTH - 2;//If we're past this index, we can't shift down a row w/o throwing an exception
// int exCount = 0;//counter for exceptions caught
boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES]; //bring this local since it will be accessed often
float screenx = 0; float screeny = 0; float screenz = 0;
float a = 0; float b = 0; float c = 0;
//Interpolation length of 16 tends to look good except at a small angle; 8 looks okay then, except for the
//above issue. When viewing close to flat, as high as 32 is often acceptable. Could add dynamic interpolation
//settings based on triangle angle - currently we just pick a value and leave it (by default I have the
//power set at 3, so every 8 pixels a true coordinate is calculated, which seems a decent compromise).
int linearInterpPower = TEX_INTERP_POWER;
int linearInterpLength = 1 << linearInterpPower;
if (accurateMode){
if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup
newax *= linearInterpLength;
newbx *= linearInterpLength;
newcx *= linearInterpLength;
screenz = nearPlaneDepth;
firstSegment = false;
} else{
accurateMode = false; //if the matrix inversion gave us garbage, revert to normal rendering (something is degenerate)
}
}
while (ytop < ybottom) {//scanline loop
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0){ xstart = 0; }
int xpixel = xstart;//accurate mode
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH){ xend = SCREEN_WIDTH; }
float xdiff = (xstart + PIXEL_CENTER) - xleft;
int iu = (int) (iuf * xdiff + uleft);
int iv = (int) (ivf * xdiff + vleft);
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
if (accurateMode){
//off by one (half, I guess) hack, w/o it the first rows are outside the texture - maybe a mistake somewhere?
screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f));
screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f));
a = screenx*ax+screeny*ay+screenz*az;//OPT - some of this could be brought out of the y-loop since
b = screenx*bx+screeny*by+screenz*bz;//xpixel and ypixel just increment by the same numbers each iteration.
c = screenx*cx+screeny*cy+screenz*cz;//Probably not a big bottleneck, though.
}
//Figure out whether triangle is going further into the screen or not as we move along scanline
boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true;
//Set up linear interpolation between calculated texture points
int interpCounter = 0;
int deltaU = 0; int deltaV = 0;
//float fdeltaU = 0; float fdeltaV = 0;//vars for floating point interpolating version of algorithm
//float fiu = 0; float fiv = 0;
float fu = 0; float fv = 0;
float oldfu = 0; float oldfv = 0;
//Bugfix (done): it's a Really Bad Thing to interpolate along a scanline when the triangle goes deeper into the screen,
//because if the angle is severe enough the last control point for interpolation may cross the vanishing
//point. This leads to some pretty nasty artifacts, and ideally we should scan from right to left if the
//triangle is better served that way, or (what we do now) precompute the offset that we'll need so that we end up
//with a control point exactly at the furthest edge of the triangle.
if (accurateMode&&goingIn){
//IMPORTANT!!! Results are horrid without this hack!
//If polygon goes into the screen along scan line, we want to match the control point to the furthest point drawn
//since the control points are less meaningful the closer you are to the vanishing point.
//We'll do this by making the first control point lie before the start of the scanline (safe since it's closer to us)
int rightOffset = (xend-xstart-1)%linearInterpLength; //"off by one" hack...probably means there's a small bug somewhere
int leftOffset = linearInterpLength-rightOffset;
float rightOffset2 = rightOffset / ((float)linearInterpLength);
float leftOffset2 = leftOffset / ((float)linearInterpLength);
interpCounter = leftOffset;
//Take step to control point to the left of start pixel
float ao = a-leftOffset2*newax;
float bo = b-leftOffset2*newbx;
float co = c-leftOffset2*newcx;
float oneoverc = 65536.0f/co;
oldfu = (ao*oneoverc); oldfv = (bo*oneoverc);
//Now step to right control point
a += rightOffset2*newax;
b += rightOffset2*newbx;
c += rightOffset2*newcx;
oneoverc = 65536.0f/c;
fu = a*oneoverc; fv = b*oneoverc;
//Get deltas for interpolation
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack
} else{
//Otherwise the left edge is further, and we pin the first control point to it
float preoneoverc = 65536.0f/c;
fu = (a*preoneoverc);
fv = (b*preoneoverc);
}
for ( ; xstart < xend; xstart++ ) {//pixel loop - keep trim, can execute thousands of times per frame
//boolean drawBlack = false; //used to display control points
if(accurateMode){
/* //Non-interpolating algorithm - slowest version, calculates exact coordinate for each pixel,
//and casts from float->int
float oneoverc = 65536.0f/c; //a bit faster to pre-divide for next two steps
iu = (int)(a*oneoverc);
iv = (int)(b*oneoverc);
a += newax;
b += newbx;
c += newcx;
*/
//Float while calculating, int while interpolating
if (interpCounter == linearInterpLength) interpCounter = 0;
if (interpCounter == 0){
//drawBlack = true;
a += newax;
b += newbx;
c += newcx;
float oneoverc = 65536.0f/c;
oldfu = fu; oldfv = fv;
fu = (a*oneoverc); fv = (b*oneoverc);
iu = (int)oldfu; iv = (int)oldfv; //ints are used for interpolation, not actual computation
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
} else{ //race through using linear interpolation if we're not at a control point
iu += deltaU;
iv += deltaV;
}
interpCounter++;
/* //Floating point interpolating version - slower than int thanks to casts during interpolation steps
if (interpCounter == 0) {
interpCounter = linearInterpLength;
a += newax;
b += newbx;
c += newcx;
float oneoverc = 65536.0f/c;
oldfu = fu;
oldfv = fv;
fu = (a*oneoverc);
fv = (b*oneoverc);
//oldu = u; oldv = v;
fiu = oldfu;
fiv = oldfv;
fdeltaU = (fu-oldfu)/linearInterpLength;
fdeltaV = (fv-oldfv)/linearInterpLength;
}
else{
fiu += fdeltaU;
fiv += fdeltaV;
}
interpCounter--;
iu = (int)(fiu); iv = (int)(fiv);*/
}
// try-catch just in case pixel offset is out of range
try{
if (noDepthTest || (iz <= m_zbuffer[xstart])) {
m_zbuffer[xstart] = iz;
if (m_bilinear) {
//We could (should?) add bounds checking on iu and iv here (keep in mind the 16 bit shift!).
//This would also be the place to add looping texture mode (bounds check == clamped).
//For looping/clamped textures, we'd also need to change PGraphics.textureVertex() to remove
//the texture range check there (it constrains normalized texture coordinates from 0->1).
int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16);
int iui = (iu & 0xFFFF) >> 9;
int ivi = (iv & 0xFFFF) >> 9;
//if(ofs < 0) { ofs += TEX_WIDTH; }
//if(ofs > m_texture.length-2) {ofs -= TEX_WIDTH; }
// get texture pixels
int pix0 = m_texture[ofs];
int pix1 = m_texture[ofs + 1];
if (ofs < lastRowStart) ofs+=TEX_WIDTH; //quick hack to thwart exceptions
int pix2 = m_texture[ofs];
int pix3 = m_texture[ofs + 1];
// red
int red0 = (pix0 & 0xFF0000);
int red2 = (pix2 & 0xFF0000);
int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7);
int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7);
int red = up + (((dn-up) * ivi) >> 7);
if (tint) red = ((red * rtint) >> 8) & 0xFF0000;
// grn
red0 = (pix0 & 0xFF00);
red2 = (pix2 & 0xFF00);
up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7);
int grn = up + (((dn-up) * ivi) >> 7);
if (tint) grn = ((grn * gtint) >> 8) & 0xFF00;
// blu
red0 = (pix0 & 0xFF);
red2 = (pix2 & 0xFF);
up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7);
int blu = up + (((dn-up) * ivi) >> 7);
if (tint) blu = ((blu * btint) >> 8) & 0xFF;
//m_pixels[xstart] = (red & 0xFF0000) | (grn & 0xFF00) | (blu & 0xFF);
m_pixels[xstart] = 0xFF000000 |
(red & 0xFF0000) | (grn & 0xFF00) | (blu & 0xFF);
} else {
m_pixels[xstart] = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)];
}
// m_stencil[xstart] = p;
}
} catch (Exception e) {/*exCount++;*/}
iz+=izadd;
xpixel++;//accurate mode
if (!accurateMode){
iu+=iuadd;
iv+=ivadd;
}
}
ypixel++; //accurate mode
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
zleft+=zleftadd;
uleft+=uleftadd;
vleft+=vleftadd;
}
//if (exCount>0) System.out.println(exCount+" exceptions in this segment");
}
/**
* Alpha 24-bit texture
*/
private void drawsegment_texture24_alpha(float leftadd,
float rghtadd,
int ytop,
int ybottom) {
//Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details
int ypixel = ytop;
int lastRowStart = m_texture.length - TEX_WIDTH - 2;
boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES];
float screenx = 0; float screeny = 0; float screenz = 0;
float a = 0; float b = 0; float c = 0;
int linearInterpPower = TEX_INTERP_POWER;
int linearInterpLength = 1 << linearInterpPower;
if (accurateMode){
if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup
newax *= linearInterpLength;
newbx *= linearInterpLength;
newcx *= linearInterpLength;
screenz = nearPlaneDepth;
firstSegment = false;
} else{
accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate)
}
}
boolean tint = (m_fill & 0xFFFFFF) != 0xFFFFFF;
int rtint = (m_fill >> 16) & 0xff;
int gtint = (m_fill >> 8) & 0xff;
int btint = m_fill & 0xFF;
ytop *= SCREEN_WIDTH;
ybottom *= SCREEN_WIDTH;
// int p = m_index;
float iuf = iuadd;
float ivf = ivadd;
float iaf = iaadd;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xpixel = xstart;//accurate mode
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
int iu = (int) (iuf * xdiff + uleft);
int iv = (int) (ivf * xdiff + vleft);
int ia = (int) (iaf * xdiff + aleft);
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
if (accurateMode){
screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f));
screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f));
a = screenx*ax+screeny*ay+screenz*az;
b = screenx*bx+screeny*by+screenz*bz;
c = screenx*cx+screeny*cy+screenz*cz;
}
boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true;
int interpCounter = 0;
int deltaU = 0; int deltaV = 0;
float fu = 0; float fv = 0;
float oldfu = 0; float oldfv = 0;
if (accurateMode&&goingIn){
int rightOffset = (xend-xstart-1)%linearInterpLength;
int leftOffset = linearInterpLength-rightOffset;
float rightOffset2 = rightOffset / ((float)linearInterpLength);
float leftOffset2 = leftOffset / ((float)linearInterpLength);
interpCounter = leftOffset;
float ao = a-leftOffset2*newax;
float bo = b-leftOffset2*newbx;
float co = c-leftOffset2*newcx;
float oneoverc = 65536.0f/co;
oldfu = (ao*oneoverc); oldfv = (bo*oneoverc);
a += rightOffset2*newax;
b += rightOffset2*newbx;
c += rightOffset2*newcx;
oneoverc = 65536.0f/c;
fu = a*oneoverc; fv = b*oneoverc;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack
} else{
float preoneoverc = 65536.0f/c;
fu = (a*preoneoverc);
fv = (b*preoneoverc);
}
for ( ; xstart < xend; xstart++ ) {
if(accurateMode){
if (interpCounter == linearInterpLength) interpCounter = 0;
if (interpCounter == 0){
a += newax;
b += newbx;
c += newcx;
float oneoverc = 65536.0f/c;
oldfu = fu; oldfv = fv;
fu = (a*oneoverc); fv = (b*oneoverc);
iu = (int)oldfu; iv = (int)oldfv;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
} else{
iu += deltaU;
iv += deltaV;
}
interpCounter++;
}
try {
if (noDepthTest || (iz <= m_zbuffer[xstart])) {
//m_zbuffer[xstart] = iz;
// get alpha
int al = ia >> 16;
if (m_bilinear) {
int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16);
int iui = (iu & 0xFFFF) >> 9;
int ivi = (iv & 0xFFFF) >> 9;
// get texture pixels
int pix0 = m_texture[ofs];
int pix1 = m_texture[ofs + 1];
if (ofs < lastRowStart) ofs+=TEX_WIDTH;
int pix2 = m_texture[ofs];
int pix3 = m_texture[ofs + 1];
// red
int red0 = (pix0 & 0xFF0000);
int red2 = (pix2 & 0xFF0000);
int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7);
int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7);
int red = up + (((dn-up) * ivi) >> 7);
if (tint) red = ((red * rtint) >> 8) & 0xFF0000;
// grn
red0 = (pix0 & 0xFF00);
red2 = (pix2 & 0xFF00);
up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7);
int grn = up + (((dn-up) * ivi) >> 7);
if (tint) grn = ((grn * gtint) >> 8) & 0xFF00;
// blu
red0 = (pix0 & 0xFF);
red2 = (pix2 & 0xFF);
up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7);
int blu = up + (((dn-up) * ivi) >> 7);
if (tint) blu = ((blu * btint) >> 8) & 0xFF;
// get buffer pixels
int bb = m_pixels[xstart];
int br = (bb & 0xFF0000); // 0x00FF0000
int bg = (bb & 0xFF00); // 0x0000FF00
bb = (bb & 0xFF); // 0x000000FF
m_pixels[xstart] = 0xFF000000 |
((br + (((red - br) * al) >> 8)) & 0xFF0000) |
((bg + (((grn - bg) * al) >> 8)) & 0xFF00) |
((bb + (((blu - bb) * al) >> 8)) & 0xFF);
} else {
int red = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)];
int grn = red & 0xFF00;
int blu = red & 0xFF;
red&=0xFF0000;
// get buffer pixels
int bb = m_pixels[xstart];
int br = (bb & 0xFF0000); // 0x00FF0000
int bg = (bb & 0xFF00); // 0x0000FF00
bb = (bb & 0xFF); // 0x000000FF
m_pixels[xstart] = 0xFF000000 |
((br + (((red - br) * al) >> 8)) & 0xFF0000) |
((bg + (((grn - bg) * al) >> 8)) & 0xFF00) |
((bb + (((blu - bb) * al) >> 8)) & 0xFF);
}
// m_stencil[xstart] = p;
}
} catch (Exception e) { }
xpixel++; // accurate mode
if (!accurateMode){
iu += iuadd;
iv += ivadd;
}
ia+=iaadd;
iz+=izadd;
}
ypixel++; // accurate mode
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
uleft+=uleftadd;
vleft+=vleftadd;
zleft+=zleftadd;
aleft+=aleftadd;
}
}
/**
* Plain 32-bit texutre
*/
private void drawsegment_texture32(float leftadd,
float rghtadd,
int ytop,
int ybottom) {
//Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details
int ypixel = ytop;
int lastRowStart = m_texture.length - TEX_WIDTH - 2;
boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES];
float screenx = 0; float screeny = 0; float screenz = 0;
float a = 0; float b = 0; float c = 0;
int linearInterpPower = TEX_INTERP_POWER;
int linearInterpLength = 1 << linearInterpPower;
if (accurateMode){
if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup
newax *= linearInterpLength;
newbx *= linearInterpLength;
newcx *= linearInterpLength;
screenz = nearPlaneDepth;
firstSegment = false;
} else{
accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate)
}
}
ytop*=SCREEN_WIDTH;
ybottom*=SCREEN_WIDTH;
// int p = m_index;
boolean tint = m_fill != 0xFFFFFFFF;
int rtint = (m_fill >> 16) & 0xff;
int gtint = (m_fill >> 8) & 0xff;
int btint = m_fill & 0xFF;
float iuf = iuadd;
float ivf = ivadd;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xpixel = xstart;//accurate mode
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
int iu = (int) (iuf * xdiff + uleft);
int iv = (int) (ivf * xdiff + vleft);
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
if (accurateMode){
screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f));
screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f));
a = screenx*ax+screeny*ay+screenz*az;
b = screenx*bx+screeny*by+screenz*bz;
c = screenx*cx+screeny*cy+screenz*cz;
}
boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true;
int interpCounter = 0;
int deltaU = 0; int deltaV = 0;
float fu = 0; float fv = 0;
float oldfu = 0; float oldfv = 0;
if (accurateMode&&goingIn){
int rightOffset = (xend-xstart-1)%linearInterpLength;
int leftOffset = linearInterpLength-rightOffset;
float rightOffset2 = rightOffset / ((float)linearInterpLength);
float leftOffset2 = leftOffset / ((float)linearInterpLength);
interpCounter = leftOffset;
float ao = a-leftOffset2*newax;
float bo = b-leftOffset2*newbx;
float co = c-leftOffset2*newcx;
float oneoverc = 65536.0f/co;
oldfu = (ao*oneoverc); oldfv = (bo*oneoverc);
a += rightOffset2*newax;
b += rightOffset2*newbx;
c += rightOffset2*newcx;
oneoverc = 65536.0f/c;
fu = a*oneoverc; fv = b*oneoverc;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack
} else{
float preoneoverc = 65536.0f/c;
fu = (a*preoneoverc);
fv = (b*preoneoverc);
}
for ( ; xstart < xend; xstart++ ) {
if(accurateMode){
if (interpCounter == linearInterpLength) interpCounter = 0;
if (interpCounter == 0){
a += newax;
b += newbx;
c += newcx;
float oneoverc = 65536.0f/c;
oldfu = fu; oldfv = fv;
fu = (a*oneoverc); fv = (b*oneoverc);
iu = (int)oldfu; iv = (int)oldfv;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
} else{
iu += deltaU;
iv += deltaV;
}
interpCounter++;
}
// try-catch just in case pixel offset it out of range
try {
if (noDepthTest || (iz <= m_zbuffer[xstart])) {
//m_zbuffer[xstart] = iz;
if (m_bilinear) {
int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16);
int iui = (iu & 0xFFFF) >> 9;
int ivi = (iv & 0xFFFF) >> 9;
// get texture pixels
int pix0 = m_texture[ofs];
int pix1 = m_texture[ofs + 1];
if (ofs < lastRowStart) ofs+=TEX_WIDTH;
int pix2 = m_texture[ofs];
int pix3 = m_texture[ofs + 1];
// red
int red0 = (pix0 & 0xFF0000);
int red2 = (pix2 & 0xFF0000);
int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7);
int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7);
int red = up + (((dn-up) * ivi) >> 7);
if (tint) red = ((red * rtint) >> 8) & 0xFF0000;
// grn
red0 = (pix0 & 0xFF00);
red2 = (pix2 & 0xFF00);
up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7);
int grn = up + (((dn-up) * ivi) >> 7);
if (tint) grn = ((grn * gtint) >> 8) & 0xFF00;
// blu
red0 = (pix0 & 0xFF);
red2 = (pix2 & 0xFF);
up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7);
int blu = up + (((dn-up) * ivi) >> 7);
if (tint) blu = ((blu * btint) >> 8) & 0xFF;
// alpha
pix0>>>=24;
pix2>>>=24;
up = pix0 + ((((pix1 >>> 24) - pix0) * iui) >> 7);
dn = pix2 + ((((pix3 >>> 24) - pix2) * iui) >> 7);
int al = up + (((dn-up) * ivi) >> 7);
// get buffer pixels
int bb = m_pixels[xstart];
int br = (bb & 0xFF0000); // 0x00FF0000
int bg = (bb & 0xFF00); // 0x0000FF00
bb = (bb & 0xFF); // 0x000000FF
m_pixels[xstart] = 0xFF000000 |
((br + (((red - br) * al) >> 8)) & 0xFF0000) |
((bg + (((grn - bg) * al) >> 8)) & 0xFF00) |
((bb + (((blu - bb) * al) >> 8)) & 0xFF);
} else {
int red = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)];
int al = red >>> 24;
int grn = red & 0xFF00;
int blu = red & 0xFF;
red&=0xFF0000;
// get buffer pixels
int bb = m_pixels[xstart];
int br = (bb & 0xFF0000); // 0x00FF0000
int bg = (bb & 0xFF00); // 0x0000FF00
bb = (bb & 0xFF); // 0x000000FF
m_pixels[xstart] = 0xFF000000 |
((br + (((red - br) * al) >> 8)) & 0xFF0000) |
((bg + (((grn - bg) * al) >> 8)) & 0xFF00) |
((bb + (((blu - bb) * al) >> 8)) & 0xFF);
}
// m_stencil[xstart] = p;
}
} catch (Exception e) { }
xpixel++;//accurate mode
if (!accurateMode){
iu+=iuadd;
iv+=ivadd;
}
iz+=izadd;
}
ypixel++;//accurate mode
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
uleft+=uleftadd;
vleft+=vleftadd;
zleft+=zleftadd;
aleft+=aleftadd;
}
}
/**
* Alpha 32-bit texutre
*/
private void drawsegment_texture32_alpha(float leftadd,
float rghtadd,
int ytop,
int ybottom) {
//Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details
int ypixel = ytop;
int lastRowStart = m_texture.length - TEX_WIDTH - 2;
boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES];
float screenx = 0; float screeny = 0; float screenz = 0;
float a = 0; float b = 0; float c = 0;
int linearInterpPower = TEX_INTERP_POWER;
int linearInterpLength = 1 << linearInterpPower;
if (accurateMode){
if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup
newax *= linearInterpLength;
newbx *= linearInterpLength;
newcx *= linearInterpLength;
screenz = nearPlaneDepth;
firstSegment = false;
} else{
accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate)
}
}
ytop *= SCREEN_WIDTH;
ybottom *= SCREEN_WIDTH;
// int p = m_index;
boolean tint = (m_fill & 0xFFFFFF) != 0xFFFFFF;
int rtint = (m_fill >> 16) & 0xff;
int gtint = (m_fill >> 8) & 0xff;
int btint = m_fill & 0xFF;
float iuf = iuadd;
float ivf = ivadd;
float iaf = iaadd;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xpixel = xstart;//accurate mode
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
int iu = (int) (iuf * xdiff + uleft);
int iv = (int) (ivf * xdiff + vleft);
int ia = (int) (iaf * xdiff + aleft);
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
if (accurateMode){
screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f));
screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f));
a = screenx*ax+screeny*ay+screenz*az;
b = screenx*bx+screeny*by+screenz*bz;
c = screenx*cx+screeny*cy+screenz*cz;
}
boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true;
int interpCounter = 0;
int deltaU = 0; int deltaV = 0;
float fu = 0; float fv = 0;
float oldfu = 0; float oldfv = 0;
if (accurateMode&&goingIn){
int rightOffset = (xend-xstart-1)%linearInterpLength;
int leftOffset = linearInterpLength-rightOffset;
float rightOffset2 = rightOffset / ((float)linearInterpLength);
float leftOffset2 = leftOffset / ((float)linearInterpLength);
interpCounter = leftOffset;
float ao = a-leftOffset2*newax;
float bo = b-leftOffset2*newbx;
float co = c-leftOffset2*newcx;
float oneoverc = 65536.0f/co;
oldfu = (ao*oneoverc); oldfv = (bo*oneoverc);
a += rightOffset2*newax;
b += rightOffset2*newbx;
c += rightOffset2*newcx;
oneoverc = 65536.0f/c;
fu = a*oneoverc; fv = b*oneoverc;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack
} else{
float preoneoverc = 65536.0f/c;
fu = (a*preoneoverc);
fv = (b*preoneoverc);
}
for ( ; xstart < xend; xstart++ ) {
if(accurateMode){
if (interpCounter == linearInterpLength) interpCounter = 0;
if (interpCounter == 0){
a += newax;
b += newbx;
c += newcx;
float oneoverc = 65536.0f/c;
oldfu = fu; oldfv = fv;
fu = (a*oneoverc); fv = (b*oneoverc);
iu = (int)oldfu; iv = (int)oldfv;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
} else{
iu += deltaU;
iv += deltaV;
}
interpCounter++;
}
// try-catch just in case pixel offset it out of range
try {
if (noDepthTest || (iz <= m_zbuffer[xstart])) {
//m_zbuffer[xstart] = iz;
// get alpha
int al = ia >> 16;
if (m_bilinear) {
int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16);
int iui = (iu & 0xFFFF) >> 9;
int ivi = (iv & 0xFFFF) >> 9;
// get texture pixels
int pix0 = m_texture[ofs];
int pix1 = m_texture[ofs + 1];
if (ofs < lastRowStart) ofs+=TEX_WIDTH;
int pix2 = m_texture[ofs];
int pix3 = m_texture[ofs + 1];
// red
int red0 = (pix0 & 0xFF0000);
int red2 = (pix2 & 0xFF0000);
int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7);
int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7);
int red = up + (((dn-up) * ivi) >> 7);
if (tint) red = ((red * rtint) >> 8) & 0xFF0000;
// grn
red0 = (pix0 & 0xFF00);
red2 = (pix2 & 0xFF00);
up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7);
int grn = up + (((dn-up) * ivi) >> 7);
if (tint) grn = ((grn * gtint) >> 8) & 0xFF00;
// blu
red0 = (pix0 & 0xFF);
red2 = (pix2 & 0xFF);
up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7);
int blu = up + (((dn-up) * ivi) >> 7);
if (tint) blu = ((blu * btint) >> 8) & 0xFF;
// alpha
pix0>>>=24;
pix2>>>=24;
up = pix0 + ((((pix1 >>> 24) - pix0) * iui) >> 7);
dn = pix2 + ((((pix3 >>> 24) - pix2) * iui) >> 7);
al = al * (up + (((dn-up) * ivi) >> 7)) >> 8;
// get buffer pixels
int bb = m_pixels[xstart];
int br = (bb & 0xFF0000); // 0x00FF0000
int bg = (bb & 0xFF00); // 0x0000FF00
bb = (bb & 0xFF); // 0x000000FF
m_pixels[xstart] = 0xFF000000 |
((br + (((red - br) * al) >> 8)) & 0xFF0000) |
((bg + (((grn - bg) * al) >> 8)) & 0xFF00) |
((bb + (((blu - bb) * al) >> 8)) & 0xFF);
} else {
int red = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)];
al = al * (red >>> 24) >> 8;
int grn = red & 0xFF00;
int blu = red & 0xFF;
red&=0xFF0000;
// get buffer pixels
int bb = m_pixels[xstart];
int br = (bb & 0xFF0000); // 0x00FF0000
int bg = (bb & 0xFF00); // 0x0000FF00
bb = (bb & 0xFF); // 0x000000FF
m_pixels[xstart] = 0xFF000000 |
((br + (((red - br) * al) >> 8)) & 0xFF0000) |
((bg + (((grn - bg) * al) >> 8)) & 0xFF00) |
((bb + (((blu - bb) * al) >> 8)) & 0xFF);
}
// m_stencil[xstart] = p;
}
} catch (Exception e) { }
xpixel++;//accurate mode
if (!accurateMode){
iu+=iuadd;
iv+=ivadd;
}
ia+=iaadd;
iz+=izadd;
}
ypixel++;//accurate mode
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
uleft+=uleftadd;
vleft+=vleftadd;
zleft+=zleftadd;
aleft+=aleftadd;
}
}
/**
* Gouraud blended with 8-bit alpha texture
*/
private void drawsegment_gouraud_texture8(float leftadd,
float rghtadd,
int ytop,
int ybottom) {
//Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details
int ypixel = ytop;
int lastRowStart = m_texture.length - TEX_WIDTH - 2;
boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES];
float screenx = 0; float screeny = 0; float screenz = 0;
float a = 0; float b = 0; float c = 0;
int linearInterpPower = TEX_INTERP_POWER;
int linearInterpLength = 1 << linearInterpPower;
if (accurateMode){
if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup
newax *= linearInterpLength;
newbx *= linearInterpLength;
newcx *= linearInterpLength;
screenz = nearPlaneDepth;
firstSegment = false;
} else{
accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate)
}
}
ytop *= SCREEN_WIDTH;
ybottom *= SCREEN_WIDTH;
// int p = m_index;
float iuf = iuadd;
float ivf = ivadd;
float irf = iradd;
float igf = igadd;
float ibf = ibadd;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xpixel = xstart;//accurate mode
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
int iu = (int) (iuf * xdiff + uleft);
int iv = (int) (ivf * xdiff + vleft);
int ir = (int) (irf * xdiff + rleft);
int ig = (int) (igf * xdiff + gleft);
int ib = (int) (ibf * xdiff + bleft);
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
if (accurateMode){
screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f));
screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f));
a = screenx*ax+screeny*ay+screenz*az;
b = screenx*bx+screeny*by+screenz*bz;
c = screenx*cx+screeny*cy+screenz*cz;
}
boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true;
int interpCounter = 0;
int deltaU = 0; int deltaV = 0;
float fu = 0; float fv = 0;
float oldfu = 0; float oldfv = 0;
if (accurateMode&&goingIn){
int rightOffset = (xend-xstart-1)%linearInterpLength;
int leftOffset = linearInterpLength-rightOffset;
float rightOffset2 = rightOffset / ((float)linearInterpLength);
float leftOffset2 = leftOffset / ((float)linearInterpLength);
interpCounter = leftOffset;
float ao = a-leftOffset2*newax;
float bo = b-leftOffset2*newbx;
float co = c-leftOffset2*newcx;
float oneoverc = 65536.0f/co;
oldfu = (ao*oneoverc); oldfv = (bo*oneoverc);
a += rightOffset2*newax;
b += rightOffset2*newbx;
c += rightOffset2*newcx;
oneoverc = 65536.0f/c;
fu = a*oneoverc; fv = b*oneoverc;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack
} else{
float preoneoverc = 65536.0f/c;
fu = (a*preoneoverc);
fv = (b*preoneoverc);
}
for ( ; xstart < xend; xstart++ ) {
if(accurateMode){
if (interpCounter == linearInterpLength) interpCounter = 0;
if (interpCounter == 0){
a += newax;
b += newbx;
c += newcx;
float oneoverc = 65536.0f/c;
oldfu = fu; oldfv = fv;
fu = (a*oneoverc); fv = (b*oneoverc);
iu = (int)oldfu; iv = (int)oldfv;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
} else{
iu += deltaU;
iv += deltaV;
}
interpCounter++;
}
try
{
if (noDepthTest || (iz <= m_zbuffer[xstart])) {
//m_zbuffer[xstart] = iz;
int al0;
if (m_bilinear) {
int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16);
int iui = iu & 0xFFFF;
al0 = m_texture[ofs] & 0xFF;
int al1 = m_texture[ofs + 1] & 0xFF;
if (ofs < lastRowStart) ofs+=TEX_WIDTH;
int al2 = m_texture[ofs] & 0xFF;
int al3 = m_texture[ofs + 1] & 0xFF;
al0 = al0 + (((al1-al0) * iui) >> 16);
al2 = al2 + (((al3-al2) * iui) >> 16);
al0 = al0 + (((al2-al0) * (iv & 0xFFFF)) >> 16);
} else {
al0 = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)] & 0xFF;
}
// get RGB colors
int red = ir & 0xFF0000;
int grn = (ig >> 8) & 0xFF00;
int blu = (ib >> 16);
// get buffer pixels
int bb = m_pixels[xstart];
int br = (bb & 0xFF0000); // 0x00FF0000
int bg = (bb & 0xFF00); // 0x0000FF00
bb = (bb & 0xFF); // 0x000000FF
m_pixels[xstart] = 0xFF000000 |
((br + (((red - br) * al0) >> 8)) & 0xFF0000) |
((bg + (((grn - bg) * al0) >> 8)) & 0xFF00) |
((bb + (((blu - bb) * al0) >> 8)) & 0xFF);
// write stencil
// m_stencil[xstart] = p;
}
}
catch (Exception e) {
}
//
xpixel++;//accurate mode
if (!accurateMode){
iu+=iuadd;
iv+=ivadd;
}
ir+=iradd;
ig+=igadd;
ib+=ibadd;
iz+=izadd;
}
ypixel++;//accurate mode
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
uleft+=uleftadd;
vleft+=vleftadd;
rleft+=rleftadd;
gleft+=gleftadd;
bleft+=bleftadd;
zleft+=zleftadd;
}
}
/**
* Texture multiplied with gouraud
*/
private void drawsegment_gouraud_texture8_alpha(float leftadd,
float rghtadd,
int ytop,
int ybottom) {
// Accurate texture mode added - comments stripped from dupe code,
// see drawsegment_texture24() for details
int ypixel = ytop;
int lastRowStart = m_texture.length - TEX_WIDTH - 2;
boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES];
float screenx = 0; float screeny = 0; float screenz = 0;
float a = 0; float b = 0; float c = 0;
int linearInterpPower = TEX_INTERP_POWER;
int linearInterpLength = 1 << linearInterpPower;
if (accurateMode) {
// see if the precomputation goes well, if so finish the setup
if (precomputeAccurateTexturing()) {
newax *= linearInterpLength;
newbx *= linearInterpLength;
newcx *= linearInterpLength;
screenz = nearPlaneDepth;
firstSegment = false;
} else{
// if the matrix inversion screwed up,
// revert to normal rendering (something is degenerate)
accurateMode = false;
}
}
ytop *= SCREEN_WIDTH;
ybottom *= SCREEN_WIDTH;
// int p = m_index;
float iuf = iuadd;
float ivf = ivadd;
float irf = iradd;
float igf = igadd;
float ibf = ibadd;
float iaf = iaadd;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xpixel = xstart;//accurate mode
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
int iu = (int) (iuf * xdiff + uleft);
int iv = (int) (ivf * xdiff + vleft);
int ir = (int) (irf * xdiff + rleft);
int ig = (int) (igf * xdiff + gleft);
int ib = (int) (ibf * xdiff + bleft);
int ia = (int) (iaf * xdiff + aleft);
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
if (accurateMode){
screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f));
screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f));
a = screenx*ax+screeny*ay+screenz*az;
b = screenx*bx+screeny*by+screenz*bz;
c = screenx*cx+screeny*cy+screenz*cz;
}
boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true;
int interpCounter = 0;
int deltaU = 0; int deltaV = 0;
float fu = 0; float fv = 0;
float oldfu = 0; float oldfv = 0;
if (accurateMode&&goingIn){
int rightOffset = (xend-xstart-1)%linearInterpLength;
int leftOffset = linearInterpLength-rightOffset;
float rightOffset2 = rightOffset / ((float)linearInterpLength);
float leftOffset2 = leftOffset / ((float)linearInterpLength);
interpCounter = leftOffset;
float ao = a-leftOffset2*newax;
float bo = b-leftOffset2*newbx;
float co = c-leftOffset2*newcx;
float oneoverc = 65536.0f/co;
oldfu = (ao*oneoverc); oldfv = (bo*oneoverc);
a += rightOffset2*newax;
b += rightOffset2*newbx;
c += rightOffset2*newcx;
oneoverc = 65536.0f/c;
fu = a*oneoverc; fv = b*oneoverc;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack
} else{
float preoneoverc = 65536.0f/c;
fu = (a*preoneoverc);
fv = (b*preoneoverc);
}
for ( ; xstart < xend; xstart++ ) {
if(accurateMode){
if (interpCounter == linearInterpLength) interpCounter = 0;
if (interpCounter == 0){
a += newax;
b += newbx;
c += newcx;
float oneoverc = 65536.0f/c;
oldfu = fu; oldfv = fv;
fu = (a*oneoverc); fv = (b*oneoverc);
iu = (int)oldfu; iv = (int)oldfv;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
} else{
iu += deltaU;
iv += deltaV;
}
interpCounter++;
}
try {
if (noDepthTest || (iz <= m_zbuffer[xstart])) {
//m_zbuffer[xstart] = iz;
int al0;
if (m_bilinear) {
int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16);
int iui = iu & 0xFFFF;
al0 = m_texture[ofs] & 0xFF;
int al1 = m_texture[ofs + 1] & 0xFF;
if (ofs < lastRowStart) ofs+=TEX_WIDTH;
int al2 = m_texture[ofs] & 0xFF;
int al3 = m_texture[ofs + 1] & 0xFF;
al0 = al0 + (((al1-al0) * iui) >> 16);
al2 = al2 + (((al3-al2) * iui) >> 16);
al0 = al0 + (((al2-al0) * (iv & 0xFFFF)) >> 16);
} else {
al0 = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)] & 0xFF;
}
al0 = (al0 * (ia >> 16)) >> 8;
// get RGB colors
int red = ir & 0xFF0000;
int grn = (ig >> 8) & 0xFF00;
int blu = (ib >> 16);
// get buffer pixels
int bb = m_pixels[xstart];
int br = (bb & 0xFF0000); // 0x00FF0000
int bg = (bb & 0xFF00); // 0x0000FF00
bb = (bb & 0xFF); // 0x000000FF
m_pixels[xstart] = 0xFF000000 |
((br + (((red - br) * al0) >> 8)) & 0xFF0000) |
((bg + (((grn - bg) * al0) >> 8)) & 0xFF00) |
((bb + (((blu - bb) * al0) >> 8)) & 0xFF);
// write stencil
// m_stencil[xstart] = p;
}
} catch (Exception e) { }
//
xpixel++;//accurate mode
if (!accurateMode){
iu+=iuadd;
iv+=ivadd;
}
ir+=iradd;
ig+=igadd;
ib+=ibadd;
ia+=iaadd;
iz+=izadd;
}
ypixel++;//accurate mode
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
uleft+=uleftadd;
vleft+=vleftadd;
rleft+=rleftadd;
gleft+=gleftadd;
bleft+=bleftadd;
aleft+=aleftadd;
zleft+=zleftadd;
}
}
/**
* Texture multiplied with gouraud
*/
private void drawsegment_gouraud_texture24(float leftadd,
float rghtadd,
int ytop,
int ybottom) {
//Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details
int ypixel = ytop;
int lastRowStart = m_texture.length - TEX_WIDTH - 2;
boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES];
float screenx = 0; float screeny = 0; float screenz = 0;
float a = 0; float b = 0; float c = 0;
int linearInterpPower = TEX_INTERP_POWER;
int linearInterpLength = 1 << linearInterpPower;
if (accurateMode){
if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup
newax *= linearInterpLength;
newbx *= linearInterpLength;
newcx *= linearInterpLength;
screenz = nearPlaneDepth;
firstSegment = false;
} else{
accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate)
}
}
ytop *= SCREEN_WIDTH;
ybottom *= SCREEN_WIDTH;
// int p = m_index;
float iuf = iuadd;
float ivf = ivadd;
float irf = iradd;
float igf = igadd;
float ibf = ibadd;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xpixel = xstart;//accurate mode
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
int iu = (int) (iuf * xdiff + uleft);
int iv = (int) (ivf * xdiff + vleft);
int ir = (int) (irf * xdiff + rleft);
int ig = (int) (igf * xdiff + gleft);
int ib = (int) (ibf * xdiff + bleft);
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
if (accurateMode){
screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f));
screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f));
a = screenx*ax+screeny*ay+screenz*az;
b = screenx*bx+screeny*by+screenz*bz;
c = screenx*cx+screeny*cy+screenz*cz;
}
boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true;
int interpCounter = 0;
int deltaU = 0; int deltaV = 0;
float fu = 0; float fv = 0;
float oldfu = 0; float oldfv = 0;
if (accurateMode&&goingIn){
int rightOffset = (xend-xstart-1)%linearInterpLength;
int leftOffset = linearInterpLength-rightOffset;
float rightOffset2 = rightOffset / ((float)linearInterpLength);
float leftOffset2 = leftOffset / ((float)linearInterpLength);
interpCounter = leftOffset;
float ao = a-leftOffset2*newax;
float bo = b-leftOffset2*newbx;
float co = c-leftOffset2*newcx;
float oneoverc = 65536.0f/co;
oldfu = (ao*oneoverc); oldfv = (bo*oneoverc);
a += rightOffset2*newax;
b += rightOffset2*newbx;
c += rightOffset2*newcx;
oneoverc = 65536.0f/c;
fu = a*oneoverc; fv = b*oneoverc;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack
} else{
float preoneoverc = 65536.0f/c;
fu = (a*preoneoverc);
fv = (b*preoneoverc);
}
for ( ; xstart < xend; xstart++ ) {
if(accurateMode){
if (interpCounter == linearInterpLength) interpCounter = 0;
if (interpCounter == 0){
a += newax;
b += newbx;
c += newcx;
float oneoverc = 65536.0f/c;
oldfu = fu; oldfv = fv;
fu = (a*oneoverc); fv = (b*oneoverc);
iu = (int)oldfu; iv = (int)oldfv;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
} else{
iu += deltaU;
iv += deltaV;
}
interpCounter++;
}
try {
if (noDepthTest || (iz <= m_zbuffer[xstart])) {
m_zbuffer[xstart] = iz;
int red;
int grn;
int blu;
if (m_bilinear) {
int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16);
int iui = (iu & 0xFFFF) >> 9;
int ivi = (iv & 0xFFFF) >> 9;
// get texture pixels
int pix0 = m_texture[ofs];
int pix1 = m_texture[ofs + 1];
if (ofs < lastRowStart) ofs+=TEX_WIDTH;
int pix2 = m_texture[ofs];
int pix3 = m_texture[ofs + 1];
// red
int red0 = (pix0 & 0xFF0000);
int red2 = (pix2 & 0xFF0000);
int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7);
int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7);
red = up + (((dn-up) * ivi) >> 7);
// grn
red0 = (pix0 & 0xFF00);
red2 = (pix2 & 0xFF00);
up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7);
grn = up + (((dn-up) * ivi) >> 7);
// blu
red0 = (pix0 & 0xFF);
red2 = (pix2 & 0xFF);
up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7);
blu = up + (((dn-up) * ivi) >> 7);
} else {
// get texture pixel color
blu = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)];
red = (blu & 0xFF0000);
grn = (blu & 0xFF00);
blu = blu & 0xFF;
}
//
int r = (ir >> 16);
int g = (ig >> 16);
// oops, namespace collision with accurate
// texture vector b...sorry [ewjordan]
int bb2 = (ib >> 16);
m_pixels[xstart] = 0xFF000000 |
((((red * r) & 0xFF000000) | ((grn * g) & 0xFF0000) | (blu * bb2)) >> 8);
// m_stencil[xstart] = p;
}
} catch (Exception e) { }
//
xpixel++;//accurate mode
if (!accurateMode){
iu+=iuadd;
iv+=ivadd;
}
ir+=iradd;
ig+=igadd;
ib+=ibadd;
iz+=izadd;
}
ypixel++;//accurate mode
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
uleft+=uleftadd;
vleft+=vleftadd;
rleft+=rleftadd;
gleft+=gleftadd;
bleft+=bleftadd;
zleft+=zleftadd;
}
}
/**
* Gouraud*texture blended with interpolating alpha
*/
private void drawsegment_gouraud_texture24_alpha
(
float leftadd,
float rghtadd,
int ytop,
int ybottom
) {
//Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details
int ypixel = ytop;
int lastRowStart = m_texture.length - TEX_WIDTH - 2;
boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES];
float screenx = 0; float screeny = 0; float screenz = 0;
float a = 0; float b = 0; float c = 0;
int linearInterpPower = TEX_INTERP_POWER;
int linearInterpLength = 1 << linearInterpPower;
if (accurateMode){
if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup
newax *= linearInterpLength;
newbx *= linearInterpLength;
newcx *= linearInterpLength;
screenz = nearPlaneDepth;
firstSegment = false;
} else{
accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate)
}
}
ytop *= SCREEN_WIDTH;
ybottom *= SCREEN_WIDTH;
// int p = m_index;
float iuf = iuadd;
float ivf = ivadd;
float irf = iradd;
float igf = igadd;
float ibf = ibadd;
float iaf = iaadd;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xpixel = xstart;//accurate mode
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
int iu = (int) (iuf * xdiff + uleft);
int iv = (int) (ivf * xdiff + vleft);
int ir = (int) (irf * xdiff + rleft);
int ig = (int) (igf * xdiff + gleft);
int ib = (int) (ibf * xdiff + bleft);
int ia = (int) (iaf * xdiff + aleft);
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
if (accurateMode){
screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f));
screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f));
a = screenx*ax+screeny*ay+screenz*az;
b = screenx*bx+screeny*by+screenz*bz;
c = screenx*cx+screeny*cy+screenz*cz;
}
boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true;
int interpCounter = 0;
int deltaU = 0; int deltaV = 0;
float fu = 0; float fv = 0;
float oldfu = 0; float oldfv = 0;
if (accurateMode&&goingIn){
int rightOffset = (xend-xstart-1)%linearInterpLength;
int leftOffset = linearInterpLength-rightOffset;
float rightOffset2 = rightOffset / ((float)linearInterpLength);
float leftOffset2 = leftOffset / ((float)linearInterpLength);
interpCounter = leftOffset;
float ao = a-leftOffset2*newax;
float bo = b-leftOffset2*newbx;
float co = c-leftOffset2*newcx;
float oneoverc = 65536.0f/co;
oldfu = (ao*oneoverc); oldfv = (bo*oneoverc);
a += rightOffset2*newax;
b += rightOffset2*newbx;
c += rightOffset2*newcx;
oneoverc = 65536.0f/c;
fu = a*oneoverc; fv = b*oneoverc;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack
} else{
float preoneoverc = 65536.0f/c;
fu = (a*preoneoverc);
fv = (b*preoneoverc);
}
for ( ;xstart < xend; xstart++ ) {
if(accurateMode){
if (interpCounter == linearInterpLength) interpCounter = 0;
if (interpCounter == 0){
a += newax;
b += newbx;
c += newcx;
float oneoverc = 65536.0f/c;
oldfu = fu; oldfv = fv;
fu = (a*oneoverc); fv = (b*oneoverc);
iu = (int)oldfu; iv = (int)oldfv;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
} else{
iu += deltaU;
iv += deltaV;
}
interpCounter++;
}
// get texture pixel color
try
{
//if (iz < m_zbuffer[xstart]) {
if (noDepthTest || (iz <= m_zbuffer[xstart])) { // [fry 041114]
//m_zbuffer[xstart] = iz;
// blend
int al = ia >> 16;
int red;
int grn;
int blu;
if (m_bilinear) {
int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16);
int iui = (iu & 0xFFFF) >> 9;
int ivi = (iv & 0xFFFF) >> 9;
// get texture pixels
int pix0 = m_texture[ofs];
int pix1 = m_texture[ofs + 1];
if (ofs < lastRowStart) ofs+=TEX_WIDTH;
int pix2 = m_texture[ofs];
int pix3 = m_texture[ofs + 1];
// red
int red0 = (pix0 & 0xFF0000);
int red2 = (pix2 & 0xFF0000);
int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7);
int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7);
red = (up + (((dn-up) * ivi) >> 7)) >> 16;
// grn
red0 = (pix0 & 0xFF00);
red2 = (pix2 & 0xFF00);
up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7);
grn = (up + (((dn-up) * ivi) >> 7)) >> 8;
// blu
red0 = (pix0 & 0xFF);
red2 = (pix2 & 0xFF);
up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7);
blu = up + (((dn-up) * ivi) >> 7);
} else {
blu = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)];
red = (blu & 0xFF0000) >> 16; // 0 - 255
grn = (blu & 0xFF00) >> 8; // 0 - 255
blu = (blu & 0xFF); // 0 - 255
}
// multiply with gouraud color
red = (red * ir) >>> 8; // 0x00FF????
grn = (grn * ig) >>> 16; // 0x0000FF??
blu = (blu * ib) >>> 24; // 0x000000FF
// get buffer pixels
int bb = m_pixels[xstart];
int br = (bb & 0xFF0000); // 0x00FF0000
int bg = (bb & 0xFF00); // 0x0000FF00
bb = (bb & 0xFF); // 0x000000FF
//
m_pixels[xstart] = 0xFF000000 |
((br + (((red - br) * al) >> 8)) & 0xFF0000) |
((bg + (((grn - bg) * al) >> 8)) & 0xFF00) |
((bb + (((blu - bb) * al) >> 8)) & 0xFF);
// m_stencil[xstart] = p;
}
}
catch (Exception e) {
}
//
xpixel++;//accurate mode
if (!accurateMode){
iu+=iuadd;
iv+=ivadd;
}
ir+=iradd;
ig+=igadd;
ib+=ibadd;
ia+=iaadd;
iz+=izadd;
}
ypixel++;//accurate mode
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
uleft+=uleftadd;
vleft+=vleftadd;
rleft+=rleftadd;
gleft+=gleftadd;
bleft+=bleftadd;
aleft+=aleftadd;
zleft+=zleftadd;
}
}
/**
* Gouraud*texture blended with interpolating alpha
*/
private void drawsegment_gouraud_texture32
(
float leftadd,
float rghtadd,
int ytop,
int ybottom
) {
//Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details
int ypixel = ytop;
int lastRowStart = m_texture.length - TEX_WIDTH - 2;
boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES];
float screenx = 0; float screeny = 0; float screenz = 0;
float a = 0; float b = 0; float c = 0;
int linearInterpPower = TEX_INTERP_POWER;
int linearInterpLength = 1 << linearInterpPower;
if (accurateMode){
if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup
newax *= linearInterpLength;
newbx *= linearInterpLength;
newcx *= linearInterpLength;
screenz = nearPlaneDepth;
firstSegment = false;
} else{
accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate)
}
}
ytop*=SCREEN_WIDTH;
ybottom*=SCREEN_WIDTH;
//int p = m_index;
float iuf = iuadd;
float ivf = ivadd;
float irf = iradd;
float igf = igadd;
float ibf = ibadd;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xpixel = xstart;//accurate mode
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
int iu = (int) (iuf * xdiff + uleft);
int iv = (int) (ivf * xdiff + vleft);
int ir = (int) (irf * xdiff + rleft);
int ig = (int) (igf * xdiff + gleft);
int ib = (int) (ibf * xdiff + bleft);
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
if (accurateMode){
screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f));
screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f));
a = screenx*ax+screeny*ay+screenz*az;
b = screenx*bx+screeny*by+screenz*bz;
c = screenx*cx+screeny*cy+screenz*cz;
}
boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true;
int interpCounter = 0;
int deltaU = 0; int deltaV = 0;
float fu = 0; float fv = 0;
float oldfu = 0; float oldfv = 0;
if (accurateMode&&goingIn){
int rightOffset = (xend-xstart-1)%linearInterpLength;
int leftOffset = linearInterpLength-rightOffset;
float rightOffset2 = rightOffset / ((float)linearInterpLength);
float leftOffset2 = leftOffset / ((float)linearInterpLength);
interpCounter = leftOffset;
float ao = a-leftOffset2*newax;
float bo = b-leftOffset2*newbx;
float co = c-leftOffset2*newcx;
float oneoverc = 65536.0f/co;
oldfu = (ao*oneoverc); oldfv = (bo*oneoverc);
a += rightOffset2*newax;
b += rightOffset2*newbx;
c += rightOffset2*newcx;
oneoverc = 65536.0f/c;
fu = a*oneoverc; fv = b*oneoverc;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack
} else{
float preoneoverc = 65536.0f/c;
fu = (a*preoneoverc);
fv = (b*preoneoverc);
}
for ( ; xstart < xend; xstart++ ) {
if(accurateMode){
if (interpCounter == linearInterpLength) interpCounter = 0;
if (interpCounter == 0){
a += newax;
b += newbx;
c += newcx;
float oneoverc = 65536.0f/c;
oldfu = fu; oldfv = fv;
fu = (a*oneoverc); fv = (b*oneoverc);
iu = (int)oldfu; iv = (int)oldfv;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
} else{
iu += deltaU;
iv += deltaV;
}
interpCounter++;
}
try {
if (noDepthTest || (iz <= m_zbuffer[xstart])) {
//m_zbuffer[xstart] = iz;
int red;
int grn;
int blu;
int al;
if (m_bilinear) {
int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16);
int iui = (iu & 0xFFFF) >> 9;
int ivi = (iv & 0xFFFF) >> 9;
// get texture pixels
int pix0 = m_texture[ofs];
int pix1 = m_texture[ofs + 1];
if (ofs < lastRowStart) ofs+=TEX_WIDTH;
int pix2 = m_texture[ofs];
int pix3 = m_texture[ofs + 1];
// red
int red0 = (pix0 & 0xFF0000);
int red2 = (pix2 & 0xFF0000);
int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7);
int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7);
red = (up + (((dn-up) * ivi) >> 7)) >> 16;
// grn
red0 = (pix0 & 0xFF00);
red2 = (pix2 & 0xFF00);
up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7);
grn = (up + (((dn-up) * ivi) >> 7)) >> 8;
// blu
red0 = (pix0 & 0xFF);
red2 = (pix2 & 0xFF);
up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7);
blu = up + (((dn-up) * ivi) >> 7);
// alpha
pix0>>>=24;
pix2>>>=24;
up = pix0 + ((((pix1 >>> 24) - pix0) * iui) >> 7);
dn = pix2 + ((((pix3 >>> 24) - pix2) * iui) >> 7);
al = up + (((dn-up) * ivi) >> 7);
} else {
// get texture pixel color
blu = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)];
al = (blu >>> 24);
red = (blu & 0xFF0000) >> 16;
grn = (blu & 0xFF00) >> 8;
blu = blu & 0xFF;
}
// multiply with gouraud color
red = (red * ir) >>> 8; // 0x00FF????
grn = (grn * ig) >>> 16; // 0x0000FF??
blu = (blu * ib) >>> 24; // 0x000000FF
// get buffer pixels
int bb = m_pixels[xstart];
int br = (bb & 0xFF0000); // 0x00FF0000
int bg = (bb & 0xFF00); // 0x0000FF00
bb = (bb & 0xFF); // 0x000000FF
//
m_pixels[xstart] = 0xFF000000 |
((br + (((red - br) * al) >> 8)) & 0xFF0000) |
((bg + (((grn - bg) * al) >> 8)) & 0xFF00) |
((bb + (((blu - bb) * al) >> 8)) & 0xFF);
}
} catch (Exception e) { }
//
xpixel++;//accurate mode
if (!accurateMode){
iu+=iuadd;
iv+=ivadd;
}
ir+=iradd;
ig+=igadd;
ib+=ibadd;
iz+=izadd;
}
ypixel++;//accurate mode
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
uleft+=uleftadd;
vleft+=vleftadd;
rleft+=rleftadd;
gleft+=gleftadd;
bleft+=bleftadd;
zleft+=zleftadd;
}
}
/**
* Gouraud*texture blended with interpolating alpha
*/
private void drawsegment_gouraud_texture32_alpha
(
float leftadd,
float rghtadd,
int ytop,
int ybottom
) {
//Accurate texture mode added - comments stripped from dupe code, see drawsegment_texture24() for details
int ypixel = ytop;
int lastRowStart = m_texture.length - TEX_WIDTH - 2;
boolean accurateMode = parent.hints[ENABLE_ACCURATE_TEXTURES];
float screenx = 0; float screeny = 0; float screenz = 0;
float a = 0; float b = 0; float c = 0;
int linearInterpPower = TEX_INTERP_POWER;
int linearInterpLength = 1 << linearInterpPower;
if (accurateMode){
if(precomputeAccurateTexturing()){ //see if the precomputation goes well, if so finish the setup
newax *= linearInterpLength;
newbx *= linearInterpLength;
newcx *= linearInterpLength;
screenz = nearPlaneDepth;
firstSegment = false;
} else{
accurateMode = false; //if the matrix inversion screwed up, revert to normal rendering (something is degenerate)
}
}
ytop *= SCREEN_WIDTH;
ybottom *= SCREEN_WIDTH;
// int p = m_index;
float iuf = iuadd;
float ivf = ivadd;
float irf = iradd;
float igf = igadd;
float ibf = ibadd;
float iaf = iaadd;
while (ytop < ybottom) {
int xstart = (int) (xleft + PIXEL_CENTER);
if (xstart < 0)
xstart = 0;
int xpixel = xstart;//accurate mode
int xend = (int) (xrght + PIXEL_CENTER);
if (xend > SCREEN_WIDTH)
xend = SCREEN_WIDTH;
float xdiff = (xstart + PIXEL_CENTER) - xleft;
int iu = (int) (iuf * xdiff + uleft);
int iv = (int) (ivf * xdiff + vleft);
int ir = (int) (irf * xdiff + rleft);
int ig = (int) (igf * xdiff + gleft);
int ib = (int) (ibf * xdiff + bleft);
int ia = (int) (iaf * xdiff + aleft);
float iz = izadd * xdiff + zleft;
xstart+=ytop;
xend+=ytop;
if (accurateMode){
screenx = xmult*(xpixel+.5f-(SCREEN_WIDTH/2.0f));
screeny = ymult*(ypixel+.5f-(SCREEN_HEIGHT/2.0f));
a = screenx*ax+screeny*ay+screenz*az;
b = screenx*bx+screeny*by+screenz*bz;
c = screenx*cx+screeny*cy+screenz*cz;
}
boolean goingIn = ( (newcx > 0) == (c > 0) )?false:true;
int interpCounter = 0;
int deltaU = 0; int deltaV = 0;
float fu = 0; float fv = 0;
float oldfu = 0; float oldfv = 0;
if (accurateMode&&goingIn){
int rightOffset = (xend-xstart-1)%linearInterpLength;
int leftOffset = linearInterpLength-rightOffset;
float rightOffset2 = rightOffset / ((float)linearInterpLength);
float leftOffset2 = leftOffset / ((float)linearInterpLength);
interpCounter = leftOffset;
float ao = a-leftOffset2*newax;
float bo = b-leftOffset2*newbx;
float co = c-leftOffset2*newcx;
float oneoverc = 65536.0f/co;
oldfu = (ao*oneoverc); oldfv = (bo*oneoverc);
a += rightOffset2*newax;
b += rightOffset2*newbx;
c += rightOffset2*newcx;
oneoverc = 65536.0f/c;
fu = a*oneoverc; fv = b*oneoverc;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
iu = ( (int)oldfu )+(leftOffset-1)*deltaU; iv = ( (int)oldfv )+(leftOffset-1)*deltaV; //another "off-by-one" hack
} else{
float preoneoverc = 65536.0f/c;
fu = (a*preoneoverc);
fv = (b*preoneoverc);
}
for ( ;xstart < xend; xstart++ ) {
if(accurateMode){
if (interpCounter == linearInterpLength) interpCounter = 0;
if (interpCounter == 0){
a += newax;
b += newbx;
c += newcx;
float oneoverc = 65536.0f/c;
oldfu = fu; oldfv = fv;
fu = (a*oneoverc); fv = (b*oneoverc);
iu = (int)oldfu; iv = (int)oldfv;
deltaU = ((int)(fu - oldfu)) >> linearInterpPower;
deltaV = ((int)(fv - oldfv)) >> linearInterpPower;
} else{
iu += deltaU;
iv += deltaV;
}
interpCounter++;
}
// get texture pixel color
try {
//if (iz < m_zbuffer[xstart]) {
if (noDepthTest || (iz <= m_zbuffer[xstart])) { // [fry 041114]
//m_zbuffer[xstart] = iz;
// blend
int al = ia >> 16;
int red;
int grn;
int blu;
if (m_bilinear) {
int ofs = (iv >> 16) * TEX_WIDTH + (iu >> 16);
int iui = (iu & 0xFFFF) >> 9;
int ivi = (iv & 0xFFFF) >> 9;
// get texture pixels
int pix0 = m_texture[ofs];
int pix1 = m_texture[ofs + 1];
if (ofs < lastRowStart) ofs+=TEX_WIDTH;
int pix2 = m_texture[ofs];
int pix3 = m_texture[ofs + 1];
// red
int red0 = (pix0 & 0xFF0000);
int red2 = (pix2 & 0xFF0000);
int up = red0 + ((((pix1 & 0xFF0000) - red0) * iui) >> 7);
int dn = red2 + ((((pix3 & 0xFF0000) - red2) * iui) >> 7);
red = (up + (((dn-up) * ivi) >> 7)) >> 16;
// grn
red0 = (pix0 & 0xFF00);
red2 = (pix2 & 0xFF00);
up = red0 + ((((pix1 & 0xFF00) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF00) - red2) * iui) >> 7);
grn = (up + (((dn-up) * ivi) >> 7)) >> 8;
// blu
red0 = (pix0 & 0xFF);
red2 = (pix2 & 0xFF);
up = red0 + ((((pix1 & 0xFF) - red0) * iui) >> 7);
dn = red2 + ((((pix3 & 0xFF) - red2) * iui) >> 7);
blu = up + (((dn-up) * ivi) >> 7);
// alpha
pix0>>>=24;
pix2>>>=24;
up = pix0 + ((((pix1 >>> 24) - pix0) * iui) >> 7);
dn = pix2 + ((((pix3 >>> 24) - pix2) * iui) >> 7);
al = al * (up + (((dn-up) * ivi) >> 7)) >> 8;
} else {
blu = m_texture[(iv >> 16) * TEX_WIDTH + (iu >> 16)];
al = al * (blu >>> 24) >> 8;
red = (blu & 0xFF0000) >> 16; // 0 - 255
grn = (blu & 0xFF00) >> 8; // 0 - 255
blu = (blu & 0xFF); // 0 - 255
}
// multiply with gouraud color
red = (red * ir) >>> 8; // 0x00FF????
grn = (grn * ig) >>> 16; // 0x0000FF??
blu = (blu * ib) >>> 24; // 0x000000FF
// get buffer pixels
int bb = m_pixels[xstart];
int br = (bb & 0xFF0000); // 0x00FF0000
int bg = (bb & 0xFF00); // 0x0000FF00
bb = (bb & 0xFF); // 0x000000FF
//
m_pixels[xstart] = 0xFF000000 |
((br + (((red - br) * al) >> 8)) & 0xFF0000) |
((bg + (((grn - bg) * al) >> 8)) & 0xFF00) |
((bb + (((blu - bb) * al) >> 8)) & 0xFF);
// m_stencil[xstart] = p;
}
} catch (Exception e) { }
//
xpixel++;//accurate mode
if (!accurateMode){
iu+=iuadd;
iv+=ivadd;
}
ir+=iradd;
ig+=igadd;
ib+=ibadd;
ia+=iaadd;
iz+=izadd;
}
ypixel++;//accurate mode
ytop+=SCREEN_WIDTH;
xleft+=leftadd;
xrght+=rghtadd;
uleft+=uleftadd;
vleft+=vleftadd;
rleft+=rleftadd;
gleft+=gleftadd;
bleft+=bleftadd;
aleft+=aleftadd;
zleft+=zleftadd;
}
}
}
processing-core-1.2.1/src/processing/core/PShapeSVG.java 0000644 0001750 0001750 00000143724 11411146532 022446 0 ustar andrew andrew /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2006-10 Ben Fry and Casey Reas
Copyright (c) 2004-06 Michael Chang
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 2.1 as published by the Free Software Foundation.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
import java.awt.Paint;
import java.awt.PaintContext;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.ColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.util.HashMap;
import processing.xml.XMLElement;
/**
* SVG stands for Scalable Vector Graphics, a portable graphics format. It is
* a vector format so it allows for infinite resolution and relatively small
* file sizes. Most modern media software can view SVG files, including Adobe
* products, Firefox, etc. Illustrator and Inkscape can edit SVG files.
*
* We have no intention of turning this into a full-featured SVG library.
* The goal of this project is a basic shape importer that is small enough
* to be included with applets, meaning that its download size should be
* in the neighborhood of 25-30k. Starting with release 0149, this library
* has been incorporated into the core via the loadShape() command, because
* vector shape data is just as important as the image data from loadImage().
*
* For more sophisticated import/export, consider the
* Batik
* library from the Apache Software Foundation. Future improvements to this
* library may focus on this properly supporting a specific subset of SVG,
* for instance the simpler SVG profiles known as
* SVG Tiny or Basic,
* although we still would not support the interactivity options.
*
*
*
* A minimal example program using SVG:
* (assuming a working moo.svg is in your data folder)
*
*
*
* Late October 2008 revisions from ricardmp, incorporated by fry (0154)
*
*
* For releases 0116 and later, if you have problems such as those seen
* in Bugs 279 and 305, use Applet.getImage() instead. You'll be stuck
* with the limitations of getImage() (the headache of dealing with
* online/offline use). Set up your own MediaTracker, and pass the resulting
* java.awt.Image to the PImage constructor that takes an AWT image.
*/
public PImage loadImage(String filename) {
return loadImage(filename, null);
}
/**
* Loads an image into a variable of type PImage. Four types of images ( .gif, .jpg, .tga, .png) images may be loaded. To load correctly, images must be located in the data directory of the current sketch. In most cases, load all images in setup() to preload them at the start of the program. Loading images inside draw() will reduce the speed of a program.
*
The filename parameter can also be a URL to a file found online. For security reasons, a Processing sketch found online can only download files from the same server from which it came. Getting around this restriction requires a signed applet.
*
The extension parameter is used to determine the image type in cases where the image filename does not end with a proper extension. Specify the extension as the second parameter to loadImage(), as shown in the third example on this page.
*
If an image is not loaded successfully, the null value is returned and an error message will be printed to the console. The error message does not halt the program, however the null value may cause a NullPointerException if your code does not check whether the value returned from loadImage() is null.
Depending on the type of error, a PImage object may still be returned, but the width and height of the image will be set to -1. This happens if bad image data is returned or cannot be decoded properly. Sometimes this happens with image URLs that produce a 403 error or that redirect to a password prompt, because loadImage() will attempt to interpret the HTML as image data.
*
* =advanced
* Identical to loadImage, but allows you to specify the type of
* image by its extension. Especially useful when downloading from
* CGI scripts.
*
* Use 'unknown' as the extension to pass off to the default
* image loader that handles gif, jpg, and png.
*
* @webref image:loading_displaying
* @param filename name of file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform.
* @param extension the type of image to load, for example "png", "gif", "jpg"
*
* @see processing.core.PImage
* @see processing.core.PApplet#image(PImage, float, float, float, float)
* @see processing.core.PApplet#imageMode(int)
* @see processing.core.PApplet#background(float, float, float)
*/
public PImage loadImage(String filename, String extension) {
if (extension == null) {
String lower = filename.toLowerCase();
int dot = filename.lastIndexOf('.');
if (dot == -1) {
extension = "unknown"; // no extension found
}
extension = lower.substring(dot + 1);
// check for, and strip any parameters on the url, i.e.
// filename.jpg?blah=blah&something=that
int question = extension.indexOf('?');
if (question != -1) {
extension = extension.substring(0, question);
}
}
// just in case. them users will try anything!
extension = extension.toLowerCase();
if (extension.equals("tga")) {
try {
return loadImageTGA(filename);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
if (extension.equals("tif") || extension.equals("tiff")) {
byte bytes[] = loadBytes(filename);
return (bytes == null) ? null : PImage.loadTIFF(bytes);
}
// For jpeg, gif, and png, load them using createImage(),
// because the javax.imageio code was found to be much slower, see
// Bug 392.
try {
if (extension.equals("jpg") || extension.equals("jpeg") ||
extension.equals("gif") || extension.equals("png") ||
extension.equals("unknown")) {
byte bytes[] = loadBytes(filename);
if (bytes == null) {
return null;
} else {
Image awtImage = Toolkit.getDefaultToolkit().createImage(bytes);
PImage image = loadImageMT(awtImage);
if (image.width == -1) {
System.err.println("The file " + filename +
" contains bad image data, or may not be an image.");
}
// if it's a .gif image, test to see if it has transparency
if (extension.equals("gif") || extension.equals("png")) {
image.checkAlpha();
}
return image;
}
}
} catch (Exception e) {
// show error, but move on to the stuff below, see if it'll work
e.printStackTrace();
}
if (loadImageFormats == null) {
loadImageFormats = ImageIO.getReaderFormatNames();
}
if (loadImageFormats != null) {
for (int i = 0; i < loadImageFormats.length; i++) {
if (extension.equals(loadImageFormats[i])) {
return loadImageIO(filename);
}
}
}
// failed, could not load image after all those attempts
System.err.println("Could not find a method to load " + filename);
return null;
}
public PImage requestImage(String filename) {
return requestImage(filename, null);
}
/**
* This function load images on a separate thread so that your sketch does not freeze while images load during setup(). While the image is loading, its width and height will be 0. If an error occurs while loading the image, its width and height will be set to -1. You'll know when the image has loaded properly because its width and height will be greater than 0. Asynchronous image loading (particularly when downloading from a server) can dramatically improve performance.
* The extension parameter is used to determine the image type in cases where the image filename does not end with a proper extension. Specify the extension as the second parameter to requestImage().
*
* @webref image:loading_displaying
* @param filename name of file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform
* @param extension the type of image to load, for example "png", "gif", "jpg"
*
* @see processing.core.PApplet#loadImage(String, String)
* @see processing.core.PImage
*/
public PImage requestImage(String filename, String extension) {
PImage vessel = createImage(0, 0, ARGB);
AsyncImageLoader ail =
new AsyncImageLoader(filename, extension, vessel);
ail.start();
return vessel;
}
/**
* By trial and error, four image loading threads seem to work best when
* loading images from online. This is consistent with the number of open
* connections that web browsers will maintain. The variable is made public
* (however no accessor has been added since it's esoteric) if you really
* want to have control over the value used. For instance, when loading local
* files, it might be better to only have a single thread (or two) loading
* images so that you're disk isn't simply jumping around.
*/
public int requestImageMax = 4;
volatile int requestImageCount;
class AsyncImageLoader extends Thread {
String filename;
String extension;
PImage vessel;
public AsyncImageLoader(String filename, String extension, PImage vessel) {
this.filename = filename;
this.extension = extension;
this.vessel = vessel;
}
public void run() {
while (requestImageCount == requestImageMax) {
try {
Thread.sleep(10);
} catch (InterruptedException e) { }
}
requestImageCount++;
PImage actual = loadImage(filename, extension);
// An error message should have already printed
if (actual == null) {
vessel.width = -1;
vessel.height = -1;
} else {
vessel.width = actual.width;
vessel.height = actual.height;
vessel.format = actual.format;
vessel.pixels = actual.pixels;
}
requestImageCount--;
}
}
/**
* Load an AWT image synchronously by setting up a MediaTracker for
* a single image, and blocking until it has loaded.
*/
protected PImage loadImageMT(Image awtImage) {
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(awtImage, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) {
//e.printStackTrace(); // non-fatal, right?
}
PImage image = new PImage(awtImage);
image.parent = this;
return image;
}
/**
* Use Java 1.4 ImageIO methods to load an image.
*/
protected PImage loadImageIO(String filename) {
InputStream stream = createInput(filename);
if (stream == null) {
System.err.println("The image " + filename + " could not be found.");
return null;
}
try {
BufferedImage bi = ImageIO.read(stream);
PImage outgoing = new PImage(bi.getWidth(), bi.getHeight());
outgoing.parent = this;
bi.getRGB(0, 0, outgoing.width, outgoing.height,
outgoing.pixels, 0, outgoing.width);
// check the alpha for this image
// was gonna call getType() on the image to see if RGB or ARGB,
// but it's not actually useful, since gif images will come through
// as TYPE_BYTE_INDEXED, which means it'll still have to check for
// the transparency. also, would have to iterate through all the other
// types and guess whether alpha was in there, so.. just gonna stick
// with the old method.
outgoing.checkAlpha();
// return the image
return outgoing;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Targa image loader for RLE-compressed TGA files.
*
* The filename parameter can also be a URL to a file found online.
* For security reasons, a Processing sketch found online can only download files from the same server from which it came.
* Getting around this restriction requires a signed applet.
*
* If a shape is not loaded successfully, the null value is returned and an error message will be printed to the console.
* The error message does not halt the program, however the null value may cause a NullPointerException if your code does not check whether the value returned from loadShape() is null.
*
* @webref shape:loading_displaying
* @see PShape
* @see PApplet#shape(PShape)
* @see PApplet#shapeMode(int)
*/
public PShape loadShape(String filename) {
if (filename.toLowerCase().endsWith(".svg")) {
return new PShapeSVG(this, filename);
} else if (filename.toLowerCase().endsWith(".svgz")) {
try {
InputStream input = new GZIPInputStream(createInput(filename));
XMLElement xml = new XMLElement(createReader(input));
return new PShapeSVG(xml);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
//////////////////////////////////////////////////////////////
// FONT I/O
public PFont loadFont(String filename) {
try {
InputStream input = createInput(filename);
return new PFont(input);
} catch (Exception e) {
die("Could not load font " + filename + ". " +
"Make sure that the font has been copied " +
"to the data folder of your sketch.", e);
}
return null;
}
/**
* Used by PGraphics to remove the requirement for loading a font!
*/
protected PFont createDefaultFont(float size) {
// Font f = new Font("SansSerif", Font.PLAIN, 12);
// println("n: " + f.getName());
// println("fn: " + f.getFontName());
// println("ps: " + f.getPSName());
return createFont("SansSerif", size, true, null);
}
public PFont createFont(String name, float size) {
return createFont(name, size, true, null);
}
public PFont createFont(String name, float size, boolean smooth) {
return createFont(name, size, smooth, null);
}
/**
* Create a .vlw font on the fly from either a font name that's
* installed on the system, or from a .ttf or .otf that's inside
* the data folder of this sketch.
*
If the requested item doesn't exist, null is returned.
*
In earlier releases, this method was called openStream().
*
If not online, this will also check to see if the user is asking for a file whose name isn't properly capitalized. If capitalization is different an error will be printed to the console. This helps prevent issues that appear when a sketch is exported to the web, where case sensitivity matters, as opposed to running from inside the Processing Development Environment on Windows or Mac OS, where case sensitivity is preserved but ignored.
*
The filename passed in can be:
* - A URL, for instance openStream("http://processing.org/");
* - A file in the sketch's data folder
* - The full path to a file to be opened locally (when running as an application)
*
* If the file ends with .gz, the stream will automatically be gzip decompressed. If you don't want the automatic decompression, use the related function createInputRaw().
*
* =advanced
* Simplified method to open a Java InputStream.
*
*
*
* @webref input:files
* @see processing.core.PApplet#createOutput(String)
* @see processing.core.PApplet#selectOutput(String)
* @see processing.core.PApplet#selectInput(String)
*
* @param filename the name of the file to use as input
*
*/
public InputStream createInput(String filename) {
InputStream input = createInputRaw(filename);
if ((input != null) && filename.toLowerCase().endsWith(".gz")) {
try {
return new GZIPInputStream(input);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return input;
}
/**
* Call openStream() without automatic gzip decompression.
*/
public InputStream createInputRaw(String filename) {
InputStream stream = null;
if (filename == null) return null;
if (filename.length() == 0) {
// an error will be called by the parent function
//System.err.println("The filename passed to openStream() was empty.");
return null;
}
// safe to check for this as a url first. this will prevent online
// access logs from being spammed with GET /sketchfolder/http://blahblah
if (filename.indexOf(":") != -1) { // at least smells like URL
try {
URL url = new URL(filename);
stream = url.openStream();
return stream;
} catch (MalformedURLException mfue) {
// not a url, that's fine
} catch (FileNotFoundException fnfe) {
// Java 1.5 likes to throw this when URL not available. (fix for 0119)
// http://dev.processing.org/bugs/show_bug.cgi?id=403
} catch (IOException e) {
// changed for 0117, shouldn't be throwing exception
e.printStackTrace();
//System.err.println("Error downloading from URL " + filename);
return null;
//throw new RuntimeException("Error downloading from URL " + filename);
}
}
// Moved this earlier than the getResourceAsStream() checks, because
// calling getResourceAsStream() on a directory lists its contents.
// http://dev.processing.org/bugs/show_bug.cgi?id=716
try {
// First see if it's in a data folder. This may fail by throwing
// a SecurityException. If so, this whole block will be skipped.
File file = new File(dataPath(filename));
if (!file.exists()) {
// next see if it's just in the sketch folder
file = new File(sketchPath, filename);
}
if (file.isDirectory()) {
return null;
}
if (file.exists()) {
try {
// handle case sensitivity check
String filePath = file.getCanonicalPath();
String filenameActual = new File(filePath).getName();
// make sure there isn't a subfolder prepended to the name
String filenameShort = new File(filename).getName();
// if the actual filename is the same, but capitalized
// differently, warn the user.
//if (filenameActual.equalsIgnoreCase(filenameShort) &&
//!filenameActual.equals(filenameShort)) {
if (!filenameActual.equals(filenameShort)) {
throw new RuntimeException("This file is named " +
filenameActual + " not " +
filename + ". Rename the file " +
"or change your code.");
}
} catch (IOException e) { }
}
// if this file is ok, may as well just load it
stream = new FileInputStream(file);
if (stream != null) return stream;
// have to break these out because a general Exception might
// catch the RuntimeException being thrown above
} catch (IOException ioe) {
} catch (SecurityException se) { }
// Using getClassLoader() prevents java from converting dots
// to slashes or requiring a slash at the beginning.
// (a slash as a prefix means that it'll load from the root of
// the jar, rather than trying to dig into the package location)
ClassLoader cl = getClass().getClassLoader();
// by default, data files are exported to the root path of the jar.
// (not the data folder) so check there first.
stream = cl.getResourceAsStream("data/" + filename);
if (stream != null) {
String cn = stream.getClass().getName();
// this is an irritation of sun's java plug-in, which will return
// a non-null stream for an object that doesn't exist. like all good
// things, this is probably introduced in java 1.5. awesome!
// http://dev.processing.org/bugs/show_bug.cgi?id=359
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
return stream;
}
}
// When used with an online script, also need to check without the
// data folder, in case it's not in a subfolder called 'data'.
// http://dev.processing.org/bugs/show_bug.cgi?id=389
stream = cl.getResourceAsStream(filename);
if (stream != null) {
String cn = stream.getClass().getName();
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
return stream;
}
}
// Finally, something special for the Internet Explorer users. Turns out
// that we can't get files that are part of the same folder using the
// methods above when using IE, so we have to resort to the old skool
// getDocumentBase() from teh applet dayz. 1996, my brotha.
try {
URL base = getDocumentBase();
if (base != null) {
URL url = new URL(base, filename);
URLConnection conn = url.openConnection();
return conn.getInputStream();
// if (conn instanceof HttpURLConnection) {
// HttpURLConnection httpConnection = (HttpURLConnection) conn;
// // test for 401 result (HTTP only)
// int responseCode = httpConnection.getResponseCode();
// }
}
} catch (Exception e) { } // IO or NPE or...
// Now try it with a 'data' subfolder. getting kinda desperate for data...
try {
URL base = getDocumentBase();
if (base != null) {
URL url = new URL(base, "data/" + filename);
URLConnection conn = url.openConnection();
return conn.getInputStream();
}
} catch (Exception e) { }
try {
// attempt to load from a local file, used when running as
// an application, or as a signed applet
try { // first try to catch any security exceptions
try {
stream = new FileInputStream(dataPath(filename));
if (stream != null) return stream;
} catch (IOException e2) { }
try {
stream = new FileInputStream(sketchPath(filename));
if (stream != null) return stream;
} catch (Exception e) { } // ignored
try {
stream = new FileInputStream(filename);
if (stream != null) return stream;
} catch (IOException e1) { }
} catch (SecurityException se) { } // online, whups
} catch (Exception e) {
//die(e.getMessage(), e);
e.printStackTrace();
}
return null;
}
static public InputStream createInput(File file) {
if (file == null) {
throw new IllegalArgumentException("File passed to createInput() was null");
}
try {
InputStream input = new FileInputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
return new GZIPInputStream(input);
}
return input;
} catch (IOException e) {
System.err.println("Could not createInput() for " + file);
e.printStackTrace();
return null;
}
}
/**
* Reads the contents of a file or url and places it in a byte array. If a file is specified, it must be located in the sketch's "data" directory/folder.
*
The filename parameter can also be a URL to a file found online. For security reasons, a Processing sketch found online can only download files from the same server from which it came. Getting around this restriction requires a signed applet.
*
* @webref input:files
* @param filename name of a file in the data folder or a URL.
*
* @see processing.core.PApplet#loadStrings(String)
* @see processing.core.PApplet#saveStrings(String, String[])
* @see processing.core.PApplet#saveBytes(String, byte[])
*
*/
public byte[] loadBytes(String filename) {
InputStream is = createInput(filename);
if (is != null) return loadBytes(is);
System.err.println("The file \"" + filename + "\" " +
"is missing or inaccessible, make sure " +
"the URL is valid or that the file has been " +
"added to your sketch and is readable.");
return null;
}
static public byte[] loadBytes(InputStream input) {
try {
BufferedInputStream bis = new BufferedInputStream(input);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int c = bis.read();
while (c != -1) {
out.write(c);
c = bis.read();
}
return out.toByteArray();
} catch (IOException e) {
e.printStackTrace();
//throw new RuntimeException("Couldn't load bytes from stream");
}
return null;
}
static public byte[] loadBytes(File file) {
InputStream is = createInput(file);
return loadBytes(is);
}
static public String[] loadStrings(File file) {
InputStream is = createInput(file);
if (is != null) return loadStrings(is);
return null;
}
/**
* Reads the contents of a file or url and creates a String array of its individual lines. If a file is specified, it must be located in the sketch's "data" directory/folder.
*
The filename parameter can also be a URL to a file found online. For security reasons, a Processing sketch found online can only download files from the same server from which it came. Getting around this restriction requires a signed applet.
*
If the file is not available or an error occurs, null will be returned and an error message will be printed to the console. The error message does not halt the program, however the null value may cause a NullPointerException if your code does not check whether the value returned is null.
*
Starting with Processing release 0134, all files loaded and saved by the Processing API use UTF-8 encoding. In previous releases, the default encoding for your platform was used, which causes problems when files are moved to other platforms.
*
* =advanced
* Load data from a file and shove it into a String array.
* arraycopy(src, 0, dst, 0, length);
*/
static public void arrayCopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* Shortcut to copy the entire contents of
* the source into the destination array.
* Identical to arraycopy(src, 0, dst, 0, src.length);
*/
static public void arrayCopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
//
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
//
static public boolean[] expand(boolean list[]) {
return expand(list, list.length << 1);
}
static public boolean[] expand(boolean list[], int newSize) {
boolean temp[] = new boolean[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public byte[] expand(byte list[]) {
return expand(list, list.length << 1);
}
static public byte[] expand(byte list[], int newSize) {
byte temp[] = new byte[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public char[] expand(char list[]) {
return expand(list, list.length << 1);
}
static public char[] expand(char list[], int newSize) {
char temp[] = new char[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public int[] expand(int list[]) {
return expand(list, list.length << 1);
}
static public int[] expand(int list[], int newSize) {
int temp[] = new int[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public float[] expand(float list[]) {
return expand(list, list.length << 1);
}
static public float[] expand(float list[], int newSize) {
float temp[] = new float[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public String[] expand(String list[]) {
return expand(list, list.length << 1);
}
static public String[] expand(String list[], int newSize) {
String temp[] = new String[newSize];
// in case the new size is smaller than list.length
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public Object expand(Object array) {
return expand(array, Array.getLength(array) << 1);
}
static public Object expand(Object list, int newSize) {
Class> type = list.getClass().getComponentType();
Object temp = Array.newInstance(type, newSize);
System.arraycopy(list, 0, temp, 0,
Math.min(Array.getLength(list), newSize));
return temp;
}
//
// contract() has been removed in revision 0124, use subset() instead.
// (expand() is also functionally equivalent)
//
static public byte[] append(byte b[], byte value) {
b = expand(b, b.length + 1);
b[b.length-1] = value;
return b;
}
static public char[] append(char b[], char value) {
b = expand(b, b.length + 1);
b[b.length-1] = value;
return b;
}
static public int[] append(int b[], int value) {
b = expand(b, b.length + 1);
b[b.length-1] = value;
return b;
}
static public float[] append(float b[], float value) {
b = expand(b, b.length + 1);
b[b.length-1] = value;
return b;
}
static public String[] append(String b[], String value) {
b = expand(b, b.length + 1);
b[b.length-1] = value;
return b;
}
static public Object append(Object b, Object value) {
int length = Array.getLength(b);
b = expand(b, length + 1);
Array.set(b, length, value);
return b;
}
//
static public boolean[] shorten(boolean list[]) {
return subset(list, 0, list.length-1);
}
static public byte[] shorten(byte list[]) {
return subset(list, 0, list.length-1);
}
static public char[] shorten(char list[]) {
return subset(list, 0, list.length-1);
}
static public int[] shorten(int list[]) {
return subset(list, 0, list.length-1);
}
static public float[] shorten(float list[]) {
return subset(list, 0, list.length-1);
}
static public String[] shorten(String list[]) {
return subset(list, 0, list.length-1);
}
static public Object shorten(Object list) {
int length = Array.getLength(list);
return subset(list, 0, length - 1);
}
//
static final public boolean[] splice(boolean list[],
boolean v, int index) {
boolean outgoing[] = new boolean[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = v;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public boolean[] splice(boolean list[],
boolean v[], int index) {
boolean outgoing[] = new boolean[list.length + v.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(v, 0, outgoing, index, v.length);
System.arraycopy(list, index, outgoing, index + v.length,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte v, int index) {
byte outgoing[] = new byte[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = v;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte v[], int index) {
byte outgoing[] = new byte[list.length + v.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(v, 0, outgoing, index, v.length);
System.arraycopy(list, index, outgoing, index + v.length,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char v, int index) {
char outgoing[] = new char[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = v;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char v[], int index) {
char outgoing[] = new char[list.length + v.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(v, 0, outgoing, index, v.length);
System.arraycopy(list, index, outgoing, index + v.length,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int v, int index) {
int outgoing[] = new int[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = v;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int v[], int index) {
int outgoing[] = new int[list.length + v.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(v, 0, outgoing, index, v.length);
System.arraycopy(list, index, outgoing, index + v.length,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float v, int index) {
float outgoing[] = new float[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = v;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float v[], int index) {
float outgoing[] = new float[list.length + v.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(v, 0, outgoing, index, v.length);
System.arraycopy(list, index, outgoing, index + v.length,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String v, int index) {
String outgoing[] = new String[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = v;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String v[], int index) {
String outgoing[] = new String[list.length + v.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(v, 0, outgoing, index, v.length);
System.arraycopy(list, index, outgoing, index + v.length,
list.length - index);
return outgoing;
}
static final public Object splice(Object list, Object v, int index) {
Object[] outgoing = null;
int length = Array.getLength(list);
// check whether item being spliced in is an array
if (v.getClass().getName().charAt(0) == '[') {
int vlength = Array.getLength(v);
outgoing = new Object[length + vlength];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(v, 0, outgoing, index, vlength);
System.arraycopy(list, index, outgoing, index + vlength, length - index);
} else {
outgoing = new Object[length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
Array.set(outgoing, index, v);
System.arraycopy(list, index, outgoing, index + 1, length - index);
}
return outgoing;
}
//
static public boolean[] subset(boolean list[], int start) {
return subset(list, start, list.length - start);
}
static public boolean[] subset(boolean list[], int start, int count) {
boolean output[] = new boolean[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public byte[] subset(byte list[], int start) {
return subset(list, start, list.length - start);
}
static public byte[] subset(byte list[], int start, int count) {
byte output[] = new byte[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public char[] subset(char list[], int start) {
return subset(list, start, list.length - start);
}
static public char[] subset(char list[], int start, int count) {
char output[] = new char[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public int[] subset(int list[], int start) {
return subset(list, start, list.length - start);
}
static public int[] subset(int list[], int start, int count) {
int output[] = new int[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public float[] subset(float list[], int start) {
return subset(list, start, list.length - start);
}
static public float[] subset(float list[], int start, int count) {
float output[] = new float[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public String[] subset(String list[], int start) {
return subset(list, start, list.length - start);
}
static public String[] subset(String list[], int start, int count) {
String output[] = new String[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public Object subset(Object list, int start) {
int length = Array.getLength(list);
return subset(list, start, length - start);
}
static public Object subset(Object list, int start, int count) {
Class> type = list.getClass().getComponentType();
Object outgoing = Array.newInstance(type, count);
System.arraycopy(list, start, outgoing, 0, count);
return outgoing;
}
//
static public boolean[] concat(boolean a[], boolean b[]) {
boolean c[] = new boolean[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public byte[] concat(byte a[], byte b[]) {
byte c[] = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public char[] concat(char a[], char b[]) {
char c[] = new char[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public int[] concat(int a[], int b[]) {
int c[] = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public float[] concat(float a[], float b[]) {
float c[] = new float[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public String[] concat(String a[], String b[]) {
String c[] = new String[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public Object concat(Object a, Object b) {
Class> type = a.getClass().getComponentType();
int alength = Array.getLength(a);
int blength = Array.getLength(b);
Object outgoing = Array.newInstance(type, alength + blength);
System.arraycopy(a, 0, outgoing, 0, alength);
System.arraycopy(b, 0, outgoing, alength, blength);
return outgoing;
}
//
static public boolean[] reverse(boolean list[]) {
boolean outgoing[] = new boolean[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public byte[] reverse(byte list[]) {
byte outgoing[] = new byte[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public char[] reverse(char list[]) {
char outgoing[] = new char[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public int[] reverse(int list[]) {
int outgoing[] = new int[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public float[] reverse(float list[]) {
float outgoing[] = new float[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public String[] reverse(String list[]) {
String outgoing[] = new String[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public Object reverse(Object list) {
Class> type = list.getClass().getComponentType();
int length = Array.getLength(list);
Object outgoing = Array.newInstance(type, length);
for (int i = 0; i < length; i++) {
Array.set(outgoing, i, Array.get(list, (length - 1) - i));
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// STRINGS
/**
* Remove whitespace characters from the beginning and ending
* of a String. Works like String.trim() but includes the
* unicode nbsp character as well.
*/
static public String trim(String str) {
return str.replace('\u00A0', ' ').trim();
}
/**
* Trim the whitespace from a String array. This returns a new
* array and does not affect the passed-in array.
*/
static public String[] trim(String[] array) {
String[] outgoing = new String[array.length];
for (int i = 0; i < array.length; i++) {
outgoing[i] = array[i].replace('\u00A0', ' ').trim();
}
return outgoing;
}
/**
* Join an array of Strings together as a single String,
* separated by the whatever's passed in for the separator.
*/
static public String join(String str[], char separator) {
return join(str, String.valueOf(separator));
}
/**
* Join an array of Strings together as a single String,
* separated by the whatever's passed in for the separator.
*
* e.g. String stuff[] = { "apple", "bear", "cat" };
* String list = join(stuff, ", ");
* // list is now "apple, bear, cat"
*/
static public String join(String str[], String separator) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < str.length; i++) {
if (i != 0) buffer.append(separator);
buffer.append(str[i]);
}
return buffer.toString();
}
/**
* Split the provided String at wherever whitespace occurs.
* Multiple whitespace (extra spaces or tabs or whatever)
* between items will count as a single break.
*
* i.e. splitTokens("a b") -> { "a", "b" }
* splitTokens("a b") -> { "a", "b" }
* splitTokens("a\tb") -> { "a", "b" }
* splitTokens("a \t b ") -> { "a", "b" }
*/
static public String[] splitTokens(String what) {
return splitTokens(what, WHITESPACE);
}
/**
* Splits a string into pieces, using any of the chars in the
* String 'delim' as separator characters. For instance,
* in addition to white space, you might want to treat commas
* as a separator. The delimeter characters won't appear in
* the returned String array.
*
* i.e. splitTokens("a, b", " ,") -> { "a", "b" }
*
* To include all the whitespace possibilities, use the variable
* WHITESPACE, found in PConstants:
*
* i.e. splitTokens("a | b", WHITESPACE + "|"); -> { "a", "b" }
*/
static public String[] splitTokens(String what, String delim) {
StringTokenizer toker = new StringTokenizer(what, delim);
String pieces[] = new String[toker.countTokens()];
int index = 0;
while (toker.hasMoreTokens()) {
pieces[index++] = toker.nextToken();
}
return pieces;
}
/**
* Split a string into pieces along a specific character.
* Most commonly used to break up a String along a space or a tab
* character.
* static public void main(String args[]) {
* PApplet.main(new String[] { "YourSketchName" });
* }
* This will properly launch your applet from a double-clickable
* .jar or from the command line.
*
* Parameters useful for launching or also used by the PDE:
*
* --location=x,y upper-lefthand corner of where the applet
* should appear on screen. if not used,
* the default is to center on the main screen.
*
* --present put the applet into full screen presentation
* mode. requires java 1.4 or later.
*
* --exclusive use full screen exclusive mode when presenting.
* disables new windows or interaction with other
* monitors, this is like a "game" mode.
*
* --hide-stop use to hide the stop button in situations where
* you don't want to allow users to exit. also
* see the FAQ on information for capturing the ESC
* key when running in presentation mode.
*
* --stop-color=#xxxxxx color of the 'stop' text used to quit an
* sketch when it's in present mode.
*
* --bgcolor=#xxxxxx background color of the window.
*
* --sketch-path location of where to save files from functions
* like saveStrings() or saveFrame(). defaults to
* the folder that the java application was
* launched from, which means if this isn't set by
* the pde, everything goes into the same folder
* as processing.exe.
*
* --display=n set what display should be used by this applet.
* displays are numbered starting from 1.
*
* Parameters used by Processing when running via the PDE
*
* --external set when the applet is being used by the PDE
*
* --editor-location=x,y position of the upper-lefthand corner of the
* editor window, for placement of applet window
*
*/
static public void main(String args[]) {
// Disable abyssmally slow Sun renderer on OS X 10.5.
if (platform == MACOSX) {
// Only run this on OS X otherwise it can cause a permissions error.
// http://dev.processing.org/bugs/show_bug.cgi?id=976
System.setProperty("apple.awt.graphics.UseQuartz",
String.valueOf(useQuartz));
}
// This doesn't do anything.
// if (platform == WINDOWS) {
// // For now, disable the D3D renderer on Java 6u10 because
// // it causes problems with Present mode.
// // http://dev.processing.org/bugs/show_bug.cgi?id=1009
// System.setProperty("sun.java2d.d3d", "false");
// }
if (args.length < 1) {
System.err.println("Usage: PApplet
Certain renderers may or may not seem to require loadPixels() or updatePixels(). However, the rule is that any time you want to manipulate the pixels[] array, you must first call loadPixels(), and after changes have been made, call updatePixels(). Even if the renderer may not seem to use this function in the current Processing release, this will always be subject to change.
* =advanced
* Override the g.pixels[] function to set the pixels[] array
* that's part of the PApplet object. Allows the use of
* pixels[] in the code, rather than g.pixels[].
*
* @webref image:pixels
* @see processing.core.PApplet#pixels
* @see processing.core.PApplet#updatePixels()
*/
public void loadPixels() {
g.loadPixels();
pixels = g.pixels;
}
/**
* Updates the display window with the data in the pixels[] array. Use in conjunction with loadPixels(). If you're only reading pixels from the array, there's no need to call updatePixels() unless there are changes.
*
Certain renderers may or may not seem to require loadPixels() or updatePixels(). However, the rule is that any time you want to manipulate the pixels[] array, you must first call loadPixels(), and after changes have been made, call updatePixels(). Even if the renderer may not seem to use this function in the current Processing release, this will always be subject to change.
*
Currently, none of the renderers use the additional parameters to updatePixels(), however this may be implemented in the future.
*
* @webref image:pixels
*
* @see processing.core.PApplet#loadPixels()
* @see processing.core.PApplet#updatePixels()
*
*/
public void updatePixels() {
g.updatePixels();
}
public void updatePixels(int x1, int y1, int x2, int y2) {
g.updatePixels(x1, y1, x2, y2);
}
//////////////////////////////////////////////////////////////
// EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH!
// This includes the Javadoc comments, which are automatically copied from
// the PImage and PGraphics source code files.
// public functions for processing.core
public void flush() {
if (recorder != null) recorder.flush();
g.flush();
}
/**
* Set various hints and hacks for the renderer. This is used to handle obscure rendering features that cannot be implemented in a consistent manner across renderers. Many options will often graduate to standard features instead of hints over time.
*
hint(ENABLE_OPENGL_4X_SMOOTH) - Enable 4x anti-aliasing for OpenGL. This can help force anti-aliasing if it has not been enabled by the user. On some graphics cards, this can also be set by the graphics driver's control panel, however not all cards make this available. This hint must be called immediately after the size() command because it resets the renderer, obliterating any settings and anything drawn (and like size(), re-running the code that came before it again).
*
hint(DISABLE_OPENGL_2X_SMOOTH) - In Processing 1.0, Processing always enables 2x smoothing when the OpenGL renderer is used. This hint disables the default 2x smoothing and returns the smoothing behavior found in earlier releases, where smooth() and noSmooth() could be used to enable and disable smoothing, though the quality was inferior.
*
hint(ENABLE_NATIVE_FONTS) - Use the native version fonts when they are installed, rather than the bitmapped version from a .vlw file. This is useful with the JAVA2D renderer setting, as it will improve font rendering speed. This is not enabled by default, because it can be misleading while testing because the type will look great on your machine (because you have the font installed) but lousy on others' machines if the identical font is unavailable. This option can only be set per-sketch, and must be called before any use of textFont().
*
hint(DISABLE_DEPTH_TEST) - Disable the zbuffer, allowing you to draw on top of everything at will. When depth testing is disabled, items will be drawn to the screen sequentially, like a painting. This hint is most often used to draw in 3D, then draw in 2D on top of it (for instance, to draw GUI controls in 2D on top of a 3D interface). Starting in release 0149, this will also clear the depth buffer. Restore the default with hint(ENABLE_DEPTH_TEST), but note that with the depth buffer cleared, any 3D drawing that happens later in draw() will ignore existing shapes on the screen.
*
hint(ENABLE_DEPTH_SORT) - Enable primitive z-sorting of triangles and lines in P3D and OPENGL. This can slow performance considerably, and the algorithm is not yet perfect. Restore the default with hint(DISABLE_DEPTH_SORT).
*
hint(DISABLE_OPENGL_ERROR_REPORT) - Speeds up the OPENGL renderer setting by not checking for errors while running. Undo with hint(ENABLE_OPENGL_ERROR_REPORT).
*
As of release 0149, unhint() has been removed in favor of adding additional ENABLE/DISABLE constants to reset the default behavior. This prevents the double negatives, and also reinforces which hints can be enabled or disabled.
*
* @webref rendering
* @param which name of the hint to be enabled or disabled
*
* @see processing.core.PGraphics
* @see processing.core.PApplet#createGraphics(int, int, String, String)
* @see processing.core.PApplet#size(int, int)
*/
public void hint(int which) {
if (recorder != null) recorder.hint(which);
g.hint(which);
}
/**
* Start a new shape of type POLYGON
*/
public void beginShape() {
if (recorder != null) recorder.beginShape();
g.beginShape();
}
/**
* Start a new shape.
*
Due to what appears to be a bug in Apple's Java implementation,
* the point() and set() methods are extremely slow in some circumstances
* when used with the default renderer. Using P2D or P3D will fix the
* problem. Grouping many calls to point() or set() together can also
* help. (Bug 1094)
*
* @webref shape:2d_primitives
* @param x x-coordinate of the point
* @param y y-coordinate of the point
* @param z z-coordinate of the point
*
* @see PGraphics#beginShape()
*/
public void point(float x, float y, float z) {
if (recorder != null) recorder.point(x, y, z);
g.point(x, y, z);
}
public void line(float x1, float y1, float x2, float y2) {
if (recorder != null) recorder.line(x1, y1, x2, y2);
g.line(x1, y1, x2, y2);
}
/**
* Draws a line (a direct path between two points) to the screen.
* The version of line() with four parameters draws the line in 2D.
* To color a line, use the stroke() function. A line cannot be
* filled, therefore the fill() method will not affect the color
* of a line. 2D lines are drawn with a width of one pixel by default,
* but this can be changed with the strokeWeight() function.
* The version with six parameters allows the line to be placed anywhere
* within XYZ space. Drawing this shape in 3D using the z parameter
* requires the P3D or OPENGL parameter in combination with size as shown
* in the above example.
*
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first point
* @param y1 y-coordinate of the first point
* @param z1 z-coordinate of the first point
* @param x2 x-coordinate of the second point
* @param y2 y-coordinate of the second point
* @param z2 z-coordinate of the second point
*
* @see PGraphics#strokeWeight(float)
* @see PGraphics#strokeJoin(int)
* @see PGraphics#strokeCap(int)
* @see PGraphics#beginShape()
*/
public void line(float x1, float y1, float z1,
float x2, float y2, float z2) {
if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2);
g.line(x1, y1, z1, x2, y2, z2);
}
/**
* A triangle is a plane created by connecting three points. The first two
* arguments specify the first point, the middle two arguments specify
* the second point, and the last two arguments specify the third point.
*
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first point
* @param y1 y-coordinate of the first point
* @param x2 x-coordinate of the second point
* @param y2 y-coordinate of the second point
* @param x3 x-coordinate of the third point
* @param y3 y-coordinate of the third point
*
* @see PApplet#beginShape()
*/
public void triangle(float x1, float y1, float x2, float y2,
float x3, float y3) {
if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3);
g.triangle(x1, y1, x2, y2, x3, y3);
}
/**
* A quad is a quadrilateral, a four sided polygon. It is similar to
* a rectangle, but the angles between its edges are not constrained
* ninety degrees. The first pair of parameters (x1,y1) sets the
* first vertex and the subsequent pairs should proceed clockwise or
* counter-clockwise around the defined shape.
*
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first corner
* @param y1 y-coordinate of the first corner
* @param x2 x-coordinate of the second corner
* @param y2 y-coordinate of the second corner
* @param x3 x-coordinate of the third corner
* @param y3 y-coordinate of the third corner
* @param x4 x-coordinate of the fourth corner
* @param y4 y-coordinate of the fourth corner
*
*/
public void quad(float x1, float y1, float x2, float y2,
float x3, float y3, float x4, float y4) {
if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4);
g.quad(x1, y1, x2, y2, x3, y3, x4, y4);
}
public void rectMode(int mode) {
if (recorder != null) recorder.rectMode(mode);
g.rectMode(mode);
}
/**
* Draws a rectangle to the screen. A rectangle is a four-sided shape with
* every angle at ninety degrees. The first two parameters set the location,
* the third sets the width, and the fourth sets the height. The origin is
* changed with the rectMode() function.
*
* @webref shape:2d_primitives
* @param a x-coordinate of the rectangle
* @param b y-coordinate of the rectangle
* @param c width of the rectangle
* @param d height of the rectangle
*
* @see PGraphics#rectMode(int)
* @see PGraphics#quad(float, float, float, float, float, float, float, float)
*/
public void rect(float a, float b, float c, float d) {
if (recorder != null) recorder.rect(a, b, c, d);
g.rect(a, b, c, d);
}
public void rect(float a, float b, float c, float d, float hr, float vr) {
if (recorder != null) recorder.rect(a, b, c, d, hr, vr);
g.rect(a, b, c, d, hr, vr);
}
public void rect(float a, float b, float c, float d,
float tl, float tr, float bl, float br) {
if (recorder != null) recorder.rect(a, b, c, d, tl, tr, bl, br);
g.rect(a, b, c, d, tl, tr, bl, br);
}
/**
* The origin of the ellipse is modified by the ellipseMode()
* function. The default configuration is ellipseMode(CENTER),
* which specifies the location of the ellipse as the center of the shape.
* The RADIUS mode is the same, but the width and height parameters to
* ellipse() specify the radius of the ellipse, rather than the
* diameter. The CORNER mode draws the shape from the upper-left corner
* of its bounding box. The CORNERS mode uses the four parameters to
* ellipse() to set two opposing corners of the ellipse's bounding
* box. The parameter must be written in "ALL CAPS" because Processing
* syntax is case sensitive.
*
* @webref shape:attributes
*
* @param mode Either CENTER, RADIUS, CORNER, or CORNERS.
* @see PApplet#ellipse(float, float, float, float)
*/
public void ellipseMode(int mode) {
if (recorder != null) recorder.ellipseMode(mode);
g.ellipseMode(mode);
}
/**
* Draws an ellipse (oval) in the display window. An ellipse with an equal
* width and height is a circle. The first two parameters set
* the location, the third sets the width, and the fourth sets the height.
* The origin may be changed with the ellipseMode() function.
*
* @webref shape:2d_primitives
* @param a x-coordinate of the ellipse
* @param b y-coordinate of the ellipse
* @param c width of the ellipse
* @param d height of the ellipse
*
* @see PApplet#ellipseMode(int)
*/
public void ellipse(float a, float b, float c, float d) {
if (recorder != null) recorder.ellipse(a, b, c, d);
g.ellipse(a, b, c, d);
}
/**
* Draws an arc in the display window.
* Arcs are drawn along the outer edge of an ellipse defined by the
* x, y, width and height parameters.
* The origin or the arc's ellipse may be changed with the
* ellipseMode() function.
* The start and stop parameters specify the angles
* at which to draw the arc.
*
* @webref shape:2d_primitives
* @param a x-coordinate of the arc's ellipse
* @param b y-coordinate of the arc's ellipse
* @param c width of the arc's ellipse
* @param d height of the arc's ellipse
* @param start angle to start the arc, specified in radians
* @param stop angle to stop the arc, specified in radians
*
* @see PGraphics#ellipseMode(int)
* @see PGraphics#ellipse(float, float, float, float)
*/
public void arc(float a, float b, float c, float d,
float start, float stop) {
if (recorder != null) recorder.arc(a, b, c, d, start, stop);
g.arc(a, b, c, d, start, stop);
}
/**
* @param size dimension of the box in all dimensions, creates a cube
*/
public void box(float size) {
if (recorder != null) recorder.box(size);
g.box(size);
}
/**
* A box is an extruded rectangle. A box with equal dimension
* on all sides is a cube.
*
* @webref shape:3d_primitives
* @param w dimension of the box in the x-dimension
* @param h dimension of the box in the y-dimension
* @param d dimension of the box in the z-dimension
*
* @see PApplet#sphere(float)
*/
public void box(float w, float h, float d) {
if (recorder != null) recorder.box(w, h, d);
g.box(w, h, d);
}
/**
* @param res number of segments (minimum 3) used per full circle revolution
*/
public void sphereDetail(int res) {
if (recorder != null) recorder.sphereDetail(res);
g.sphereDetail(res);
}
/**
* Controls the detail used to render a sphere by adjusting the number of
* vertices of the sphere mesh. The default resolution is 30, which creates
* a fairly detailed sphere definition with vertices every 360/30 = 12
* degrees. If you're going to render a great number of spheres per frame,
* it is advised to reduce the level of detail using this function.
* The setting stays active until sphereDetail() is called again with
* a new parameter and so should not be called prior to every
* sphere() statement, unless you wish to render spheres with
* different settings, e.g. using less detail for smaller spheres or ones
* further away from the camera. To control the detail of the horizontal
* and vertical resolution independently, use the version of the functions
* with two parameters.
*
* =advanced
* Code for sphereDetail() submitted by toxi [031031].
* Code for enhanced u/v version from davbol [080801].
*
* @webref shape:3d_primitives
* @param ures number of segments used horizontally (longitudinally)
* per full circle revolution
* @param vres number of segments used vertically (latitudinally)
* from top to bottom
*
* @see PGraphics#sphere(float)
*/
/**
* Set the detail level for approximating a sphere. The ures and vres params
* control the horizontal and vertical resolution.
*
*/
public void sphereDetail(int ures, int vres) {
if (recorder != null) recorder.sphereDetail(ures, vres);
g.sphereDetail(ures, vres);
}
/**
* Draw a sphere with radius r centered at coordinate 0, 0, 0.
* A sphere is a hollow ball made from tessellated triangles.
* =advanced
*
* [toxi 031031] new sphere code. removed all multiplies with
* radius, as scale() will take care of that anyway
*
* [toxi 031223] updated sphere code (removed modulos)
* and introduced sphereAt(x,y,z,r)
* to avoid additional translate()'s on the user/sketch side
*
* [davbol 080801] now using separate sphereDetailU/V
*
*
* @webref shape:3d_primitives
* @param r the radius of the sphere
*/
public void sphere(float r) {
if (recorder != null) recorder.sphere(r);
g.sphere(r);
}
/**
* Evalutes quadratic bezier at point t for points a, b, c, d.
* The parameter t varies between 0 and 1. The a and d parameters are the
* on-curve points, b and c are the control points. To make a two-dimensional
* curve, call this function once with the x coordinates and a second time
* with the y coordinates to get the location of a bezier curve at t.
*
* =advanced
* For instance, to convert the following example:
* stroke(255, 102, 0);
* line(85, 20, 10, 10);
* line(90, 90, 15, 80);
* stroke(0, 0, 0);
* bezier(85, 20, 10, 10, 90, 90, 15, 80);
*
* // draw it in gray, using 10 steps instead of the default 20
* // this is a slower way to do it, but useful if you need
* // to do things with the coordinates at each step
* stroke(128);
* beginShape(LINE_STRIP);
* for (int i = 0; i <= 10; i++) {
* float t = i / 10.0f;
* float x = bezierPoint(85, 10, 90, 15, t);
* float y = bezierPoint(20, 10, 90, 80, t);
* vertex(x, y);
* }
* endShape();
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
*
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
*/
public float bezierPoint(float a, float b, float c, float d, float t) {
return g.bezierPoint(a, b, c, d, t);
}
/**
* Calculates the tangent of a point on a Bezier curve. There is a good
* definition of "tangent" at Wikipedia: http://en.wikipedia.org/wiki/Tangent
*
* =advanced
* Code submitted by Dave Bollinger (davol) for release 0136.
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
*
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
*/
public float bezierTangent(float a, float b, float c, float d, float t) {
return g.bezierTangent(a, b, c, d, t);
}
/**
* Sets the resolution at which Beziers display. The default value is 20. This function is only useful when using the P3D or OPENGL renderer as the default (JAVA2D) renderer does not use this information.
*
* @webref shape:curves
* @param detail resolution of the curves
*
* @see PApplet#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PApplet#curveVertex(float, float)
* @see PApplet#curveTightness(float)
*/
public void bezierDetail(int detail) {
if (recorder != null) recorder.bezierDetail(detail);
g.bezierDetail(detail);
}
/**
* Draws a Bezier curve on the screen. These curves are defined by a series
* of anchor and control points. The first two parameters specify the first
* anchor point and the last two parameters specify the other anchor point.
* The middle parameters specify the control points which define the shape
* of the curve. Bezier curves were developed by French engineer Pierre
* Bezier. Using the 3D version of requires rendering with P3D or OPENGL
* (see the Environment reference for more information).
*
* =advanced
* Draw a cubic bezier curve. The first and last points are
* the on-curve points. The middle two are the 'control' points,
* or 'handles' in an application like Illustrator.
* beginShape();
* vertex(x1, y1);
* bezierVertex(x2, y2, x3, y3, x4, y4);
* endShape();
*
* In Postscript-speak, this would be:
* moveto(x1, y1);
* curveto(x2, y2, x3, y3, x4, y4);
* If you were to try and continue that curve like so:
* curveto(x5, y5, x6, y6, x7, y7);
* This would be done in processing by adding these statements:
* bezierVertex(x5, y5, x6, y6, x7, y7)
*
* To draw a quadratic (instead of cubic) curve,
* use the control point twice by doubling it:
* bezier(x1, y1, cx, cy, cx, cy, x2, y2);
*
* @webref shape:curves
* @param x1 coordinates for the first anchor point
* @param y1 coordinates for the first anchor point
* @param z1 coordinates for the first anchor point
* @param x2 coordinates for the first control point
* @param y2 coordinates for the first control point
* @param z2 coordinates for the first control point
* @param x3 coordinates for the second control point
* @param y3 coordinates for the second control point
* @param z3 coordinates for the second control point
* @param x4 coordinates for the second anchor point
* @param y4 coordinates for the second anchor point
* @param z4 coordinates for the second anchor point
*
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void bezier(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
g.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
}
public void bezier(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
/**
* Evalutes the Catmull-Rom curve at point t for points a, b, c, d. The
* parameter t varies between 0 and 1, a and d are points on the curve,
* and b and c are the control points. This can be done once with the x
* coordinates and a second time with the y coordinates to get the
* location of a curve at t.
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of second point on the curve
* @param c coordinate of third point on the curve
* @param d coordinate of fourth point on the curve
* @param t value between 0 and 1
*
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#bezierPoint(float, float, float, float, float)
*/
public float curvePoint(float a, float b, float c, float d, float t) {
return g.curvePoint(a, b, c, d, t);
}
/**
* Calculates the tangent of a point on a Catmull-Rom curve. There is a good definition of "tangent" at Wikipedia: http://en.wikipedia.org/wiki/Tangent.
*
* =advanced
* Code thanks to Dave Bollinger (Bug #715)
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
*
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
* @see PGraphics#bezierTangent(float, float, float, float, float)
*/
public float curveTangent(float a, float b, float c, float d, float t) {
return g.curveTangent(a, b, c, d, t);
}
/**
* Sets the resolution at which curves display. The default value is 20.
* This function is only useful when using the P3D or OPENGL renderer as
* the default (JAVA2D) renderer does not use this information.
*
* @webref shape:curves
* @param detail resolution of the curves
*
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curveTightness(float)
*/
public void curveDetail(int detail) {
if (recorder != null) recorder.curveDetail(detail);
g.curveDetail(detail);
}
/**
* Modifies the quality of forms created with curve() and
*curveVertex(). The parameter squishy determines how the
* curve fits to the vertex points. The value 0.0 is the default value for
* squishy (this value defines the curves to be Catmull-Rom splines)
* and the value 1.0 connects all the points with straight lines.
* Values within the range -5.0 and 5.0 will deform the curves but
* will leave them recognizable and as values increase in magnitude,
* they will continue to deform.
*
* @webref shape:curves
* @param tightness amount of deformation from the original vertices
*
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
*
*/
public void curveTightness(float tightness) {
if (recorder != null) recorder.curveTightness(tightness);
g.curveTightness(tightness);
}
/**
* Draws a curved line on the screen. The first and second parameters
* specify the beginning control point and the last two parameters specify
* the ending control point. The middle parameters specify the start and
* stop of the curve. Longer curves can be created by putting a series of
* curve() functions together or using curveVertex().
* An additional function called curveTightness() provides control
* for the visual quality of the curve. The curve() function is an
* implementation of Catmull-Rom splines. Using the 3D version of requires
* rendering with P3D or OPENGL (see the Environment reference for more
* information).
*
* =advanced
* As of revision 0070, this function no longer doubles the first
* and last points. The curves are a bit more boring, but it's more
* mathematically correct, and properly mirrored in curvePoint().
*
* beginShape();
* curveVertex(x1, y1);
* curveVertex(x2, y2);
* curveVertex(x3, y3);
* curveVertex(x4, y4);
* endShape();
*
*
* @webref shape:curves
* @param x1 coordinates for the beginning control point
* @param y1 coordinates for the beginning control point
* @param z1 coordinates for the beginning control point
* @param x2 coordinates for the first point
* @param y2 coordinates for the first point
* @param z2 coordinates for the first point
* @param x3 coordinates for the second point
* @param y3 coordinates for the second point
* @param z3 coordinates for the second point
* @param x4 coordinates for the ending control point
* @param y4 coordinates for the ending control point
* @param z4 coordinates for the ending control point
*
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curveTightness(float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void curve(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4);
g.curve(x1, y1, x2, y2, x3, y3, x4, y4);
}
public void curve(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
/**
* If true in PImage, use bilinear interpolation for copy()
* operations. When inherited by PGraphics, also controls shapes.
*/
public void smooth() {
if (recorder != null) recorder.smooth();
g.smooth();
}
/**
* Disable smoothing. See smooth().
*/
public void noSmooth() {
if (recorder != null) recorder.noSmooth();
g.noSmooth();
}
/**
* Modifies the location from which images draw. The default mode is
* imageMode(CORNER), which specifies the location to be the
* upper-left corner and uses the fourth and fifth parameters of
* image() to set the image's width and height. The syntax
* imageMode(CORNERS) uses the second and third parameters of
* image() to set the location of one corner of the image and
* uses the fourth and fifth parameters to set the opposite corner.
* Use imageMode(CENTER) to draw images centered at the given
* x and y position.
*
The parameter to imageMode() must be written in
* ALL CAPS because Processing syntax is case sensitive.
*
* @webref image:loading_displaying
* @param mode Either CORNER, CORNERS, or CENTER
*
* @see processing.core.PApplet#loadImage(String, String)
* @see processing.core.PImage
* @see processing.core.PApplet#image(PImage, float, float, float, float)
* @see processing.core.PGraphics#background(float, float, float, float)
*/
public void imageMode(int mode) {
if (recorder != null) recorder.imageMode(mode);
g.imageMode(mode);
}
public void image(PImage image, float x, float y) {
if (recorder != null) recorder.image(image, x, y);
g.image(image, x, y);
}
/**
* Displays images to the screen. The images must be in the sketch's "data"
* directory to load correctly. Select "Add file..." from the "Sketch" menu
* to add the image. Processing currently works with GIF, JPEG, and Targa
* images. The color of an image may be modified with the tint()
* function and if a GIF has transparency, it will maintain its transparency.
* The img parameter specifies the image to display and the x
* and y parameters define the location of the image from its
* upper-left corner. The image is displayed at its original size unless
* the width and height parameters specify a different size.
* The imageMode() function changes the way the parameters work.
* A call to imageMode(CORNERS) will change the width and height
* parameters to define the x and y values of the opposite corner of the
* image.
*
* =advanced
* Starting with release 0124, when using the default (JAVA2D) renderer,
* smooth() will also improve image quality of resized images.
*
* @webref image:loading_displaying
* @param image the image to display
* @param x x-coordinate of the image
* @param y y-coordinate of the image
* @param c width to display the image
* @param d height to display the image
*
* @see processing.core.PApplet#loadImage(String, String)
* @see processing.core.PImage
* @see processing.core.PGraphics#imageMode(int)
* @see processing.core.PGraphics#tint(float)
* @see processing.core.PGraphics#background(float, float, float, float)
* @see processing.core.PGraphics#alpha(int)
*/
public void image(PImage image, float x, float y, float c, float d) {
if (recorder != null) recorder.image(image, x, y, c, d);
g.image(image, x, y, c, d);
}
/**
* Draw an image(), also specifying u/v coordinates.
* In this method, the u, v coordinates are always based on image space
* location, regardless of the current textureMode().
*/
public void image(PImage image,
float a, float b, float c, float d,
int u1, int v1, int u2, int v2) {
if (recorder != null) recorder.image(image, a, b, c, d, u1, v1, u2, v2);
g.image(image, a, b, c, d, u1, v1, u2, v2);
}
/**
* Modifies the location from which shapes draw.
* The default mode is shapeMode(CORNER), which specifies the
* location to be the upper left corner of the shape and uses the third
* and fourth parameters of shape() to specify the width and height.
* The syntax shapeMode(CORNERS) uses the first and second parameters
* of shape() to set the location of one corner and uses the third
* and fourth parameters to set the opposite corner.
* The syntax shapeMode(CENTER) draws the shape from its center point
* and uses the third and forth parameters of shape() to specify the
* width and height.
* The parameter must be written in "ALL CAPS" because Processing syntax
* is case sensitive.
*
* @param mode One of CORNER, CORNERS, CENTER
*
* @webref shape:loading_displaying
* @see PGraphics#shape(PShape)
* @see PGraphics#rectMode(int)
*/
public void shapeMode(int mode) {
if (recorder != null) recorder.shapeMode(mode);
g.shapeMode(mode);
}
public void shape(PShape shape) {
if (recorder != null) recorder.shape(shape);
g.shape(shape);
}
/**
* Convenience method to draw at a particular location.
*/
public void shape(PShape shape, float x, float y) {
if (recorder != null) recorder.shape(shape, x, y);
g.shape(shape, x, y);
}
/**
* Displays shapes to the screen. The shapes must be in the sketch's "data"
* directory to load correctly. Select "Add file..." from the "Sketch" menu
* to add the shape.
* Processing currently works with SVG shapes only.
* The sh parameter specifies the shape to display and the x
* and y parameters define the location of the shape from its
* upper-left corner.
* The shape is displayed at its original size unless the width
* and height parameters specify a different size.
* The shapeMode() function changes the way the parameters work.
* A call to shapeMode(CORNERS), for example, will change the width
* and height parameters to define the x and y values of the opposite corner
* of the shape.
*
* Note complex shapes may draw awkwardly with P2D, P3D, and OPENGL. Those
* renderers do not yet support shapes that have holes or complicated breaks.
*
* @param shape
* @param x x-coordinate of the shape
* @param y y-coordinate of the shape
* @param c width to display the shape
* @param d height to display the shape
*
* @webref shape:loading_displaying
* @see PShape
* @see PGraphics#loadShape(String)
* @see PGraphics#shapeMode(int)
*/
public void shape(PShape shape, float x, float y, float c, float d) {
if (recorder != null) recorder.shape(shape, x, y, c, d);
g.shape(shape, x, y, c, d);
}
/**
* Sets the alignment of the text to one of LEFT, CENTER, or RIGHT.
* This will also reset the vertical text alignment to BASELINE.
*/
public void textAlign(int align) {
if (recorder != null) recorder.textAlign(align);
g.textAlign(align);
}
/**
* Sets the horizontal and vertical alignment of the text. The horizontal
* alignment can be one of LEFT, CENTER, or RIGHT. The vertical alignment
* can be TOP, BOTTOM, CENTER, or the BASELINE (the default).
*/
public void textAlign(int alignX, int alignY) {
if (recorder != null) recorder.textAlign(alignX, alignY);
g.textAlign(alignX, alignY);
}
/**
* Returns the ascent of the current font at the current size.
* This is a method, rather than a variable inside the PGraphics object
* because it requires calculation.
*/
public float textAscent() {
return g.textAscent();
}
/**
* Returns the descent of the current font at the current size.
* This is a method, rather than a variable inside the PGraphics object
* because it requires calculation.
*/
public float textDescent() {
return g.textDescent();
}
/**
* Sets the current font. The font's size will be the "natural"
* size of this font (the size that was set when using "Create Font").
* The leading will also be reset.
*/
public void textFont(PFont which) {
if (recorder != null) recorder.textFont(which);
g.textFont(which);
}
/**
* Useful function to set the font and size at the same time.
*/
public void textFont(PFont which, float size) {
if (recorder != null) recorder.textFont(which, size);
g.textFont(which, size);
}
/**
* Set the text leading to a specific value. If using a custom
* value for the text leading, you'll have to call textLeading()
* again after any calls to textSize().
*/
public void textLeading(float leading) {
if (recorder != null) recorder.textLeading(leading);
g.textLeading(leading);
}
/**
* Sets the text rendering/placement to be either SCREEN (direct
* to the screen, exact coordinates, only use the font's original size)
* or MODEL (the default, where text is manipulated by translate() and
* can have a textSize). The text size cannot be set when using
* textMode(SCREEN), because it uses the pixels directly from the font.
*/
public void textMode(int mode) {
if (recorder != null) recorder.textMode(mode);
g.textMode(mode);
}
/**
* Sets the text size, also resets the value for the leading.
*/
public void textSize(float size) {
if (recorder != null) recorder.textSize(size);
g.textSize(size);
}
public float textWidth(char c) {
return g.textWidth(c);
}
/**
* Return the width of a line of text. If the text has multiple
* lines, this returns the length of the longest line.
*/
public float textWidth(String str) {
return g.textWidth(str);
}
/**
* TODO not sure if this stays...
*/
public float textWidth(char[] chars, int start, int length) {
return g.textWidth(chars, start, length);
}
/**
* Write text where we just left off.
*/
public void text(char c) {
if (recorder != null) recorder.text(c);
g.text(c);
}
/**
* Draw a single character on screen.
* Extremely slow when used with textMode(SCREEN) and Java 2D,
* because loadPixels has to be called first and updatePixels last.
*/
public void text(char c, float x, float y) {
if (recorder != null) recorder.text(c, x, y);
g.text(c, x, y);
}
/**
* Draw a single character on screen (with a z coordinate)
*/
public void text(char c, float x, float y, float z) {
if (recorder != null) recorder.text(c, x, y, z);
g.text(c, x, y, z);
}
/**
* Write text where we just left off.
*/
public void text(String str) {
if (recorder != null) recorder.text(str);
g.text(str);
}
/**
* Draw a chunk of text.
* Newlines that are \n (Unix newline or linefeed char, ascii 10)
* are honored, but \r (carriage return, Windows and Mac OS) are
* ignored.
*/
public void text(String str, float x, float y) {
if (recorder != null) recorder.text(str, x, y);
g.text(str, x, y);
}
/**
* Method to draw text from an array of chars. This method will usually be
* more efficient than drawing from a String object, because the String will
* not be converted to a char array before drawing.
*/
public void text(char[] chars, int start, int stop, float x, float y) {
if (recorder != null) recorder.text(chars, start, stop, x, y);
g.text(chars, start, stop, x, y);
}
/**
* Same as above but with a z coordinate.
*/
public void text(String str, float x, float y, float z) {
if (recorder != null) recorder.text(str, x, y, z);
g.text(str, x, y, z);
}
public void text(char[] chars, int start, int stop,
float x, float y, float z) {
if (recorder != null) recorder.text(chars, start, stop, x, y, z);
g.text(chars, start, stop, x, y, z);
}
/**
* Draw text in a box that is constrained to a particular size.
* The current rectMode() determines what the coordinates mean
* (whether x1/y1/x2/y2 or x/y/w/h).
*
* Note that the x,y coords of the start of the box
* will align with the *ascent* of the text, not the baseline,
* as is the case for the other text() functions.
*
* Newlines that are \n (Unix newline or linefeed char, ascii 10)
* are honored, and \r (carriage return, Windows and Mac OS) are
* ignored.
*/
public void text(String str, float x1, float y1, float x2, float y2) {
if (recorder != null) recorder.text(str, x1, y1, x2, y2);
g.text(str, x1, y1, x2, y2);
}
public void text(String s, float x1, float y1, float x2, float y2, float z) {
if (recorder != null) recorder.text(s, x1, y1, x2, y2, z);
g.text(s, x1, y1, x2, y2, z);
}
public void text(int num, float x, float y) {
if (recorder != null) recorder.text(num, x, y);
g.text(num, x, y);
}
public void text(int num, float x, float y, float z) {
if (recorder != null) recorder.text(num, x, y, z);
g.text(num, x, y, z);
}
/**
* This does a basic number formatting, to avoid the
* generally ugly appearance of printing floats.
* Users who want more control should use their own nf() cmmand,
* or if they want the long, ugly version of float,
* use String.valueOf() to convert the float to a String first.
*/
public void text(float num, float x, float y) {
if (recorder != null) recorder.text(num, x, y);
g.text(num, x, y);
}
public void text(float num, float x, float y, float z) {
if (recorder != null) recorder.text(num, x, y, z);
g.text(num, x, y, z);
}
/**
* Push a copy of the current transformation matrix onto the stack.
*/
public void pushMatrix() {
if (recorder != null) recorder.pushMatrix();
g.pushMatrix();
}
/**
* Replace the current transformation matrix with the top of the stack.
*/
public void popMatrix() {
if (recorder != null) recorder.popMatrix();
g.popMatrix();
}
/**
* Translate in X and Y.
*/
public void translate(float tx, float ty) {
if (recorder != null) recorder.translate(tx, ty);
g.translate(tx, ty);
}
/**
* Translate in X, Y, and Z.
*/
public void translate(float tx, float ty, float tz) {
if (recorder != null) recorder.translate(tx, ty, tz);
g.translate(tx, ty, tz);
}
/**
* Two dimensional rotation.
*
* Same as rotateZ (this is identical to a 3D rotation along the z-axis)
* but included for clarity. It'd be weird for people drawing 2D graphics
* to be using rotateZ. And they might kick our a-- for the confusion.
*
* Additional background.
*/
public void rotate(float angle) {
if (recorder != null) recorder.rotate(angle);
g.rotate(angle);
}
/**
* Rotate around the X axis.
*/
public void rotateX(float angle) {
if (recorder != null) recorder.rotateX(angle);
g.rotateX(angle);
}
/**
* Rotate around the Y axis.
*/
public void rotateY(float angle) {
if (recorder != null) recorder.rotateY(angle);
g.rotateY(angle);
}
/**
* Rotate around the Z axis.
*
* The functions rotate() and rotateZ() are identical, it's just that it make
* sense to have rotate() and then rotateX() and rotateY() when using 3D;
* nor does it make sense to use a function called rotateZ() if you're only
* doing things in 2D. so we just decided to have them both be the same.
*/
public void rotateZ(float angle) {
if (recorder != null) recorder.rotateZ(angle);
g.rotateZ(angle);
}
/**
* Rotate about a vector in space. Same as the glRotatef() function.
*/
public void rotate(float angle, float vx, float vy, float vz) {
if (recorder != null) recorder.rotate(angle, vx, vy, vz);
g.rotate(angle, vx, vy, vz);
}
/**
* Scale in all dimensions.
*/
public void scale(float s) {
if (recorder != null) recorder.scale(s);
g.scale(s);
}
/**
* Scale in X and Y. Equivalent to scale(sx, sy, 1).
*
* Not recommended for use in 3D, because the z-dimension is just
* scaled by 1, since there's no way to know what else to scale it by.
*/
public void scale(float sx, float sy) {
if (recorder != null) recorder.scale(sx, sy);
g.scale(sx, sy);
}
/**
* Scale in X, Y, and Z.
*/
public void scale(float x, float y, float z) {
if (recorder != null) recorder.scale(x, y, z);
g.scale(x, y, z);
}
/**
* Skew along X axis
*/
public void skewX(float angle) {
if (recorder != null) recorder.skewX(angle);
g.skewX(angle);
}
/**
* Skew along Y axis
*/
public void skewY(float angle) {
if (recorder != null) recorder.skewY(angle);
g.skewY(angle);
}
/**
* Set the current transformation matrix to identity.
*/
public void resetMatrix() {
if (recorder != null) recorder.resetMatrix();
g.resetMatrix();
}
public void applyMatrix(PMatrix source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
public void applyMatrix(PMatrix2D source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
/**
* Apply a 3x2 affine transformation matrix.
*/
public void applyMatrix(float n00, float n01, float n02,
float n10, float n11, float n12) {
if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12);
g.applyMatrix(n00, n01, n02, n10, n11, n12);
}
public void applyMatrix(PMatrix3D source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
/**
* Apply a 4x4 transformation matrix.
*/
public void applyMatrix(float n00, float n01, float n02, float n03,
float n10, float n11, float n12, float n13,
float n20, float n21, float n22, float n23,
float n30, float n31, float n32, float n33) {
if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
}
public PMatrix getMatrix() {
return g.getMatrix();
}
/**
* Copy the current transformation matrix into the specified target.
* Pass in null to create a new matrix.
*/
public PMatrix2D getMatrix(PMatrix2D target) {
return g.getMatrix(target);
}
/**
* Copy the current transformation matrix into the specified target.
* Pass in null to create a new matrix.
*/
public PMatrix3D getMatrix(PMatrix3D target) {
return g.getMatrix(target);
}
/**
* Set the current transformation matrix to the contents of another.
*/
public void setMatrix(PMatrix source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
/**
* Set the current transformation to the contents of the specified source.
*/
public void setMatrix(PMatrix2D source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
/**
* Set the current transformation to the contents of the specified source.
*/
public void setMatrix(PMatrix3D source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
/**
* Print the current model (or "transformation") matrix.
*/
public void printMatrix() {
if (recorder != null) recorder.printMatrix();
g.printMatrix();
}
public void beginCamera() {
if (recorder != null) recorder.beginCamera();
g.beginCamera();
}
public void endCamera() {
if (recorder != null) recorder.endCamera();
g.endCamera();
}
public void camera() {
if (recorder != null) recorder.camera();
g.camera();
}
public void camera(float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ,
float upX, float upY, float upZ) {
if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
}
public void printCamera() {
if (recorder != null) recorder.printCamera();
g.printCamera();
}
public void ortho() {
if (recorder != null) recorder.ortho();
g.ortho();
}
public void ortho(float left, float right,
float bottom, float top,
float near, float far) {
if (recorder != null) recorder.ortho(left, right, bottom, top, near, far);
g.ortho(left, right, bottom, top, near, far);
}
public void perspective() {
if (recorder != null) recorder.perspective();
g.perspective();
}
public void perspective(float fovy, float aspect, float zNear, float zFar) {
if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar);
g.perspective(fovy, aspect, zNear, zFar);
}
public void frustum(float left, float right,
float bottom, float top,
float near, float far) {
if (recorder != null) recorder.frustum(left, right, bottom, top, near, far);
g.frustum(left, right, bottom, top, near, far);
}
public void printProjection() {
if (recorder != null) recorder.printProjection();
g.printProjection();
}
/**
* Given an x and y coordinate, returns the x position of where
* that point would be placed on screen, once affected by translate(),
* scale(), or any other transformations.
*/
public float screenX(float x, float y) {
return g.screenX(x, y);
}
/**
* Given an x and y coordinate, returns the y position of where
* that point would be placed on screen, once affected by translate(),
* scale(), or any other transformations.
*/
public float screenY(float x, float y) {
return g.screenY(x, y);
}
/**
* Maps a three dimensional point to its placement on-screen.
*
When using hexadecimal notation to specify a color, use "#" or
* "0x" before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six
* digits to specify a color (the way colors are specified in HTML and CSS).
* When using the hexadecimal notation starting with "0x", the hexadecimal
* value must be specified with eight characters; the first two characters
* define the alpha component and the remainder the red, green, and blue
* components.
*
The value for the parameter "gray" must be less than or equal
* to the current maximum value as specified by colorMode().
* The default maximum value is 255.
*
* @webref color:setting
* @param alpha opacity of the stroke
* @param x red or hue value (depending on the current color mode)
* @param y green or saturation value (depending on the current color mode)
* @param z blue or brightness value (depending on the current color mode)
*/
public void stroke(float x, float y, float z, float a) {
if (recorder != null) recorder.stroke(x, y, z, a);
g.stroke(x, y, z, a);
}
/**
* Removes the current fill value for displaying images and reverts to displaying images with their original hues.
*
* @webref image:loading_displaying
* @see processing.core.PGraphics#tint(float, float, float, float)
* @see processing.core.PGraphics#image(PImage, float, float, float, float)
*/
public void noTint() {
if (recorder != null) recorder.noTint();
g.noTint();
}
/**
* Set the tint to either a grayscale or ARGB value.
*/
public void tint(int rgb) {
if (recorder != null) recorder.tint(rgb);
g.tint(rgb);
}
/**
* @param rgb color value in hexadecimal notation
* (i.e. #FFCC00 or 0xFFFFCC00) or any value of the color datatype
* @param alpha opacity of the image
*/
public void tint(int rgb, float alpha) {
if (recorder != null) recorder.tint(rgb, alpha);
g.tint(rgb, alpha);
}
/**
* @param gray any valid number
*/
public void tint(float gray) {
if (recorder != null) recorder.tint(gray);
g.tint(gray);
}
public void tint(float gray, float alpha) {
if (recorder != null) recorder.tint(gray, alpha);
g.tint(gray, alpha);
}
public void tint(float x, float y, float z) {
if (recorder != null) recorder.tint(x, y, z);
g.tint(x, y, z);
}
/**
* Sets the fill value for displaying images. Images can be tinted to
* specified colors or made transparent by setting the alpha.
*
To make an image transparent, but not change it's color,
* use white as the tint color and specify an alpha value. For instance,
* tint(255, 128) will make an image 50% transparent (unless
* colorMode() has been used).
*
*
When using hexadecimal notation to specify a color, use "#" or
* "0x" before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six
* digits to specify a color (the way colors are specified in HTML and CSS).
* When using the hexadecimal notation starting with "0x", the hexadecimal
* value must be specified with eight characters; the first two characters
* define the alpha component and the remainder the red, green, and blue
* components.
*
The value for the parameter "gray" must be less than or equal
* to the current maximum value as specified by colorMode().
* The default maximum value is 255.
*
The tint() method is also used to control the coloring of
* textures in 3D.
*
* @webref image:loading_displaying
* @param x red or hue value
* @param y green or saturation value
* @param z blue or brightness value
*
* @see processing.core.PGraphics#noTint()
* @see processing.core.PGraphics#image(PImage, float, float, float, float)
*/
public void tint(float x, float y, float z, float a) {
if (recorder != null) recorder.tint(x, y, z, a);
g.tint(x, y, z, a);
}
/**
* Disables filling geometry. If both noStroke() and noFill()
* are called, no shapes will be drawn to the screen.
*
* @webref color:setting
*
* @see PGraphics#fill(float, float, float, float)
*
*/
public void noFill() {
if (recorder != null) recorder.noFill();
g.noFill();
}
/**
* Set the fill to either a grayscale value or an ARGB int.
* @param rgb color value in hexadecimal notation (i.e. #FFCC00 or 0xFFFFCC00) or any value of the color datatype
*/
public void fill(int rgb) {
if (recorder != null) recorder.fill(rgb);
g.fill(rgb);
}
public void fill(int rgb, float alpha) {
if (recorder != null) recorder.fill(rgb, alpha);
g.fill(rgb, alpha);
}
/**
* @param gray number specifying value between white and black
*/
public void fill(float gray) {
if (recorder != null) recorder.fill(gray);
g.fill(gray);
}
public void fill(float gray, float alpha) {
if (recorder != null) recorder.fill(gray, alpha);
g.fill(gray, alpha);
}
public void fill(float x, float y, float z) {
if (recorder != null) recorder.fill(x, y, z);
g.fill(x, y, z);
}
/**
* Sets the color used to fill shapes. For example, if you run fill(204, 102, 0), all subsequent shapes will be filled with orange. This color is either specified in terms of the RGB or HSB color depending on the current colorMode() (the default color space is RGB, with each value in the range from 0 to 255).
*
When using hexadecimal notation to specify a color, use "#" or "0x" before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six digits to specify a color (the way colors are specified in HTML and CSS). When using the hexadecimal notation starting with "0x", the hexadecimal value must be specified with eight characters; the first two characters define the alpha component and the remainder the red, green, and blue components.
*
The value for the parameter "gray" must be less than or equal to the current maximum value as specified by colorMode(). The default maximum value is 255.
*
To change the color of an image (or a texture), use tint().
*
* @webref color:setting
* @param x red or hue value
* @param y green or saturation value
* @param z blue or brightness value
* @param alpha opacity of the fill
*
* @see PGraphics#noFill()
* @see PGraphics#stroke(float)
* @see PGraphics#tint(float)
* @see PGraphics#background(float, float, float, float)
* @see PGraphics#colorMode(int, float, float, float, float)
*/
public void fill(float x, float y, float z, float a) {
if (recorder != null) recorder.fill(x, y, z, a);
g.fill(x, y, z, a);
}
public void ambient(int rgb) {
if (recorder != null) recorder.ambient(rgb);
g.ambient(rgb);
}
public void ambient(float gray) {
if (recorder != null) recorder.ambient(gray);
g.ambient(gray);
}
public void ambient(float x, float y, float z) {
if (recorder != null) recorder.ambient(x, y, z);
g.ambient(x, y, z);
}
public void specular(int rgb) {
if (recorder != null) recorder.specular(rgb);
g.specular(rgb);
}
public void specular(float gray) {
if (recorder != null) recorder.specular(gray);
g.specular(gray);
}
public void specular(float x, float y, float z) {
if (recorder != null) recorder.specular(x, y, z);
g.specular(x, y, z);
}
public void shininess(float shine) {
if (recorder != null) recorder.shininess(shine);
g.shininess(shine);
}
public void emissive(int rgb) {
if (recorder != null) recorder.emissive(rgb);
g.emissive(rgb);
}
public void emissive(float gray) {
if (recorder != null) recorder.emissive(gray);
g.emissive(gray);
}
public void emissive(float x, float y, float z) {
if (recorder != null) recorder.emissive(x, y, z);
g.emissive(x, y, z);
}
public void lights() {
if (recorder != null) recorder.lights();
g.lights();
}
public void noLights() {
if (recorder != null) recorder.noLights();
g.noLights();
}
public void ambientLight(float red, float green, float blue) {
if (recorder != null) recorder.ambientLight(red, green, blue);
g.ambientLight(red, green, blue);
}
public void ambientLight(float red, float green, float blue,
float x, float y, float z) {
if (recorder != null) recorder.ambientLight(red, green, blue, x, y, z);
g.ambientLight(red, green, blue, x, y, z);
}
public void directionalLight(float red, float green, float blue,
float nx, float ny, float nz) {
if (recorder != null) recorder.directionalLight(red, green, blue, nx, ny, nz);
g.directionalLight(red, green, blue, nx, ny, nz);
}
public void pointLight(float red, float green, float blue,
float x, float y, float z) {
if (recorder != null) recorder.pointLight(red, green, blue, x, y, z);
g.pointLight(red, green, blue, x, y, z);
}
public void spotLight(float red, float green, float blue,
float x, float y, float z,
float nx, float ny, float nz,
float angle, float concentration) {
if (recorder != null) recorder.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration);
g.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration);
}
public void lightFalloff(float constant, float linear, float quadratic) {
if (recorder != null) recorder.lightFalloff(constant, linear, quadratic);
g.lightFalloff(constant, linear, quadratic);
}
public void lightSpecular(float x, float y, float z) {
if (recorder != null) recorder.lightSpecular(x, y, z);
g.lightSpecular(x, y, z);
}
/**
* Set the background to a gray or ARGB color.
*
or any value of the color datatype
*/
public void background(int rgb) {
if (recorder != null) recorder.background(rgb);
g.background(rgb);
}
/**
* See notes about alpha in background(x, y, z, a).
*/
public void background(int rgb, float alpha) {
if (recorder != null) recorder.background(rgb, alpha);
g.background(rgb, alpha);
}
/**
* Set the background to a grayscale value, based on the
* current colorMode.
*/
public void background(float gray) {
if (recorder != null) recorder.background(gray);
g.background(gray);
}
/**
* See notes about alpha in background(x, y, z, a).
* @param gray specifies a value between white and black
* @param alpha opacity of the background
*/
public void background(float gray, float alpha) {
if (recorder != null) recorder.background(gray, alpha);
g.background(gray, alpha);
}
/**
* Set the background to an r, g, b or h, s, b value,
* based on the current colorMode.
*/
public void background(float x, float y, float z) {
if (recorder != null) recorder.background(x, y, z);
g.background(x, y, z);
}
/**
* The background() function sets the color used for the background of the Processing window. The default background is light gray. In the draw() function, the background color is used to clear the display window at the beginning of each frame.
*
An image can also be used as the background for a sketch, however its width and height must be the same size as the sketch window. To resize an image 'b' to the size of the sketch window, use b.resize(width, height).
*
Images used as background will ignore the current tint() setting.
*
It is not possible to use transparency (alpha) in background colors with the main drawing surface, however they will work properly with createGraphics.
*
* =advanced
* colorMode(HSB, 360, 100, 100);
* because the alpha values were still between 0 and 255.
*/
public void colorMode(int mode, float maxX, float maxY, float maxZ) {
if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ);
g.colorMode(mode, maxX, maxY, maxZ);
}
/**
* Changes the way Processing interprets color data. By default, the parameters for fill(), stroke(), background(), and color() are defined by values between 0 and 255 using the RGB color model. The colorMode() function is used to change the numerical range used for specifying colors and to switch color systems. For example, calling colorMode(RGB, 1.0) will specify that values are specified between 0 and 1. The limits for defining colors are altered by setting the parameters range1, range2, range3, and range 4.
*
* @webref color:setting
* @param maxX range for the red or hue depending on the current color mode
* @param maxY range for the green or saturation depending on the current color mode
* @param maxZ range for the blue or brightness depending on the current color mode
* @param maxA range for the alpha
*
* @see PGraphics#background(float)
* @see PGraphics#fill(float)
* @see PGraphics#stroke(float)
*/
public void colorMode(int mode,
float maxX, float maxY, float maxZ, float maxA) {
if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ, maxA);
g.colorMode(mode, maxX, maxY, maxZ, maxA);
}
/**
* Extracts the alpha value from a color.
*
* @webref color:creating_reading
* @param what any value of the color datatype
*/
public final float alpha(int what) {
return g.alpha(what);
}
/**
* Extracts the red value from a color, scaled to match current colorMode(). This value is always returned as a float so be careful not to assign it to an int value.
The red() function is easy to use and undestand, but is slower than another technique. To achieve the same results when working in colorMode(RGB, 255), but with greater speed, use the >> (right shift) operator with a bit mask. For example, the following two lines of code are equivalent:float r1 = red(myColor);
*
* @webref color:creating_reading
* @param what any value of the color datatype
*
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
* @ref rightshift
*/
public final float red(int what) {
return g.red(what);
}
/**
* Extracts the green value from a color, scaled to match current colorMode(). This value is always returned as a float so be careful not to assign it to an int value.
float r2 = myColor >> 16 & 0xFF;
The green() function is easy to use and undestand, but is slower than another technique. To achieve the same results when working in colorMode(RGB, 255), but with greater speed, use the >> (right shift) operator with a bit mask. For example, the following two lines of code are equivalent:float r1 = green(myColor);
*
* @webref color:creating_reading
* @param what any value of the color datatype
*
* @see PGraphics#red(int)
* @see PGraphics#blue(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
* @ref rightshift
*/
public final float green(int what) {
return g.green(what);
}
/**
* Extracts the blue value from a color, scaled to match current colorMode(). This value is always returned as a float so be careful not to assign it to an int value.
float r2 = myColor >> 8 & 0xFF;
The blue() function is easy to use and undestand, but is slower than another technique. To achieve the same results when working in colorMode(RGB, 255), but with greater speed, use a bit mask to remove the other color components. For example, the following two lines of code are equivalent:float r1 = blue(myColor);
*
* @webref color:creating_reading
* @param what any value of the color datatype
*
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
*/
public final float blue(int what) {
return g.blue(what);
}
/**
* Extracts the hue value from a color.
*
* @webref color:creating_reading
* @param what any value of the color datatype
*
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
*/
public final float hue(int what) {
return g.hue(what);
}
/**
* Extracts the saturation value from a color.
*
* @webref color:creating_reading
* @param what any value of the color datatype
*
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#hue(int)
* @see PGraphics#brightness(int)
*/
public final float saturation(int what) {
return g.saturation(what);
}
/**
* Extracts the brightness value from a color.
*
*
* @webref color:creating_reading
* @param what any value of the color datatype
*
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
*/
public final float brightness(int what) {
return g.brightness(what);
}
/**
* Calculates a color or colors between two color at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc.
*
* @webref color:creating_reading
* @param c1 interpolate from this color
* @param c2 interpolate to this color
* @param amt between 0.0 and 1.0
*
* @see PGraphics#blendColor(int, int, int)
* @see PGraphics#color(float, float, float, float)
*/
public int lerpColor(int c1, int c2, float amt) {
return g.lerpColor(c1, c2, amt);
}
/**
* Interpolate between two colors. Like lerp(), but for the
* individual color components of a color supplied as an int value.
*/
static public int lerpColor(int c1, int c2, float amt, int mode) {
return PGraphics.lerpColor(c1, c2, amt, mode);
}
/**
* Return true if this renderer should be drawn to the screen. Defaults to
* returning true, since nearly all renderers are on-screen beasts. But can
* be overridden for subclasses like PDF so that a window doesn't open up.
*
float r2 = myColor & 0xFF;
* A better name? showFrame, displayable, isVisible, visible, shouldDisplay,
* what to call this?
*/
public boolean displayable() {
return g.displayable();
}
/**
* Store data of some kind for a renderer that requires extra metadata of
* some kind. Usually this is a renderer-specific representation of the
* image data, for instance a BufferedImage with tint() settings applied for
* PGraphicsJava2D, or resized image data and OpenGL texture indices for
* PGraphicsOpenGL.
*/
public void setCache(Object parent, Object storage) {
if (recorder != null) recorder.setCache(parent, storage);
g.setCache(parent, storage);
}
/**
* Get cache storage data for the specified renderer. Because each renderer
* will cache data in different formats, it's necessary to store cache data
* keyed by the renderer object. Otherwise, attempting to draw the same
* image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors.
* @param parent The PGraphics object (or any object, really) associated
* @return data stored for the specified parent
*/
public Object getCache(Object parent) {
return g.getCache(parent);
}
/**
* Remove information associated with this renderer from the cache, if any.
* @param parent The PGraphics object whose cache data should be removed
*/
public void removeCache(Object parent) {
if (recorder != null) recorder.removeCache(parent);
g.removeCache(parent);
}
/**
* Returns an ARGB "color" type (a packed 32 bit int with the color.
* If the coordinate is outside the image, zero is returned
* (black, but completely transparent).
*
Getting the color of a single pixel with get(x, y) is easy, but not as fast as grabbing the data directly from pixels[]. The equivalent statement to "get(x, y)" using pixels[] is "pixels[y*width+x]". Processing requires calling loadPixels() to load the display window data into the pixels[] array before getting the values.
*
As of release 0149, this function ignores imageMode().
*
* @webref
* @brief Reads the color of any pixel or grabs a rectangle of pixels
* @param x x-coordinate of the pixel
* @param y y-coordinate of the pixel
* @param w width of pixel rectangle to get
* @param h height of pixel rectangle to get
*
* @see processing.core.PImage#set(int, int, int)
* @see processing.core.PImage#pixels
* @see processing.core.PImage#copy(PImage, int, int, int, int, int, int, int, int)
*/
public PImage get(int x, int y, int w, int h) {
return g.get(x, y, w, h);
}
/**
* Returns a copy of this PImage. Equivalent to get(0, 0, width, height).
*/
public PImage get() {
return g.get();
}
/**
* Changes the color of any pixel or writes an image directly into the display window. The x and y parameters specify the pixel to change and the color parameter specifies the color value. The color parameter is affected by the current color mode (the default is RGB values from 0 to 255). When setting an image, the x and y parameters define the coordinates for the upper-left corner of the image.
*
Setting the color of a single pixel with set(x, y) is easy, but not as fast as putting the data directly into pixels[]. The equivalent statement to "set(x, y, #000000)" using pixels[] is "pixels[y*width+x] = #000000". You must call loadPixels() to load the display window data into the pixels[] array before setting the values and calling updatePixels() to update the window with any changes.
*
As of release 1.0, this function ignores imageMode().
*
Due to what appears to be a bug in Apple's Java implementation, the point() and set() methods are extremely slow in some circumstances when used with the default renderer. Using P2D or P3D will fix the problem. Grouping many calls to point() or set() together can also help. (Bug 1094)
* =advanced
*
As of release 0149, this function ignores imageMode().
*
* @webref image:pixels
* @param x x-coordinate of the pixel
* @param y y-coordinate of the pixel
* @param c any value of the color datatype
*/
public void set(int x, int y, int c) {
if (recorder != null) recorder.set(x, y, c);
g.set(x, y, c);
}
/**
* Efficient method of drawing an image's pixels directly to this surface.
* No variations are employed, meaning that any scale, tint, or imageMode
* settings will be ignored.
*/
public void set(int x, int y, PImage src) {
if (recorder != null) recorder.set(x, y, src);
g.set(x, y, src);
}
/**
* Set alpha channel for an image. Black colors in the source
* image will make the destination image completely transparent,
* and white will make things fully opaque. Gray values will
* be in-between steps.
*
THRESHOLD - converts the image to black and white pixels depending if they are above or below the threshold defined by the level parameter. The level must be between 0.0 (black) and 1.0(white). If no level is specified, 0.5 is used.
GRAY - converts any colors in the image to grayscale equivalents
INVERT - sets each pixel to its inverse value
POSTERIZE - limits each channel of the image to the number of colors specified as the level parameter
BLUR - executes a Guassian blur with the level parameter specifying the extent of the blurring. If no level parameter is used, the blur is equivalent to Guassian blur of radius 1.
OPAQUE - sets the alpha channel to entirely opaque.
ERODE - reduces the light areas with the amount defined by the level parameter.
DILATE - increases the light areas with the amount defined by the level parameter
* =advanced
* Method to apply a variety of basic filters to this image.
*
*
* Luminance conversion code contributed by
* toxi
*
* Gaussian blur code contributed by
* Mario Klingemann
*
* @webref
* @brief Converts the image to grayscale or black and white
* @param kind Either THRESHOLD, GRAY, INVERT, POSTERIZE, BLUR, OPAQUE, ERODE, or DILATE
* @param param in the range from 0 to 1
*/
public void filter(int kind, float param) {
if (recorder != null) recorder.filter(kind, param);
g.filter(kind, param);
}
/**
* Copy things from one area of this image
* to another area in the same image.
*/
public void copy(int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh);
g.copy(sx, sy, sw, sh, dx, dy, dw, dh);
}
/**
* Copies a region of pixels from one image into another. If the source and destination regions aren't the same size, it will automatically resize source pixels to fit the specified target region. No alpha information is used in the process, however if the source image has an alpha channel set, it will be copied as well.
*
As of release 0149, this function ignores imageMode().
*
* @webref
* @brief Copies the entire image
* @param sx X coordinate of the source's upper left corner
* @param sy Y coordinate of the source's upper left corner
* @param sw source image width
* @param sh source image height
* @param dx X coordinate of the destination's upper left corner
* @param dy Y coordinate of the destination's upper left corner
* @param dw destination image width
* @param dh destination image height
* @param src an image variable referring to the source image.
*
* @see processing.core.PGraphics#alpha(int)
* @see processing.core.PImage#blend(PImage, int, int, int, int, int, int, int, int, int)
*/
public void copy(PImage src,
int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
}
/**
* Blend two colors based on a particular mode.
*
*
*
* BLEND - linear interpolation of colours: C = A*factor + B
* ADD - additive blending with white clip: C = min(A*factor + B, 255)
* SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, 0)
* DARKEST - only the darkest colour succeeds: C = min(A*factor, B)
* LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)
* DIFFERENCE - subtract colors from underlying image.
* EXCLUSION - similar to DIFFERENCE, but less extreme.
* MULTIPLY - Multiply the colors, result will always be darker.
* SCREEN - Opposite multiply, uses inverse values of the colors.
* OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, and screens light values.
* HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.
* SOFT_LIGHT - Mix of DARKEST and LIGHTEST. Works like OVERLAY, but not as harsh.
* DODGE - Lightens light tones and increases contrast, ignores darks. Called "Color Dodge" in Illustrator and Photoshop.
* BURN - Darker areas are applied, increasing contrast, ignores lights. Called "Color Burn" in Illustrator and Photoshop.
* All modes use the alpha information (highest byte) of source image pixels as the blending factor. If the source and destination regions are different sizes, the image will be automatically resized to match the destination size. If the srcImg parameter is not used, the display window is used as the source image.
* As of release 0149, this function ignores imageMode().
*
* @webref
* @brief Copies a pixel or rectangle of pixels using different blending modes
* @param src an image variable referring to the source image
* @param sx X coordinate of the source's upper left corner
* @param sy Y coordinate of the source's upper left corner
* @param sw source image width
* @param sh source image height
* @param dx X coordinate of the destinations's upper left corner
* @param dy Y coordinate of the destinations's upper left corner
* @param dw destination image width
* @param dh destination image height
* @param mode Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN
*
* @see processing.core.PGraphics#alpha(int)
* @see processing.core.PGraphics#copy(PImage, int, int, int, int, int, int, int, int)
* @see processing.core.PImage#blendColor(int,int,int)
*/
public void blend(PImage src,
int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh, int mode) {
if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
}
}
processing-core-1.2.1/src/processing/core/PStyle.java 0000644 0001750 0001750 00000003431 11070251526 022115 0 ustar andrew andrew /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2008 Ben Fry and Casey Reas
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
public class PStyle implements PConstants {
public int imageMode;
public int rectMode;
public int ellipseMode;
public int shapeMode;
public int colorMode;
public float colorModeX;
public float colorModeY;
public float colorModeZ;
public float colorModeA;
public boolean tint;
public int tintColor;
public boolean fill;
public int fillColor;
public boolean stroke;
public int strokeColor;
public float strokeWeight;
public int strokeCap;
public int strokeJoin;
// TODO these fellas are inconsistent, and may need to go elsewhere
public float ambientR, ambientG, ambientB;
public float specularR, specularG, specularB;
public float emissiveR, emissiveG, emissiveB;
public float shininess;
public PFont textFont;
public int textAlign;
public int textAlignY;
public int textMode;
public float textSize;
public float textLeading;
}
processing-core-1.2.1/src/processing/core/PGraphics3D.java 0000644 0001750 0001750 00000402630 11402142471 022745 0 ustar andrew andrew /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-08 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
import java.awt.Toolkit;
import java.awt.image.*;
import java.util.*;
/**
* Subclass of PGraphics that handles 3D rendering.
* It can render 3D inside a browser window and requires no plug-ins.
*
* The renderer is mostly set up based on the structure of the OpenGL API,
* if you have questions about specifics that aren't covered here,
* look for reference on the OpenGL implementation of a similar feature.
*
* Lighting and camera implementation by Simon Greenwold.
*/
public class PGraphics3D extends PGraphics {
/** The depth buffer. */
public float[] zbuffer;
// ........................................................
/** The modelview matrix. */
public PMatrix3D modelview;
/** Inverse modelview matrix, used for lighting. */
public PMatrix3D modelviewInv;
/**
* Marks when changes to the size have occurred, so that the camera
* will be reset in beginDraw().
*/
protected boolean sizeChanged;
/** The camera matrix, the modelview will be set to this on beginDraw. */
public PMatrix3D camera;
/** Inverse camera matrix */
protected PMatrix3D cameraInv;
/** Camera field of view. */
public float cameraFOV;
/** Position of the camera. */
public float cameraX, cameraY, cameraZ;
public float cameraNear, cameraFar;
/** Aspect ratio of camera's view. */
public float cameraAspect;
/** Current projection matrix. */
public PMatrix3D projection;
//////////////////////////////////////////////////////////////
/**
* Maximum lights by default is 8, which is arbitrary for this renderer,
* but is the minimum defined by OpenGL
*/
public static final int MAX_LIGHTS = 8;
public int lightCount = 0;
/** Light types */
public int[] lightType;
/** Light positions */
//public float[][] lightPosition;
public PVector[] lightPosition;
/** Light direction (normalized vector) */
//public float[][] lightNormal;
public PVector[] lightNormal;
/** Light falloff */
public float[] lightFalloffConstant;
public float[] lightFalloffLinear;
public float[] lightFalloffQuadratic;
/** Light spot angle */
public float[] lightSpotAngle;
/** Cosine of light spot angle */
public float[] lightSpotAngleCos;
/** Light spot concentration */
public float[] lightSpotConcentration;
/** Diffuse colors for lights.
* For an ambient light, this will hold the ambient color.
* Internally these are stored as numbers between 0 and 1. */
public float[][] lightDiffuse;
/** Specular colors for lights.
Internally these are stored as numbers between 0 and 1. */
public float[][] lightSpecular;
/** Current specular color for lighting */
public float[] currentLightSpecular;
/** Current light falloff */
public float currentLightFalloffConstant;
public float currentLightFalloffLinear;
public float currentLightFalloffQuadratic;
//////////////////////////////////////////////////////////////
static public final int TRI_DIFFUSE_R = 0;
static public final int TRI_DIFFUSE_G = 1;
static public final int TRI_DIFFUSE_B = 2;
static public final int TRI_DIFFUSE_A = 3;
static public final int TRI_SPECULAR_R = 4;
static public final int TRI_SPECULAR_G = 5;
static public final int TRI_SPECULAR_B = 6;
static public final int TRI_COLOR_COUNT = 7;
// ........................................................
// Whether or not we have to worry about vertex position for lighting calcs
private boolean lightingDependsOnVertexPosition;
static final int LIGHT_AMBIENT_R = 0;
static final int LIGHT_AMBIENT_G = 1;
static final int LIGHT_AMBIENT_B = 2;
static final int LIGHT_DIFFUSE_R = 3;
static final int LIGHT_DIFFUSE_G = 4;
static final int LIGHT_DIFFUSE_B = 5;
static final int LIGHT_SPECULAR_R = 6;
static final int LIGHT_SPECULAR_G = 7;
static final int LIGHT_SPECULAR_B = 8;
static final int LIGHT_COLOR_COUNT = 9;
// Used to shuttle lighting calcs around
// (no need to re-allocate all the time)
protected float[] tempLightingContribution = new float[LIGHT_COLOR_COUNT];
// protected float[] worldNormal = new float[4];
/// Used in lightTriangle(). Allocated here once to avoid re-allocating
protected PVector lightTriangleNorm = new PVector();
// ........................................................
/**
* This is turned on at beginCamera, and off at endCamera
* Currently we don't support nested begin/end cameras.
* If we wanted to, this variable would have to become a stack.
*/
protected boolean manipulatingCamera;
float[][] matrixStack = new float[MATRIX_STACK_DEPTH][16];
float[][] matrixInvStack = new float[MATRIX_STACK_DEPTH][16];
int matrixStackDepth;
// These two matrices always point to either the modelview
// or the modelviewInv, but they are swapped during
// when in camera manipulation mode. That way camera transforms
// are automatically accumulated in inverse on the modelview matrix.
protected PMatrix3D forwardTransform;
protected PMatrix3D reverseTransform;
// Added by ewjordan for accurate texturing purposes. Screen plane is
// not scaled to pixel-size, so these manually keep track of its size
// from frustum() calls. Sorry to add public vars, is there a way
// to compute these from something publicly available without matrix ops?
// (used once per triangle in PTriangle with ENABLE_ACCURATE_TEXTURES)
protected float leftScreen;
protected float rightScreen;
protected float topScreen;
protected float bottomScreen;
protected float nearPlane; //depth of near clipping plane
/** true if frustum has been called to set perspective, false if ortho */
private boolean frustumMode = false;
/**
* Use PSmoothTriangle for rendering instead of PTriangle?
* Usually set by calling smooth() or noSmooth()
*/
static protected boolean s_enableAccurateTextures = false; //maybe just use smooth instead?
/** Used for anti-aliased and perspective corrected rendering. */
public PSmoothTriangle smoothTriangle;
// ........................................................
// pos of first vertex of current shape in vertices array
protected int shapeFirst;
// i think vertex_end is actually the last vertex in the current shape
// and is separate from vertexCount for occasions where drawing happens
// on endDraw() with all the triangles being depth sorted
protected int shapeLast;
// vertices may be added during clipping against the near plane.
protected int shapeLastPlusClipped;
// used for sorting points when triangulating a polygon
// warning - maximum number of vertices for a polygon is DEFAULT_VERTICES
protected int vertexOrder[] = new int[DEFAULT_VERTICES];
// ........................................................
// This is done to keep track of start/stop information for lines in the
// line array, so that lines can be shown as a single path, rather than just
// individual segments. Currently only in use inside PGraphicsOpenGL.
protected int pathCount;
protected int[] pathOffset = new int[64];
protected int[] pathLength = new int[64];
// ........................................................
// line & triangle fields (note that these overlap)
// static protected final int INDEX = 0; // shape index
static protected final int VERTEX1 = 0;
static protected final int VERTEX2 = 1;
static protected final int VERTEX3 = 2; // (triangles only)
/** used to store the strokeColor int for efficient drawing. */
static protected final int STROKE_COLOR = 1; // (points only)
static protected final int TEXTURE_INDEX = 3; // (triangles only)
//static protected final int STROKE_MODE = 2; // (lines only)
//static protected final int STROKE_WEIGHT = 3; // (lines only)
static protected final int POINT_FIELD_COUNT = 2; //4
static protected final int LINE_FIELD_COUNT = 2; //4
static protected final int TRIANGLE_FIELD_COUNT = 4;
// points
static final int DEFAULT_POINTS = 512;
protected int[][] points = new int[DEFAULT_POINTS][POINT_FIELD_COUNT];
protected int pointCount;
// lines
static final int DEFAULT_LINES = 512;
public PLine line; // used for drawing
protected int[][] lines = new int[DEFAULT_LINES][LINE_FIELD_COUNT];
protected int lineCount;
// triangles
static final int DEFAULT_TRIANGLES = 256;
public PTriangle triangle;
protected int[][] triangles =
new int[DEFAULT_TRIANGLES][TRIANGLE_FIELD_COUNT];
protected float triangleColors[][][] =
new float[DEFAULT_TRIANGLES][3][TRI_COLOR_COUNT];
protected int triangleCount; // total number of triangles
// cheap picking someday
//public int shape_index;
// ........................................................
static final int DEFAULT_TEXTURES = 3;
protected PImage[] textures = new PImage[DEFAULT_TEXTURES];
int textureIndex;
// ........................................................
DirectColorModel cm;
MemoryImageSource mis;
//////////////////////////////////////////////////////////////
public PGraphics3D() { }
//public void setParent(PApplet parent)
//public void setPrimary(boolean primary)
//public void setPath(String path)
/**
* Called in response to a resize event, handles setting the
* new width and height internally, as well as re-allocating
* the pixel buffer for the new size.
*
* Note that this will nuke any cameraMode() settings.
*
* No drawing can happen in this function, and no talking to the graphics
* context. That is, no glXxxx() calls, or other things that change state.
*/
public void setSize(int iwidth, int iheight) { // ignore
width = iwidth;
height = iheight;
width1 = width - 1;
height1 = height - 1;
allocate();
reapplySettings();
// init lights (in resize() instead of allocate() b/c needed by opengl)
lightType = new int[MAX_LIGHTS];
lightPosition = new PVector[MAX_LIGHTS];
lightNormal = new PVector[MAX_LIGHTS];
for (int i = 0; i < MAX_LIGHTS; i++) {
lightPosition[i] = new PVector();
lightNormal[i] = new PVector();
}
lightDiffuse = new float[MAX_LIGHTS][3];
lightSpecular = new float[MAX_LIGHTS][3];
lightFalloffConstant = new float[MAX_LIGHTS];
lightFalloffLinear = new float[MAX_LIGHTS];
lightFalloffQuadratic = new float[MAX_LIGHTS];
lightSpotAngle = new float[MAX_LIGHTS];
lightSpotAngleCos = new float[MAX_LIGHTS];
lightSpotConcentration = new float[MAX_LIGHTS];
currentLightSpecular = new float[3];
projection = new PMatrix3D();
modelview = new PMatrix3D();
modelviewInv = new PMatrix3D();
// modelviewStack = new float[MATRIX_STACK_DEPTH][16];
// modelviewInvStack = new float[MATRIX_STACK_DEPTH][16];
// modelviewStackPointer = 0;
forwardTransform = modelview;
reverseTransform = modelviewInv;
// init perspective projection based on new dimensions
cameraFOV = 60 * DEG_TO_RAD; // at least for now
cameraX = width / 2.0f;
cameraY = height / 2.0f;
cameraZ = cameraY / ((float) Math.tan(cameraFOV / 2.0f));
cameraNear = cameraZ / 10.0f;
cameraFar = cameraZ * 10.0f;
cameraAspect = (float)width / (float)height;
camera = new PMatrix3D();
cameraInv = new PMatrix3D();
// set this flag so that beginDraw() will do an update to the camera.
sizeChanged = true;
}
protected void allocate() {
//System.out.println(this + " allocating for " + width + " " + height);
//new Exception().printStackTrace();
pixelCount = width * height;
pixels = new int[pixelCount];
zbuffer = new float[pixelCount];
if (primarySurface) {
cm = new DirectColorModel(32, 0x00ff0000, 0x0000ff00, 0x000000ff);;
mis = new MemoryImageSource(width, height, pixels, 0, width);
mis.setFullBufferUpdates(true);
mis.setAnimated(true);
image = Toolkit.getDefaultToolkit().createImage(mis);
} else {
// when not the main drawing surface, need to set the zbuffer,
// because there's a possibility that background() will not be called
Arrays.fill(zbuffer, Float.MAX_VALUE);
}
line = new PLine(this);
triangle = new PTriangle(this);
smoothTriangle = new PSmoothTriangle(this);
}
//public void dispose()
////////////////////////////////////////////////////////////
//public boolean canDraw()
public void beginDraw() {
// need to call defaults(), but can only be done when it's ok
// to draw (i.e. for opengl, no drawing can be done outside
// beginDraw/endDraw).
if (!settingsInited) defaultSettings();
if (sizeChanged) {
// set up the default camera
camera();
// defaults to perspective, if the user has setup up their
// own projection, they'll need to fix it after resize anyway.
// this helps the people who haven't set up their own projection.
perspective();
// clear the flag
sizeChanged = false;
}
resetMatrix(); // reset model matrix
// reset vertices
vertexCount = 0;
modelview.set(camera);
modelviewInv.set(cameraInv);
// clear out the lights, they'll have to be turned on again
lightCount = 0;
lightingDependsOnVertexPosition = false;
lightFalloff(1, 0, 0);
lightSpecular(0, 0, 0);
/*
// reset lines
lineCount = 0;
if (line != null) line.reset(); // is this necessary?
pathCount = 0;
// reset triangles
triangleCount = 0;
if (triangle != null) triangle.reset(); // necessary?
*/
shapeFirst = 0;
// reset textures
Arrays.fill(textures, null);
textureIndex = 0;
normal(0, 0, 1);
}
/**
* See notes in PGraphics.
* If z-sorting has been turned on, then the triangles will
* all be quicksorted here (to make alpha work more properly)
* and then blit to the screen.
*/
public void endDraw() {
// no need to z order and render
// shapes were already rendered in endShape();
// (but can't return, since needs to update memimgsrc)
if (hints[ENABLE_DEPTH_SORT]) {
flush();
}
if (mis != null) {
mis.newPixels(pixels, cm, 0, width);
}
// mark pixels as having been updated, so that they'll work properly
// when this PGraphics is drawn using image().
updatePixels();
}
////////////////////////////////////////////////////////////
//protected void checkSettings()
protected void defaultSettings() {
super.defaultSettings();
manipulatingCamera = false;
forwardTransform = modelview;
reverseTransform = modelviewInv;
// set up the default camera
camera();
// defaults to perspective, if the user has setup up their
// own projection, they'll need to fix it after resize anyway.
// this helps the people who haven't set up their own projection.
perspective();
// easiest for beginners
textureMode(IMAGE);
emissive(0.0f);
specular(0.5f);
shininess(1.0f);
}
//protected void reapplySettings()
////////////////////////////////////////////////////////////
public void hint(int which) {
if (which == DISABLE_DEPTH_SORT) {
flush();
} else if (which == DISABLE_DEPTH_TEST) {
if (zbuffer != null) { // will be null in OpenGL and others
Arrays.fill(zbuffer, Float.MAX_VALUE);
}
}
super.hint(which);
}
//////////////////////////////////////////////////////////////
//public void beginShape()
public void beginShape(int kind) {
shape = kind;
// shape_index = shape_index + 1;
// if (shape_index == -1) {
// shape_index = 0;
// }
if (hints[ENABLE_DEPTH_SORT]) {
// continue with previous vertex, line and triangle count
// all shapes are rendered at endDraw();
shapeFirst = vertexCount;
shapeLast = 0;
} else {
// reset vertex, line and triangle information
// every shape is rendered at endShape();
vertexCount = 0;
if (line != null) line.reset(); // necessary?
lineCount = 0;
// pathCount = 0;
if (triangle != null) triangle.reset(); // necessary?
triangleCount = 0;
}
textureImage = null;
curveVertexCount = 0;
normalMode = NORMAL_MODE_AUTO;
// normalCount = 0;
}
//public void normal(float nx, float ny, float nz)
//public void textureMode(int mode)
public void texture(PImage image) {
textureImage = image;
if (textureIndex == textures.length - 1) {
textures = (PImage[]) PApplet.expand(textures);
}
if (textures[textureIndex] != null) { // ???
textureIndex++;
}
textures[textureIndex] = image;
}
public void vertex(float x, float y) {
// override so that the default 3D implementation will be used,
// which will pick up all 3D settings (e.g. emissive, ambient)
vertex(x, y, 0);
}
//public void vertex(float x, float y, float z)
public void vertex(float x, float y, float u, float v) {
// see vertex(x, y) for note
vertex(x, y, 0, u, v);
}
//public void vertex(float x, float y, float z, float u, float v)
//public void breakShape()
//public void endShape()
public void endShape(int mode) {
shapeLast = vertexCount;
shapeLastPlusClipped = shapeLast;
// don't try to draw if there are no vertices
// (fixes a bug in LINE_LOOP that re-adds a nonexistent vertex)
if (vertexCount == 0) {
shape = 0;
return;
}
// convert points from model (X/Y/Z) to camera space (VX/VY/VZ).
// Do this now because we will be clipping them on add_triangle.
endShapeModelToCamera(shapeFirst, shapeLast);
if (stroke) {
endShapeStroke(mode);
}
if (fill || textureImage != null) {
endShapeFill();
}
// transform, light, and clip
endShapeLighting(lightCount > 0 && fill);
// convert points from camera space (VX, VY, VZ) to screen space (X, Y, Z)
// (this appears to be wasted time with the OpenGL renderer)
endShapeCameraToScreen(shapeFirst, shapeLastPlusClipped);
// render shape and fill here if not saving the shapes for later
// if true, the shapes will be rendered on endDraw
if (!hints[ENABLE_DEPTH_SORT]) {
if (fill || textureImage != null) {
if (triangleCount > 0) {
renderTriangles(0, triangleCount);
if (raw != null) {
rawTriangles(0, triangleCount);
}
triangleCount = 0;
}
}
if (stroke) {
if (pointCount > 0) {
renderPoints(0, pointCount);
if (raw != null) {
rawPoints(0, pointCount);
}
pointCount = 0;
}
if (lineCount > 0) {
renderLines(0, lineCount);
if (raw != null) {
rawLines(0, lineCount);
}
lineCount = 0;
}
}
pathCount = 0;
}
shape = 0;
}
protected void endShapeModelToCamera(int start, int stop) {
for (int i = start; i < stop; i++) {
float vertex[] = vertices[i];
vertex[VX] =
modelview.m00*vertex[X] + modelview.m01*vertex[Y] +
modelview.m02*vertex[Z] + modelview.m03;
vertex[VY] =
modelview.m10*vertex[X] + modelview.m11*vertex[Y] +
modelview.m12*vertex[Z] + modelview.m13;
vertex[VZ] =
modelview.m20*vertex[X] + modelview.m21*vertex[Y] +
modelview.m22*vertex[Z] + modelview.m23;
vertex[VW] =
modelview.m30*vertex[X] + modelview.m31*vertex[Y] +
modelview.m32*vertex[Z] + modelview.m33;
// normalize
if (vertex[VW] != 0 && vertex[VW] != 1) {
vertex[VX] /= vertex[VW];
vertex[VY] /= vertex[VW];
vertex[VZ] /= vertex[VW];
}
vertex[VW] = 1;
}
}
protected void endShapeStroke(int mode) {
switch (shape) {
case POINTS:
{
int stop = shapeLast;
for (int i = shapeFirst; i < stop; i++) {
// if (strokeWeight == 1) {
addPoint(i);
// } else {
// addLineBreak(); // total overkill for points
// addLine(i, i);
// }
}
}
break;
case LINES:
{
// store index of first vertex
int first = lineCount;
int stop = shapeLast - 1;
//increment = (shape == LINES) ? 2 : 1;
// for LINE_STRIP and LINE_LOOP, make this all one path
if (shape != LINES) addLineBreak();
for (int i = shapeFirst; i < stop; i += 2) {
// for LINES, make a new path for each segment
if (shape == LINES) addLineBreak();
addLine(i, i+1);
}
// for LINE_LOOP, close the loop with a final segment
//if (shape == LINE_LOOP) {
if (mode == CLOSE) {
addLine(stop, lines[first][VERTEX1]);
}
}
break;
case TRIANGLES:
{
for (int i = shapeFirst; i < shapeLast-2; i += 3) {
addLineBreak();
//counter = i - vertex_start;
addLine(i+0, i+1);
addLine(i+1, i+2);
addLine(i+2, i+0);
}
}
break;
case TRIANGLE_STRIP:
{
// first draw all vertices as a line strip
int stop = shapeLast-1;
addLineBreak();
for (int i = shapeFirst; i < stop; i++) {
//counter = i - vertex_start;
addLine(i, i+1);
}
// then draw from vertex (n) to (n+2)
stop = shapeLast-2;
for (int i = shapeFirst; i < stop; i++) {
addLineBreak();
addLine(i, i+2);
}
}
break;
case TRIANGLE_FAN:
{
// this just draws a series of line segments
// from the center to each exterior point
for (int i = shapeFirst + 1; i < shapeLast; i++) {
addLineBreak();
addLine(shapeFirst, i);
}
// then a single line loop around the outside.
addLineBreak();
for (int i = shapeFirst + 1; i < shapeLast-1; i++) {
addLine(i, i+1);
}
// closing the loop
addLine(shapeLast-1, shapeFirst + 1);
}
break;
case QUADS:
{
for (int i = shapeFirst; i < shapeLast; i += 4) {
addLineBreak();
//counter = i - vertex_start;
addLine(i+0, i+1);
addLine(i+1, i+2);
addLine(i+2, i+3);
addLine(i+3, i+0);
}
}
break;
case QUAD_STRIP:
{
for (int i = shapeFirst; i < shapeLast - 3; i += 2) {
addLineBreak();
addLine(i+0, i+2);
addLine(i+2, i+3);
addLine(i+3, i+1);
addLine(i+1, i+0);
}
}
break;
case POLYGON:
{
// store index of first vertex
int stop = shapeLast - 1;
addLineBreak();
for (int i = shapeFirst; i < stop; i++) {
addLine(i, i+1);
}
if (mode == CLOSE) {
// draw the last line connecting back to the first point in poly
addLine(stop, shapeFirst); //lines[first][VERTEX1]);
}
}
break;
}
}
protected void endShapeFill() {
switch (shape) {
case TRIANGLE_FAN:
{
int stop = shapeLast - 1;
for (int i = shapeFirst + 1; i < stop; i++) {
addTriangle(shapeFirst, i, i+1);
}
}
break;
case TRIANGLES:
{
int stop = shapeLast - 2;
for (int i = shapeFirst; i < stop; i += 3) {
// have to switch between clockwise/counter-clockwise
// otherwise the feller is backwards and renderer won't draw
if ((i % 2) == 0) {
addTriangle(i, i+2, i+1);
} else {
addTriangle(i, i+1, i+2);
}
}
}
break;
case TRIANGLE_STRIP:
{
int stop = shapeLast - 2;
for (int i = shapeFirst; i < stop; i++) {
// have to switch between clockwise/counter-clockwise
// otherwise the feller is backwards and renderer won't draw
if ((i % 2) == 0) {
addTriangle(i, i+2, i+1);
} else {
addTriangle(i, i+1, i+2);
}
}
}
break;
case QUADS:
{
int stop = vertexCount-3;
for (int i = shapeFirst; i < stop; i += 4) {
// first triangle
addTriangle(i, i+1, i+2);
// second triangle
addTriangle(i, i+2, i+3);
}
}
break;
case QUAD_STRIP:
{
int stop = vertexCount-3;
for (int i = shapeFirst; i < stop; i += 2) {
// first triangle
addTriangle(i+0, i+2, i+1);
// second triangle
addTriangle(i+2, i+3, i+1);
}
}
break;
case POLYGON:
{
addPolygonTriangles();
}
break;
}
}
protected void endShapeLighting(boolean lights) {
if (lights) {
// If the lighting does not depend on vertex position and there is a single
// normal specified for this shape, go ahead and apply the same lighting
// contribution to every vertex in this shape (one lighting calc!)
if (!lightingDependsOnVertexPosition && normalMode == NORMAL_MODE_SHAPE) {
calcLightingContribution(shapeFirst, tempLightingContribution);
for (int tri = 0; tri < triangleCount; tri++) {
lightTriangle(tri, tempLightingContribution);
}
} else { // Otherwise light each triangle individually...
for (int tri = 0; tri < triangleCount; tri++) {
lightTriangle(tri);
}
}
} else {
for (int tri = 0; tri < triangleCount; tri++) {
int index = triangles[tri][VERTEX1];
copyPrelitVertexColor(tri, index, 0);
index = triangles[tri][VERTEX2];
copyPrelitVertexColor(tri, index, 1);
index = triangles[tri][VERTEX3];
copyPrelitVertexColor(tri, index, 2);
}
}
}
protected void endShapeCameraToScreen(int start, int stop) {
for (int i = start; i < stop; i++) {
float vx[] = vertices[i];
float ox =
projection.m00*vx[VX] + projection.m01*vx[VY] +
projection.m02*vx[VZ] + projection.m03*vx[VW];
float oy =
projection.m10*vx[VX] + projection.m11*vx[VY] +
projection.m12*vx[VZ] + projection.m13*vx[VW];
float oz =
projection.m20*vx[VX] + projection.m21*vx[VY] +
projection.m22*vx[VZ] + projection.m23*vx[VW];
float ow =
projection.m30*vx[VX] + projection.m31*vx[VY] +
projection.m32*vx[VZ] + projection.m33*vx[VW];
if (ow != 0 && ow != 1) {
ox /= ow; oy /= ow; oz /= ow;
}
vx[TX] = width * (1 + ox) / 2.0f;
vx[TY] = height * (1 + oy) / 2.0f;
vx[TZ] = (oz + 1) / 2.0f;
}
}
/////////////////////////////////////////////////////////////////////////////
// POINTS
protected void addPoint(int a) {
if (pointCount == points.length) {
int[][] temp = new int[pointCount << 1][LINE_FIELD_COUNT];
System.arraycopy(points, 0, temp, 0, pointCount);
points = temp;
}
points[pointCount][VERTEX1] = a;
//points[pointCount][STROKE_MODE] = strokeCap | strokeJoin;
points[pointCount][STROKE_COLOR] = strokeColor;
//points[pointCount][STROKE_WEIGHT] = (int) (strokeWeight + 0.5f); // hmm
pointCount++;
}
protected void renderPoints(int start, int stop) {
if (strokeWeight != 1) {
for (int i = start; i < stop; i++) {
float[] a = vertices[points[i][VERTEX1]];
renderLineVertices(a, a);
}
} else {
for (int i = start; i < stop; i++) {
float[] a = vertices[points[i][VERTEX1]];
int sx = (int) (a[TX] + 0.4999f);
int sy = (int) (a[TY] + 0.4999f);
if (sx >= 0 && sx < width && sy >= 0 && sy < height) {
int index = sy*width + sx;
pixels[index] = points[i][STROKE_COLOR];
zbuffer[index] = a[TZ];
}
}
}
}
// alternative implementations of point rendering code...
/*
int sx = (int) (screenX(x, y, z) + 0.5f);
int sy = (int) (screenY(x, y, z) + 0.5f);
int index = sy*width + sx;
pixels[index] = strokeColor;
zbuffer[index] = screenZ(x, y, z);
*/
/*
protected void renderPoints(int start, int stop) {
for (int i = start; i < stop; i++) {
float a[] = vertices[points[i][VERTEX1]];
line.reset();
line.setIntensities(a[SR], a[SG], a[SB], a[SA],
a[SR], a[SG], a[SB], a[SA]);
line.setVertices(a[TX], a[TY], a[TZ],
a[TX] + 0.5f, a[TY] + 0.5f, a[TZ] + 0.5f);
line.draw();
}
}
*/
/*
// handle points with an actual stroke weight (or scaled by renderer)
private void point3(float x, float y, float z, int color) {
// need to get scaled version of the stroke
float x1 = screenX(x - 0.5f, y - 0.5f, z);
float y1 = screenY(x - 0.5f, y - 0.5f, z);
float x2 = screenX(x + 0.5f, y + 0.5f, z);
float y2 = screenY(x + 0.5f, y + 0.5f, z);
float weight = (abs(x2 - x1) + abs(y2 - y1)) / 2f;
if (weight < 1.5f) {
int xx = (int) ((x1 + x2) / 2f);
int yy = (int) ((y1 + y2) / 2f);
//point0(xx, yy, z, color);
zbuffer[yy*width + xx] = screenZ(x, y, z);
//stencil?
} else {
// actually has some weight, need to draw shapes instead
// these will be
}
}
*/
protected void rawPoints(int start, int stop) {
raw.colorMode(RGB, 1);
raw.noFill();
raw.strokeWeight(vertices[lines[start][VERTEX1]][SW]);
raw.beginShape(POINTS);
for (int i = start; i < stop; i++) {
float a[] = vertices[lines[i][VERTEX1]];
if (raw.is3D()) {
if (a[VW] != 0) {
raw.stroke(a[SR], a[SG], a[SB], a[SA]);
raw.vertex(a[VX] / a[VW], a[VY] / a[VW], a[VZ] / a[VW]);
}
} else { // if is2D()
raw.stroke(a[SR], a[SG], a[SB], a[SA]);
raw.vertex(a[TX], a[TY]);
}
}
raw.endShape();
}
/////////////////////////////////////////////////////////////////////////////
// LINES
/**
* Begin a new section of stroked geometry.
*/
protected final void addLineBreak() {
if (pathCount == pathOffset.length) {
pathOffset = PApplet.expand(pathOffset);
pathLength = PApplet.expand(pathLength);
}
pathOffset[pathCount] = lineCount;
pathLength[pathCount] = 0;
pathCount++;
}
protected void addLine(int a, int b) {
addLineWithClip(a, b);
}
protected final void addLineWithClip(int a, int b) {
float az = vertices[a][VZ];
float bz = vertices[b][VZ];
if (az > cameraNear) {
if (bz > cameraNear) {
return;
}
int cb = interpolateClipVertex(a, b);
addLineWithoutClip(cb, b);
return;
}
else {
if (bz <= cameraNear) {
addLineWithoutClip(a, b);
return;
}
int cb = interpolateClipVertex(a, b);
addLineWithoutClip(a, cb);
return;
}
}
protected final void addLineWithoutClip(int a, int b) {
if (lineCount == lines.length) {
int temp[][] = new int[lineCount<<1][LINE_FIELD_COUNT];
System.arraycopy(lines, 0, temp, 0, lineCount);
lines = temp;
}
lines[lineCount][VERTEX1] = a;
lines[lineCount][VERTEX2] = b;
//lines[lineCount][STROKE_MODE] = strokeCap | strokeJoin;
//lines[lineCount][STROKE_WEIGHT] = (int) (strokeWeight + 0.5f); // hmm
lineCount++;
// mark this piece as being part of the current path
pathLength[pathCount-1]++;
}
protected void renderLines(int start, int stop) {
for (int i = start; i < stop; i++) {
renderLineVertices(vertices[lines[i][VERTEX1]],
vertices[lines[i][VERTEX2]]);
}
}
protected void renderLineVertices(float[] a, float[] b) {
// 2D hack added by ewjordan 6/13/07
// Offset coordinates by a little bit if drawing 2D graphics.
// http://dev.processing.org/bugs/show_bug.cgi?id=95
// This hack fixes a bug caused by numerical precision issues when
// applying the 3D transformations to coordinates in the screen plane
// that should actually not be altered under said transformations.
// It will not be applied if any transformations other than translations
// are active, nor should it apply in OpenGL mode (PGraphicsOpenGL
// overrides render_lines(), so this should be fine).
// This fix exposes a last-pixel bug in the lineClipCode() function
// of PLine.java, so that fix must remain in place if this one is used.
// Note: the "true" fix for this bug is to change the pixel coverage
// model so that the threshold for display does not lie on an integer
// boundary. Search "diamond exit rule" for info the OpenGL approach.
/*
// removing for 0149 with the return of P2D
if (drawing2D() && a[Z] == 0) {
a[TX] += 0.01;
a[TY] += 0.01;
a[VX] += 0.01*a[VW];
a[VY] += 0.01*a[VW];
b[TX] += 0.01;
b[TY] += 0.01;
b[VX] += 0.01*b[VW];
b[VY] += 0.01*b[VW];
}
*/
// end 2d-hack
if (a[SW] > 1.25f || a[SW] < 0.75f) {
float ox1 = a[TX];
float oy1 = a[TY];
float ox2 = b[TX];
float oy2 = b[TY];
// TODO strokeWeight should be transformed!
float weight = a[SW] / 2;
// when drawing points with stroke weight, need to extend a bit
if (ox1 == ox2 && oy1 == oy2) {
oy1 -= weight;
oy2 += weight;
}
float dX = ox2 - ox1 + EPSILON;
float dY = oy2 - oy1 + EPSILON;
float len = (float) Math.sqrt(dX*dX + dY*dY);
float rh = weight / len;
float dx0 = rh * dY;
float dy0 = rh * dX;
float dx1 = rh * dY;
float dy1 = rh * dX;
float ax1 = ox1+dx0;
float ay1 = oy1-dy0;
float ax2 = ox1-dx0;
float ay2 = oy1+dy0;
float bx1 = ox2+dx1;
float by1 = oy2-dy1;
float bx2 = ox2-dx1;
float by2 = oy2+dy1;
if (smooth) {
smoothTriangle.reset(3);
smoothTriangle.smooth = true;
smoothTriangle.interpARGB = true; // ?
// render first triangle for thick line
smoothTriangle.setVertices(ax1, ay1, a[TZ],
bx2, by2, b[TZ],
ax2, ay2, a[TZ]);
smoothTriangle.setIntensities(a[SR], a[SG], a[SB], a[SA],
b[SR], b[SG], b[SB], b[SA],
a[SR], a[SG], a[SB], a[SA]);
smoothTriangle.render();
// render second triangle for thick line
smoothTriangle.setVertices(ax1, ay1, a[TZ],
bx2, by2, b[TZ],
bx1, by1, b[TZ]);
smoothTriangle.setIntensities(a[SR], a[SG], a[SB], a[SA],
b[SR], b[SG], b[SB], b[SA],
b[SR], b[SG], b[SB], b[SA]);
smoothTriangle.render();
} else {
triangle.reset();
// render first triangle for thick line
triangle.setVertices(ax1, ay1, a[TZ],
bx2, by2, b[TZ],
ax2, ay2, a[TZ]);
triangle.setIntensities(a[SR], a[SG], a[SB], a[SA],
b[SR], b[SG], b[SB], b[SA],
a[SR], a[SG], a[SB], a[SA]);
triangle.render();
// render second triangle for thick line
triangle.setVertices(ax1, ay1, a[TZ],
bx2, by2, b[TZ],
bx1, by1, b[TZ]);
triangle.setIntensities(a[SR], a[SG], a[SB], a[SA],
b[SR], b[SG], b[SB], b[SA],
b[SR], b[SG], b[SB], b[SA]);
triangle.render();
}
} else {
line.reset();
line.setIntensities(a[SR], a[SG], a[SB], a[SA],
b[SR], b[SG], b[SB], b[SA]);
line.setVertices(a[TX], a[TY], a[TZ],
b[TX], b[TY], b[TZ]);
/*
// Seems okay to remove this because these vertices are not used again,
// but if problems arise, this needs to be uncommented because the above
// change is destructive and may need to be undone before proceeding.
if (drawing2D() && a[MZ] == 0) {
a[X] -= 0.01;
a[Y] -= 0.01;
a[VX] -= 0.01*a[VW];
a[VY] -= 0.01*a[VW];
b[X] -= 0.01;
b[Y] -= 0.01;
b[VX] -= 0.01*b[VW];
b[VY] -= 0.01*b[VW];
}
*/
line.draw();
}
}
/**
* Handle echoing line data to a raw shape recording renderer. This has been
* broken out of the renderLines() procedure so that renderLines() can be
* optimized per-renderer without having to deal with this code. This code,
* for instance, will stay the same when OpenGL is in use, but renderLines()
* can be optimized significantly.
*
* Values for start and stop are specified, so that in the future, sorted
* rendering can be implemented, which will require sequences of lines,
* triangles, or points to be rendered in the neighborhood of one another.
* That is, if we're gonna depth sort, we can't just draw all the triangles
* and then draw all the lines, cuz that defeats the purpose.
*/
protected void rawLines(int start, int stop) {
raw.colorMode(RGB, 1);
raw.noFill();
raw.beginShape(LINES);
for (int i = start; i < stop; i++) {
float a[] = vertices[lines[i][VERTEX1]];
float b[] = vertices[lines[i][VERTEX2]];
raw.strokeWeight(vertices[lines[i][VERTEX2]][SW]);
if (raw.is3D()) {
if ((a[VW] != 0) && (b[VW] != 0)) {
raw.stroke(a[SR], a[SG], a[SB], a[SA]);
raw.vertex(a[VX] / a[VW], a[VY] / a[VW], a[VZ] / a[VW]);
raw.stroke(b[SR], b[SG], b[SB], b[SA]);
raw.vertex(b[VX] / b[VW], b[VY] / b[VW], b[VZ] / b[VW]);
}
} else if (raw.is2D()) {
raw.stroke(a[SR], a[SG], a[SB], a[SA]);
raw.vertex(a[TX], a[TY]);
raw.stroke(b[SR], b[SG], b[SB], b[SA]);
raw.vertex(b[TX], b[TY]);
}
}
raw.endShape();
}
/////////////////////////////////////////////////////////////////////////////
// TRIANGLES
protected void addTriangle(int a, int b, int c) {
addTriangleWithClip(a, b, c);
}
protected final void addTriangleWithClip(int a, int b, int c) {
boolean aClipped = false;
boolean bClipped = false;
int clippedCount = 0;
// This is a hack for temporary clipping. Clipping still needs to
// be implemented properly, however. Please help!
// http://dev.processing.org/bugs/show_bug.cgi?id=1393
cameraNear = -8;
if (vertices[a][VZ] > cameraNear) {
aClipped = true;
clippedCount++;
}
if (vertices[b][VZ] > cameraNear) {
bClipped = true;
clippedCount++;
}
if (vertices[c][VZ] > cameraNear) {
//cClipped = true;
clippedCount++;
}
if (clippedCount == 0) {
// if (vertices[a][VZ] < cameraFar &&
// vertices[b][VZ] < cameraFar &&
// vertices[c][VZ] < cameraFar) {
addTriangleWithoutClip(a, b, c);
// }
// } else if (true) {
// return;
} else if (clippedCount == 3) {
// In this case there is only one visible point. |/|
// So we'll have to make two new points on the clip line <| |
// and add that triangle instead. |\|
} else if (clippedCount == 2) {
//System.out.println("Clipped two");
int ca, cb, cc, cd, ce;
if (!aClipped) {
ca = a;
cb = b;
cc = c;
}
else if (!bClipped) {
ca = b;
cb = a;
cc = c;
}
else { //if (!cClipped) {
ca = c;
cb = b;
cc = a;
}
cd = interpolateClipVertex(ca, cb);
ce = interpolateClipVertex(ca, cc);
addTriangleWithoutClip(ca, cd, ce);
} else { // (clippedCount == 1) {
// . |
// In this case there are two visible points. |\|
// So we'll have to make two new points on the clip line | |>
// and then add two new triangles. |/|
// . |
//System.out.println("Clipped one");
int ca, cb, cc, cd, ce;
if (aClipped) {
//System.out.println("aClipped");
ca = c;
cb = b;
cc = a;
}
else if (bClipped) {
//System.out.println("bClipped");
ca = a;
cb = c;
cc = b;
}
else { //if (cClipped) {
//System.out.println("cClipped");
ca = a;
cb = b;
cc = c;
}
cd = interpolateClipVertex(ca, cc);
ce = interpolateClipVertex(cb, cc);
addTriangleWithoutClip(ca, cd, cb);
//System.out.println("ca: " + ca + ", " + vertices[ca][VX] + ", " + vertices[ca][VY] + ", " + vertices[ca][VZ]);
//System.out.println("cd: " + cd + ", " + vertices[cd][VX] + ", " + vertices[cd][VY] + ", " + vertices[cd][VZ]);
//System.out.println("cb: " + cb + ", " + vertices[cb][VX] + ", " + vertices[cb][VY] + ", " + vertices[cb][VZ]);
addTriangleWithoutClip(cb, cd, ce);
}
}
protected final int interpolateClipVertex(int a, int b) {
float[] va;
float[] vb;
// Set up va, vb such that va[VZ] >= vb[VZ]
if (vertices[a][VZ] < vertices[b][VZ]) {
va = vertices[b];
vb = vertices[a];
}
else {
va = vertices[a];
vb = vertices[b];
}
float az = va[VZ];
float bz = vb[VZ];
float dz = az - bz;
// If they have the same z, just use pt. a.
if (dz == 0) {
return a;
}
//float pa = (az - cameraNear) / dz;
//float pb = (cameraNear - bz) / dz;
float pa = (cameraNear - bz) / dz;
float pb = 1 - pa;
vertex(pa * va[X] + pb * vb[X],
pa * va[Y] + pb * vb[Y],
pa * va[Z] + pb * vb[Z]);
int irv = vertexCount - 1;
shapeLastPlusClipped++;
float[] rv = vertices[irv];
rv[TX] = pa * va[TX] + pb * vb[TX];
rv[TY] = pa * va[TY] + pb * vb[TY];
rv[TZ] = pa * va[TZ] + pb * vb[TZ];
rv[VX] = pa * va[VX] + pb * vb[VX];
rv[VY] = pa * va[VY] + pb * vb[VY];
rv[VZ] = pa * va[VZ] + pb * vb[VZ];
rv[VW] = pa * va[VW] + pb * vb[VW];
rv[R] = pa * va[R] + pb * vb[R];
rv[G] = pa * va[G] + pb * vb[G];
rv[B] = pa * va[B] + pb * vb[B];
rv[A] = pa * va[A] + pb * vb[A];
rv[U] = pa * va[U] + pb * vb[U];
rv[V] = pa * va[V] + pb * vb[V];
rv[SR] = pa * va[SR] + pb * vb[SR];
rv[SG] = pa * va[SG] + pb * vb[SG];
rv[SB] = pa * va[SB] + pb * vb[SB];
rv[SA] = pa * va[SA] + pb * vb[SA];
rv[NX] = pa * va[NX] + pb * vb[NX];
rv[NY] = pa * va[NY] + pb * vb[NY];
rv[NZ] = pa * va[NZ] + pb * vb[NZ];
// rv[SW] = pa * va[SW] + pb * vb[SW];
rv[AR] = pa * va[AR] + pb * vb[AR];
rv[AG] = pa * va[AG] + pb * vb[AG];
rv[AB] = pa * va[AB] + pb * vb[AB];
rv[SPR] = pa * va[SPR] + pb * vb[SPR];
rv[SPG] = pa * va[SPG] + pb * vb[SPG];
rv[SPB] = pa * va[SPB] + pb * vb[SPB];
//rv[SPA] = pa * va[SPA] + pb * vb[SPA];
rv[ER] = pa * va[ER] + pb * vb[ER];
rv[EG] = pa * va[EG] + pb * vb[EG];
rv[EB] = pa * va[EB] + pb * vb[EB];
rv[SHINE] = pa * va[SHINE] + pb * vb[SHINE];
rv[BEEN_LIT] = 0;
return irv;
}
protected final void addTriangleWithoutClip(int a, int b, int c) {
if (triangleCount == triangles.length) {
int temp[][] = new int[triangleCount<<1][TRIANGLE_FIELD_COUNT];
System.arraycopy(triangles, 0, temp, 0, triangleCount);
triangles = temp;
//message(CHATTER, "allocating more triangles " + triangles.length);
float ftemp[][][] = new float[triangleCount<<1][3][TRI_COLOR_COUNT];
System.arraycopy(triangleColors, 0, ftemp, 0, triangleCount);
triangleColors = ftemp;
}
triangles[triangleCount][VERTEX1] = a;
triangles[triangleCount][VERTEX2] = b;
triangles[triangleCount][VERTEX3] = c;
if (textureImage == null) {
triangles[triangleCount][TEXTURE_INDEX] = -1;
} else {
triangles[triangleCount][TEXTURE_INDEX] = textureIndex;
}
// triangles[triangleCount][INDEX] = shape_index;
triangleCount++;
}
/**
* Triangulate the current polygon.
*
* Simple ear clipping polygon triangulation adapted from code by
* John W. Ratcliff (jratcliff at verant.com). Presumably
* this
* bit of code from the web.
*/
protected void addPolygonTriangles() {
if (vertexOrder.length != vertices.length) {
int[] temp = new int[vertices.length];
// vertex_start may not be zero, might need to keep old stuff around
// also, copy vertexOrder.length, not vertexCount because vertexCount
// may be larger than vertexOrder.length (since this is a post-processing
// step that happens after the vertex arrays are built).
PApplet.arrayCopy(vertexOrder, temp, vertexOrder.length);
vertexOrder = temp;
}
// this clipping algorithm only works in 2D, so in cases where a
// polygon is drawn perpendicular to the z-axis, the area will be zero,
// and triangulation will fail. as such, when the area calculates to
// zero, figure out whether x or y is empty, and calculate based on the
// two dimensions that actually contain information.
// http://dev.processing.org/bugs/show_bug.cgi?id=111
int d1 = X;
int d2 = Y;
// this brings up the nastier point that there may be cases where
// a polygon is irregular in space and will throw off the
// clockwise/counterclockwise calculation. for instance, if clockwise
// relative to x and z, but counter relative to y and z or something
// like that.. will wait to see if this is in fact a problem before
// hurting my head on the math.
/*
// trying to track down bug #774
for (int i = vertex_start; i < vertex_end; i++) {
if (i > vertex_start) {
if (vertices[i-1][MX] == vertices[i][MX] &&
vertices[i-1][MY] == vertices[i][MY]) {
System.out.print("**** " );
}
}
System.out.println(i + " " + vertices[i][MX] + " " + vertices[i][MY]);
}
System.out.println();
*/
// first we check if the polygon goes clockwise or counterclockwise
float area = 0;
for (int p = shapeLast - 1, q = shapeFirst; q < shapeLast; p = q++) {
area += (vertices[q][d1] * vertices[p][d2] -
vertices[p][d1] * vertices[q][d2]);
}
// rather than checking for the perpendicular case first, only do it
// when the area calculates to zero. checking for perpendicular would be
// a needless waste of time for the 99% case.
if (area == 0) {
// figure out which dimension is the perpendicular axis
boolean foundValidX = false;
boolean foundValidY = false;
for (int i = shapeFirst; i < shapeLast; i++) {
for (int j = i; j < shapeLast; j++){
if ( vertices[i][X] != vertices[j][X] ) foundValidX = true;
if ( vertices[i][Y] != vertices[j][Y] ) foundValidY = true;
}
}
if (foundValidX) {
//d1 = MX; // already the case
d2 = Z;
} else if (foundValidY) {
// ermm.. which is the proper order for cw/ccw here?
d1 = Y;
d2 = Z;
} else {
// screw it, this polygon is just f-ed up
return;
}
// re-calculate the area, with what should be good values
for (int p = shapeLast - 1, q = shapeFirst; q < shapeLast; p = q++) {
area += (vertices[q][d1] * vertices[p][d2] -
vertices[p][d1] * vertices[q][d2]);
}
}
// don't allow polygons to come back and meet themselves,
// otherwise it will anger the triangulator
// http://dev.processing.org/bugs/show_bug.cgi?id=97
float vfirst[] = vertices[shapeFirst];
float vlast[] = vertices[shapeLast-1];
if ((abs(vfirst[X] - vlast[X]) < EPSILON) &&
(abs(vfirst[Y] - vlast[Y]) < EPSILON) &&
(abs(vfirst[Z] - vlast[Z]) < EPSILON)) {
shapeLast--;
}
// then sort the vertices so they are always in a counterclockwise order
int j = 0;
if (area > 0) {
for (int i = shapeFirst; i < shapeLast; i++) {
j = i - shapeFirst;
vertexOrder[j] = i;
}
} else {
for (int i = shapeFirst; i < shapeLast; i++) {
j = i - shapeFirst;
vertexOrder[j] = (shapeLast - 1) - j;
}
}
// remove vc-2 Vertices, creating 1 triangle every time
int vc = shapeLast - shapeFirst;
int count = 2*vc; // complex polygon detection
for (int m = 0, v = vc - 1; vc > 2; ) {
boolean snip = true;
// if we start over again, is a complex polygon
if (0 >= (count--)) {
break; // triangulation failed
}
// get 3 consecutive vertices
int u = v ; if (vc <= u) u = 0; // previous
v = u + 1; if (vc <= v) v = 0; // current
int w = v + 1; if (vc <= w) w = 0; // next
// Upgrade values to doubles, and multiply by 10 so that we can have
// some better accuracy as we tessellate. This seems to have negligible
// speed differences on Windows and Intel Macs, but causes a 50% speed
// drop for PPC Macs with the bug's example code that draws ~200 points
// in a concave polygon. Apple has abandoned PPC so we may as well too.
// http://dev.processing.org/bugs/show_bug.cgi?id=774
// triangle A B C
double Ax = -10 * vertices[vertexOrder[u]][d1];
double Ay = 10 * vertices[vertexOrder[u]][d2];
double Bx = -10 * vertices[vertexOrder[v]][d1];
double By = 10 * vertices[vertexOrder[v]][d2];
double Cx = -10 * vertices[vertexOrder[w]][d1];
double Cy = 10 * vertices[vertexOrder[w]][d2];
// first we check if continues going ccw
if (EPSILON > (((Bx-Ax) * (Cy-Ay)) - ((By-Ay) * (Cx-Ax)))) {
continue;
}
for (int p = 0; p < vc; p++) {
if ((p == u) || (p == v) || (p == w)) {
continue;
}
double Px = -10 * vertices[vertexOrder[p]][d1];
double Py = 10 * vertices[vertexOrder[p]][d2];
double ax = Cx - Bx; double ay = Cy - By;
double bx = Ax - Cx; double by = Ay - Cy;
double cx = Bx - Ax; double cy = By - Ay;
double apx = Px - Ax; double apy = Py - Ay;
double bpx = Px - Bx; double bpy = Py - By;
double cpx = Px - Cx; double cpy = Py - Cy;
double aCROSSbp = ax * bpy - ay * bpx;
double cCROSSap = cx * apy - cy * apx;
double bCROSScp = bx * cpy - by * cpx;
if ((aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0)) {
snip = false;
}
}
if (snip) {
addTriangle(vertexOrder[u], vertexOrder[v], vertexOrder[w]);
m++;
// remove v from remaining polygon
for (int s = v, t = v + 1; t < vc; s++, t++) {
vertexOrder[s] = vertexOrder[t];
}
vc--;
// reset error detection counter
count = 2 * vc;
}
}
}
private void toWorldNormal(float nx, float ny, float nz, float[] out) {
out[0] =
modelviewInv.m00*nx + modelviewInv.m10*ny +
modelviewInv.m20*nz + modelviewInv.m30;
out[1] =
modelviewInv.m01*nx + modelviewInv.m11*ny +
modelviewInv.m21*nz + modelviewInv.m31;
out[2] =
modelviewInv.m02*nx + modelviewInv.m12*ny +
modelviewInv.m22*nz + modelviewInv.m32;
out[3] =
modelviewInv.m03*nx + modelviewInv.m13*ny +
modelviewInv.m23*nz + modelviewInv.m33;
if (out[3] != 0 && out[3] != 1) {
// divide by perspective coordinate
out[0] /= out[3]; out[1] /= out[3]; out[2] /= out[3];
}
out[3] = 1;
float nlen = mag(out[0], out[1], out[2]); // normalize
if (nlen != 0 && nlen != 1) {
out[0] /= nlen; out[1] /= nlen; out[2] /= nlen;
}
}
//private PVector calcLightingNorm = new PVector();
//private PVector calcLightingWorldNorm = new PVector();
float[] worldNormal = new float[4];
private void calcLightingContribution(int vIndex,
float[] contribution) {
calcLightingContribution(vIndex, contribution, false);
}
private void calcLightingContribution(int vIndex,
float[] contribution,
boolean normalIsWorld) {
float[] v = vertices[vIndex];
float sr = v[SPR];
float sg = v[SPG];
float sb = v[SPB];
float wx = v[VX];
float wy = v[VY];
float wz = v[VZ];
float shine = v[SHINE];
float nx = v[NX];
float ny = v[NY];
float nz = v[NZ];
if (!normalIsWorld) {
// System.out.println("um, hello?");
// calcLightingNorm.set(nx, ny, nz);
// //modelviewInv.mult(calcLightingNorm, calcLightingWorldNorm);
//
//// PMatrix3D mvi = modelViewInv;
//// float ox = mvi.m00*nx + mvi.m10*ny + mvi*m20+nz +
// modelviewInv.cmult(calcLightingNorm, calcLightingWorldNorm);
//
// calcLightingWorldNorm.normalize();
// nx = calcLightingWorldNorm.x;
// ny = calcLightingWorldNorm.y;
// nz = calcLightingWorldNorm.z;
toWorldNormal(v[NX], v[NY], v[NZ], worldNormal);
nx = worldNormal[X];
ny = worldNormal[Y];
nz = worldNormal[Z];
// float wnx = modelviewInv.multX(nx, ny, nz);
// float wny = modelviewInv.multY(nx, ny, nz);
// float wnz = modelviewInv.multZ(nx, ny, nz);
// float wnw = modelviewInv.multW(nx, ny, nz);
// if (wnw != 0 && wnw != 1) {
// wnx /= wnw;
// wny /= wnw;
// wnz /= wnw;
// }
// float nlen = mag(wnx, wny, wnw);
// if (nlen != 0 && nlen != 1) {
// nx = wnx / nlen;
// ny = wny / nlen;
// nz = wnz / nlen;
// } else {
// nx = wnx;
// ny = wny;
// nz = wnz;
// }
// */
} else {
nx = v[NX];
ny = v[NY];
nz = v[NZ];
}
// Since the camera space == world space,
// we can test for visibility by the dot product of
// the normal with the direction from pt. to eye.
float dir = dot(nx, ny, nz, -wx, -wy, -wz);
// If normal is away from camera, choose its opposite.
// If we add backface culling, this will be backfacing
// (but since this is per vertex, it's more complicated)
if (dir < 0) {
nx = -nx;
ny = -ny;
nz = -nz;
}
// These two terms will sum the contributions from the various lights
contribution[LIGHT_AMBIENT_R] = 0;
contribution[LIGHT_AMBIENT_G] = 0;
contribution[LIGHT_AMBIENT_B] = 0;
contribution[LIGHT_DIFFUSE_R] = 0;
contribution[LIGHT_DIFFUSE_G] = 0;
contribution[LIGHT_DIFFUSE_B] = 0;
contribution[LIGHT_SPECULAR_R] = 0;
contribution[LIGHT_SPECULAR_G] = 0;
contribution[LIGHT_SPECULAR_B] = 0;
// for (int i = 0; i < MAX_LIGHTS; i++) {
// if (!light[i]) continue;
for (int i = 0; i < lightCount; i++) {
float denom = lightFalloffConstant[i];
float spotTerm = 1;
if (lightType[i] == AMBIENT) {
if (lightFalloffQuadratic[i] != 0 || lightFalloffLinear[i] != 0) {
// Falloff depends on distance
float distSq = mag(lightPosition[i].x - wx,
lightPosition[i].y - wy,
lightPosition[i].z - wz);
denom +=
lightFalloffQuadratic[i] * distSq +
lightFalloffLinear[i] * sqrt(distSq);
}
if (denom == 0) denom = 1;
contribution[LIGHT_AMBIENT_R] += lightDiffuse[i][0] / denom;
contribution[LIGHT_AMBIENT_G] += lightDiffuse[i][1] / denom;
contribution[LIGHT_AMBIENT_B] += lightDiffuse[i][2] / denom;
} else {
// If not ambient, we must deal with direction
// li is the vector from the vertex to the light
float lix, liy, liz;
float lightDir_dot_li = 0;
float n_dot_li = 0;
if (lightType[i] == DIRECTIONAL) {
lix = -lightNormal[i].x;
liy = -lightNormal[i].y;
liz = -lightNormal[i].z;
denom = 1;
n_dot_li = (nx * lix + ny * liy + nz * liz);
// If light is lighting the face away from the camera, ditch
if (n_dot_li <= 0) {
continue;
}
} else { // Point or spot light (must deal also with light location)
lix = lightPosition[i].x - wx;
liy = lightPosition[i].y - wy;
liz = lightPosition[i].z - wz;
// normalize
float distSq = mag(lix, liy, liz);
if (distSq != 0) {
lix /= distSq;
liy /= distSq;
liz /= distSq;
}
n_dot_li = (nx * lix + ny * liy + nz * liz);
// If light is lighting the face away from the camera, ditch
if (n_dot_li <= 0) {
continue;
}
if (lightType[i] == SPOT) { // Must deal with spot cone
lightDir_dot_li =
-(lightNormal[i].x * lix +
lightNormal[i].y * liy +
lightNormal[i].z * liz);
// Outside of spot cone
if (lightDir_dot_li <= lightSpotAngleCos[i]) {
continue;
}
spotTerm = (float) Math.pow(lightDir_dot_li, lightSpotConcentration[i]);
}
if (lightFalloffQuadratic[i] != 0 || lightFalloffLinear[i] != 0) {
// Falloff depends on distance
denom +=
lightFalloffQuadratic[i] * distSq +
lightFalloffLinear[i] * (float) sqrt(distSq);
}
}
// Directional, point, or spot light:
// We know n_dot_li > 0 from above "continues"
if (denom == 0)
denom = 1;
float mul = n_dot_li * spotTerm / denom;
contribution[LIGHT_DIFFUSE_R] += lightDiffuse[i][0] * mul;
contribution[LIGHT_DIFFUSE_G] += lightDiffuse[i][1] * mul;
contribution[LIGHT_DIFFUSE_B] += lightDiffuse[i][2] * mul;
// SPECULAR
// If the material and light have a specular component.
if ((sr > 0 || sg > 0 || sb > 0) &&
(lightSpecular[i][0] > 0 ||
lightSpecular[i][1] > 0 ||
lightSpecular[i][2] > 0)) {
float vmag = mag(wx, wy, wz);
if (vmag != 0) {
wx /= vmag;
wy /= vmag;
wz /= vmag;
}
float sx = lix - wx;
float sy = liy - wy;
float sz = liz - wz;
vmag = mag(sx, sy, sz);
if (vmag != 0) {
sx /= vmag;
sy /= vmag;
sz /= vmag;
}
float s_dot_n = (sx * nx + sy * ny + sz * nz);
if (s_dot_n > 0) {
s_dot_n = (float) Math.pow(s_dot_n, shine);
mul = s_dot_n * spotTerm / denom;
contribution[LIGHT_SPECULAR_R] += lightSpecular[i][0] * mul;
contribution[LIGHT_SPECULAR_G] += lightSpecular[i][1] * mul;
contribution[LIGHT_SPECULAR_B] += lightSpecular[i][2] * mul;
}
}
}
}
return;
}
// Multiply the lighting contribution into the vertex's colors.
// Only do this when there is ONE lighting per vertex
// (MANUAL_VERTEX_NORMAL or SHAPE_NORMAL mode).
private void applyLightingContribution(int vIndex, float[] contribution) {
float[] v = vertices[vIndex];
v[R] = clamp(v[ER] + v[AR] * contribution[LIGHT_AMBIENT_R] + v[DR] * contribution[LIGHT_DIFFUSE_R]);
v[G] = clamp(v[EG] + v[AG] * contribution[LIGHT_AMBIENT_G] + v[DG] * contribution[LIGHT_DIFFUSE_G]);
v[B] = clamp(v[EB] + v[AB] * contribution[LIGHT_AMBIENT_B] + v[DB] * contribution[LIGHT_DIFFUSE_B]);
v[A] = clamp(v[DA]);
v[SPR] = clamp(v[SPR] * contribution[LIGHT_SPECULAR_R]);
v[SPG] = clamp(v[SPG] * contribution[LIGHT_SPECULAR_G]);
v[SPB] = clamp(v[SPB] * contribution[LIGHT_SPECULAR_B]);
//v[SPA] = min(1, v[SPA]);
v[BEEN_LIT] = 1;
}
private void lightVertex(int vIndex, float[] contribution) {
calcLightingContribution(vIndex, contribution);
applyLightingContribution(vIndex, contribution);
}
private void lightUnlitVertex(int vIndex, float[] contribution) {
if (vertices[vIndex][BEEN_LIT] == 0) {
lightVertex(vIndex, contribution);
}
}
private void copyPrelitVertexColor(int triIndex, int index, int colorIndex) {
float[] triColor = triangleColors[triIndex][colorIndex];
float[] v = vertices[index];
triColor[TRI_DIFFUSE_R] = v[R];
triColor[TRI_DIFFUSE_G] = v[G];
triColor[TRI_DIFFUSE_B] = v[B];
triColor[TRI_DIFFUSE_A] = v[A];
triColor[TRI_SPECULAR_R] = v[SPR];
triColor[TRI_SPECULAR_G] = v[SPG];
triColor[TRI_SPECULAR_B] = v[SPB];
//triColor[TRI_SPECULAR_A] = v[SPA];
}
private void copyVertexColor(int triIndex, int index, int colorIndex,
float[] contrib) {
float[] triColor = triangleColors[triIndex][colorIndex];
float[] v = vertices[index];
triColor[TRI_DIFFUSE_R] =
clamp(v[ER] + v[AR] * contrib[LIGHT_AMBIENT_R] + v[DR] * contrib[LIGHT_DIFFUSE_R]);
triColor[TRI_DIFFUSE_G] =
clamp(v[EG] + v[AG] * contrib[LIGHT_AMBIENT_G] + v[DG] * contrib[LIGHT_DIFFUSE_G]);
triColor[TRI_DIFFUSE_B] =
clamp(v[EB] + v[AB] * contrib[LIGHT_AMBIENT_B] + v[DB] * contrib[LIGHT_DIFFUSE_B]);
triColor[TRI_DIFFUSE_A] = clamp(v[DA]);
triColor[TRI_SPECULAR_R] = clamp(v[SPR] * contrib[LIGHT_SPECULAR_R]);
triColor[TRI_SPECULAR_G] = clamp(v[SPG] * contrib[LIGHT_SPECULAR_G]);
triColor[TRI_SPECULAR_B] = clamp(v[SPB] * contrib[LIGHT_SPECULAR_B]);
}
private void lightTriangle(int triIndex, float[] lightContribution) {
int vIndex = triangles[triIndex][VERTEX1];
copyVertexColor(triIndex, vIndex, 0, lightContribution);
vIndex = triangles[triIndex][VERTEX2];
copyVertexColor(triIndex, vIndex, 1, lightContribution);
vIndex = triangles[triIndex][VERTEX3];
copyVertexColor(triIndex, vIndex, 2, lightContribution);
}
private void lightTriangle(int triIndex) {
int vIndex;
// Handle lighting on, but no lights (in this case, just use emissive)
// This wont be used currently because lightCount == 0 is don't use
// lighting at all... So. OK. If that ever changes, use the below:
/*
if (lightCount == 0) {
vIndex = triangles[triIndex][VERTEX1];
copy_emissive_vertex_color_to_triangle(triIndex, vIndex, 0);
vIndex = triangles[triIndex][VERTEX2];
copy_emissive_vertex_color_to_triangle(triIndex, vIndex, 1);
vIndex = triangles[triIndex][VERTEX3];
copy_emissive_vertex_color_to_triangle(triIndex, vIndex, 2);
return;
}
*/
// In MANUAL_VERTEX_NORMAL mode, we have a specific normal
// for each vertex. In that case, we light any verts that
// haven't already been lit and copy their colors straight
// into the triangle.
if (normalMode == NORMAL_MODE_VERTEX) {
vIndex = triangles[triIndex][VERTEX1];
lightUnlitVertex(vIndex, tempLightingContribution);
copyPrelitVertexColor(triIndex, vIndex, 0);
vIndex = triangles[triIndex][VERTEX2];
lightUnlitVertex(vIndex, tempLightingContribution);
copyPrelitVertexColor(triIndex, vIndex, 1);
vIndex = triangles[triIndex][VERTEX3];
lightUnlitVertex(vIndex, tempLightingContribution);
copyPrelitVertexColor(triIndex, vIndex, 2);
}
// If the lighting doesn't depend on the vertex position, do the
// following: We've already dealt with NORMAL_MODE_SHAPE mode before
// we got into this function, so here we only have to deal with
// NORMAL_MODE_AUTO. So we calculate the normal for this triangle,
// and use that for the lighting.
else if (!lightingDependsOnVertexPosition) {
vIndex = triangles[triIndex][VERTEX1];
int vIndex2 = triangles[triIndex][VERTEX2];
int vIndex3 = triangles[triIndex][VERTEX3];
/*
dv1[0] = vertices[vIndex2][VX] - vertices[vIndex][VX];
dv1[1] = vertices[vIndex2][VY] - vertices[vIndex][VY];
dv1[2] = vertices[vIndex2][VZ] - vertices[vIndex][VZ];
dv2[0] = vertices[vIndex3][VX] - vertices[vIndex][VX];
dv2[1] = vertices[vIndex3][VY] - vertices[vIndex][VY];
dv2[2] = vertices[vIndex3][VZ] - vertices[vIndex][VZ];
cross(dv1, dv2, norm);
*/
cross(vertices[vIndex2][VX] - vertices[vIndex][VX],
vertices[vIndex2][VY] - vertices[vIndex][VY],
vertices[vIndex2][VZ] - vertices[vIndex][VZ],
vertices[vIndex3][VX] - vertices[vIndex][VX],
vertices[vIndex3][VY] - vertices[vIndex][VY],
vertices[vIndex3][VZ] - vertices[vIndex][VZ], lightTriangleNorm);
lightTriangleNorm.normalize();
vertices[vIndex][NX] = lightTriangleNorm.x;
vertices[vIndex][NY] = lightTriangleNorm.y;
vertices[vIndex][NZ] = lightTriangleNorm.z;
// The true at the end says the normal is already in world coordinates
calcLightingContribution(vIndex, tempLightingContribution, true);
copyVertexColor(triIndex, vIndex, 0, tempLightingContribution);
copyVertexColor(triIndex, vIndex2, 1, tempLightingContribution);
copyVertexColor(triIndex, vIndex3, 2, tempLightingContribution);
}
// If lighting is position-dependent
else {
if (normalMode == NORMAL_MODE_SHAPE) {
vIndex = triangles[triIndex][VERTEX1];
vertices[vIndex][NX] = vertices[shapeFirst][NX];
vertices[vIndex][NY] = vertices[shapeFirst][NY];
vertices[vIndex][NZ] = vertices[shapeFirst][NZ];
calcLightingContribution(vIndex, tempLightingContribution);
copyVertexColor(triIndex, vIndex, 0, tempLightingContribution);
vIndex = triangles[triIndex][VERTEX2];
vertices[vIndex][NX] = vertices[shapeFirst][NX];
vertices[vIndex][NY] = vertices[shapeFirst][NY];
vertices[vIndex][NZ] = vertices[shapeFirst][NZ];
calcLightingContribution(vIndex, tempLightingContribution);
copyVertexColor(triIndex, vIndex, 1, tempLightingContribution);
vIndex = triangles[triIndex][VERTEX3];
vertices[vIndex][NX] = vertices[shapeFirst][NX];
vertices[vIndex][NY] = vertices[shapeFirst][NY];
vertices[vIndex][NZ] = vertices[shapeFirst][NZ];
calcLightingContribution(vIndex, tempLightingContribution);
copyVertexColor(triIndex, vIndex, 2, tempLightingContribution);
}
// lighting mode is AUTO_NORMAL
else {
vIndex = triangles[triIndex][VERTEX1];
int vIndex2 = triangles[triIndex][VERTEX2];
int vIndex3 = triangles[triIndex][VERTEX3];
/*
dv1[0] = vertices[vIndex2][VX] - vertices[vIndex][VX];
dv1[1] = vertices[vIndex2][VY] - vertices[vIndex][VY];
dv1[2] = vertices[vIndex2][VZ] - vertices[vIndex][VZ];
dv2[0] = vertices[vIndex3][VX] - vertices[vIndex][VX];
dv2[1] = vertices[vIndex3][VY] - vertices[vIndex][VY];
dv2[2] = vertices[vIndex3][VZ] - vertices[vIndex][VZ];
cross(dv1, dv2, norm);
*/
cross(vertices[vIndex2][VX] - vertices[vIndex][VX],
vertices[vIndex2][VY] - vertices[vIndex][VY],
vertices[vIndex2][VZ] - vertices[vIndex][VZ],
vertices[vIndex3][VX] - vertices[vIndex][VX],
vertices[vIndex3][VY] - vertices[vIndex][VY],
vertices[vIndex3][VZ] - vertices[vIndex][VZ], lightTriangleNorm);
// float nmag = mag(norm[X], norm[Y], norm[Z]);
// if (nmag != 0 && nmag != 1) {
// norm[X] /= nmag; norm[Y] /= nmag; norm[Z] /= nmag;
// }
lightTriangleNorm.normalize();
vertices[vIndex][NX] = lightTriangleNorm.x;
vertices[vIndex][NY] = lightTriangleNorm.y;
vertices[vIndex][NZ] = lightTriangleNorm.z;
// The true at the end says the normal is already in world coordinates
calcLightingContribution(vIndex, tempLightingContribution, true);
copyVertexColor(triIndex, vIndex, 0, tempLightingContribution);
vertices[vIndex2][NX] = lightTriangleNorm.x;
vertices[vIndex2][NY] = lightTriangleNorm.y;
vertices[vIndex2][NZ] = lightTriangleNorm.z;
// The true at the end says the normal is already in world coordinates
calcLightingContribution(vIndex2, tempLightingContribution, true);
copyVertexColor(triIndex, vIndex2, 1, tempLightingContribution);
vertices[vIndex3][NX] = lightTriangleNorm.x;
vertices[vIndex3][NY] = lightTriangleNorm.y;
vertices[vIndex3][NZ] = lightTriangleNorm.z;
// The true at the end says the normal is already in world coordinates
calcLightingContribution(vIndex3, tempLightingContribution, true);
copyVertexColor(triIndex, vIndex3, 2, tempLightingContribution);
}
}
}
protected void renderTriangles(int start, int stop) {
for (int i = start; i < stop; i++) {
float a[] = vertices[triangles[i][VERTEX1]];
float b[] = vertices[triangles[i][VERTEX2]];
float c[] = vertices[triangles[i][VERTEX3]];
int tex = triangles[i][TEXTURE_INDEX];
/*
// removing for 0149 with the return of P2D
// ewjordan: hack to 'fix' accuracy issues when drawing in 2d
// see also render_lines() where similar hack is employed
float shift = 0.15f;//was 0.49f
boolean shifted = false;
if (drawing2D() && (a[Z] == 0)) {
shifted = true;
a[TX] += shift;
a[TY] += shift;
a[VX] += shift*a[VW];
a[VY] += shift*a[VW];
b[TX] += shift;
b[TY] += shift;
b[VX] += shift*b[VW];
b[VY] += shift*b[VW];
c[TX] += shift;
c[TY] += shift;
c[VX] += shift*c[VW];
c[VY] += shift*c[VW];
}
*/
triangle.reset();
// This is only true when not textured.
// We really should pass specular straight through to triangle rendering.
float ar = clamp(triangleColors[i][0][TRI_DIFFUSE_R] + triangleColors[i][0][TRI_SPECULAR_R]);
float ag = clamp(triangleColors[i][0][TRI_DIFFUSE_G] + triangleColors[i][0][TRI_SPECULAR_G]);
float ab = clamp(triangleColors[i][0][TRI_DIFFUSE_B] + triangleColors[i][0][TRI_SPECULAR_B]);
float br = clamp(triangleColors[i][1][TRI_DIFFUSE_R] + triangleColors[i][1][TRI_SPECULAR_R]);
float bg = clamp(triangleColors[i][1][TRI_DIFFUSE_G] + triangleColors[i][1][TRI_SPECULAR_G]);
float bb = clamp(triangleColors[i][1][TRI_DIFFUSE_B] + triangleColors[i][1][TRI_SPECULAR_B]);
float cr = clamp(triangleColors[i][2][TRI_DIFFUSE_R] + triangleColors[i][2][TRI_SPECULAR_R]);
float cg = clamp(triangleColors[i][2][TRI_DIFFUSE_G] + triangleColors[i][2][TRI_SPECULAR_G]);
float cb = clamp(triangleColors[i][2][TRI_DIFFUSE_B] + triangleColors[i][2][TRI_SPECULAR_B]);
// ACCURATE TEXTURE CODE
boolean failedToPrecalc = false;
if (s_enableAccurateTextures && frustumMode){
boolean textured = true;
smoothTriangle.reset(3);
smoothTriangle.smooth = true;
smoothTriangle.interpARGB = true;
smoothTriangle.setIntensities(ar, ag, ab, a[A],
br, bg, bb, b[A],
cr, cg, cb, c[A]);
if (tex > -1 && textures[tex] != null) {
smoothTriangle.setCamVertices(a[VX], a[VY], a[VZ],
b[VX], b[VY], b[VZ],
c[VX], c[VY], c[VZ]);
smoothTriangle.interpUV = true;
smoothTriangle.texture(textures[tex]);
float umult = textures[tex].width; // apparently no check for textureMode is needed here
float vmult = textures[tex].height;
smoothTriangle.vertices[0][U] = a[U]*umult;
smoothTriangle.vertices[0][V] = a[V]*vmult;
smoothTriangle.vertices[1][U] = b[U]*umult;
smoothTriangle.vertices[1][V] = b[V]*vmult;
smoothTriangle.vertices[2][U] = c[U]*umult;
smoothTriangle.vertices[2][V] = c[V]*vmult;
} else {
smoothTriangle.interpUV = false;
textured = false;
}
smoothTriangle.setVertices(a[TX], a[TY], a[TZ],
b[TX], b[TY], b[TZ],
c[TX], c[TY], c[TZ]);
if (!textured || smoothTriangle.precomputeAccurateTexturing()){
smoothTriangle.render();
} else {
// Something went wrong with the precomputation,
// so we need to fall back on normal PTriangle
// rendering.
failedToPrecalc = true;
}
}
// Normal triangle rendering
// Note: this is not an end-if from the smoothed texturing mode
// because it's possible that the precalculation will fail and we
// need to fall back on normal rendering.
if (!s_enableAccurateTextures || failedToPrecalc || (frustumMode == false)){
if (tex > -1 && textures[tex] != null) {
triangle.setTexture(textures[tex]);
triangle.setUV(a[U], a[V], b[U], b[V], c[U], c[V]);
}
triangle.setIntensities(ar, ag, ab, a[A],
br, bg, bb, b[A],
cr, cg, cb, c[A]);
triangle.setVertices(a[TX], a[TY], a[TZ],
b[TX], b[TY], b[TZ],
c[TX], c[TY], c[TZ]);
triangle.render();
}
/*
// removing for 0149 with the return of P2D
if (drawing2D() && shifted){
a[TX] -= shift;
a[TY] -= shift;
a[VX] -= shift*a[VW];
a[VY] -= shift*a[VW];
b[TX] -= shift;
b[TY] -= shift;
b[VX] -= shift*b[VW];
b[VY] -= shift*b[VW];
c[TX] -= shift;
c[TY] -= shift;
c[VX] -= shift*c[VW];
c[VY] -= shift*c[VW];
}
*/
}
}
protected void rawTriangles(int start, int stop) {
raw.colorMode(RGB, 1);
raw.noStroke();
raw.beginShape(TRIANGLES);
for (int i = start; i < stop; i++) {
float a[] = vertices[triangles[i][VERTEX1]];
float b[] = vertices[triangles[i][VERTEX2]];
float c[] = vertices[triangles[i][VERTEX3]];
float ar = clamp(triangleColors[i][0][TRI_DIFFUSE_R] + triangleColors[i][0][TRI_SPECULAR_R]);
float ag = clamp(triangleColors[i][0][TRI_DIFFUSE_G] + triangleColors[i][0][TRI_SPECULAR_G]);
float ab = clamp(triangleColors[i][0][TRI_DIFFUSE_B] + triangleColors[i][0][TRI_SPECULAR_B]);
float br = clamp(triangleColors[i][1][TRI_DIFFUSE_R] + triangleColors[i][1][TRI_SPECULAR_R]);
float bg = clamp(triangleColors[i][1][TRI_DIFFUSE_G] + triangleColors[i][1][TRI_SPECULAR_G]);
float bb = clamp(triangleColors[i][1][TRI_DIFFUSE_B] + triangleColors[i][1][TRI_SPECULAR_B]);
float cr = clamp(triangleColors[i][2][TRI_DIFFUSE_R] + triangleColors[i][2][TRI_SPECULAR_R]);
float cg = clamp(triangleColors[i][2][TRI_DIFFUSE_G] + triangleColors[i][2][TRI_SPECULAR_G]);
float cb = clamp(triangleColors[i][2][TRI_DIFFUSE_B] + triangleColors[i][2][TRI_SPECULAR_B]);
int tex = triangles[i][TEXTURE_INDEX];
PImage texImage = (tex > -1) ? textures[tex] : null;
if (texImage != null) {
if (raw.is3D()) {
if ((a[VW] != 0) && (b[VW] != 0) && (c[VW] != 0)) {
raw.fill(ar, ag, ab, a[A]);
raw.vertex(a[VX] / a[VW], a[VY] / a[VW], a[VZ] / a[VW], a[U], a[V]);
raw.fill(br, bg, bb, b[A]);
raw.vertex(b[VX] / b[VW], b[VY] / b[VW], b[VZ] / b[VW], b[U], b[V]);
raw.fill(cr, cg, cb, c[A]);
raw.vertex(c[VX] / c[VW], c[VY] / c[VW], c[VZ] / c[VW], c[U], c[V]);
}
} else if (raw.is2D()) {
raw.fill(ar, ag, ab, a[A]);
raw.vertex(a[TX], a[TY], a[U], a[V]);
raw.fill(br, bg, bb, b[A]);
raw.vertex(b[TX], b[TY], b[U], b[V]);
raw.fill(cr, cg, cb, c[A]);
raw.vertex(c[TX], c[TY], c[U], c[V]);
}
} else { // no texture
if (raw.is3D()) {
if ((a[VW] != 0) && (b[VW] != 0) && (c[VW] != 0)) {
raw.fill(ar, ag, ab, a[A]);
raw.vertex(a[VX] / a[VW], a[VY] / a[VW], a[VZ] / a[VW]);
raw.fill(br, bg, bb, b[A]);
raw.vertex(b[VX] / b[VW], b[VY] / b[VW], b[VZ] / b[VW]);
raw.fill(cr, cg, cb, c[A]);
raw.vertex(c[VX] / c[VW], c[VY] / c[VW], c[VZ] / c[VW]);
}
} else if (raw.is2D()) {
raw.fill(ar, ag, ab, a[A]);
raw.vertex(a[TX], a[TY]);
raw.fill(br, bg, bb, b[A]);
raw.vertex(b[TX], b[TY]);
raw.fill(cr, cg, cb, c[A]);
raw.vertex(c[TX], c[TY]);
}
}
}
raw.endShape();
}
//////////////////////////////////////////////////////////////
//public void bezierVertex(float x2, float y2,
// float x3, float y3,
// float x4, float y4)
//public void bezierVertex(float x2, float y2, float z2,
// float x3, float y3, float z3,
// float x4, float y4, float z4)
//////////////////////////////////////////////////////////////
//public void curveVertex(float x, float y)
//public void curveVertex(float x, float y, float z)
////////////////////////////////////////////////////////////
/**
* Emit any sorted geometry that's been collected on this frame.
*/
public void flush() {
if (hints[ENABLE_DEPTH_SORT]) {
sort();
}
render();
/*
if (triangleCount > 0) {
if (hints[ENABLE_DEPTH_SORT]) {
sortTriangles();
}
renderTriangles();
}
if (lineCount > 0) {
if (hints[ENABLE_DEPTH_SORT]) {
sortLines();
}
renderLines();
}
// Clear this out in case flush() is called again.
// For instance, with hint(ENABLE_DEPTH_SORT), it will be called
// once on endRaw(), and once again at endDraw().
triangleCount = 0;
lineCount = 0;
*/
}
protected void render() {
if (pointCount > 0) {
renderPoints(0, pointCount);
if (raw != null) {
rawPoints(0, pointCount);
}
pointCount = 0;
}
if (lineCount > 0) {
renderLines(0, lineCount);
if (raw != null) {
rawLines(0, lineCount);
}
lineCount = 0;
pathCount = 0;
}
if (triangleCount > 0) {
renderTriangles(0, triangleCount);
if (raw != null) {
rawTriangles(0, triangleCount);
}
triangleCount = 0;
}
}
/**
* Handle depth sorting of geometry. Currently this only handles triangles,
* however in the future it will be expanded for points and lines, which
* will also need to be interspersed with one another while rendering.
*/
protected void sort() {
if (triangleCount > 0) {
sortTrianglesInternal(0, triangleCount-1);
}
}
private void sortTrianglesInternal(int i, int j) {
int pivotIndex = (i+j)/2;
sortTrianglesSwap(pivotIndex, j);
int k = sortTrianglesPartition(i-1, j);
sortTrianglesSwap(k, j);
if ((k-i) > 1) sortTrianglesInternal(i, k-1);
if ((j-k) > 1) sortTrianglesInternal(k+1, j);
}
private int sortTrianglesPartition(int left, int right) {
int pivot = right;
do {
while (sortTrianglesCompare(++left, pivot) < 0) { }
while ((right != 0) &&
(sortTrianglesCompare(--right, pivot) > 0)) { }
sortTrianglesSwap(left, right);
} while (left < right);
sortTrianglesSwap(left, right);
return left;
}
private void sortTrianglesSwap(int a, int b) {
int tempi[] = triangles[a];
triangles[a] = triangles[b];
triangles[b] = tempi;
float tempf[][] = triangleColors[a];
triangleColors[a] = triangleColors[b];
triangleColors[b] = tempf;
}
private float sortTrianglesCompare(int a, int b) {
/*
if (Float.isNaN(vertices[triangles[a][VERTEX1]][TZ]) ||
Float.isNaN(vertices[triangles[a][VERTEX2]][TZ]) ||
Float.isNaN(vertices[triangles[a][VERTEX3]][TZ]) ||
Float.isNaN(vertices[triangles[b][VERTEX1]][TZ]) ||
Float.isNaN(vertices[triangles[b][VERTEX2]][TZ]) ||
Float.isNaN(vertices[triangles[b][VERTEX3]][TZ])) {
System.err.println("NaN values in triangle");
}
*/
return ((vertices[triangles[b][VERTEX1]][TZ] +
vertices[triangles[b][VERTEX2]][TZ] +
vertices[triangles[b][VERTEX3]][TZ]) -
(vertices[triangles[a][VERTEX1]][TZ] +
vertices[triangles[a][VERTEX2]][TZ] +
vertices[triangles[a][VERTEX3]][TZ]));
}
//////////////////////////////////////////////////////////////
// POINT, LINE, TRIANGLE, QUAD
// Because vertex(x, y) is mapped to vertex(x, y, 0), none of these commands
// need to be overridden from their default implementation in PGraphics.
//public void point(float x, float y)
//public void point(float x, float y, float z)
//public void line(float x1, float y1, float x2, float y2)
//public void line(float x1, float y1, float z1,
// float x2, float y2, float z2)
//public void triangle(float x1, float y1, float x2, float y2,
// float x3, float y3)
//public void quad(float x1, float y1, float x2, float y2,
// float x3, float y3, float x4, float y4)
//////////////////////////////////////////////////////////////
// RECT
//public void rectMode(int mode)
//public void rect(float a, float b, float c, float d)
//protected void rectImpl(float x1, float y1, float x2, float y2)
//////////////////////////////////////////////////////////////
// ELLIPSE
//public void ellipseMode(int mode)
//public void ellipse(float a, float b, float c, float d)
protected void ellipseImpl(float x, float y, float w, float h) {
float radiusH = w / 2;
float radiusV = h / 2;
float centerX = x + radiusH;
float centerY = y + radiusV;
// float sx1 = screenX(x, y);
// float sy1 = screenY(x, y);
// float sx2 = screenX(x+w, y+h);
// float sy2 = screenY(x+w, y+h);
// returning to pre-1.0 version of algorithm because of problems
int rough = (int)(4+Math.sqrt(w+h)*3);
int accuracy = PApplet.constrain(rough, 6, 100);
if (fill) {
// returning to pre-1.0 version of algorithm because of problems
// int rough = (int)(4+Math.sqrt(w+h)*3);
// int rough = (int) (TWO_PI * PApplet.dist(sx1, sy1, sx2, sy2) / 20);
// int accuracy = PApplet.constrain(rough, 6, 100);
float inc = (float)SINCOS_LENGTH / accuracy;
float val = 0;
boolean strokeSaved = stroke;
stroke = false;
boolean smoothSaved = smooth;
if (smooth && stroke) {
smooth = false;
}
beginShape(TRIANGLE_FAN);
normal(0, 0, 1);
vertex(centerX, centerY);
for (int i = 0; i < accuracy; i++) {
vertex(centerX + cosLUT[(int) val] * radiusH,
centerY + sinLUT[(int) val] * radiusV);
val = (val + inc) % SINCOS_LENGTH;
}
// back to the beginning
vertex(centerX + cosLUT[0] * radiusH,
centerY + sinLUT[0] * radiusV);
endShape();
stroke = strokeSaved;
smooth = smoothSaved;
}
if (stroke) {
// int rough = (int) (TWO_PI * PApplet.dist(sx1, sy1, sx2, sy2) / 8);
// int accuracy = PApplet.constrain(rough, 6, 100);
float inc = (float)SINCOS_LENGTH / accuracy;
float val = 0;
boolean savedFill = fill;
fill = false;
val = 0;
beginShape();
for (int i = 0; i < accuracy; i++) {
vertex(centerX + cosLUT[(int) val] * radiusH,
centerY + sinLUT[(int) val] * radiusV);
val = (val + inc) % SINCOS_LENGTH;
}
endShape(CLOSE);
fill = savedFill;
}
}
//public void arc(float a, float b, float c, float d,
// float start, float stop)
protected void arcImpl(float x, float y, float w, float h,
float start, float stop) {
float hr = w / 2f;
float vr = h / 2f;
float centerX = x + hr;
float centerY = y + vr;
if (fill) {
// shut off stroke for a minute
boolean savedStroke = stroke;
stroke = false;
int startLUT = (int) (0.5f + (start / TWO_PI) * SINCOS_LENGTH);
int stopLUT = (int) (0.5f + (stop / TWO_PI) * SINCOS_LENGTH);
beginShape(TRIANGLE_FAN);
vertex(centerX, centerY);
int increment = 1; // what's a good algorithm? stopLUT - startLUT;
for (int i = startLUT; i < stopLUT; i += increment) {
int ii = i % SINCOS_LENGTH;
// modulo won't make the value positive
if (ii < 0) ii += SINCOS_LENGTH;
vertex(centerX + cosLUT[ii] * hr,
centerY + sinLUT[ii] * vr);
}
// draw last point explicitly for accuracy
vertex(centerX + cosLUT[stopLUT % SINCOS_LENGTH] * hr,
centerY + sinLUT[stopLUT % SINCOS_LENGTH] * vr);
endShape();
stroke = savedStroke;
}
if (stroke) {
// Almost identical to above, but this uses a LINE_STRIP
// and doesn't include the first (center) vertex.
boolean savedFill = fill;
fill = false;
int startLUT = (int) (0.5f + (start / TWO_PI) * SINCOS_LENGTH);
int stopLUT = (int) (0.5f + (stop / TWO_PI) * SINCOS_LENGTH);
beginShape(); //LINE_STRIP);
int increment = 1; // what's a good algorithm? stopLUT - startLUT;
for (int i = startLUT; i < stopLUT; i += increment) {
int ii = i % SINCOS_LENGTH;
if (ii < 0) ii += SINCOS_LENGTH;
vertex(centerX + cosLUT[ii] * hr,
centerY + sinLUT[ii] * vr);
}
// draw last point explicitly for accuracy
vertex(centerX + cosLUT[stopLUT % SINCOS_LENGTH] * hr,
centerY + sinLUT[stopLUT % SINCOS_LENGTH] * vr);
endShape();
fill = savedFill;
}
}
//////////////////////////////////////////////////////////////
// BOX
//public void box(float size)
public void box(float w, float h, float d) {
if (triangle != null) { // triangle is null in gl
triangle.setCulling(true);
}
super.box(w, h, d);
if (triangle != null) { // triangle is null in gl
triangle.setCulling(false);
}
}
//////////////////////////////////////////////////////////////
// SPHERE
//public void sphereDetail(int res)
//public void sphereDetail(int ures, int vres)
public void sphere(float r) {
if (triangle != null) { // triangle is null in gl
triangle.setCulling(true);
}
super.sphere(r);
if (triangle != null) { // triangle is null in gl
triangle.setCulling(false);
}
}
//////////////////////////////////////////////////////////////
// BEZIER
//public float bezierPoint(float a, float b, float c, float d, float t)
//public float bezierTangent(float a, float b, float c, float d, float t)
//public void bezierDetail(int detail)
//public void bezier(float x1, float y1,
// float x2, float y2,
// float x3, float y3,
// float x4, float y4)
//public void bezier(float x1, float y1, float z1,
// float x2, float y2, float z2,
// float x3, float y3, float z3,
// float x4, float y4, float z4)
//////////////////////////////////////////////////////////////
// CATMULL-ROM CURVES
//public float curvePoint(float a, float b, float c, float d, float t)
//public float curveTangent(float a, float b, float c, float d, float t)
//public void curveDetail(int detail)
//public void curveTightness(float tightness)
//public void curve(float x1, float y1,
// float x2, float y2,
// float x3, float y3,
// float x4, float y4)
//public void curve(float x1, float y1, float z1,
// float x2, float y2, float z2,
// float x3, float y3, float z3,
// float x4, float y4, float z4)
//////////////////////////////////////////////////////////////
// SMOOTH
public void smooth() {
//showMethodWarning("smooth");
s_enableAccurateTextures = true;
smooth = true;
}
public void noSmooth() {
s_enableAccurateTextures = false;
smooth = false;
}
//////////////////////////////////////////////////////////////
// IMAGES
//public void imageMode(int mode)
//public void image(PImage image, float x, float y)
//public void image(PImage image, float x, float y, float c, float d)
//public void image(PImage image,
// float a, float b, float c, float d,
// int u1, int v1, int u2, int v2)
//protected void imageImpl(PImage image,
// float x1, float y1, float x2, float y2,
// int u1, int v1, int u2, int v2)
//////////////////////////////////////////////////////////////
// SHAPE
//public void shapeMode(int mode)
//public void shape(PShape shape)
//public void shape(PShape shape, float x, float y)
//public void shape(PShape shape, float x, float y, float c, float d)
//////////////////////////////////////////////////////////////
// TEXT SETTINGS
// Only textModeCheck overridden from PGraphics, no textAlign, textAscent,
// textDescent, textFont, textLeading, textMode, textSize, textWidth
protected boolean textModeCheck(int mode) {
return (textMode == MODEL) || (textMode == SCREEN);
}
//////////////////////////////////////////////////////////////
// TEXT
// None of the variations of text() are overridden from PGraphics.
//////////////////////////////////////////////////////////////
// TEXT IMPL
// Not even the text drawing implementation stuff is overridden.
//////////////////////////////////////////////////////////////
// MATRIX STACK
public void pushMatrix() {
if (matrixStackDepth == MATRIX_STACK_DEPTH) {
throw new RuntimeException(ERROR_PUSHMATRIX_OVERFLOW);
}
modelview.get(matrixStack[matrixStackDepth]);
modelviewInv.get(matrixInvStack[matrixStackDepth]);
matrixStackDepth++;
}
public void popMatrix() {
if (matrixStackDepth == 0) {
throw new RuntimeException(ERROR_PUSHMATRIX_UNDERFLOW);
}
matrixStackDepth--;
modelview.set(matrixStack[matrixStackDepth]);
modelviewInv.set(matrixInvStack[matrixStackDepth]);
}
//////////////////////////////////////////////////////////////
// MATRIX TRANSFORMATIONS
public void translate(float tx, float ty) {
translate(tx, ty, 0);
}
public void translate(float tx, float ty, float tz) {
forwardTransform.translate(tx, ty, tz);
reverseTransform.invTranslate(tx, ty, tz);
}
/**
* Two dimensional rotation. Same as rotateZ (this is identical
* to a 3D rotation along the z-axis) but included for clarity --
* it'd be weird for people drawing 2D graphics to be using rotateZ.
* And they might kick our a-- for the confusion.
*/
public void rotate(float angle) {
rotateZ(angle);
}
public void rotateX(float angle) {
forwardTransform.rotateX(angle);
reverseTransform.invRotateX(angle);
}
public void rotateY(float angle) {
forwardTransform.rotateY(angle);
reverseTransform.invRotateY(angle);
}
public void rotateZ(float angle) {
forwardTransform.rotateZ(angle);
reverseTransform.invRotateZ(angle);
}
/**
* Rotate around an arbitrary vector, similar to glRotate(),
* except that it takes radians (instead of degrees).
*/
public void rotate(float angle, float v0, float v1, float v2) {
forwardTransform.rotate(angle, v0, v1, v2);
reverseTransform.invRotate(angle, v0, v1, v2);
}
/**
* Same as scale(s, s, s).
*/
public void scale(float s) {
scale(s, s, s);
}
/**
* Same as scale(sx, sy, 1).
*/
public void scale(float sx, float sy) {
scale(sx, sy, 1);
}
/**
* Scale in three dimensions.
*/
public void scale(float x, float y, float z) {
forwardTransform.scale(x, y, z);
reverseTransform.invScale(x, y, z);
}
public void skewX(float angle) {
float t = (float) Math.tan(angle);
applyMatrix(1, t, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
}
public void skewY(float angle) {
float t = (float) Math.tan(angle);
applyMatrix(1, 0, 0, 0,
t, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
}
//////////////////////////////////////////////////////////////
// MATRIX MORE!
public void resetMatrix() {
forwardTransform.reset();
reverseTransform.reset();
}
public void applyMatrix(PMatrix2D source) {
applyMatrix(source.m00, source.m01, source.m02,
source.m10, source.m11, source.m12);
}
public void applyMatrix(float n00, float n01, float n02,
float n10, float n11, float n12) {
applyMatrix(n00, n01, n02, 0,
n10, n11, n12, 0,
0, 0, 1, 0,
0, 0, 0, 1);
}
public void applyMatrix(PMatrix3D source) {
applyMatrix(source.m00, source.m01, source.m02, source.m03,
source.m10, source.m11, source.m12, source.m13,
source.m20, source.m21, source.m22, source.m23,
source.m30, source.m31, source.m32, source.m33);
}
/**
* Apply a 4x4 transformation matrix. Same as glMultMatrix().
* This call will be slow because it will try to calculate the
* inverse of the transform. So avoid it whenever possible.
*/
public void applyMatrix(float n00, float n01, float n02, float n03,
float n10, float n11, float n12, float n13,
float n20, float n21, float n22, float n23,
float n30, float n31, float n32, float n33) {
forwardTransform.apply(n00, n01, n02, n03,
n10, n11, n12, n13,
n20, n21, n22, n23,
n30, n31, n32, n33);
reverseTransform.invApply(n00, n01, n02, n03,
n10, n11, n12, n13,
n20, n21, n22, n23,
n30, n31, n32, n33);
}
//////////////////////////////////////////////////////////////
// MATRIX GET/SET/PRINT
public PMatrix getMatrix() {
return modelview.get();
}
//public PMatrix2D getMatrix(PMatrix2D target)
public PMatrix3D getMatrix(PMatrix3D target) {
if (target == null) {
target = new PMatrix3D();
}
target.set(modelview);
return target;
}
//public void setMatrix(PMatrix source)
public void setMatrix(PMatrix2D source) {
// not efficient, but at least handles the inverse stuff.
resetMatrix();
applyMatrix(source);
}
/**
* Set the current transformation to the contents of the specified source.
*/
public void setMatrix(PMatrix3D source) {
// not efficient, but at least handles the inverse stuff.
resetMatrix();
applyMatrix(source);
}
/**
* Print the current model (or "transformation") matrix.
*/
public void printMatrix() {
modelview.print();
}
/*
* This function checks if the modelview matrix is set up to likely be
* drawing in 2D. It merely checks if the non-translational piece of the
* matrix is unity. If this is to be used, it should be coupled with a
* check that the raw vertex coordinates lie in the z=0 plane.
* Mainly useful for applying sub-pixel shifts to avoid 2d artifacts
* in the screen plane.
* Added by ewjordan 6/13/07
*
* TODO need to invert the logic here so that we can simply return
* the value, rather than calculating true/false and returning it.
*/
/*
private boolean drawing2D() {
if (modelview.m00 != 1.0f ||
modelview.m11 != 1.0f ||
modelview.m22 != 1.0f || // check scale
modelview.m01 != 0.0f ||
modelview.m02 != 0.0f || // check rotational pieces
modelview.m10 != 0.0f ||
modelview.m12 != 0.0f ||
modelview.m20 != 0.0f ||
modelview.m21 != 0.0f ||
!((camera.m23-modelview.m23) <= EPSILON &&
(camera.m23-modelview.m23) >= -EPSILON)) { // check for z-translation
// Something about the modelview matrix indicates 3d drawing
// (or rotated 2d, in which case 2d subpixel fixes probably aren't needed)
return false;
} else {
//The matrix is mapping z=0 vertices to the screen plane,
// which means it's likely that 2D drawing is happening.
return true;
}
}
*/
//////////////////////////////////////////////////////////////
// CAMERA
/**
* Set matrix mode to the camera matrix (instead of the current
* transformation matrix). This means applyMatrix, resetMatrix, etc.
* will affect the camera.
*
* beginCamera();
* translate(0, 0, 10);
* endCamera();
*
* at the top of draw(), will result in a runaway camera that shoots
* infinitely out of the screen over time. In order to prevent this,
* it is necessary to call some function that does a hard reset of the
* camera transform matrix inside of begin/endCamera. Two options are
*
* camera(); // sets up the nice default camera transform
* resetMatrix(); // sets up the identity camera transform
*
* So to rotate a camera a constant amount, you might try
*
* beginCamera();
* camera();
* rotateY(PI/8);
* endCamera();
*
*/
public void beginCamera() {
if (manipulatingCamera) {
throw new RuntimeException("beginCamera() cannot be called again " +
"before endCamera()");
} else {
manipulatingCamera = true;
forwardTransform = cameraInv;
reverseTransform = camera;
}
}
/**
* Record the current settings into the camera matrix, and set
* the matrix mode back to the current transformation matrix.
*
* camera(); or
* camera(ex, ey, ez, cx, cy, cz, ux, uy, uz);
*
* do not need to be called from with beginCamera();/endCamera();
* That's because they always apply to the camera transformation,
* and they always totally replace it. That means that any coordinate
* transforms done before camera(); in draw() will be wiped out.
* It also means that camera() always operates in untransformed world
* coordinates. Therefore it is always redundant to call resetMatrix();
* before camera(); This isn't technically true of gluLookat, but it's
* pretty much how it's used.
*
* beginCamera();
* rotateY(PI/8);
* endCamera();
*
* will result in a camera that spins without stopping. If you want to
* just rotate a small constant amount, try this:
*
* beginCamera();
* camera(); // sets up the default view
* rotateY(PI/8);
* endCamera();
*
* That will rotate a little off of the default view. Note that this
* is entirely equivalent to
*
* camera(); // sets up the default view
* beginCamera();
* rotateY(PI/8);
* endCamera();
*
* because camera() doesn't care whether or not it's inside a
* begin/end clause. Basically it's safe to use camera() or
* camera(ex, ey, ez, cx, cy, cz, ux, uy, uz) as naked calls because
* they do all the matrix resetting automatically.
*/
public void camera(float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ,
float upX, float upY, float upZ) {
float z0 = eyeX - centerX;
float z1 = eyeY - centerY;
float z2 = eyeZ - centerZ;
float mag = sqrt(z0*z0 + z1*z1 + z2*z2);
if (mag != 0) {
z0 /= mag;
z1 /= mag;
z2 /= mag;
}
float y0 = upX;
float y1 = upY;
float y2 = upZ;
float x0 = y1*z2 - y2*z1;
float x1 = -y0*z2 + y2*z0;
float x2 = y0*z1 - y1*z0;
y0 = z1*x2 - z2*x1;
y1 = -z0*x2 + z2*x0;
y2 = z0*x1 - z1*x0;
mag = sqrt(x0*x0 + x1*x1 + x2*x2);
if (mag != 0) {
x0 /= mag;
x1 /= mag;
x2 /= mag;
}
mag = sqrt(y0*y0 + y1*y1 + y2*y2);
if (mag != 0) {
y0 /= mag;
y1 /= mag;
y2 /= mag;
}
// just does an apply to the main matrix,
// since that'll be copied out on endCamera
camera.set(x0, x1, x2, 0,
y0, y1, y2, 0,
z0, z1, z2, 0,
0, 0, 0, 1);
camera.translate(-eyeX, -eyeY, -eyeZ);
cameraInv.reset();
cameraInv.invApply(x0, x1, x2, 0,
y0, y1, y2, 0,
z0, z1, z2, 0,
0, 0, 0, 1);
cameraInv.translate(eyeX, eyeY, eyeZ);
modelview.set(camera);
modelviewInv.set(cameraInv);
}
/**
* Print the current camera matrix.
*/
public void printCamera() {
camera.print();
}
//////////////////////////////////////////////////////////////
// PROJECTION
/**
* Calls ortho() with the proper parameters for Processing's
* standard orthographic projection.
*/
public void ortho() {
ortho(0, width, 0, height, -10, 10);
}
/**
* Similar to gluOrtho(), but wipes out the current projection matrix.
*
*
* Each of these three functions completely replaces the projection
* matrix with a new one. They can be called inside setup(), and their
* effects will be felt inside draw(). At the top of draw(), the projection
* matrix is not reset. Therefore the last projection function to be
* called always dominates. On resize, the default projection is always
* established, which has perspective.
*
* The Lighting Skinny:
*
* The way lighting works is complicated enough that it's worth
* producing a document to describe it. Lighting calculations proceed
* pretty much exactly as described in the OpenGL red book.
*
* Light-affecting material properties:
*
* AMBIENT COLOR
* - multiplies by light's ambient component
* - for believability this should match diffuse color
*
* DIFFUSE COLOR
* - multiplies by light's diffuse component
*
* SPECULAR COLOR
* - multiplies by light's specular component
* - usually less colored than diffuse/ambient
*
* SHININESS
* - the concentration of specular effect
* - this should be set pretty high (20-50) to see really
* noticeable specularity
*
* EMISSIVE COLOR
* - constant additive color effect
*
* Light types:
*
* AMBIENT
* - one color
* - no specular color
* - no direction
* - may have falloff (constant, linear, and quadratic)
* - may have position (which matters in non-constant falloff case)
* - multiplies by a material's ambient reflection
*
* DIRECTIONAL
* - has diffuse color
* - has specular color
* - has direction
* - no position
* - no falloff
* - multiplies by a material's diffuse and specular reflections
*
* POINT
* - has diffuse color
* - has specular color
* - has position
* - no direction
* - may have falloff (constant, linear, and quadratic)
* - multiplies by a material's diffuse and specular reflections
*
* SPOT
* - has diffuse color
* - has specular color
* - has position
* - has direction
* - has cone angle (set to half the total cone angle)
* - has concentration value
* - may have falloff (constant, linear, and quadratic)
* - multiplies by a material's diffuse and specular reflections
*
* Normal modes:
*
* All of the primitives (rect, box, sphere, etc.) have their normals
* set nicely. During beginShape/endShape normals can be set by the user.
*
* AUTO-NORMAL
* - if no normal is set during the shape, we are in auto-normal mode
* - auto-normal calculates one normal per triangle (face-normal mode)
*
* SHAPE-NORMAL
* - if one normal is set during the shape, it will be used for
* all vertices
*
* VERTEX-NORMAL
* - if multiple normals are set, each normal applies to
* subsequent vertices
* - (except for the first one, which applies to previous
* and subsequent vertices)
*
* Efficiency consequences:
*
* There is a major efficiency consequence of position-dependent
* lighting calculations per vertex. (See below for determining
* whether lighting is vertex position-dependent.) If there is no
* position dependency then the only factors that affect the lighting
* contribution per vertex are its colors and its normal.
* There is a major efficiency win if
*
* 1) lighting is not position dependent
* 2) we are in AUTO-NORMAL or SHAPE-NORMAL mode
*
* because then we can calculate one lighting contribution per shape
* (SHAPE-NORMAL) or per triangle (AUTO-NORMAL) and simply multiply it
* into the vertex colors. The converse is our worst-case performance when
*
* 1) lighting is position dependent
* 2) we are in AUTO-NORMAL mode
*
* because then we must calculate lighting per-face * per-vertex.
* Each vertex has a different lighting contribution per face in
* which it appears. Yuck.
*
* Determining vertex position dependency:
*
* If any of the following factors are TRUE then lighting is
* vertex position dependent:
*
* 1) Any lights uses non-constant falloff
* 2) There are any point or spot lights
* 3) There is a light with specular color AND there is a
* material with specular color
*
* So worth noting is that default lighting (a no-falloff ambient
* and a directional without specularity) is not position-dependent.
* We should capitalize.
*
* Simon Greenwold, April 2005
*
*/
public void lights() {
// need to make sure colorMode is RGB 255 here
int colorModeSaved = colorMode;
colorMode = RGB;
lightFalloff(1, 0, 0);
lightSpecular(0, 0, 0);
ambientLight(colorModeX * 0.5f,
colorModeY * 0.5f,
colorModeZ * 0.5f);
directionalLight(colorModeX * 0.5f,
colorModeY * 0.5f,
colorModeZ * 0.5f,
0, 0, -1);
colorMode = colorModeSaved;
lightingDependsOnVertexPosition = false;
}
/**
* Turn off all lights.
*/
public void noLights() {
// write any queued geometry, because lighting will be goofed after
flush();
// set the light count back to zero
lightCount = 0;
}
/**
* Add an ambient light based on the current color mode.
*/
public void ambientLight(float r, float g, float b) {
ambientLight(r, g, b, 0, 0, 0);
}
/**
* Add an ambient light based on the current color mode.
* This version includes an (x, y, z) position for situations
* where the falloff distance is used.
*/
public void ambientLight(float r, float g, float b,
float x, float y, float z) {
if (lightCount == MAX_LIGHTS) {
throw new RuntimeException("can only create " + MAX_LIGHTS + " lights");
}
colorCalc(r, g, b);
lightDiffuse[lightCount][0] = calcR;
lightDiffuse[lightCount][1] = calcG;
lightDiffuse[lightCount][2] = calcB;
lightType[lightCount] = AMBIENT;
lightFalloffConstant[lightCount] = currentLightFalloffConstant;
lightFalloffLinear[lightCount] = currentLightFalloffLinear;
lightFalloffQuadratic[lightCount] = currentLightFalloffQuadratic;
lightPosition(lightCount, x, y, z);
lightCount++;
//return lightCount-1;
}
public void directionalLight(float r, float g, float b,
float nx, float ny, float nz) {
if (lightCount == MAX_LIGHTS) {
throw new RuntimeException("can only create " + MAX_LIGHTS + " lights");
}
colorCalc(r, g, b);
lightDiffuse[lightCount][0] = calcR;
lightDiffuse[lightCount][1] = calcG;
lightDiffuse[lightCount][2] = calcB;
lightType[lightCount] = DIRECTIONAL;
lightFalloffConstant[lightCount] = currentLightFalloffConstant;
lightFalloffLinear[lightCount] = currentLightFalloffLinear;
lightFalloffQuadratic[lightCount] = currentLightFalloffQuadratic;
lightSpecular[lightCount][0] = currentLightSpecular[0];
lightSpecular[lightCount][1] = currentLightSpecular[1];
lightSpecular[lightCount][2] = currentLightSpecular[2];
lightDirection(lightCount, nx, ny, nz);
lightCount++;
}
public void pointLight(float r, float g, float b,
float x, float y, float z) {
if (lightCount == MAX_LIGHTS) {
throw new RuntimeException("can only create " + MAX_LIGHTS + " lights");
}
colorCalc(r, g, b);
lightDiffuse[lightCount][0] = calcR;
lightDiffuse[lightCount][1] = calcG;
lightDiffuse[lightCount][2] = calcB;
lightType[lightCount] = POINT;
lightFalloffConstant[lightCount] = currentLightFalloffConstant;
lightFalloffLinear[lightCount] = currentLightFalloffLinear;
lightFalloffQuadratic[lightCount] = currentLightFalloffQuadratic;
lightSpecular[lightCount][0] = currentLightSpecular[0];
lightSpecular[lightCount][1] = currentLightSpecular[1];
lightSpecular[lightCount][2] = currentLightSpecular[2];
lightPosition(lightCount, x, y, z);
lightCount++;
lightingDependsOnVertexPosition = true;
}
public void spotLight(float r, float g, float b,
float x, float y, float z,
float nx, float ny, float nz,
float angle, float concentration) {
if (lightCount == MAX_LIGHTS) {
throw new RuntimeException("can only create " + MAX_LIGHTS + " lights");
}
colorCalc(r, g, b);
lightDiffuse[lightCount][0] = calcR;
lightDiffuse[lightCount][1] = calcG;
lightDiffuse[lightCount][2] = calcB;
lightType[lightCount] = SPOT;
lightFalloffConstant[lightCount] = currentLightFalloffConstant;
lightFalloffLinear[lightCount] = currentLightFalloffLinear;
lightFalloffQuadratic[lightCount] = currentLightFalloffQuadratic;
lightSpecular[lightCount][0] = currentLightSpecular[0];
lightSpecular[lightCount][1] = currentLightSpecular[1];
lightSpecular[lightCount][2] = currentLightSpecular[2];
lightPosition(lightCount, x, y, z);
lightDirection(lightCount, nx, ny, nz);
lightSpotAngle[lightCount] = angle;
lightSpotAngleCos[lightCount] = Math.max(0, (float) Math.cos(angle));
lightSpotConcentration[lightCount] = concentration;
lightCount++;
lightingDependsOnVertexPosition = true;
}
/**
* Set the light falloff rates for the last light that was created.
* Default is lightFalloff(1, 0, 0).
*/
public void lightFalloff(float constant, float linear, float quadratic) {
currentLightFalloffConstant = constant;
currentLightFalloffLinear = linear;
currentLightFalloffQuadratic = quadratic;
lightingDependsOnVertexPosition = true;
}
/**
* Set the specular color of the last light created.
*/
public void lightSpecular(float x, float y, float z) {
colorCalc(x, y, z);
currentLightSpecular[0] = calcR;
currentLightSpecular[1] = calcG;
currentLightSpecular[2] = calcB;
lightingDependsOnVertexPosition = true;
}
/**
* internal function to set the light position
* based on the current modelview matrix.
*/
protected void lightPosition(int num, float x, float y, float z) {
lightPositionVec.set(x, y, z);
modelview.mult(lightPositionVec, lightPosition[num]);
/*
lightPosition[num][0] =
modelview.m00*x + modelview.m01*y + modelview.m02*z + modelview.m03;
lightPosition[num][1] =
modelview.m10*x + modelview.m11*y + modelview.m12*z + modelview.m13;
lightPosition[num][2] =
modelview.m20*x + modelview.m21*y + modelview.m22*z + modelview.m23;
*/
}
/**
* internal function to set the light direction
* based on the current modelview matrix.
*/
protected void lightDirection(int num, float x, float y, float z) {
lightNormal[num].set(modelviewInv.m00*x + modelviewInv.m10*y + modelviewInv.m20*z + modelviewInv.m30,
modelviewInv.m01*x + modelviewInv.m11*y + modelviewInv.m21*z + modelviewInv.m31,
modelviewInv.m02*x + modelviewInv.m12*y + modelviewInv.m22*z + modelviewInv.m32);
lightNormal[num].normalize();
/*
lightDirectionVec.set(x, y, z);
System.out.println("dir vec " + lightDirectionVec);
//modelviewInv.mult(lightDirectionVec, lightNormal[num]);
modelviewInv.cmult(lightDirectionVec, lightNormal[num]);
System.out.println("cmult vec " + lightNormal[num]);
lightNormal[num].normalize();
System.out.println("setting light direction " + lightNormal[num]);
*/
/*
// Multiply by inverse transpose.
lightNormal[num][0] =
modelviewInv.m00*x + modelviewInv.m10*y +
modelviewInv.m20*z + modelviewInv.m30;
lightNormal[num][1] =
modelviewInv.m01*x + modelviewInv.m11*y +
modelviewInv.m21*z + modelviewInv.m31;
lightNormal[num][2] =
modelviewInv.m02*x + modelviewInv.m12*y +
modelviewInv.m22*z + modelviewInv.m32;
float n = mag(lightNormal[num][0], lightNormal[num][1], lightNormal[num][2]);
if (n == 0 || n == 1) return;
lightNormal[num][0] /= n;
lightNormal[num][1] /= n;
lightNormal[num][2] /= n;
*/
}
//////////////////////////////////////////////////////////////
// BACKGROUND
// Base background() variations inherited from PGraphics.
protected void backgroundImpl(PImage image) {
System.arraycopy(image.pixels, 0, pixels, 0, pixels.length);
Arrays.fill(zbuffer, Float.MAX_VALUE);
}
/**
* Clear pixel buffer. With P3D and OPENGL, this also clears the zbuffer.
*/
protected void backgroundImpl() {
Arrays.fill(pixels, backgroundColor);
Arrays.fill(zbuffer, Float.MAX_VALUE);
}
//////////////////////////////////////////////////////////////
// COLOR MODE
// all colorMode() variations inherited from PGraphics.
//////////////////////////////////////////////////////////////
// COLOR CALCULATIONS
// protected colorCalc and colorCalcARGB inherited.
//////////////////////////////////////////////////////////////
// COLOR DATATYPE STUFFING
// final color() variations inherited.
//////////////////////////////////////////////////////////////
// COLOR DATATYPE EXTRACTION
// final methods alpha, red, green, blue,
// hue, saturation, and brightness all inherited.
//////////////////////////////////////////////////////////////
// COLOR DATATYPE INTERPOLATION
// both lerpColor variants inherited.
//////////////////////////////////////////////////////////////
// BEGIN/END RAW
// beginRaw, endRaw() both inherited.
//////////////////////////////////////////////////////////////
// WARNINGS and EXCEPTIONS
// showWarning and showException inherited.
//////////////////////////////////////////////////////////////
// RENDERER SUPPORT QUERIES
//public boolean displayable()
public boolean is2D() {
return false;
}
public boolean is3D() {
return true;
}
//////////////////////////////////////////////////////////////
// PIMAGE METHODS
// All these methods are inherited, because this render has a
// pixels[] array that can be accessed directly.
// getImage
// setCache, getCache, removeCache
// isModified, setModified
// loadPixels, updatePixels
// resize
// get, getImpl, set, setImpl
// mask
// filter
// copy
// blendColor, blend
//////////////////////////////////////////////////////////////
// MATH (internal use only)
private final float sqrt(float a) {
return (float) Math.sqrt(a);
}
private final float mag(float a, float b, float c) {
return (float) Math.sqrt(a*a + b*b + c*c);
}
private final float clamp(float a) {
return (a < 1) ? a : 1;
}
private final float abs(float a) {
return (a < 0) ? -a : a;
}
private float dot(float ax, float ay, float az,
float bx, float by, float bz) {
return ax*bx + ay*by + az*bz;
}
/*
private final void cross(float a0, float a1, float a2,
float b0, float b1, float b2,
float[] out) {
out[0] = a1*b2 - a2*b1;
out[1] = a2*b0 - a0*b2;
out[2] = a0*b1 - a1*b0;
}
*/
private final void cross(float a0, float a1, float a2,
float b0, float b1, float b2,
PVector out) {
out.x = a1*b2 - a2*b1;
out.y = a2*b0 - a0*b2;
out.z = a0*b1 - a1*b0;
}
/*
private final void cross(float[] a, float[] b, float[] out) {
out[0] = a[1]*b[2] - a[2]*b[1];
out[1] = a[2]*b[0] - a[0]*b[2];
out[2] = a[0]*b[1] - a[1]*b[0];
}
*/
}
processing-core-1.2.1/src/processing/core/PSmoothTriangle.java 0000644 0001750 0001750 00000075676 11112435354 024000 0 ustar andrew andrew /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-08 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
/**
* Smoothed triangle renderer for P3D.
*
* Based off of the PPolygon class in old versions of Processing.
* Name and location of this class will change in a future release.
*/
public class PSmoothTriangle implements PConstants {
// really this is "debug" but..
private static final boolean EWJORDAN = false;
private static final boolean FRY = false;
// identical to the constants from PGraphics
static final int X = 0; // transformed xyzw
static final int Y = 1; // formerly SX SY SZ
static final int Z = 2;
static final int R = 3; // actual rgb, after lighting
static final int G = 4; // fill stored here, transform in place
static final int B = 5;
static final int A = 6;
static final int U = 7; // texture
static final int V = 8;
static final int DEFAULT_SIZE = 64; // this is needed for spheres
float vertices[][] = new float[DEFAULT_SIZE][PGraphics.VERTEX_FIELD_COUNT];
int vertexCount;
// after some fiddling, this seems to produce the best results
static final int ZBUFFER_MIN_COVERAGE = 204;
float r[] = new float[DEFAULT_SIZE]; // storage used by incrementalize
float dr[] = new float[DEFAULT_SIZE];
float l[] = new float[DEFAULT_SIZE]; // more storage for incrementalize
float dl[] = new float[DEFAULT_SIZE];
float sp[] = new float[DEFAULT_SIZE]; // temporary storage for scanline
float sdp[] = new float[DEFAULT_SIZE];
// color and xyz are always interpolated
boolean interpX;
boolean interpZ;
boolean interpUV; // is this necessary? could just check timage != null
boolean interpARGB;
int rgba;
int r2, g2, b2, a2, a2orig;
boolean noDepthTest;
PGraphics3D parent;
int pixels[];
float[] zbuffer;
// the parent's width/height,
// or if smooth is enabled, parent's w/h scaled
// up by the smooth dimension
int width, height;
int width1, height1;
PImage timage;
int tpixels[];
int theight, twidth;
int theight1, twidth1;
int tformat;
// temp fix to behave like SMOOTH_IMAGES
// TODO ewjordan: can probably remove this variable
boolean texture_smooth;
// for anti-aliasing
static final int SUBXRES = 8;
static final int SUBXRES1 = 7;
static final int SUBYRES = 8;
static final int SUBYRES1 = 7;
static final int MAX_COVERAGE = SUBXRES * SUBYRES;
boolean smooth;
int firstModY;
int lastModY;
int lastY;
int aaleft[] = new int[SUBYRES];
int aaright[] = new int[SUBYRES];
int aaleftmin, aarightmin;
int aaleftmax, aarightmax;
int aaleftfull, aarightfull;
/* Variables needed for accurate texturing. */
//private PMatrix textureMatrix = new PMatrix3D();
private float[] camX = new float[3];
private float[] camY = new float[3];
private float[] camZ = new float[3];
private float ax,ay,az;
private float bx,by,bz;
private float cx,cy,cz;
private float nearPlaneWidth, nearPlaneHeight, nearPlaneDepth;
//private float newax, newbx, newcx;
private float xmult, ymult;
final private int MODYRES(int y) {
return (y & SUBYRES1);
}
public PSmoothTriangle(PGraphics3D iparent) {
parent = iparent;
reset(0);
}
public void reset(int count) {
vertexCount = count;
interpX = true;
interpZ = true;
interpUV = false;
interpARGB = true;
timage = null;
}
public float[] nextVertex() {
if (vertexCount == vertices.length) {
//parent.message(CHATTER, "re-allocating for " +
// (vertexCount*2) + " vertices");
float temp[][] = new float[vertexCount<<1][PGraphics.VERTEX_FIELD_COUNT];
System.arraycopy(vertices, 0, temp, 0, vertexCount);
vertices = temp;
r = new float[vertices.length];
dr = new float[vertices.length];
l = new float[vertices.length];
dl = new float[vertices.length];
sp = new float[vertices.length];
sdp = new float[vertices.length];
}
return vertices[vertexCount++]; // returns v[0], sets vc to 1
}
public void texture(PImage image) {
this.timage = image;
this.tpixels = image.pixels;
this.twidth = image.width;
this.theight = image.height;
this.tformat = image.format;
twidth1 = twidth - 1;
theight1 = theight - 1;
interpUV = true;
}
public void render() {
if (vertexCount < 3) return;
smooth = true;//TODO
// these may have changed due to a resize()
// so they should be refreshed here
pixels = parent.pixels;
zbuffer = parent.zbuffer;
noDepthTest = false;//parent.hints[DISABLE_DEPTH_TEST];
// In 0148+, should always be true if this code is called at all
//smooth = parent.smooth;
// by default, text turns on smooth for the textures
// themselves. but this should be shut off if the hint
// for DISABLE_TEXT_SMOOTH is set.
texture_smooth = true;
width = smooth ? parent.width*SUBXRES : parent.width;
height = smooth ? parent.height*SUBYRES : parent.height;
width1 = width - 1;
height1 = height - 1;
if (!interpARGB) {
r2 = (int) (vertices[0][R] * 255);
g2 = (int) (vertices[0][G] * 255);
b2 = (int) (vertices[0][B] * 255);
a2 = (int) (vertices[0][A] * 255);
a2orig = a2; // save an extra copy
rgba = 0xff000000 | (r2 << 16) | (g2 << 8) | b2;
}
for (int i = 0; i < vertexCount; i++) {
r[i] = 0; dr[i] = 0; l[i] = 0; dl[i] = 0;
}
if (smooth) {
for (int i = 0; i < vertexCount; i++) {
vertices[i][X] *= SUBXRES;
vertices[i][Y] *= SUBYRES;
}
firstModY = -1;
}
// find top vertex (y is zero at top, higher downwards)
int topi = 0;
float ymin = vertices[0][Y];
float ymax = vertices[0][Y]; // fry 031001
for (int i = 1; i < vertexCount; i++) {
if (vertices[i][Y] < ymin) {
ymin = vertices[i][Y];
topi = i;
}
if (vertices[i][Y] > ymax) ymax = vertices[i][Y];
}
// the last row is an exceptional case, because there won't
// necessarily be 8 rows of subpixel lines that will force
// the final line to render. so instead, the algo keeps track
// of the lastY (in subpixel resolution) that will be rendered
// and that will force a scanline to happen the same as
// every eighth in the other situations
//lastY = -1; // fry 031001
lastY = (int) (ymax - 0.5f); // global to class bc used by other fxns
int lefti = topi; // li, index of left vertex
int righti = topi; // ri, index of right vertex
int y = (int) (ymin + 0.5f); // current scan line
int lefty = y - 1; // lower end of left edge
int righty = y - 1; // lower end of right edge
interpX = true;
int remaining = vertexCount;
// scan in y, activating new edges on left & right
// as scan line passes over new vertices
while (remaining > 0) {
// advance left edge?
while ((lefty <= y) && (remaining > 0)) {
remaining--;
// step ccw down left side
int i = (lefti != 0) ? (lefti-1) : (vertexCount-1);
incrementalize_y(vertices[lefti], vertices[i], l, dl, y);
lefty = (int) (vertices[i][Y] + 0.5f);
lefti = i;
}
// advance right edge?
while ((righty <= y) && (remaining > 0)) {
remaining--;
// step cw down right edge
int i = (righti != vertexCount-1) ? (righti + 1) : 0;
incrementalize_y(vertices[righti], vertices[i], r, dr, y);
righty = (int) (vertices[i][Y] + 0.5f);
righti = i;
}
// do scanlines till end of l or r edge
while (y < lefty && y < righty) {
// this doesn't work because it's not always set here
//if (remaining == 0) {
//lastY = (lefty < righty) ? lefty-1 : righty-1;
//System.out.println("lastY is " + lastY);
//}
if ((y >= 0) && (y < height)) {
//try { // hopefully this bug is fixed
if (l[X] <= r[X]) scanline(y, l, r);
else scanline(y, r, l);
//} catch (ArrayIndexOutOfBoundsException e) {
//e.printStackTrace();
//}
}
y++;
// this increment probably needs to be different
// UV and RGB shouldn't be incremented until line is emitted
increment(l, dl);
increment(r, dr);
}
}
//if (smooth) {
//System.out.println("y/lasty/lastmody = " + y + " " + lastY + " " + lastModY);
//}
}
public void unexpand() {
if (smooth) {
for (int i = 0; i < vertexCount; i++) {
vertices[i][X] /= SUBXRES;
vertices[i][Y] /= SUBYRES;
}
}
}
private void scanline(int y, float l[], float r[]) {
//System.out.println("scanline " + y);
for (int i = 0; i < vertexCount; i++) { // should be moved later
sp[i] = 0; sdp[i] = 0;
}
// this rounding doesn't seem to be relevant with smooth
int lx = (int) (l[X] + 0.49999f); // ceil(l[X]-.5);
if (lx < 0) lx = 0;
int rx = (int) (r[X] - 0.5f);
if (rx > width1) rx = width1;
if (lx > rx) return;
if (smooth) {
int mody = MODYRES(y);
aaleft[mody] = lx;
aaright[mody] = rx;
if (firstModY == -1) {
firstModY = mody;
aaleftmin = lx; aaleftmax = lx;
aarightmin = rx; aarightmax = rx;
} else {
if (aaleftmin > aaleft[mody]) aaleftmin = aaleft[mody];
if (aaleftmax < aaleft[mody]) aaleftmax = aaleft[mody];
if (aarightmin > aaright[mody]) aarightmin = aaright[mody];
if (aarightmax < aaright[mody]) aarightmax = aaright[mody];
}
lastModY = mody; // moved up here (before the return) 031001
// not the eighth (or lastY) line, so not scanning this time
if ((mody != SUBYRES1) && (y != lastY)) return;
//lastModY = mody; // eeK! this was missing
//return;
//if (y == lastY) {
//System.out.println("y is lasty");
//}
//lastModY = mody;
aaleftfull = aaleftmax/SUBXRES + 1;
aarightfull = aarightmin/SUBXRES - 1;
}
// this is the setup, based on lx
incrementalize_x(l, r, sp, sdp, lx);
//System.out.println(l[V] + " " + r[V] + " " +sp[V] + " " +sdp[V]);
// scan in x, generating pixels
// using parent.width to get actual pixel index
// rather than scaled by smooth factor
int offset = smooth ? parent.width * (y / SUBYRES) : parent.width*y;
int truelx = 0, truerx = 0;
if (smooth) {
truelx = lx / SUBXRES;
truerx = (rx + SUBXRES1) / SUBXRES;
lx = aaleftmin / SUBXRES;
rx = (aarightmax + SUBXRES1) / SUBXRES;
if (lx < 0) lx = 0;
if (rx > parent.width1) rx = parent.width1;
}
// System.out.println("P3D interp uv " + interpUV + " " +
// vertices[2][U] + " " + vertices[2][V]);
interpX = false;
int tr, tg, tb, ta;
//System.out.println("lx: "+lx + "\nrx: "+rx);
for (int x = lx; x <= rx; x++) {
// added == because things on same plane weren't replacing each other
// makes for strangeness in 3D [ewj: yup!], but totally necessary for 2D
//if (noDepthTest || (sp[Z] < zbuffer[offset+x])) {
if (noDepthTest || (sp[Z] <= zbuffer[offset+x])) {
//if (true) {
// map texture based on U, V coords in sp[U] and sp[V]
if (interpUV) {
int tu = (int)sp[U];
int tv = (int)sp[V];
if (tu > twidth1) tu = twidth1;
if (tv > theight1) tv = theight1;
if (tu < 0) tu = 0;
if (tv < 0) tv = 0;
int txy = tv*twidth + tu;
//System.out.println("tu: "+tu+" ; tv: "+tv+" ; txy: "+txy);
float[] uv = new float[2];
txy = getTextureIndex(x, y*1.0f/SUBYRES, uv);
// txy = getTextureIndex(x* 1.0f/SUBXRES, y*1.0f/SUBYRES, uv);
tu = (int)uv[0]; tv = (int)uv[1];
// if (tu > twidth1) tu = twidth1;
// if (tv > theight1) tv = theight1;
// if (tu < 0) tu = 0;
// if (tv < 0) tv = 0;
txy = twidth*tv + tu;
// if (EWJORDAN) System.out.println("x/y/txy:"+x + " " + y + " " +txy);
//PApplet.println(sp);
//smooth = true;
if (smooth || texture_smooth) {
//if (FRY) System.out.println("sp u v = " + sp[U] + " " + sp[V]);
//System.out.println("sp u v = " + sp[U] + " " + sp[V]);
// tuf1/tvf1 is the amount of coverage for the adjacent
// pixel, which is the decimal percentage.
// int tuf1 = (int) (255f * (sp[U] - (float)tu));
// int tvf1 = (int) (255f * (sp[V] - (float)tv));
int tuf1 = (int) (255f * (uv[0] - tu));
int tvf1 = (int) (255f * (uv[1] - tv));
// the closer sp[U or V] is to the decimal being zero
// the more coverage it should get of the original pixel
int tuf = 255 - tuf1;
int tvf = 255 - tvf1;
// this code sucks! filled with bugs and slow as hell!
int pixel00 = tpixels[txy];
int pixel01 = (tv < theight1) ? tpixels[txy + twidth] : tpixels[txy];
int pixel10 = (tu < twidth1) ? tpixels[txy + 1] : tpixels[txy];
int pixel11 = ((tv < theight1) && (tu < twidth1)) ? tpixels[txy + twidth + 1] : tpixels[txy];
//System.out.println("1: "+pixel00);
//check
int p00, p01, p10, p11;
int px0, px1; //, pxy;
if (tformat == ALPHA) {
px0 = (pixel00*tuf + pixel10*tuf1) >> 8;
px1 = (pixel01*tuf + pixel11*tuf1) >> 8;
ta = (((px0*tvf + px1*tvf1) >> 8) *
(interpARGB ? ((int) (sp[A]*255)) : a2orig)) >> 8;
} else if (tformat == ARGB) {
p00 = (pixel00 >> 24) & 0xff;
p01 = (pixel01 >> 24) & 0xff;
p10 = (pixel10 >> 24) & 0xff;
p11 = (pixel11 >> 24) & 0xff;
px0 = (p00*tuf + p10*tuf1) >> 8;
px1 = (p01*tuf + p11*tuf1) >> 8;
ta = (((px0*tvf + px1*tvf1) >> 8) *
(interpARGB ? ((int) (sp[A]*255)) : a2orig)) >> 8;
} else { // RGB image, no alpha
//ACCTEX: Getting here when smooth is on
ta = interpARGB ? ((int) (sp[A]*255)) : a2orig;
//System.out.println("4: "+ta + " " +interpARGB + " " + sp[A] + " " + a2orig);
//check
}
if ((tformat == RGB) || (tformat == ARGB)) {
p00 = (pixel00 >> 16) & 0xff; // red
p01 = (pixel01 >> 16) & 0xff;
p10 = (pixel10 >> 16) & 0xff;
p11 = (pixel11 >> 16) & 0xff;
px0 = (p00*tuf + p10*tuf1) >> 8;
px1 = (p01*tuf + p11*tuf1) >> 8;
tr = (((px0*tvf + px1*tvf1) >> 8) * (interpARGB ? ((int) (sp[R]*255)) : r2)) >> 8;
p00 = (pixel00 >> 8) & 0xff; // green
p01 = (pixel01 >> 8) & 0xff;
p10 = (pixel10 >> 8) & 0xff;
p11 = (pixel11 >> 8) & 0xff;
px0 = (p00*tuf + p10*tuf1) >> 8;
px1 = (p01*tuf + p11*tuf1) >> 8;
tg = (((px0*tvf + px1*tvf1) >> 8) * (interpARGB ? ((int) (sp[G]*255)) : g2)) >> 8;
p00 = pixel00 & 0xff; // blue
p01 = pixel01 & 0xff;
p10 = pixel10 & 0xff;
p11 = pixel11 & 0xff;
px0 = (p00*tuf + p10*tuf1) >> 8;
px1 = (p01*tuf + p11*tuf1) >> 8;
tb = (((px0*tvf + px1*tvf1) >> 8) * (interpARGB ? ((int) (sp[B]*255)) : b2)) >> 8;
//System.out.println("5: "+tr + " " + tg + " " +tb);
//check
} else { // alpha image, only use current fill color
if (interpARGB) {
tr = (int) (sp[R] * 255);
tg = (int) (sp[G] * 255);
tb = (int) (sp[B] * 255);
} else {
tr = r2;
tg = g2;
tb = b2;
}
}
// get coverage for pixel if smooth
// checks smooth again here because of
// hints[SMOOTH_IMAGES] used up above
int weight = smooth ? coverage(x) : 255;
if (weight != 255) ta = (ta*weight) >> 8;
//System.out.println(ta);
//System.out.println("8");
//check
} else { // no smooth, just get the pixels
int tpixel = tpixels[txy];
// TODO i doubt splitting these guys really gets us
// all that much speed.. is it worth it?
if (tformat == ALPHA) {
ta = tpixel;
if (interpARGB) {
tr = (int) (sp[R]*255);
tg = (int) (sp[G]*255);
tb = (int) (sp[B]*255);
if (sp[A] != 1) {
ta = (((int) (sp[A]*255)) * ta) >> 8;
}
} else {
tr = r2;
tg = g2;
tb = b2;
ta = (a2orig * ta) >> 8;
}
} else { // RGB or ARGB
ta = (tformat == RGB) ? 255 : (tpixel >> 24) & 0xff;
if (interpARGB) {
tr = (((int) (sp[R]*255)) * ((tpixel >> 16) & 0xff)) >> 8;
tg = (((int) (sp[G]*255)) * ((tpixel >> 8) & 0xff)) >> 8;
tb = (((int) (sp[B]*255)) * ((tpixel) & 0xff)) >> 8;
ta = (((int) (sp[A]*255)) * ta) >> 8;
} else {
tr = (r2 * ((tpixel >> 16) & 0xff)) >> 8;
tg = (g2 * ((tpixel >> 8) & 0xff)) >> 8;
tb = (b2 * ((tpixel) & 0xff)) >> 8;
ta = (a2orig * ta) >> 8;
}
}
}
if ((ta == 254) || (ta == 255)) { // if (ta & 0xf8) would be good
// no need to blend
pixels[offset+x] = 0xff000000 | (tr << 16) | (tg << 8) | tb;
zbuffer[offset+x] = sp[Z];
} else {
// blend with pixel on screen
int a1 = 255-ta;
int r1 = (pixels[offset+x] >> 16) & 0xff;
int g1 = (pixels[offset+x] >> 8) & 0xff;
int b1 = (pixels[offset+x]) & 0xff;
pixels[offset+x] =
0xff000000 |
(((tr*ta + r1*a1) >> 8) << 16) |
((tg*ta + g1*a1) & 0xff00) |
((tb*ta + b1*a1) >> 8);
//System.out.println("17");
//check
if (ta > ZBUFFER_MIN_COVERAGE) zbuffer[offset+x] = sp[Z];
}
//System.out.println("18");
//check
} else { // no image applied
int weight = smooth ? coverage(x) : 255;
if (interpARGB) {
r2 = (int) (sp[R] * 255);
g2 = (int) (sp[G] * 255);
b2 = (int) (sp[B] * 255);
if (sp[A] != 1) weight = (weight * ((int) (sp[A] * 255))) >> 8;
if (weight == 255) {
rgba = 0xff000000 | (r2 << 16) | (g2 << 8) | b2;
}
} else {
if (a2orig != 255) weight = (weight * a2orig) >> 8;
}
if (weight == 255) {
// no blend, no aa, just the rgba
pixels[offset+x] = rgba;
zbuffer[offset+x] = sp[Z];
} else {
int r1 = (pixels[offset+x] >> 16) & 0xff;
int g1 = (pixels[offset+x] >> 8) & 0xff;
int b1 = (pixels[offset+x]) & 0xff;
a2 = weight;
int a1 = 255 - a2;
pixels[offset+x] = (0xff000000 |
((r1*a1 + r2*a2) >> 8) << 16 |
// use & instead of >> and << below
((g1*a1 + g2*a2) >> 8) << 8 |
((b1*a1 + b2*a2) >> 8));
if (a2 > ZBUFFER_MIN_COVERAGE) zbuffer[offset+x] = sp[Z];
}
}
}
// if smooth enabled, don't increment values
// for the pixel in the stretch out version
// of the scanline used to get smooth edges.
if (!smooth || ((x >= truelx) && (x <= truerx))) {
//if (!smooth)
increment(sp, sdp);
}
}
firstModY = -1;
interpX = true;
}
// x is in screen, not huge 8x coordinates
private int coverage(int x) {
if ((x >= aaleftfull) && (x <= aarightfull) &&
// important since not all SUBYRES lines may have been covered
(firstModY == 0) && (lastModY == SUBYRES1)) {
return 255;
}
int pixelLeft = x*SUBXRES; // huh?
int pixelRight = pixelLeft + 8;
int amt = 0;
for (int i = firstModY; i <= lastModY; i++) {
if ((aaleft[i] > pixelRight) || (aaright[i] < pixelLeft)) {
continue;
}
// does this need a +1 ?
amt += ((aaright[i] < pixelRight ? aaright[i] : pixelRight) -
(aaleft[i] > pixelLeft ? aaleft[i] : pixelLeft));
}
amt <<= 2;
return (amt == 256) ? 255 : amt;
}
private void incrementalize_y(float p1[], float p2[],
float p[], float dp[], int y) {
float delta = p2[Y] - p1[Y];
if (delta == 0) delta = 1;
float fraction = y + 0.5f - p1[Y];
if (interpX) {
dp[X] = (p2[X] - p1[X]) / delta;
p[X] = p1[X] + dp[X] * fraction;
}
if (interpZ) {
dp[Z] = (p2[Z] - p1[Z]) / delta;
p[Z] = p1[Z] + dp[Z] * fraction;
}
if (interpARGB) {
dp[R] = (p2[R] - p1[R]) / delta;
dp[G] = (p2[G] - p1[G]) / delta;
dp[B] = (p2[B] - p1[B]) / delta;
dp[A] = (p2[A] - p1[A]) / delta;
p[R] = p1[R] + dp[R] * fraction;
p[G] = p1[G] + dp[G] * fraction;
p[B] = p1[B] + dp[B] * fraction;
p[A] = p1[A] + dp[A] * fraction;
}
if (interpUV) {
dp[U] = (p2[U] - p1[U]) / delta;
dp[V] = (p2[V] - p1[V]) / delta;
//if (smooth) {
//p[U] = p1[U]; //+ dp[U] * fraction;
//p[V] = p1[V]; //+ dp[V] * fraction;
//} else {
p[U] = p1[U] + dp[U] * fraction;
p[V] = p1[V] + dp[V] * fraction;
//}
if (FRY) System.out.println("inc y p[U] p[V] = " + p[U] + " " + p[V]);
}
}
//incrementalize_x(l, r, sp, sdp, lx);
private void incrementalize_x(float p1[], float p2[],
float p[], float dp[], int x) {
float delta = p2[X] - p1[X];
if (delta == 0) delta = 1;
float fraction = x + 0.5f - p1[X];
if (smooth) {
delta /= SUBXRES;
fraction /= SUBXRES;
}
if (interpX) {
dp[X] = (p2[X] - p1[X]) / delta;
p[X] = p1[X] + dp[X] * fraction;
}
if (interpZ) {
dp[Z] = (p2[Z] - p1[Z]) / delta;
p[Z] = p1[Z] + dp[Z] * fraction;
//System.out.println(p2[Z]+" " +p1[Z]+" " +dp[Z]);
}
if (interpARGB) {
dp[R] = (p2[R] - p1[R]) / delta;
dp[G] = (p2[G] - p1[G]) / delta;
dp[B] = (p2[B] - p1[B]) / delta;
dp[A] = (p2[A] - p1[A]) / delta;
p[R] = p1[R] + dp[R] * fraction;
p[G] = p1[G] + dp[G] * fraction;
p[B] = p1[B] + dp[B] * fraction;
p[A] = p1[A] + dp[A] * fraction;
}
if (interpUV) {
if (FRY) System.out.println("delta, frac = " + delta + ", " + fraction);
dp[U] = (p2[U] - p1[U]) / delta;
dp[V] = (p2[V] - p1[V]) / delta;
//if (smooth) {
//p[U] = p1[U];
// offset for the damage that will be done by the
// 8 consecutive calls to scanline
// agh.. this won't work b/c not always 8 calls before render
// maybe lastModY - firstModY + 1 instead?
if (FRY) System.out.println("before inc x p[V] = " + p[V] + " " + p1[V] + " " + p2[V]);
//p[V] = p1[V] - SUBXRES1 * fraction;
//} else {
p[U] = p1[U] + dp[U] * fraction;
p[V] = p1[V] + dp[V] * fraction;
//}
}
}
private void increment(float p[], float dp[]) {
if (interpX) p[X] += dp[X];
if (interpZ) p[Z] += dp[Z];
if (interpARGB) {
p[R] += dp[R];
p[G] += dp[G];
p[B] += dp[B];
p[A] += dp[A];
}
if (interpUV) {
if (FRY) System.out.println("increment() " + p[V] + " " + dp[V]);
p[U] += dp[U];
p[V] += dp[V];
}
}
/**
* Pass camera-space coordinates for the triangle.
* Needed to render if hint(ENABLE_ACCURATE_TEXTURES) enabled.
* Generally this will not need to be called manually,
* currently called from PGraphics3D.render_triangles()
*/
public void setCamVertices(float x0, float y0, float z0,
float x1, float y1, float z1,
float x2, float y2, float z2) {
camX[0] = x0;
camX[1] = x1;
camX[2] = x2;
camY[0] = y0;
camY[1] = y1;
camY[2] = y2;
camZ[0] = z0;
camZ[1] = z1;
camZ[2] = z2;
}
public void setVertices(float x0, float y0, float z0,
float x1, float y1, float z1,
float x2, float y2, float z2) {
vertices[0][X] = x0;
vertices[1][X] = x1;
vertices[2][X] = x2;
vertices[0][Y] = y0;
vertices[1][Y] = y1;
vertices[2][Y] = y2;
vertices[0][Z] = z0;
vertices[1][Z] = z1;
vertices[2][Z] = z2;
}
/**
* Precompute a bunch of variables needed to perform
* texture mapping.
* @return True unless texture mapping is degenerate
*/
boolean precomputeAccurateTexturing() {
int o0 = 0;
int o1 = 1;
int o2 = 2;
PMatrix3D myMatrix = new PMatrix3D(vertices[o0][U], vertices[o0][V], 1, 0,
vertices[o1][U], vertices[o1][V], 1, 0,
vertices[o2][U], vertices[o2][V], 1, 0,
0, 0, 0, 1);
// A 3x3 inversion would be more efficient here,
// given that the fourth r/c are unity
boolean invertSuccess = myMatrix.invert();// = myMatrix.invert();
// If the matrix inversion had trouble, let the caller know.
// Note that this does not catch everything that could go wrong
// here, like if the renderer is in ortho() mode (which really
// must be caught in PGraphics3D instead of here).
if (!invertSuccess) return false;
float m00, m01, m02, m10, m11, m12, m20, m21, m22;
m00 = myMatrix.m00*camX[o0]+myMatrix.m01*camX[o1]+myMatrix.m02*camX[o2];
m01 = myMatrix.m10*camX[o0]+myMatrix.m11*camX[o1]+myMatrix.m12*camX[o2];
m02 = myMatrix.m20*camX[o0]+myMatrix.m21*camX[o1]+myMatrix.m22*camX[o2];
m10 = myMatrix.m00*camY[o0]+myMatrix.m01*camY[o1]+myMatrix.m02*camY[o2];
m11 = myMatrix.m10*camY[o0]+myMatrix.m11*camY[o1]+myMatrix.m12*camY[o2];
m12 = myMatrix.m20*camY[o0]+myMatrix.m21*camY[o1]+myMatrix.m22*camY[o2];
m20 = -(myMatrix.m00*camZ[o0]+myMatrix.m01*camZ[o1]+myMatrix.m02*camZ[o2]);
m21 = -(myMatrix.m10*camZ[o0]+myMatrix.m11*camZ[o1]+myMatrix.m12*camZ[o2]);
m22 = -(myMatrix.m20*camZ[o0]+myMatrix.m21*camZ[o1]+myMatrix.m22*camZ[o2]);
float px = m02;
float py = m12;
float pz = m22;
float TEX_WIDTH = this.twidth;
float TEX_HEIGHT = this.theight;
float resultT0x = m00*TEX_WIDTH+m02;
float resultT0y = m10*TEX_WIDTH+m12;
float resultT0z = m20*TEX_WIDTH+m22;
float result0Tx = m01*TEX_HEIGHT+m02;
float result0Ty = m11*TEX_HEIGHT+m12;
float result0Tz = m21*TEX_HEIGHT+m22;
float mx = resultT0x-m02;
float my = resultT0y-m12;
float mz = resultT0z-m22;
float nx = result0Tx-m02;
float ny = result0Ty-m12;
float nz = result0Tz-m22;
//avec = p x n
ax = (py*nz-pz*ny)*TEX_WIDTH; //F_TEX_WIDTH/HEIGHT?
ay = (pz*nx-px*nz)*TEX_WIDTH;
az = (px*ny-py*nx)*TEX_WIDTH;
//bvec = m x p
bx = (my*pz-mz*py)*TEX_HEIGHT;
by = (mz*px-mx*pz)*TEX_HEIGHT;
bz = (mx*py-my*px)*TEX_HEIGHT;
//cvec = n x m
cx = ny*mz-nz*my;
cy = nz*mx-nx*mz;
cz = nx*my-ny*mx;
//System.out.println("a/b/c: "+ax+" " + ay + " " + az + " " + bx + " " + by + " " + bz + " " + cx + " " + cy + " " + cz);
nearPlaneWidth = (parent.rightScreen-parent.leftScreen);
nearPlaneHeight = (parent.topScreen-parent.bottomScreen);
nearPlaneDepth = parent.nearPlane;
// one pixel width in nearPlane coordinates
xmult = nearPlaneWidth / parent.width;
ymult = nearPlaneHeight / parent.height;
// Extra scalings to map screen plane units to pixel units
// newax = ax*xmult;
// newbx = bx*xmult;
// newcx = cx*xmult;
// System.out.println("nearplane: "+ nearPlaneWidth + " " + nearPlaneHeight + " " + nearPlaneDepth);
// System.out.println("mults: "+ xmult + " " + ymult);
// System.out.println("news: "+ newax + " " + newbx + " " + newcx);
return true;
}
/**
* Get the texture map location based on the current screen
* coordinates. Assumes precomputeAccurateTexturing() has
* been called already for this texture mapping.
* @param sx
* @param sy
* @return
*/
private int getTextureIndex(float sx, float sy, float[] uv) {
if (EWJORDAN) System.out.println("Getting texel at "+sx + ", "+sy);
//System.out.println("Screen: "+ sx + " " + sy);
sx = xmult*(sx-(parent.width/2.0f) +.5f);//+.5f)
sy = ymult*(sy-(parent.height/2.0f)+.5f);//+.5f)
//sx /= SUBXRES;
//sy /= SUBYRES;
float sz = nearPlaneDepth;
float a = sx * ax + sy * ay + sz * az;
float b = sx * bx + sy * by + sz * bz;
float c = sx * cx + sy * cy + sz * cz;
int u = (int)(a / c);
int v = (int)(b / c);
uv[0] = a / c;
uv[1] = b / c;
if (uv[0] < 0) {
uv[0] = u = 0;
}
if (uv[1] < 0) {
uv[1] = v = 0;
}
if (uv[0] >= twidth) {
uv[0] = twidth-1;
u = twidth-1;
}
if (uv[1] >= theight) {
uv[1] = theight-1;
v = theight-1;
}
int result = v*twidth + u;
//System.out.println("a/b/c: "+a + " " + b + " " + c);
//System.out.println("cx/y/z: "+cx + " " + cy + " " + cz);
//if (result < 0) result = 0;
//if (result >= timage.pixels.length-2) result = timage.pixels.length - 2;
if (EWJORDAN) System.out.println("Got texel "+result);
return result;
}
public void setIntensities(float ar, float ag, float ab, float aa,
float br, float bg, float bb, float ba,
float cr, float cg, float cb, float ca) {
vertices[0][R] = ar;
vertices[0][G] = ag;
vertices[0][B] = ab;
vertices[0][A] = aa;
vertices[1][R] = br;
vertices[1][G] = bg;
vertices[1][B] = bb;
vertices[1][A] = ba;
vertices[2][R] = cr;
vertices[2][G] = cg;
vertices[2][B] = cb;
vertices[2][A] = ca;
}
}
processing-core-1.2.1/src/processing/core/PMatrix2D.java 0000644 0001750 0001750 00000025062 11352203453 022452 0 ustar andrew andrew /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2005-08 Ben Fry and Casey Reas
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
/**
* 3x2 affine matrix implementation.
*/
public class PMatrix2D implements PMatrix {
public float m00, m01, m02;
public float m10, m11, m12;
public PMatrix2D() {
reset();
}
public PMatrix2D(float m00, float m01, float m02,
float m10, float m11, float m12) {
set(m00, m01, m02,
m10, m11, m12);
}
public PMatrix2D(PMatrix matrix) {
set(matrix);
}
public void reset() {
set(1, 0, 0,
0, 1, 0);
}
/**
* Returns a copy of this PMatrix.
*/
public PMatrix2D get() {
PMatrix2D outgoing = new PMatrix2D();
outgoing.set(this);
return outgoing;
}
/**
* Copies the matrix contents into a 6 entry float array.
* If target is null (or not the correct size), a new array will be created.
*/
public float[] get(float[] target) {
if ((target == null) || (target.length != 6)) {
target = new float[6];
}
target[0] = m00;
target[1] = m01;
target[2] = m02;
target[3] = m10;
target[4] = m11;
target[5] = m12;
return target;
}
public void set(PMatrix matrix) {
if (matrix instanceof PMatrix2D) {
PMatrix2D src = (PMatrix2D) matrix;
set(src.m00, src.m01, src.m02,
src.m10, src.m11, src.m12);
} else {
throw new IllegalArgumentException("PMatrix2D.set() only accepts PMatrix2D objects.");
}
}
public void set(PMatrix3D src) {
}
public void set(float[] source) {
m00 = source[0];
m01 = source[1];
m02 = source[2];
m10 = source[3];
m11 = source[4];
m12 = source[5];
}
public void set(float m00, float m01, float m02,
float m10, float m11, float m12) {
this.m00 = m00; this.m01 = m01; this.m02 = m02;
this.m10 = m10; this.m11 = m11; this.m12 = m12;
}
public void set(float m00, float m01, float m02, float m03,
float m10, float m11, float m12, float m13,
float m20, float m21, float m22, float m23,
float m30, float m31, float m32, float m33) {
}
public void translate(float tx, float ty) {
m02 = tx*m00 + ty*m01 + m02;
m12 = tx*m10 + ty*m11 + m12;
}
public void translate(float x, float y, float z) {
throw new IllegalArgumentException("Cannot use translate(x, y, z) on a PMatrix2D.");
}
// Implementation roughly based on AffineTransform.
public void rotate(float angle) {
float s = sin(angle);
float c = cos(angle);
float temp1 = m00;
float temp2 = m01;
m00 = c * temp1 + s * temp2;
m01 = -s * temp1 + c * temp2;
temp1 = m10;
temp2 = m11;
m10 = c * temp1 + s * temp2;
m11 = -s * temp1 + c * temp2;
}
public void rotateX(float angle) {
throw new IllegalArgumentException("Cannot use rotateX() on a PMatrix2D.");
}
public void rotateY(float angle) {
throw new IllegalArgumentException("Cannot use rotateY() on a PMatrix2D.");
}
public void rotateZ(float angle) {
rotate(angle);
}
public void rotate(float angle, float v0, float v1, float v2) {
throw new IllegalArgumentException("Cannot use this version of rotate() on a PMatrix2D.");
}
public void scale(float s) {
scale(s, s);
}
public void scale(float sx, float sy) {
m00 *= sx; m01 *= sy;
m10 *= sx; m11 *= sy;
}
public void scale(float x, float y, float z) {
throw new IllegalArgumentException("Cannot use this version of scale() on a PMatrix2D.");
}
public void skewX(float angle) {
apply(1, 0, 1, tan(angle), 0, 0);
}
public void skewY(float angle) {
apply(1, 0, 1, 0, tan(angle), 0);
}
public void apply(PMatrix source) {
if (source instanceof PMatrix2D) {
apply((PMatrix2D) source);
} else if (source instanceof PMatrix3D) {
apply((PMatrix3D) source);
}
}
public void apply(PMatrix2D source) {
apply(source.m00, source.m01, source.m02,
source.m10, source.m11, source.m12);
}
public void apply(PMatrix3D source) {
throw new IllegalArgumentException("Cannot use apply(PMatrix3D) on a PMatrix2D.");
}
public void apply(float n00, float n01, float n02,
float n10, float n11, float n12) {
float t0 = m00;
float t1 = m01;
m00 = n00 * t0 + n10 * t1;
m01 = n01 * t0 + n11 * t1;
m02 += n02 * t0 + n12 * t1;
t0 = m10;
t1 = m11;
m10 = n00 * t0 + n10 * t1;
m11 = n01 * t0 + n11 * t1;
m12 += n02 * t0 + n12 * t1;
}
public void apply(float n00, float n01, float n02, float n03,
float n10, float n11, float n12, float n13,
float n20, float n21, float n22, float n23,
float n30, float n31, float n32, float n33) {
throw new IllegalArgumentException("Cannot use this version of apply() on a PMatrix2D.");
}
/**
* Apply another matrix to the left of this one.
*/
public void preApply(PMatrix2D left) {
preApply(left.m00, left.m01, left.m02,
left.m10, left.m11, left.m12);
}
public void preApply(PMatrix3D left) {
throw new IllegalArgumentException("Cannot use preApply(PMatrix3D) on a PMatrix2D.");
}
public void preApply(float n00, float n01, float n02,
float n10, float n11, float n12) {
float t0 = m02;
float t1 = m12;
n02 += t0 * n00 + t1 * n01;
n12 += t0 * n10 + t1 * n11;
m02 = n02;
m12 = n12;
t0 = m00;
t1 = m10;
m00 = t0 * n00 + t1 * n01;
m10 = t0 * n10 + t1 * n11;
t0 = m01;
t1 = m11;
m01 = t0 * n00 + t1 * n01;
m11 = t0 * n10 + t1 * n11;
}
public void preApply(float n00, float n01, float n02, float n03,
float n10, float n11, float n12, float n13,
float n20, float n21, float n22, float n23,
float n30, float n31, float n32, float n33) {
throw new IllegalArgumentException("Cannot use this version of preApply() on a PMatrix2D.");
}
//////////////////////////////////////////////////////////////
/**
* Multiply the x and y coordinates of a PVector against this matrix.
*/
public PVector mult(PVector source, PVector target) {
if (target == null) {
target = new PVector();
}
target.x = m00*source.x + m01*source.y + m02;
target.y = m10*source.x + m11*source.y + m12;
return target;
}
/**
* Multiply a two element vector against this matrix.
* If out is null or not length four, a new float array will be returned.
* The values for vec and out can be the same (though that's less efficient).
*/
public float[] mult(float vec[], float out[]) {
if (out == null || out.length != 2) {
out = new float[2];
}
if (vec == out) {
float tx = m00*vec[0] + m01*vec[1] + m02;
float ty = m10*vec[0] + m11*vec[1] + m12;
out[0] = tx;
out[1] = ty;
} else {
out[0] = m00*vec[0] + m01*vec[1] + m02;
out[1] = m10*vec[0] + m11*vec[1] + m12;
}
return out;
}
public float multX(float x, float y) {
return m00*x + m01*y + m02;
}
public float multY(float x, float y) {
return m10*x + m11*y + m12;
}
/**
* Transpose this matrix.
*/
public void transpose() {
}
/**
* Invert this matrix. Implementation stolen from OpenJDK.
* @return true if successful
*/
public boolean invert() {
float determinant = determinant();
if (Math.abs(determinant) <= Float.MIN_VALUE) {
return false;
}
float t00 = m00;
float t01 = m01;
float t02 = m02;
float t10 = m10;
float t11 = m11;
float t12 = m12;
m00 = t11 / determinant;
m10 = -t10 / determinant;
m01 = -t01 / determinant;
m11 = t00 / determinant;
m02 = (t01 * t12 - t11 * t02) / determinant;
m12 = (t10 * t02 - t00 * t12) / determinant;
return true;
}
/**
* @return the determinant of the matrix
*/
public float determinant() {
return m00 * m11 - m01 * m10;
}
//////////////////////////////////////////////////////////////
public void print() {
int big = (int) abs(max(PApplet.max(abs(m00), abs(m01), abs(m02)),
PApplet.max(abs(m10), abs(m11), abs(m12))));
int digits = 1;
if (Float.isNaN(big) || Float.isInfinite(big)) { // avoid infinite loop
digits = 5;
} else {
while ((big /= 10) != 0) digits++; // cheap log()
}
System.out.println(PApplet.nfs(m00, digits, 4) + " " +
PApplet.nfs(m01, digits, 4) + " " +
PApplet.nfs(m02, digits, 4));
System.out.println(PApplet.nfs(m10, digits, 4) + " " +
PApplet.nfs(m11, digits, 4) + " " +
PApplet.nfs(m12, digits, 4));
System.out.println();
}
//////////////////////////////////////////////////////////////
// TODO these need to be added as regular API, but the naming and
// implementation needs to be improved first. (e.g. actually keeping track
// of whether the matrix is in fact identity internally.)
protected boolean isIdentity() {
return ((m00 == 1) && (m01 == 0) && (m02 == 0) &&
(m10 == 0) && (m11 == 1) && (m12 == 0));
}
// TODO make this more efficient, or move into PMatrix2D
protected boolean isWarped() {
return ((m00 != 1) || (m01 != 0) &&
(m10 != 0) || (m11 != 1));
}
//////////////////////////////////////////////////////////////
private final float max(float a, float b) {
return (a > b) ? a : b;
}
private final float abs(float a) {
return (a < 0) ? -a : a;
}
private final float sin(float angle) {
return (float)Math.sin(angle);
}
private final float cos(float angle) {
return (float)Math.cos(angle);
}
private final float tan(float angle) {
return (float)Math.tan(angle);
}
}
processing-core-1.2.1/src/processing/core/PLine.java 0000644 0001750 0001750 00000100476 11111372137 021711 0 ustar andrew andrew /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-07 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
/**
* Code for rendering lines with P2D and P3D.
* @author rocha
* @author fry
*/
public class PLine implements PConstants
{
private int[] m_pixels;
private float[] m_zbuffer;
//private int[] m_stencil;
private int m_index;
static final int R_COLOR = 0x1;
static final int R_ALPHA = 0x2;
static final int R_SPATIAL = 0x8;
static final int R_THICK = 0x4;
static final int R_SMOOTH = 0x10;
private int SCREEN_WIDTH;
private int SCREEN_HEIGHT;
private int SCREEN_WIDTH1;
private int SCREEN_HEIGHT1;
public boolean INTERPOLATE_RGB;
public boolean INTERPOLATE_ALPHA;
public boolean INTERPOLATE_Z;
public boolean INTERPOLATE_THICK;
// antialias
private boolean SMOOTH;
// blender
//private boolean BLENDER;
// stroke color
private int m_stroke;
// draw flags
public int m_drawFlags;
// vertex coordinates
private float[] x_array;
private float[] y_array;
private float[] z_array;
// vertex intensity
private float[] r_array;
private float[] g_array;
private float[] b_array;
private float[] a_array;
// vertex offsets
private int o0;
private int o1;
// start values
private float m_r0;
private float m_g0;
private float m_b0;
private float m_a0;
private float m_z0;
// deltas
private float dz;
// rgba deltas
private float dr;
private float dg;
private float db;
private float da;
private PGraphics parent;
public PLine(PGraphics g) {
INTERPOLATE_Z = false;
x_array = new float[2];
y_array = new float[2];
z_array = new float[2];
r_array = new float[2];
g_array = new float[2];
b_array = new float[2];
a_array = new float[2];
this.parent = g;
}
public void reset() {
// reset these in case PGraphics was resized
SCREEN_WIDTH = parent.width;
SCREEN_HEIGHT = parent.height;
SCREEN_WIDTH1 = SCREEN_WIDTH-1;
SCREEN_HEIGHT1 = SCREEN_HEIGHT-1;
m_pixels = parent.pixels;
//m_stencil = parent.stencil;
if (parent instanceof PGraphics3D) {
m_zbuffer = ((PGraphics3D) parent).zbuffer;
}
// other things to reset
INTERPOLATE_RGB = false;
INTERPOLATE_ALPHA = false;
//INTERPOLATE_Z = false;
m_drawFlags = 0;
m_index = 0;
//BLENDER = false;
}
public void setVertices(float x0, float y0, float z0,
float x1, float y1, float z1) {
// [rocha] fixed z drawing, so whenever a line turns on
// z interpolation, all the lines are z interpolated
if (z0 != z1 || z0 != 0.0f || z1 != 0.0f || INTERPOLATE_Z) {
INTERPOLATE_Z = true;
m_drawFlags |= R_SPATIAL;
} else {
INTERPOLATE_Z = false;
m_drawFlags &= ~R_SPATIAL;
}
z_array[0] = z0;
z_array[1] = z1;
x_array[0] = x0;
x_array[1] = x1;
y_array[0] = y0;
y_array[1] = y1;
}
public void setIntensities(float r0, float g0, float b0, float a0,
float r1, float g1, float b1, float a1) {
a_array[0] = (a0 * 253f + 1.0f) * 65536f;
a_array[1] = (a1 * 253f + 1.0f) * 65536f;
// check if we need alpha or not?
if ((a0 != 1.0f) || (a1 != 1.0f)) {
INTERPOLATE_ALPHA = true;
m_drawFlags |= R_ALPHA;
} else {
INTERPOLATE_ALPHA = false;
m_drawFlags &= ~R_ALPHA;
}
// extra scaling added to prevent color "overflood" due to rounding errors
r_array[0] = (r0 * 253f + 1.0f) * 65536f;
r_array[1] = (r1 * 253f + 1.0f) * 65536f;
g_array[0] = (g0 * 253f + 1.0f) * 65536f;
g_array[1] = (g1 * 253f + 1.0f) * 65536f;
b_array[0] = (b0 * 253f + 1.0f) * 65536f;
b_array[1] = (b1 * 253f + 1.0f) * 65536f;
// check if we need to interpolate the intensity values
if (r0 != r1) {
INTERPOLATE_RGB = true;
m_drawFlags |= R_COLOR;
} else if (g0 != g1) {
INTERPOLATE_RGB = true;
m_drawFlags |= R_COLOR;
} else if (b0 != b1) {
INTERPOLATE_RGB = true;
m_drawFlags |= R_COLOR;
} else {
// when plain we use the stroke color of the first vertex
m_stroke = 0xFF000000 |
((int)(255*r0) << 16) | ((int)(255*g0) << 8) | (int)(255*b0);
INTERPOLATE_RGB = false;
m_drawFlags &= ~R_COLOR;
}
}
public void setIndex(int index) {
m_index = index;
//BLENDER = false;
if (m_index != -1) {
//BLENDER = true;
} else {
m_index = 0;
}
}
public void draw() {
int xi;
int yi;
int length;
boolean visible = true;
if (parent.smooth) {
SMOOTH = true;
m_drawFlags |= R_SMOOTH;
} else {
SMOOTH = false;
m_drawFlags &= ~R_SMOOTH;
}
/*
// line hack
if (parent.hints[DISABLE_FLYING_POO]) {
float nwidth2 = -SCREEN_WIDTH;
float nheight2 = -SCREEN_HEIGHT;
float width2 = SCREEN_WIDTH * 2;
float height2 = SCREEN_HEIGHT * 2;
if ((x_array[1] < nwidth2) ||
(x_array[1] > width2) ||
(x_array[0] < nwidth2) ||
(x_array[0] > width2) ||
(y_array[1] < nheight2) ||
(y_array[1] > height2) ||
(y_array[0] < nheight2) ||
(y_array[0] > height2)) {
return; // this is a bad line
}
}
*/
///////////////////////////////////////
// line clipping
visible = lineClipping();
if (!visible) {
return;
}
///////////////////////////////////////
// calculate line values
int shortLen;
int longLen;
boolean yLonger;
int dt;
yLonger = false;
// HACK for drawing lines left-to-right for rev 0069
// some kind of bug exists with the line-stepping algorithm
// that causes strange patterns in the anti-aliasing.
// [040228 fry]
//
// swap rgba as well as the coords.. oops
// [040712 fry]
//
if (x_array[1] < x_array[0]) {
float t;
t = x_array[1]; x_array[1] = x_array[0]; x_array[0] = t;
t = y_array[1]; y_array[1] = y_array[0]; y_array[0] = t;
t = z_array[1]; z_array[1] = z_array[0]; z_array[0] = t;
t = r_array[1]; r_array[1] = r_array[0]; r_array[0] = t;
t = g_array[1]; g_array[1] = g_array[0]; g_array[0] = t;
t = b_array[1]; b_array[1] = b_array[0]; b_array[0] = t;
t = a_array[1]; a_array[1] = a_array[0]; a_array[0] = t;
}
// important - don't change the casts
// is needed this way for line drawing algorithm
longLen = (int)x_array[1] - (int)x_array[0];
shortLen = (int)y_array[1] - (int)y_array[0];
if (Math.abs(shortLen) > Math.abs(longLen)) {
int swap = shortLen;
shortLen = longLen;
longLen = swap;
yLonger = true;
}
// now we sort points so longLen is always positive
// and we always start drawing from x[0], y[0]
if (longLen < 0) {
// swap order
o0 = 1;
o1 = 0;
xi = (int) x_array[1];
yi = (int) y_array[1];
length = -longLen;
} else {
o0 = 0;
o1 = 1;
xi = (int) x_array[0];
yi = (int) y_array[0];
length = longLen;
}
// calculate dt
if (length == 0) {
dt = 0;
} else {
dt = (shortLen << 16) / longLen;
}
m_r0 = r_array[o0];
m_g0 = g_array[o0];
m_b0 = b_array[o0];
if (INTERPOLATE_RGB) {
dr = (r_array[o1] - r_array[o0]) / length;
dg = (g_array[o1] - g_array[o0]) / length;
db = (b_array[o1] - b_array[o0]) / length;
} else {
dr = 0;
dg = 0;
db = 0;
}
m_a0 = a_array[o0];
if (INTERPOLATE_ALPHA) {
da = (a_array[o1] - a_array[o0]) / length;
} else {
da = 0;
}
m_z0 = z_array[o0];
//z0 += -0.001f; // [rocha] ugly fix for z buffer precision
if (INTERPOLATE_Z) {
dz = (z_array[o1] - z_array[o0]) / length;
} else {
dz = 0;
}
// draw thin points
if (length == 0) {
if (INTERPOLATE_ALPHA) {
drawPoint_alpha(xi, yi);
} else {
drawPoint(xi, yi);
}
return;
}
/*
// draw antialias polygon lines for non stroked polygons
if (BLENDER && SMOOTH) {
// fix for endpoints not being drawn
// [rocha]
drawPoint_alpha((int)x_array[0], (int)x_array[0]);
drawPoint_alpha((int)x_array[1], (int)x_array[1]);
drawline_blender(x_array[0], y_array[0], x_array[1], y_array[1]);
return;
}
*/
// draw normal strokes
if (SMOOTH) {
// if ((m_drawFlags & R_SPATIAL) != 0) {
// drawLine_smooth_spatial(xi, yi, dt, length, yLonger);
// } else {
drawLine_smooth(xi, yi, dt, length, yLonger);
// }
} else {
if (m_drawFlags == 0) {
drawLine_plain(xi, yi, dt, length, yLonger);
} else if (m_drawFlags == R_ALPHA) {
drawLine_plain_alpha(xi, yi, dt, length, yLonger);
} else if (m_drawFlags == R_COLOR) {
drawLine_color(xi, yi, dt, length, yLonger);
} else if (m_drawFlags == (R_COLOR + R_ALPHA)) {
drawLine_color_alpha(xi, yi, dt, length, yLonger);
} else if (m_drawFlags == R_SPATIAL) {
drawLine_plain_spatial(xi, yi, dt, length, yLonger);
} else if (m_drawFlags == (R_SPATIAL + R_ALPHA)) {
drawLine_plain_alpha_spatial(xi, yi, dt, length, yLonger);
} else if (m_drawFlags == (R_SPATIAL + R_COLOR)) {
drawLine_color_spatial(xi, yi, dt, length, yLonger);
} else if (m_drawFlags == (R_SPATIAL + R_COLOR + R_ALPHA)) {
drawLine_color_alpha_spatial(xi, yi, dt, length, yLonger);
}
}
}
public boolean lineClipping() {
// new cohen-sutherland clipping code, as old one was buggy [toxi]
// get the "dips" for the points to clip
int code1 = lineClipCode(x_array[0], y_array[0]);
int code2 = lineClipCode(x_array[1], y_array[1]);
int dip = code1 | code2;
if ((code1 & code2)!=0) {
return false;
} else if (dip != 0) {
// now calculate the clipped points
float a0 = 0, a1 = 1, a = 0;
for (int i = 0; i < 4; i++) {
if (((dip>>i)%2)==1){
a = lineSlope(x_array[0], y_array[0], x_array[1], y_array[1], i+1);
if (((code1 >> i) % 2) == 1) {
a0 = (a>a0)?a:a0; // max(a,a0)
} else {
a1 = (a
* PShape moo;
*
* void setup() {
* size(400, 400);
* moo = loadShape("moo.svg");
* }
* void draw() {
* background(255);
* shape(moo, mouseX, mouseY);
* }
*
*
* This code is based on the Candy library written by Michael Chang, which was
* later revised and expanded for use as a Processing core library by Ben Fry.
* Thanks to Ricard Marxer Pinon for help with better Inkscape support in 0154.
*
*
*
*
* October 2008 revisions by fry (Processing 0149, pre-1.0)
*
*
*
* August 2008 revisions by fry (Processing 0149)
*
*
*
* February 2008 revisions by fry (Processing 0136)
*
*
*
* Revisions for "Candy 2" November 2006 by fry
*
*
*
* Revision 10/31/06 by flux
*
*
*
* Some SVG objects and features may not yet be supported.
* Here is a partial list of non-included features
*
*
*
* For those interested, the SVG specification can be found
* here.
*/
public class PShapeSVG extends PShape {
XMLElement element;
/// Values between 0 and 1.
float opacity;
float strokeOpacity;
float fillOpacity;
Gradient strokeGradient;
Paint strokeGradientPaint;
String strokeName; // id of another object, gradients only?
Gradient fillGradient;
Paint fillGradientPaint;
String fillName; // id of another object
/**
* Initializes a new SVG Object with the given filename.
*/
public PShapeSVG(PApplet parent, String filename) {
// this will grab the root document, starting Layers added for Candy 2
*
*
* All versions are RLE compressed.
*
* As of revision 0100, this function requires an absolute path, * in order to avoid confusion. To save inside the sketch folder, * use the function savePath() from PApplet, or use saveFrame() instead. * As of revision 0116, savePath() is not needed if this object has been * created (as recommended) via createImage() or createGraphics() or * one of its neighbors. *
* As of revision 0115, when using Java 1.4 and later, you can write
* to several formats besides tga and tiff. If Java 1.4 is installed
* and the extension used is supported (usually png, jpg, jpeg, bmp,
* and tiff), then those methods will be used to write the image.
* To get a list of the supported formats for writing, use:
* println(javax.imageio.ImageIO.getReaderFormatNames())
*
* To use the original built-in image writers, use .tga or .tif as the * extension, or don't include an extension. When no extension is used, * the extension .tif will be added to the file name. *
* The ImageIO API claims to support wbmp files, however they probably
* require a black and white image. Basic testing produced a zero-length
* file with no error.
*
* @webref
* @brief Saves the image to a TIFF, TARGA, PNG, or JPEG file
* @param filename a sequence of letters and numbers
*/
public void save(String filename) { // ignore
boolean success = false;
File file = new File(filename);
if (!file.isAbsolute()) {
if (parent != null) {
//file = new File(parent.savePath(filename));
filename = parent.savePath(filename);
} else {
String msg = "PImage.save() requires an absolute path. " +
"Use createImage(), or pass savePath() to save().";
PGraphics.showException(msg);
}
}
// Make sure the pixel data is ready to go
loadPixels();
try {
OutputStream os = null;
if (saveImageFormats == null) {
saveImageFormats = javax.imageio.ImageIO.getWriterFormatNames();
}
if (saveImageFormats != null) {
for (int i = 0; i < saveImageFormats.length; i++) {
if (filename.endsWith("." + saveImageFormats[i])) {
saveImageIO(filename);
return;
}
}
}
if (filename.toLowerCase().endsWith(".tga")) {
os = new BufferedOutputStream(new FileOutputStream(filename), 32768);
success = saveTGA(os); //, pixels, width, height, format);
} else {
if (!filename.toLowerCase().endsWith(".tif") &&
!filename.toLowerCase().endsWith(".tiff")) {
// if no .tif extension, add it..
filename += ".tif";
}
os = new BufferedOutputStream(new FileOutputStream(filename), 32768);
success = saveTIFF(os); //, pixels, width, height);
}
os.flush();
os.close();
} catch (IOException e) {
//System.err.println("Error while saving image.");
e.printStackTrace();
success = false;
}
if (!success) {
throw new RuntimeException("Error while saving image.");
}
}
}
processing-core-1.2.1/src/processing/xml/ 0000755 0001750 0001750 00000000000 11550154145 017703 5 ustar andrew andrew processing-core-1.2.1/src/processing/xml/XMLValidationException.java 0000644 0001750 0001750 00000011742 11074134155 025105 0 ustar andrew andrew /* XMLValidationException.java NanoXML/Java
*
* $Revision: 1.3 $
* $Date: 2002/01/04 21:03:29 $
* $Name: RELEASE_2_2_1 $
*
* This file is part of NanoXML 2 for Java.
* Copyright (C) 2000-2002 Marc De Scheemaecker, All Rights Reserved.
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the
* use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in
* a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
package processing.xml;
/**
* An XMLValidationException is thrown when the XML passed to the XML parser is
* well-formed but not valid.
*
* @author Marc De Scheemaecker
* @version $Name: RELEASE_2_2_1 $, $Revision: 1.3 $
*/
public class XMLValidationException
extends XMLException
{
/**
* An element was missing.
*/
public static final int MISSING_ELEMENT = 1;
/**
* An unexpected element was encountered.
*/
public static final int UNEXPECTED_ELEMENT = 2;
/**
* An attribute was missing.
*/
public static final int MISSING_ATTRIBUTE = 3;
/**
* An unexpected attribute was encountered.
*/
public static final int UNEXPECTED_ATTRIBUTE = 4;
/**
* An attribute has an invalid value.
*/
public static final int ATTRIBUTE_WITH_INVALID_VALUE = 5;
/**
* A PCDATA element was missing.
*/
public static final int MISSING_PCDATA = 6;
/**
* An unexpected PCDATA element was encountered.
*/
public static final int UNEXPECTED_PCDATA = 7;
/**
* Another error than those specified in this class was encountered.
*/
public static final int MISC_ERROR = 0;
/**
* Which error occurred.
*/
//private int errorType;
/**
* The name of the element where the exception occurred.
*/
private String elementName;
/**
* The name of the attribute where the exception occurred.
*/
private String attributeName;
/**
* The value of the attribute where the exception occurred.
*/
private String attributeValue;
/**
* Creates a new exception.
*
* @param errorType the type of validity error
* @param systemID the system ID from where the data came
* @param lineNr the line number in the XML data where the
* exception occurred.
* @param elementName the name of the offending element
* @param attributeName the name of the offending attribute
* @param attributeValue the value of the offending attribute
* @param msg the message of the exception.
*/
public XMLValidationException(int errorType,
String systemID,
int lineNr,
String elementName,
String attributeName,
String attributeValue,
String msg)
{
super(systemID, lineNr, null,
msg + ((elementName == null) ? "" : (", element=" + elementName))
+ ((attributeName == null) ? ""
: (", attribute=" + attributeName))
+ ((attributeValue == null) ? ""
: (", value='" + attributeValue + "'")),
false);
this.elementName = elementName;
this.attributeName = attributeName;
this.attributeValue = attributeValue;
}
/**
* Cleans up the object when it's destroyed.
*/
protected void finalize()
throws Throwable
{
this.elementName = null;
this.attributeName = null;
this.attributeValue = null;
super.finalize();
}
/**
* Returns the name of the element in which the validation is violated.
* If there is no current element, null is returned.
*/
public String getElementName()
{
return this.elementName;
}
/**
* Returns the name of the attribute in which the validation is violated.
* If there is no current attribute, null is returned.
*/
public String getAttributeName()
{
return this.attributeName;
}
/**
* Returns the value of the attribute in which the validation is violated.
* If there is no current attribute, null is returned.
*/
public String getAttributeValue()
{
return this.attributeValue;
}
}
processing-core-1.2.1/src/processing/xml/StdXMLParser.java 0000644 0001750 0001750 00000047627 11074234572 023062 0 ustar andrew andrew /* StdXMLParser.java NanoXML/Java
*
* $Revision: 1.5 $
* $Date: 2002/03/24 11:37:00 $
* $Name: RELEASE_2_2_1 $
*
* This file is part of NanoXML 2 for Java.
* Copyright (C) 2000-2002 Marc De Scheemaecker, All Rights Reserved.
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the
* use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in
* a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
package processing.xml;
import java.io.Reader;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
/**
* StdXMLParser is the core parser of NanoXML.
*
* @author Marc De Scheemaecker
* @version $Name: RELEASE_2_2_1 $, $Revision: 1.5 $
*/
public class StdXMLParser {
/**
* The builder which creates the logical structure of the XML data.
*/
private StdXMLBuilder builder;
/**
* The reader from which the parser retrieves its data.
*/
private StdXMLReader reader;
/**
* The entity resolver.
*/
private XMLEntityResolver entityResolver;
/**
* The validator that will process entity references and validate the XML
* data.
*/
private XMLValidator validator;
/**
* Creates a new parser.
*/
public StdXMLParser()
{
this.builder = null;
this.validator = null;
this.reader = null;
this.entityResolver = new XMLEntityResolver();
}
/**
* Cleans up the object when it's destroyed.
*/
protected void finalize()
throws Throwable
{
this.builder = null;
this.reader = null;
this.entityResolver = null;
this.validator = null;
super.finalize();
}
/**
* Sets the builder which creates the logical structure of the XML data.
*
* @param builder the non-null builder
*/
public void setBuilder(StdXMLBuilder builder)
{
this.builder = builder;
}
/**
* Returns the builder which creates the logical structure of the XML data.
*
* @return the builder
*/
public StdXMLBuilder getBuilder()
{
return this.builder;
}
/**
* Sets the validator that validates the XML data.
*
* @param validator the non-null validator
*/
public void setValidator(XMLValidator validator)
{
this.validator = validator;
}
/**
* Returns the validator that validates the XML data.
*
* @return the validator
*/
public XMLValidator getValidator()
{
return this.validator;
}
/**
* Sets the entity resolver.
*
* @param resolver the non-null resolver
*/
public void setResolver(XMLEntityResolver resolver)
{
this.entityResolver = resolver;
}
/**
* Returns the entity resolver.
*
* @return the non-null resolver
*/
public XMLEntityResolver getResolver()
{
return this.entityResolver;
}
/**
* Sets the reader from which the parser retrieves its data.
*
* @param reader the reader
*/
public void setReader(StdXMLReader reader)
{
this.reader = reader;
}
/**
* Returns the reader from which the parser retrieves its data.
*
* @return the reader
*/
public StdXMLReader getReader()
{
return this.reader;
}
/**
* Parses the data and lets the builder create the logical data structure.
*
* @return the logical structure built by the builder
*
* @throws net.n3.nanoxml.XMLException
* if an error occurred reading or parsing the data
*/
public Object parse()
throws XMLException
{
try {
this.builder.startBuilding(this.reader.getSystemID(),
this.reader.getLineNr());
this.scanData();
return this.builder.getResult();
} catch (XMLException e) {
throw e;
} catch (Exception e) {
throw new XMLException(e);
}
}
/**
* Scans the XML data for elements.
*
* @throws java.lang.Exception
* if something went wrong
*/
protected void scanData() throws Exception {
while ((! this.reader.atEOF()) && (this.builder.getResult() == null)) {
String str = XMLUtil.read(this.reader, '&');
char ch = str.charAt(0);
if (ch == '&') {
XMLUtil.processEntity(str, this.reader, this.entityResolver);
continue;
}
switch (ch) {
case '<':
this.scanSomeTag(false, // don't allow CDATA
null, // no default namespace
new Properties());
break;
case ' ':
case '\t':
case '\r':
case '\n':
// skip whitespace
break;
default:
XMLUtil.errorInvalidInput(reader.getSystemID(),
reader.getLineNr(),
"`" + ch + "' (0x"
+ Integer.toHexString((int) ch)
+ ')');
}
}
}
/**
* Scans an XML tag.
*
* @param allowCDATA true if CDATA sections are allowed at this point
* @param defaultNamespace the default namespace URI (or null)
* @param namespaces list of defined namespaces
*
* @throws java.lang.Exception
* if something went wrong
*/
protected void scanSomeTag(boolean allowCDATA,
String defaultNamespace,
Properties namespaces)
throws Exception
{
String str = XMLUtil.read(this.reader, '&');
char ch = str.charAt(0);
if (ch == '&') {
XMLUtil.errorUnexpectedEntity(reader.getSystemID(),
reader.getLineNr(),
str);
}
switch (ch) {
case '?':
this.processPI();
break;
case '!':
this.processSpecialTag(allowCDATA);
break;
default:
this.reader.unread(ch);
this.processElement(defaultNamespace, namespaces);
}
}
/**
* Processes a "processing instruction".
*
* @throws java.lang.Exception
* if something went wrong
*/
protected void processPI()
throws Exception
{
XMLUtil.skipWhitespace(this.reader, null);
String target = XMLUtil.scanIdentifier(this.reader);
XMLUtil.skipWhitespace(this.reader, null);
Reader r = new PIReader(this.reader);
if (!target.equalsIgnoreCase("xml")) {
this.builder.newProcessingInstruction(target, r);
}
r.close();
}
/**
* Processes a tag that starts with a bang (<!...>).
*
* @param allowCDATA true if CDATA sections are allowed at this point
*
* @throws java.lang.Exception
* if something went wrong
*/
protected void processSpecialTag(boolean allowCDATA)
throws Exception
{
String str = XMLUtil.read(this.reader, '&');
char ch = str.charAt(0);
if (ch == '&') {
XMLUtil.errorUnexpectedEntity(reader.getSystemID(),
reader.getLineNr(),
str);
}
switch (ch) {
case '[':
if (allowCDATA) {
this.processCDATA();
} else {
XMLUtil.errorUnexpectedCDATA(reader.getSystemID(),
reader.getLineNr());
}
return;
case 'D':
this.processDocType();
return;
case '-':
XMLUtil.skipComment(this.reader);
return;
}
}
/**
* Processes a CDATA section.
*
* @throws java.lang.Exception
* if something went wrong
*/
protected void processCDATA() throws Exception {
if (! XMLUtil.checkLiteral(this.reader, "CDATA[")) {
XMLUtil.errorExpectedInput(reader.getSystemID(),
reader.getLineNr(),
"') {
XMLUtil.errorExpectedInput(reader.getSystemID(),
reader.getLineNr(),
"`>'");
}
// TODO DTD checking is currently disabled, because it breaks
// applications that don't have access to a net connection
// (since it insists on going and checking out the DTD).
if (false) {
if (systemID != null) {
Reader r = this.reader.openStream(publicID.toString(), systemID);
this.reader.startNewStream(r);
this.reader.setSystemID(systemID);
this.reader.setPublicID(publicID.toString());
this.validator.parseDTD(publicID.toString(),
this.reader,
this.entityResolver,
true);
}
}
}
/**
* Processes a regular element.
*
* @param defaultNamespace the default namespace URI (or null)
* @param namespaces list of defined namespaces
*
* @throws java.lang.Exception
* if something went wrong
*/
protected void processElement(String defaultNamespace,
Properties namespaces)
throws Exception
{
String fullName = XMLUtil.scanIdentifier(this.reader);
String name = fullName;
XMLUtil.skipWhitespace(this.reader, null);
String prefix = null;
int colonIndex = name.indexOf(':');
if (colonIndex > 0) {
prefix = name.substring(0, colonIndex);
name = name.substring(colonIndex + 1);
}
Vector
* The encoding parameter inside XML files is ignored, only UTF-8 (or plain ASCII) are parsed properly.
* =advanced
* XMLElement is an XML element. This is the base class used for the
* Processing XML library, representing a single node of an XML tree.
*
* This code is based on a modified version of NanoXML by Marc De Scheemaecker.
*
* @author Marc De Scheemaecker
* @author processing.org
*
* @webref data:composite
* @usage Web & Application
* @instanceName xml any variable of type XMLElement
*/
public class XMLElement implements Serializable {
/**
* No line number defined.
*/
public static final int NO_LINE = -1;
/**
* The parent element.
*/
private XMLElement parent;
/**
* The attributes of the element.
*/
private Vector